Sub topic 4
Understanding the history format
This chapter assumes you can write a basic Python function and have already built a first gr.ChatInterface. It covers what the history argument contains, why the format matters, and the errors people hit most often.
What history is
Gradio calls your chat function as fn(message, history). The history argument holds every earlier turn of the conversation, not including the current message. With type="messages", history is a list of dictionaries. Each dictionary has a role key ("user" or "assistant") and a content key (the text).
history = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello! How can I help?"},
{"role": "user", "content": "What is Gradio?"},
{"role": "assistant", "content": "A Python library for building web UIs."},
]This matches the message format used by OpenAI-style chat APIs. That is the main reason to choose it: you can often pass the list straight to a model client.
import gradio as gr
def respond(message, history):
turns = len(history) // 2
return f"This is turn {turns + 1}. You said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()On the first message, history is an empty list. After each exchange it grows by two entries: one user message and one assistant reply.
The older tuple format
Older Gradio code uses a different shape: a list of [user_text, assistant_text] pairs. This is the "tuples" format. It cannot hold system messages or extra metadata, and Gradio has deprecated it. If you copy an example that does for user, bot in history:, it will fail with type="messages", because each item is now a dictionary.
| Aspect | `type="tuples"` (old) | `type="messages"` (current) |
|---|---|---|
| Item shape | `[user, assistant]` pair | `{"role": ..., "content": ...}` dict |
| Items per exchange | 1 | 2 |
| Matches OpenAI-style APIs | No, needs conversion | Yes |
Converting history for an LLM
Because the format is already close to what chat APIs expect, conversion is short. Put a system message first, then the history, then the new message.
def build_messages(system_prompt, message, history):
messages = [{"role": "system", "content": system_prompt}]
messages += [{"role": h["role"], "content": h["content"]} for h in history]
messages.append({"role": "user", "content": message})
return messages
print(build_messages(
"You are terse.",
"And in Python?",
[
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello."},
],
))Copying only role and content is deliberate. Gradio may add other keys, such as metadata, and a strict API can reject keys it does not know.
Common errors
KeyErrororTypeErroronhistory: your code uses tuple-style unpacking. Index withh["role"]andh["content"]instead.- The current message appears twice:
messageis not inhistory. Append it once yourself. - The conversation grows without limit: the full history is sent each call. Long chats cost more and can exceed the model's context window. Trim old turns, for example with
history[-10:], when needed. - A warning about
type: settype="messages"explicitly on bothgr.ChatInterfaceandgr.Chatbot. Newer Gradio versions may use it by default, but being explicit works on both.
Exercise
A chat function receives history with type="messages". After the user has sent three messages and received three replies, they send a fourth message. How many items are in history inside the function, and does it include the fourth message?
Show answer
It has 6 items (three user dictionaries and three assistant dictionaries). It does not include the fourth message, which arrives separately as the message argument.
Exercise
Write a function last_user_message(history) that returns the content of the most recent user entry in a messages-style history, or None if there is none.
Show answer
def lastusermessage(history): for item in reversed(history): if item["role"] == "user": return item["content"] return None