Sub topic 11
Keeping per-session state with gr.State
This chapter assumes you can build a gr.Blocks chat with gr.Chatbot and wire events with .submit() and .then(). It also assumes you know that event handlers take component values as inputs and return new values as outputs.
Why global variables fail
A Gradio app is one Python process serving many browser tabs. A module-level variable is shared by every visitor. If you store a message counter in a global, one user's messages change another user's count.
# Wrong for per-user data: every visitor shares this counter.
count = 0
def respond(message, history):
global count
count += 1
return f"Message {count}"gr.State solves this. It stores a value on the server, separately for each browser session.
How gr.State works
You create a gr.State with an initial value and pass it in the inputs and outputs lists of an event, like any other component. Three rules define its behavior:
- Each session gets its own copy of the initial value. Gradio deep-copies it, so a list or dictionary is not shared between users.
- The value stays on the server. It is never rendered in the page, so it can hold objects that a visible component could not, such as a client object or a parsed document.
- The value is lost when the user reloads the page, because a reload starts a new session.
A chat with a per-session counter
This app counts how many messages each session has sent. The counter is a gr.State that the submit handler reads and returns.
import gradio as gr
def add_user_message(message, history, count):
history = history + [{"role": "user", "content": message}]
return "", history, count + 1
def bot_reply(history, count):
text = f"You said: {history[-1]['content']} (message {count} in this session)"
return history + [{"role": "assistant", "content": text}]
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox(placeholder="Type a message and press Enter")
count = gr.State(0)
msg.submit(
add_user_message, [msg, chatbot, count], [msg, chatbot, count]
).then(bot_reply, [chatbot, count], chatbot)
if __name__ == "__main__":
demo.launch()Open the app in two tabs and send messages in each. The counts are independent. Reload one tab and its count starts again at 1.
Mutable state and common errors
A handler receives the current value and must return the new value for the update to be stored. These errors come up most often:
- Forgetting to return the state. If you change a list in place but do not list the state in
outputs, later events can still see the old value. - Listing the state in
inputsonly. The handler reads the value, but nothing updates it. - Storing things that cannot be copied. Gradio deep-copies the initial value. Open sockets, locks, and some client objects fail this step. Create such objects lazily inside the handler instead.
- Expecting persistence. State lives in server memory. A server restart or a page reload clears it. Use a database for anything that must last.
- Storing large data. Every active session keeps its own copy, so memory use grows with the number of users.
State and ChatInterface
gr.ChatInterface already keeps the conversation history per session for you, so you do not need gr.State for the chat messages. Reach for gr.State when you build with gr.Blocks and need extra per-user values, such as a counter, a selected document, or a user's settings.
Exercise
Two users open your Blocks chat app. Your handler increments a module-level variable total, and also increments a gr.State(0) called mine. After user A sends three messages and user B sends two, what do total and each user's mine equal?
Show answer
total is 5, because the global is shared by all sessions. User A's mine is 3 and user B's mine is 2, because each session has its own copy of the state. If user A reloads the page, A's mine resets to 0 but total stays 5.
Exercise
A handler runs items.append(x) on a list received from a gr.State([]), but the list is not in the event's outputs. Why can the next event still see the old list, and how do you fix it?
Show answer
The state is only stored when the handler returns it through outputs. Without that, the stored value is not updated. Return the list from the handler and add the gr.State to the event's outputs.