import gradio as gr def reply(user_msg: str, history: list, name: str): name = name or "friend" assistant_msg = f"Nice to meet you, {name}! You said: {user_msg}" history = history + [ {"role": "user", "content": user_msg}, {"role": "assistant", "content": assistant_msg}, ] return history, "" # clear the textbox def set_name_and_greet(name: str): name = name or "friend" greeting = [ {"role": "assistant", "content": f"Hi, {name}! How can I help you?"} ] return name, greeting # matches the two outputs with gr.Blocks() as demo: name_state = gr.State("") # remembers the chosen name with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Enter your name, then click **Set Name**") name_input = gr.Textbox(placeholder="Type your name here…") set_btn = gr.Button("Set Name") gr.Markdown("_After the greeting appears, start chatting →_") with gr.Column(scale=2): chatbot = gr.Chatbot(label="Chat", type="messages") user_text = gr.Textbox(placeholder="Ask me something…") set_btn.click( fn=set_name_and_greet, inputs=name_input, outputs=[name_state, chatbot], # update state & chatbot history show_progress=False, ) user_text.submit( fn=reply, inputs=[user_text, chatbot, name_state], # latest msg, history, name outputs=[chatbot, user_text], # update history & clear input ) demo.launch()