Sub topic 11
Keeping per-session state with gr.State
This chapter covers how to store data for one browser session in a Gradio app, and how that differs from module-level variables. It assumes you can write Python functions and generators, and that you have built a chat UI with gr.Blocks and gr.Chatbot. It also assumes you know how event listeners such as submit and click pass component values into a function and write the return values back.
Why chat apps need session state
A Gradio server is one Python process that serves many browser tabs. A chat app often needs to remember something about each visitor: a running token count, a user profile, a conversation ID, or an object that cannot be shown in the UI.
The obvious first attempt is a global variable.
import gradio as gr
message_count = 0 # shared by every visitor
def count(message, history):
global message_count
message_count += 1
return f"Total messages so far: {message_count}"
gr.ChatInterface(fn=count, type="messages").launch()This runs, but the counter is shared. If two people open the app, they increment the same number. Global variables belong to the process, not to a visitor. They are also lost on restart, and they can be corrupted when two requests run at once.
gr.State solves the first problem. It holds a value that belongs to one browser session and is not shared with other sessions.
What gr.State is
gr.State is a component with no visible UI. You pass it as an input or output of an event listener, like any other component. Gradio stores its value on the server, keyed by the session. The value is not sent to the browser, so it can be any Python object, including objects that JSON cannot represent.
A session is one open browser tab, identified by a session hash that Gradio generates when the page loads. Reloading the page starts a new session and resets the state. Two tabs in the same browser are two sessions.
| Storage | Scope | Survives page reload | Visible to the user |
|---|---|---|---|
| Module-level variable | Whole server process | Yes, until restart | No |
| `gr.State` | One browser session | No | No |
| `gr.BrowserState` | One browser, saved in local storage | Yes | Yes, in browser storage |
| Visible component such as `gr.Chatbot` | One session | No | Yes |
Choose gr.State for data that is only meaningful during one visit. Use a database for anything that must survive restarts or be shared between users.
The initial value and the copy rule
You create a state with an initial value:
import gradio as gr
state = gr.State(0)Each new session gets its own copy of that initial value. Gradio deep-copies it, so a mutable initial value such as a list is not shared across sessions. If the object cannot be deep-copied, Gradio falls back to using the value directly and you must make sure the object is safe to share. For a value that must be created fresh, such as a client object, pass a callable instead:
import gradio as gr
state = gr.State(value=lambda: {"turns": 0, "topics": []})If value is a callable, Gradio calls it when each session starts. This is the safest way to build a per-session container.
A worked example: a per-session turn counter
The next app shows the full cycle. The function receives the current state as an input and returns the new state as an output.
import gradio as gr
def add_user_message(message, history, turns):
history = history + [{"role": "user", "content": message}]
return "", history, turns + 1
def bot_reply(history, turns):
last = history[-1]["content"]
reply = f"You said: {last} (this session has sent {turns} message(s))"
return history + [{"role": "assistant", "content": reply}]
with gr.Blocks() as demo:
chatbot = gr.Chatbot(type="messages")
msg = gr.Textbox(placeholder="Type a message and press Enter")
turns = gr.State(0)
msg.submit(
add_user_message, [msg, chatbot, turns], [msg, chatbot, turns]
).then(bot_reply, [chatbot, turns], chatbot)
if __name__ == "__main__":
demo.launch()Three points matter here.
turnsappears in both the inputs list and the outputs list ofmsg.submit. Listing it as an input reads the current value. Listing it as an output writes the returned value back.- The function returns values in the same order as the outputs list: the empty string for the textbox, the new history for the chatbot, and the new count for the state.
- The chained
.thenstep readsturnsagain. It sees the updated value because the first step has already finished and stored it.
Open the app in two tabs and send messages in each. The counts stay independent.
Updating state in the right way
Gradio saves whatever your function returns for the state output. It does not watch for in-place changes to the object. The behavior depends on whether you return the object.
import gradio as gr
def remember(message, topics):
topics.append(message) # mutates the list in place
return topics # returned, so it is saved
def forgetful(message, topics):
topics.append(message) # mutates, but nothing is returned
return f"Saved {len(topics)} topics"
with gr.Blocks() as demo:
topics = gr.State(value=lambda: [])
box = gr.Textbox(label="Topic")
out = gr.Textbox(label="Result")
box.submit(remember, [box, topics], topics)In forgetful, the list is mutated, and because Gradio hands the function the stored object itself, the change often appears to persist. Do not rely on that. Whether the stored object is the same one passed to your function is an implementation detail. Return the state from the function and list it in outputs. This also keeps the code readable, because the data flow is visible in the event wiring.
Prefer returning a new object over mutating the old one when the state is small. For large objects, such as a long list or a loaded model, mutating and returning the same object avoids copying.
State with ChatInterface
gr.ChatInterface has no direct state parameter on its function, but there are two approaches.
The first is additional_inputs combined with a gr.State. The state is passed to your function as an extra argument.
import gradio as gr
def respond(message, history, notes):
notes = notes or []
notes.append(message)
return f"I have now seen {len(notes)} message(s) in this session."
with gr.Blocks() as demo:
notes = gr.State(value=lambda: [])
gr.ChatInterface(fn=respond, type="messages", additional_inputs=[notes])
if __name__ == "__main__":
demo.launch()Because the function does not return a new value for notes, this relies on in-place mutation and is the pattern the previous section warned about. It is acceptable here for a small demo, but for anything that matters, build the chat with gr.Blocks and explicit outputs.
The second approach is to keep the data in the history itself. The history is already per-session. If you only need to remember facts about earlier turns, read them from history and skip gr.State entirely. This is often the simplest choice.
Gradio also lets a function read the session identifier by adding a request: gr.Request parameter. request.session_hash is a stable key for one session. You can use it to index a database or a dictionary of server-side objects. This works well for data that must outlive the page reload within your own storage, though you then own cleanup.
import gradio as gr
def respond(message, history, request: gr.Request):
return f"Session {request.session_hash} said: {message}"
gr.ChatInterface(fn=respond, type="messages").launch()Limits and common errors
- State resets on reload. A reload creates a new session, so the value returns to its initial value. Use
gr.BrowserStateor a database if the user expects persistence. - State is not shared between users. This is the intended behavior. If you need shared data, use a module-level object with a lock, or a database.
- State expires. Gradio removes a session's state after the session is closed or has been idle for a period. The
time_to_liveargument ongr.Stateand thedelete_cachesetting control cleanup in newer versions. Check the documentation for the version you run. - State must be in
inputsto be read. If a function needs the value but the state is only an output, the function receives nothing for it. - Wrong return count. If the outputs list has three components and the function returns two values, Gradio raises an error. Match the order and the count exactly.
- Event listeners that skip state. Streaming generators that
yieldpartial results must yield every output on each step, including the state, or the state keeps its previous value for that yield. - Large state and memory. Every session keeps its own copy in server memory. A loaded model or large list per session can exhaust memory under load. Share heavy read-only objects at module level and keep only small, session-specific data in
gr.State. - Sensitive data. State stays on the server, which is safer than hidden fields, but it is still in process memory. Do not store secrets you would not otherwise keep in the process.
Choosing between the options
Use the conversation history when the information is already in the messages. Use gr.State when you need extra per-session data that is not shown, such as a counter, a token budget, or a parsed document. Use gr.BrowserState when the data should come back after a reload. Use a database keyed by request.session_hash or by a user name when the data must be durable or visible to your own code outside Gradio.
Exercise
Two users open your Blocks chat app. The app keeps a message counter in a module-level variable and also has a separate gr.State(0) counter. User A sends three messages, then user B sends two. What does each counter show for user B, and what happens to each counter if user B reloads the page?
Show answer
The module-level counter shows 5 for user B because it is shared by all sessions. The gr.State counter shows 2 because it is per session. After user B reloads the page, the module-level counter still shows 5 (it lives in the server process), while the gr.State counter resets to 0 because the reload starts a new session.
Exercise
A function takes turns from a gr.State input and computes turns + 1, but the count never increases between messages. The event is msg.submit(add, [msg, turns], [msg]). What is the bug and how do you fix it?
Show answer
The state is listed as an input but not as an output, and the function does not return the new value, so Gradio never saves the increment. Add turns to the outputs list, as in [msg, turns], and make the function return both the textbox value and turns + 1 in that order.