Sub topic 3
Your first chat UI with gr.ChatInterface
This chapter assumes you can write Python functions and generators, install packages with pip, and run a script from a terminal. It also assumes you know what a chat API does: you send a list of messages and get a reply. The earlier chapters introduced how a Gradio app launches and what the (message, history) contract looks like. Here you put them together into a working chat UI and learn what gr.ChatInterface does for you and where it stops.
What gr.ChatInterface gives you
gr.ChatInterface is a high-level class. You give it one function, and it builds a complete chat page: a message list, a textbox, a submit button, and a few helper buttons such as retry, undo, and clear. It also wires up the events that call your function and keep the conversation on screen.
You would otherwise build this by hand with gr.Blocks, gr.Chatbot, and gr.Textbox. That route gives you control, and a later chapter covers it. For a first chat UI, ChatInterface is the right choice because it removes the wiring code.
Install Gradio first:
# Run in a terminal, not in Python:
# pip install --upgrade gradioThe smallest working app
Save this as app.py:
import gradio as gr
def respond(message, history):
return f"You said: {message}"
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()Run python app.py. Gradio prints a local address, usually http://127.0.0.1:7860. Open it, type a message, and press Enter. The reply "You said: ..." appears below your message.
Four things happen in this short program:
respondis an ordinary function. It takes the newest user message and the earlier conversation, and returns a string.gr.ChatInterface(fn=respond, ...)builds the page around that function.demo.launch()starts a local web server and serves the page.- The
if __name__ == "__main__":guard keeps the server from starting if another file imports this module.
What your function receives
Gradio calls your function every time the user submits a message. It passes at least two arguments:
message: the text the user just sent, as a string.history: the earlier turns of the conversation, as a list. It does not include the current message.
With type="messages", each item in history is a dictionary with a role key ("user" or "assistant") and a content key. You can see this by printing the history:
import gradio as gr
def respond(message, history):
print("history so far:", history)
return f"You said: {message}. I have seen {len(history)} earlier messages."
demo = gr.ChatInterface(fn=respond, type="messages")
if __name__ == "__main__":
demo.launch()After two exchanges, the terminal shows a list of four dictionaries, alternating between user and assistant. The count in the reply counts messages, not exchanges, so it goes 0, 2, 4. The next chapter covers the format in detail. For now, remember that history is the transcript so far and message is the new turn.
How a request flows
The browser never calls your function directly. It sends an event to the Gradio server, and the server calls your function and sends the result back.
Two consequences follow from this design:
- Your function runs on the server, in your Python process. Any secrets it uses, such as API keys, stay there and never reach the browser.
- The server holds the conversation state for the session, and the browser sends the history along with each request. Your function should not rely on module-level variables to remember a conversation, because every visitor shares those variables. Use
historyinstead, orgr.State(covered later) for extra per-session data.
Streaming with a generator
If your function is a generator, Gradio shows each yielded value as it arrives. This is how chat apps display text that appears gradually.
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 replaces the displayed reply with the longer text. It does not append to it. So you must yield the whole reply so far, not just the newest word. A common mistake is to yield only the new piece, which makes the visible reply flicker between single words.
The time.sleep(0.1) call is only there to make the effect visible. With a real model, the delay comes from the network.
Changing what the function returns
A chat function returns a string in the simplest case. The table lists what the return value can be and what the user sees.
| Return value | Result in the chat |
|---|---|
| A string | One assistant message with that text |
| A generator that yields strings | One assistant message that updates as values arrive |
| A string with Markdown | Rendered Markdown, such as bold text and lists |
Because replies are rendered as Markdown, a model that returns code blocks or lists displays them correctly without extra work. It also means that text containing characters like * or _ can be formatted unexpectedly. If your reply contains literal Markdown characters you want to show as typed, escape them or wrap them in backticks.
Common errors
These are the problems you are most likely to hit in a first project.
The function has the wrong number of parameters. Gradio passes message and history, plus one argument per component in additional_inputs if you use that option. A function defined as def respond(message): raises a TypeError when called with two arguments. Always accept both, even if you ignore history.
Mixing up history formats. If you write code that reads h["content"] but the app is configured for the older tuple format, you get an error such as TypeError: tuple indices must be integers. The reverse also fails. Set type="messages" and treat each history item as a dictionary.
Forgetting that history excludes the current message. If you build a list for a model from history alone, the model never sees the user's latest question. Append message yourself.
Starting the server on import. Calling demo.launch() at module level without the __main__ guard starts the server whenever the file is imported. This matters once you write tests or run the app through another tool.
Port already in use. If port 7860 is taken, Gradio tries the next free port by default and prints the one it chose. To pin a port, pass server_port= to launch, and expect an error if it is unavailable.
Blocking calls that make the page feel frozen. A function that does long work and returns once shows nothing until it finishes. If the work takes more than a second or two, yield intermediate text so the user sees progress.
Reload mode during development
Running python app.py requires you to stop and restart the script after each edit. Gradio has a reload mode that restarts the server when the file changes. Run the app with the gradio command instead of python:
# Run in a terminal, not in Python:
# gradio app.pyThe command looks for a Gradio object named demo in the file, which is why the examples in this tutorial use that name. Code inside the if __name__ == "__main__": block is skipped in reload mode, so keep your ChatInterface definition outside it.
Limits of ChatInterface
ChatInterface makes a specific trade. It hides the wiring, so you can't rearrange the page freely. You can add inputs, set a title, and change the theme, which later chapters cover. You can't put the textbox above the chat, add a side panel of your own components, or run several steps with different outputs. When you need that, move to gr.Blocks with gr.Chatbot. The function contract carries over, so little of your chat logic needs to change.
Exercise
You write def respond(message, history): return history[-1]["content"] and run it as the first message in a new gr.ChatInterface(fn=respond, type="messages"). What happens, and why?
Show answer
The call fails with an IndexError. On the first message history is an empty list, because it holds only earlier turns and excludes the current message. history[-1] has nothing to return. To use the user's text, read message instead.
Exercise
Your streaming function yields only the newest word each time, so the reply keeps flashing single words. What is the fix?
Show answer
Keep an accumulating string, add each new piece to it, and yield the accumulated string. Each yield replaces the displayed reply, so it must contain the whole reply so far, not just the latest piece.
Exercise
Write a chat function that returns the number of user messages sent so far, including the current one, using the messages-style history.
Show answer
Count the history items whose role is "user" and add one for the current message: def respond(message, history): userturns = sum(1 for h in history if h["role"] == "user") + 1 return f"This is user message number {userturns}."