Sub topic 2
The chat function: message and history in, reply out
This chapter assumes you can write Python functions and generators, run a script from a terminal, and have installed Gradio with pip install gradio. You don't need an LLM API key yet. The goal is to understand the one function that every Gradio chat app is built around, so you can write it correctly before any UI or model is involved.
The contract in one sentence
A Gradio chat app is a function that takes the user's newest message and the earlier conversation, and returns the assistant's reply. Gradio handles the page, the text box, the message bubbles, and the network calls. You supply only the function.
def respond(message, history):
return f"You said: {message}"The function has two parts:
- Inputs.
messageis what the user just sent.historyis everything said before that message. - Output. The reply to show next. In the simplest case it is a string.
Gradio calls the function once per user submission, each time with the newest message and the conversation so far.
What each argument contains
| Argument | Type | Meaning |
|---|---|---|
| `message` | `str` | The text the user just submitted. It is not yet part of `history`. |
| `history` | `list` | The earlier turns, oldest first. It is empty on the first message. |
| Return value | `str` | The text shown as the assistant's reply. |
The most common mistake is expecting the current message to appear at the end of history. It does not. If you build a prompt for a model, you must add message yourself.
Positional arguments
Gradio passes the arguments by position, so the names message and history are conventions, not requirements. This function works the same way:
def respond(user_text, past_turns):
return f"You said: {user_text}"The order matters. If you swap the parameters, user_text receives the history list and your output will look wrong without raising an error.
Argument count
Gradio passes two positional arguments, plus one more for each component you list in additional_inputs. A later chapter covers those. Until then, the function must accept exactly two. A function with one parameter fails with a TypeError when the first message is sent, not when the app starts. A function that needs extra arguments must give them default values or declare them as additional inputs.
The history format
With type="messages", each history entry is a dictionary with a role and a content key. The role is "user" or "assistant". After two exchanges, the history sent to your function looks like this:
[
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "You said: Hi"},
{"role": "user", "content": "What is Gradio?"},
{"role": "assistant", "content": "You said: What is Gradio?"},
]The shape matches the message lists used by OpenAI-style chat APIs, which is why connecting a model is easy later. A following chapter covers the format in detail. For now, remember that history is a flat list of role/content dictionaries in chronological order.
The type="messages" argument applies to Gradio 5.x. Newer versions may use this format by default. Older Gradio versions used a list of [user, assistant] pairs, and older tutorials still show it. If you see for user_msg, bot_msg in history: in someone else's code, it was written for the older format and will fail on message dictionaries.
Testing the function without Gradio
The contract is plain Python, so you can test it before any UI exists. This script builds history the way Gradio would:
def respond(message, history):
turns = len(history) // 2
return f"You said: {message} (earlier turns: {turns})"
history = []
for text in ["Hi", "What is Gradio?"]:
reply = respond(text, history)
print(reply)
history.append({"role": "user", "content": text})
history.append({"role": "assistant", "content": reply})It prints:
You said: Hi (earlier turns: 0)
You said: What is Gradio? (earlier turns: 1)The loop plays the role of Gradio. It calls the function, then appends both sides of the exchange so the next call sees them. Testing this way is faster than clicking through a browser, and it separates bugs in your logic from bugs in the interface.
Putting the function in an app
To see the contract in a browser, hand the function to gr.ChatInterface. The next chapter covers that class in detail, but this much is enough to try it:
import gradio as gr
def respond(message, history):
turns = len(history) // 2
return f"You said: {message} (earlier turns: {turns})"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()Run the script and open the local address printed in the terminal, usually http://127.0.0.1:7860. Send a few messages. The turn counter rises because Gradio sends the whole conversation to your function on each submission.
Your function is stateless
Gradio keeps the conversation, not your function. Each call receives the history as an argument and should compute its reply from message and history alone. Avoid keeping conversation data in a module-level list:
# Wrong: this list is shared by every visitor.
all_messages = []
def respond(message, history):
all_messages.append(message)
return f"I have seen {len(all_messages)} messages"A global like this mixes the conversations of everyone using the app. Two browser tabs would see each other's counts, and the count would survive after a user clears the chat. Derive everything from history. For data that must persist across turns but is not part of the visible chat, Gradio provides per-session state, which a later chapter covers.
Returning a reply
The reply must be something Gradio can display. A string is the normal case and the only one you need for now. Returning None shows an empty or missing reply, which usually means you forgot a return on some code path. This function has that bug:
def respond(message, history):
if message.strip():
return f"You said: {message}"
# Empty message: falls through and returns None.Make every branch return text:
def respond(message, history):
if not message.strip():
return "Please type something."
return f"You said: {message}"Gradio can also accept richer return values, such as message dictionaries with files attached. Those belong with the multimodal chapter. For text chat, return a string.
Replying in pieces
A function that ends with return produces its whole reply at once. If it uses yield instead, it becomes a generator, and Gradio updates the displayed reply each time a value is yielded:
import time
import gradio as gr
def respond(message, history):
reply = ""
for word in f"You said: {message}".split():
reply += word + " "
time.sleep(0.1)
yield reply
gr.ChatInterface(fn=respond, type="messages").launch()Each yield carries the full reply so far, not only the newest word. Gradio replaces the visible text with each yielded value. If you yielded only the new word, the reply would flicker through single words and end showing only the last one. A later chapter covers streaming from a model; the rule to remember here is that every yield is the whole answer up to that point.
Common errors
- Wrong number of parameters. A one-parameter function raises
TypeErroron the first message. Accept bothmessageandhistory. - Expecting the new message in
history. It is passed separately. Add it to your prompt yourself. - Using the old tuple format. Code that unpacks
user_msg, bot_msgfrom each entry fails against message dictionaries. Match your code to thetypeyou set. - Forgetting to return. A path that ends without
returngivesNone. - Yielding deltas. In a generator, yield the accumulated text.
- Shared global state. Module-level variables are shared by all visitors.
Summary
The contract is small. Your function takes message and history by position and returns a string, or yields growing strings to stream. With type="messages", history is a list of {"role", "content"} dictionaries, the new message is not in it, and the function keeps no memory of its own. Getting these details right makes every later chapter easier, because adding a model, extra inputs, or a custom layout only changes what happens inside or around this function.
Exercise
A teammate writes def respond(message, history): return f"Last thing I said: {history[-1]['content']}" and passes it to gr.ChatInterface with type="messages". The app works for the second message but fails on the first. Why does it fail, and how would you fix it?
Show answer
On the first message the history is empty, so history[-1] raises an IndexError. Check for an empty history before indexing, for example: if not history: return "This is our first message." and only then read history[-1]["content"]. Also note that the last history entry is the assistant's previous reply, which is why the output reads "Last thing I said". The current message is not in history at all.
Exercise
You change respond into a generator that does for word in text.split(): yield word. The chat shows a single word at a time instead of building up the reply. What is wrong?
Show answer
Each yield replaces the displayed reply, so yielding only the new word shows just that word. Accumulate the text in a variable (reply += word + " ") and yield reply each time, so every yield contains the whole reply so far.