Sub topic 10
Building a custom layout with gr.Blocks and gr.Chatbot
gr.ChatInterface gives you a finished chat app from one function. Sometimes you need more: controls beside the chat, several panels, buttons that do different things, or a message flow that you control step by step. gr.Blocks is Gradio's lower-level API for that. This chapter shows how to rebuild a chat app from gr.Chatbot, gr.Textbox, and event listeners.
This chapter assumes you have read the earlier chapters on the (message, history) contract, the messages-style history format, and streaming with generators. You should also be comfortable with Python functions and lists of dictionaries.
When to leave ChatInterface
Stay with gr.ChatInterface if your app is a single chat box with a few extra inputs. Move to gr.Blocks when you need one of these:
- A layout that is not "chat on top, input below", such as a side panel, tabs, or two chatbots next to each other.
- Several buttons with different behavior, such as "Regenerate", "Clear", or "Export".
- Control over the order of steps after a submit, such as validating input, then calling a model, then updating a status label.
- Components that read or write the history outside the normal chat flow.
The price is that you now write the plumbing that ChatInterface did for you. You append the user message, clear the textbox, call the model, and store the reply yourself.
The pieces
A Blocks chat app has three kinds of parts.
| Part | Role | Example |
|---|---|---|
| Layout containers | Arrange components on the page | `gr.Row`, `gr.Column`, `gr.Tab` |
| Components | Show or collect data | `gr.Chatbot`, `gr.Textbox`, `gr.Button` |
| Event listeners | Connect a component action to a Python function | `msg.submit(...)`, `clear.click(...)` |
gr.Chatbot only displays a conversation. It does not call any function by itself. Its value is the history list, so whatever function returns a new list of messages to the chatbot changes what the user sees.
For the type="messages" format, each message is a dictionary with role ("user" or "assistant") and content. This is the same shape you used with ChatInterface.
The two-step submit pattern
The core pattern is to split one chat turn into two chained events.
- Add the user message. Append the user's text to the history and clear the textbox. This runs fast and should show up immediately.
- Produce the assistant reply. Read the history, call your model, and write the reply back into the history. This may be slow.
Splitting the turn means the user's message appears at once, before the model starts. Here is the minimal version.
import gradio as gr
def bot_reply(history):
last = history[-1]["content"]
history.append({"role": "assistant", "content": f"You said: {last}"})
return history
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox(placeholder="Type a message and press Enter")
def add_user_message(message, history):
return "", history + [{"role": "user", "content": message}]
msg.submit(add_user_message, [msg, chatbot], [msg, chatbot]).then(
bot_reply, chatbot, chatbot
)
if __name__ == "__main__":
demo.launch()Read the wiring carefully, because it is the heart of every Blocks chat app:
msg.submit(...)fires when the user presses Enter in the textbox.- The second argument,
[msg, chatbot], lists the inputs. Gradio reads the current value of each component and passes them to the function in order. Soadd_user_messagereceivesmessageandhistory. - The third argument,
[msg, chatbot], lists the outputs. The function returns two values, and Gradio assigns them to the components in that order. Returning""for the textbox clears it. .then(...)runs a second function after the first finishes.bot_replytakes the chatbot value as its only input and returns the updated history to the same chatbot.
Streaming in Blocks
To stream, make the second function a generator. Each yield sends the whole updated history to the chatbot, so you add an empty assistant message first and then grow its content.
The next example also shows layout and a second button. It echoes the user's text word by word, and a checkbox changes how the reply is written.
import time
import gradio as gr
def add_user_message(message, history):
return "", history + [{"role": "user", "content": message}]
def stream_reply(history, shout):
text = f"You said: {history[-1]['content']}"
if shout:
text = text.upper()
history = history + [{"role": "assistant", "content": ""}]
for word in text.split():
history[-1]["content"] += word + " "
time.sleep(0.1)
yield history
with gr.Blocks() as demo:
gr.Markdown("## Echo bot")
with gr.Row():
with gr.Column(scale=4):
chatbot = gr.Chatbot(type="messages", height=400)
msg = gr.Textbox(placeholder="Type a message and press Enter", show_label=False)
with gr.Column(scale=1):
shout = gr.Checkbox(label="Shout")
clear = gr.Button("Clear")
msg.submit(
add_user_message, [msg, chatbot], [msg, chatbot], queue=False
).then(stream_reply, [chatbot, shout], chatbot)
clear.click(lambda: [], None, chatbot, queue=False)
if __name__ == "__main__":
demo.launch()Points worth noting:
gr.Rowplaces its children side by side.gr.Column(scale=4)andgr.Column(scale=1)split the width in a four to one ratio.stream_replytakes two inputs, the chatbot and the checkbox. Extra controls work the same way asadditional_inputsinChatInterface: add the component to the inputs list and accept one more argument.queue=Falseon the quick steps skips the event queue, so the user message appears without waiting behind slow model calls. Keep the slow, streaming step on the default queue.clear.click(lambda: [], None, chatbot)has no inputs (None) and resets the history to an empty list.
Using a real model
Replace the body of the streaming step with your LLM call. The history is already in the shape OpenAI-style clients expect, apart from the system prompt. This sketch reuses the client from the earlier chapter.
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from the environment
def stream_reply(history, system_prompt):
messages = [{"role": "system", "content": system_prompt}]
messages += [{"role": m["role"], "content": m["content"]} for m in history]
history = history + [{"role": "assistant", "content": ""}]
stream = client.chat.completions.create(
model="gpt-4o-mini", messages=messages, stream=True
)
for chunk in stream:
history[-1]["content"] += chunk.choices[0].delta.content or ""
yield historyWire it with .then(stream_reply, [chatbot, system_box], chatbot), where system_box is a gr.Textbox you place in a side column. The model receives the history before the empty assistant placeholder is added, so it sees only real turns.
Common errors
- The chat shows an error about message format. The chatbot was created without
type="messages", or your function returned tuples. Return dictionaries withroleandcontent. - The user message appears only after the model finishes. You put both steps in one function. Split them with
.then, as shown above. - The textbox does not clear. The first function must return
""for the textbox and list the textbox among the outputs. - The reply is replaced instead of extended. You yielded only the new text. The chatbot expects the full history list each time.
- Wrong number of return values. Gradio matches returned values to the output list in order. Two outputs need two return values.
- History from another user appears. You stored the conversation in a global variable. Keep it in the chatbot value or in
gr.State, which is per browser session.
Design checklist
Before you ship a Blocks chat app, check that you have:
- A textbox submit event that appends the user message and clears the input.
- A chained step that writes the assistant reply, ideally as a generator.
- A way to clear the conversation.
queue=Falseonly on the fast steps.- No shared global state between users.
Exercise
In the two-step submit pattern, why does add_user_message return "" as its first value, and what would happen if you removed that value from both the function and the outputs list?
Show answer
The first return value is assigned to the msg textbox, the first component in the outputs list, so returning "" clears the input after the user submits. If you removed it from both places, the function would update only the chatbot. The user's text would stay in the textbox after sending, and the user would have to delete it by hand before typing the next message.
Exercise
Write the single line that adds a "Retry" button's click handler so that it removes the last assistant message from the history and streams a new reply. Assume retry is a gr.Button, chatbot is the chatbot, shout is the checkbox, and stream_reply(history, shout) is the generator from this chapter.
Show answer
First define a helper that drops the last assistant message: def drop_last(history): return history[:-1] if history and history[-1]["role"] == "assistant" else history. Then wire it with retry.click(drop_last, chatbot, chatbot, queue=False).then(stream_reply, [chatbot, shout], chatbot). The first step trims the history so that the last message is the user's. The chained step then streams a new reply to it, as in a normal submit.