Sub topic 4
Understanding the history format
This chapter assumes you can write a (message, history) function and launch it with gr.ChatInterface, as in the previous chapters. It also assumes you know what the system, user, and assistant roles mean in an LLM chat API. Here you will learn exactly what history contains, why type="messages" matters, and how to convert, filter, and trim history before it reaches a model.
What history is
Gradio does not remember your conversation on the server inside your function. Each time the user submits a message, the browser sends the visible conversation along with it. Gradio passes that conversation to your function as the second argument, history.
Two facts follow from this:
historyholds the turns before the current one. The new message arrives separately asmessage, so it is not inhistoryyet.historyis whatever the chat window currently shows, in order. If the user clears the chat,historyis empty again.
The messages format
With type="messages", history is a list of dictionaries. Each dictionary has a role, which is "user" or "assistant", and a content value. For text-only chats, content is a string.
A conversation after two exchanges looks like this:
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 shape is intentionally the same as the message lists used by OpenAI-style chat APIs. That is why converting history for an LLM call takes only a few lines.
Gradio may also add other keys to a dictionary, such as metadata (used to display things like tool-call titles) or options. Your function should not assume that a dictionary contains only role and content.
Inspecting history yourself
The quickest way to learn the format is to look at it. This app prints the raw history to your terminal and tells the user how many messages it received.
import gradio as gr
def respond(message, history):
print("message:", repr(message))
print("history:", history)
return f"I received {len(history)} earlier messages. Now you said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()Send three messages and watch the terminal. On the first call history is []. On the second call it has two entries, the first user message and the first reply. The count grows by two per exchange.
The diagram shows what the browser sends and what your function returns.
Messages versus tuples
Older Gradio versions used a different default: history was a list of [user_text, assistant_text] pairs. That is called the tuples format. Gradio 5.x still accepts it, and type="messages" opts into the newer dictionary format. Newer releases are moving to the messages format as the only one, so it is the safe choice for new code.
| Aspect | Tuples format | Messages format |
|---|---|---|
| Shape of an entry | `[user, assistant]` pair | `{"role": ..., "content": ...}` dictionary |
| One exchange is | One entry | Two entries |
| System or tool turns | Not representable | Possible through `role` and `metadata` |
| Matches LLM API lists | No, needs conversion | Yes, nearly directly |
| Status | Legacy | Current |
The most common error here is a mismatch. If you write h["role"] while the app is still running in tuples mode, you get a TypeError because h is a list. If you write for user, bot in history while using messages mode, Python raises a ValueError because a dictionary with two keys unpacks into the key names, or fails outright with a different number of keys. Check that type="messages" is set on both gr.ChatInterface and, later, on gr.Chatbot.
Converting for an LLM call
An LLM API wants a system prompt first, then the earlier turns, then the new user message. Gradio gives you the last two pieces separately, so you assemble the list.
def to_openai_messages(message, history, system_prompt):
messages = [{"role": "system", "content": system_prompt}]
for turn in history:
if turn["role"] not in ("user", "assistant"):
continue
if not isinstance(turn["content"], str):
continue
messages.append({"role": turn["role"], "content": turn["content"]})
messages.append({"role": "user", "content": message})
return messages
history = [
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
]
print(to_openai_messages("What is Gradio?", history, "You are concise."))Three details are worth noting:
- The loop copies only
roleandcontent. Extra keys such asmetadatacan cause a provider to reject the request, so do not pass the whole dictionary through. - The
isinstancecheck skips entries whose content is not a string. With file uploads (covered in a later chapter), content can be a file reference, and a text-only model cannot use it. - The system prompt is never in
history. Gradio does not store it, so you must add it on every call.
Converting from legacy tuples
If you maintain code that still receives tuples, or you read old saved conversations, you can convert them into messages. Treat None as "no text on this side", which can occur when a turn has only a file.
def tuples_to_messages(pairs):
messages = []
for user, assistant in pairs:
if user is not None:
messages.append({"role": "user", "content": user})
if assistant is not None:
messages.append({"role": "assistant", "content": assistant})
return messages
print(tuples_to_messages([["Hi", "Hello!"], ["Bye", None]]))The result is the same shape used everywhere else in this chapter, so the rest of your code needs only one path.
Keeping history within limits
Models have a context window, which is the maximum amount of text they accept in one request. Because the browser resends the whole conversation every turn, a long chat will eventually exceed it, and cost and latency grow along the way. Trimming is your responsibility.
The simplest approach keeps the most recent messages:
def trim_history(history, max_messages=10):
trimmed = history[-max_messages:]
# Avoid starting the list with an assistant reply that has lost its question.
while trimmed and trimmed[0]["role"] != "user":
trimmed = trimmed[1:]
return trimmed
history = [
{"role": "user", "content": "one"},
{"role": "assistant", "content": "two"},
{"role": "user", "content": "three"},
{"role": "assistant", "content": "four"},
{"role": "user", "content": "five"},
]
print(trim_history(history, max_messages=4))Here the last four messages begin with an assistant turn, so the loop drops it and the result starts with "three". Some providers require the first non-system message to be from the user, which makes this check worthwhile.
Counting messages is crude. A single pasted document can be larger than twenty short turns. For a production app, count tokens with your provider's tokenizer and drop the oldest turns until the total fits.
Common mistakes and edge cases
- Appending the current message to
historyand sending both. The current message is not inhistory, so you add it once. Adding it twice makes the model see the question repeated. - Mutating
historyin place. Changing the list insideresponddoes not update the chat window. The window updates from what you return or yield. Build a new list for the model and leavehistoryalone. - Returning a list or dictionary from a plain
ChatInterfacefunction. The function should return a string for a simple text reply. Return the reply text only, not the whole conversation. - Expecting history to survive a page reload. The history lives in the browser session. A reload or the clear button resets it. Persistence needs your own storage, which is covered with state later in the tutorial.
- Trusting history as authoritative. The browser sends it, so a user with developer tools or the API can send any history they like, including fake assistant turns. Do not rely on past assistant messages for security decisions, and validate anything that matters on the server.
Summary of the contract
messageis the new user input, andhistoryis the earlier turns only.- With
type="messages", each history entry is a dictionary withroleandcontent. - One exchange produces two entries, one
userand oneassistant. - The system prompt is not part of history. Add it yourself on each call.
- Copy only the keys the model API needs, skip non-string content if the model is text-only, and trim long histories.
Exercise
Your respond function receives history containing 6 entries in messages format. How many user turns and assistant turns does it contain if the conversation alternates normally, and how many messages (including the system prompt and the new message) should you send to an LLM API?
Show answer
Six entries alternate normally, so there are 3 user turns and 3 assistant turns. The list for the LLM is 1 system message + 6 history messages + 1 new user message = 8 messages. The system prompt and the new message are added by your code because neither is stored in history.
Exercise
A teammate's function contains for user, bot in history: and the app uses type="messages". What goes wrong, and how do you fix it?
Show answer
In messages mode each history entry is a dictionary with role and content keys, not a pair, so unpacking into user, bot fails or produces the wrong values. Fix it by looping over turn in history and reading turn["role"] and turn["content"], or by switching the whole app to a consistent format. Keep type="messages" set on the interface and use dictionary access everywhere.