State Streaming
Stream partial agent state to your React Native UI while a tool call is still running.
What is this?
By default, agent state only updates between backend checkpoints, so a long tool call (writing a full document, drafting an email) reaches the UI as one burst at the end. In an agent-native app, that feels broken: users expect to watch the output appear.
State streaming copies one tool argument into an agent state key while the model writes the argument. Your screen, subscribed with useAgent, re-renders on every token.
When should I use this?
Use state streaming when a tool's output is long-form text or a growing structured value, and you want the user to see it build up in real time. Common shapes:
- A writing agent that produces a document
- A research agent that collects a list of findings
- A planning agent that builds a step-by-step plan
The backend: one streaming state mapping
The adapter streams a tool call's arguments as TOOL_CALL_ARGS events while
the model writes them, but it does not copy them into state. The tool writes
the finished value to state when it runs:
@function_tool
def write_document(document: str) -> str:
"""Write a document for the user. Always call this tool when the user asks
you to write, draft, or revise any text. The `document` argument is
streamed into shared state under the `document` key so the UI renders
the body live.
"""
shared_state().update(document=document)
return "Document written to shared state."
To fill the state while the model is still writing the argument, subclass
OpenAIAgentsAgent and turn those argument chunks into STATE_DELTA events.
The arguments are unfinished JSON until the call ends, so parse them with
pydantic_core.from_json(..., allow_partial="trailing-strings"), which keeps
a string that is cut off mid-way:
def _document_so_far(arguments: str) -> str | None:
"""The ``document`` argument as far as the model has written it."""
try:
# Unfinished JSON: a string cut off mid-way is kept as it stands.
value = from_json(arguments, allow_partial="trailing-strings")
except ValueError:
return None
document = value.get("document") if isinstance(value, dict) else None
return document if isinstance(document, str) else None
class DocumentStreamingAgent(OpenAIAgentsAgent):
"""Streams ``write_document``'s ``document`` argument into the state."""
async def run_streamed(self, input: RunAgentInput) -> AsyncIterator[BaseEvent]:
arguments: dict[str, str] = {} # tool call id -> arguments so far
async with aclosing(super().run_streamed(input)) as events:
async for event in events:
yield event
if (
event.type == EventType.TOOL_CALL_START
and event.tool_call_name == write_document.name
):
arguments[event.tool_call_id] = ""
elif (
event.type == EventType.TOOL_CALL_ARGS
and event.tool_call_id in arguments
):
arguments[event.tool_call_id] += event.delta
document = _document_so_far(arguments[event.tool_call_id])
if document is not None:
yield StateDeltaEvent(
type=EventType.STATE_DELTA,
delta=[
{"op": "add", "path": "/document", "value": document}
],
)
Mount the agent wrapped in that subclass,
DocumentStreamingAgent(shared_state_streaming_agent), instead of a plain
OpenAIAgentsAgent. The page then sees the document grow token by token, and
the tool's own STATE_SNAPSHOT settles it once the call runs.
The backend pattern is always the same: map one streaming tool argument to one shared-state key. Each framework does this in its own way:
- LangGraph Python:
StateStreamingMiddlewarewithStateItem(...)entries. - LangGraph TypeScript:
copilotkitCustomizeConfigwith anemitIntermediateStatemapping. - Direct SDK adapters: parse partial tool arguments in the streaming loop, and emit
STATE_SNAPSHOTwhenever the mapped value changes. - LlamaIndex and Pydantic AI: there is no per-token mapping. A backend tool sends a state snapshot after each step or tool call instead (see the setup above).
When the model streams that argument, CopilotKit writes every partial value into shared state before the tool finishes.
def _document_so_far(arguments: str) -> str | None:
"""The ``document`` argument as far as the model has written it."""
try:
# Unfinished JSON: a string cut off mid-way is kept as it stands.
value = from_json(arguments, allow_partial="trailing-strings")
except ValueError:
return None
document = value.get("document") if isinstance(value, dict) else None
return document if isinstance(document, str) else None
class DocumentStreamingAgent(OpenAIAgentsAgent):
"""Streams ``write_document``'s ``document`` argument into the state."""
async def run_streamed(self, input: RunAgentInput) -> AsyncIterator[BaseEvent]:
arguments: dict[str, str] = {} # tool call id -> arguments so far
async with aclosing(super().run_streamed(input)) as events:
async for event in events:
yield event
if (
event.type == EventType.TOOL_CALL_START
and event.tool_call_name == write_document.name
):
arguments[event.tool_call_id] = ""
elif (
event.type == EventType.TOOL_CALL_ARGS
and event.tool_call_id in arguments
):
arguments[event.tool_call_id] += event.delta
document = _document_so_far(arguments[event.tool_call_id])
if document is not None:
yield StateDeltaEvent(
type=EventType.STATE_DELTA,
delta=[
{"op": "add", "path": "/document", "value": document}
],
)
A few things to note:
- The state key must exist in your agent state (
documentin this example). - The tool and argument names must match the exact tool call the model makes (
write_document.documenthere). - Streamed values are previews. When the step ends, the state the agent saves replaces them, so save the final value when the tool finishes. On CrewAI, LlamaIndex, and Pydantic AI, write the final value to the agent state yourself, or it is overwritten when the step returns.
The frontend: useAgent and OnStateChanged
The app side is the same as any other shared-state subscription: useAgent with OnStateChanged gives you a live agent.state. Add OnRunStatusChanged for a "writing" indicator.
import { ActivityIndicator, ScrollView, Text, View } from "react-native";
import { useAgent, UseAgentUpdate } from "@copilotkit/react-native/headless";
export function DocumentView() {
const { agent } = useAgent({
agentId: "default",
updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
});
const document = (agent.state as { document?: string } | undefined)?.document ?? "";
return (
<View style={{ padding: 16, gap: 8 }}>
{agent.isRunning ? <ActivityIndicator /> : null}
<ScrollView style={{ maxHeight: 320 }}>
<Text>{document}</Text>
</ScrollView>
</View>
);
}agent.state.document is a string that grows on every token, and agent.isRunning tells you whether to show the indicator. The ScrollView with a maxHeight keeps a long document from pushing the rest of the screen away.
If a fast stream re-renders a heavy screen too often, pass throttleMs to useAgent to batch the updates.
Try it
Ask the agent to write a short poem. The document text grows on your screen while the agent writes. When the run ends, agent.isRunning is false, so the indicator goes away.
How is this guide?