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
Build an agent that streams a tool argument into state
Deep Agents has no live demo on this page yet, so the demo code on this
page does not show for it. Define the state key, add a tool that saves the
completed value, and add StateStreamingMiddleware with one StateItem
that maps the tool argument to the state key. This example streams a
searches list:
from typing import Any, TypedDict
from copilotkit import (
CopilotKitMiddleware,
CopilotKitState,
StateItem,
StateStreamingMiddleware,
)
from deepagents import create_deep_agent
from langchain_openai import ChatOpenAI
from langchain.agents.middleware import AgentMiddleware
from langchain.messages import ToolMessage
from langchain.tools import ToolRuntime, tool
from langgraph.types import Command
class Search(TypedDict):
query: str
done: bool
class AgentState(CopilotKitState):
searches: list[Search]
class SearchesStateMiddleware(AgentMiddleware[AgentState, Any, Any]):
state_schema = AgentState
@tool
def report_research_progress(
searches: list[Search],
runtime: ToolRuntime[None, AgentState],
) -> Command:
"""Report the current research tasks and completion status."""
return Command(
update={
"searches": searches,
"messages": [
ToolMessage(
content="Research progress saved.",
tool_call_id=runtime.tool_call_id,
)
],
}
)
agent = create_deep_agent(
model=ChatOpenAI(model="gpt-6-luna", reasoning_effort="none"),
tools=[report_research_progress],
middleware=[
SearchesStateMiddleware(),
CopilotKitMiddleware(),
StateStreamingMiddleware(
StateItem(
state_key="searches",
tool="report_research_progress",
tool_argument="searches",
)
),
],
system_prompt=(
"You are a research assistant. Use report_research_progress "
"to show each task and mark it done when complete."
),
)Understand the two update phases
The state-streaming middleware sends the partial searches argument while
the model writes it. The frontend can show each partial value at once.
The tool then returns a Command that saves the completed list. Its
ToolMessage closes the active tool call.
When the run finishes, the agent's final state is the single source of
truth. A streamed value that the tool does not also save in its Command
disappears at the end of the run, with no error.
Each setting must match your code. A mismatch sends updates to the wrong state field, or to none:
state_key(stateKey): the state field.tool: the name of the tool.tool_argument(toolArgument): the argument of the tool.
Render the state in the UI
Use useAgent to read the state anywhere in your app: in the chat, in a
dashboard, in a sidebar.
import { useAgent } from "@copilotkit/react-core/v2";
function YourMainContent() {
const { agent } = useAgent({
agentId: "sample_agent",
});
const state = (agent.state ?? {}) as {
searches?: { query: string; done: boolean }[];
};
const searches = state.searches ?? [];
return (
<div>
{searches.map((search, index) => (
<div key={index}>
{search.done ? "✅" : "⏳"} {search.query}
</div>
))}
</div>
);
}Ask the agent to research a topic. The search items appear and update while the agent works.
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.
Not available for Langchain DeepAgents yet
shared-state-streaming demo, and Langchain DeepAgents doesn't have it yet.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?