State Rendering
Render your agent's state with your own React Native components in real time.
What is this?
State rendering lets you build UI that reflects your agent's state in real time. As your agent works and writes to its state, your app renders those changes: progress, drafts, or intermediate results.
When should I use this?
Use state rendering when you want to:
- Show real-time progress (for example, "Researching... 2/5 complete")
- Display drafts that update as the agent works
- Build dashboards that reflect agent state
- Render structured output outside the chat
How it works in code
Declare the shared keys on your Flow state
A Flow keeps its state in self.state. Type the Flow on a subclass of
CopilotKitState and declare every key the UI reads or writes, with a
default. CopilotKitState brings the CopilotKit messages and actions.
from typing import List, Optional
from ag_ui_crewai import CopilotKitState
from pydantic import BaseModel, Field
class Preferences(BaseModel):
name: str = ""
tone: str = "casual"
language: str = "English"
interests: List[str] = Field(default_factory=list)
class AgentState(CopilotKitState):
# Written by the UI with agent.setState
preferences: Optional[Preferences] = None
# Written by the agent, read by the UI with useAgent
notes: List[str] = Field(default_factory=list)Import CopilotKitState from ag_ui_crewai. If you promoted the Flow to a
Conversational Flow, keep inheriting
from ag_ui_crewai.CopilotKitState: it also carries the conversation
fields CrewAI needs.
Read what the UI wrote
Values the UI writes with agent.setState are on self.state when the
next run starts. A nested model can arrive as a plain dict, so convert it
before you use it:
from crewai.flow.flow import Flow, start
class SharedStateReadWriteFlow(Flow[AgentState]):
@start()
async def chat(self) -> None:
prefs = self.state.preferences
if isinstance(prefs, dict):
prefs = Preferences(**prefs)
self.state.preferences = prefsWrite state and emit it
By default the UI receives the Flow's state only when a method finishes.
To update the UI mid-run, assign the value and call
copilotkit_emit_state:
import asyncio
from typing import TypedDict
from crewai.flow.flow import Flow, start
from ag_ui_crewai import CopilotKitState, copilotkit_emit_state
class Searches(TypedDict):
query: str
done: bool
class AgentState(CopilotKitState):
searches: list[Searches] = []
class SearchFlow(Flow[AgentState]):
@start()
async def chat(self):
self.state.searches = [
{"query": "Initial research", "done": False},
{"query": "Retrieving sources", "done": False},
{"query": "Forming an answer", "done": False},
]
await copilotkit_emit_state(self.state)
for search in self.state.searches:
await asyncio.sleep(1)
search["done"] = True
await copilotkit_emit_state(self.state)The showcase's src/agents/shared_state_read_write.py does the same after
the model calls its set_notes tool: it assigns self.state.notes and
emits the state, so the notes card updates before the turn ends.
- On the backend, write the value to a key in the agent state. To stream a tool argument into a state key token by token, see State Streaming.
- On the frontend, subscribe to the agent's state with
useAgent. Each time the state changes, your component renders again with the latest value. - Read the keys from
agent.stateand render them.
import { Text, View } from "react-native";
import { useAgent, UseAgentUpdate } from "@copilotkit/react-native/headless";
type ResearchState = {
status?: string;
draft?: string;
completed?: number;
total?: number;
};
export function ResearchProgress() {
const { agent } = useAgent({
agentId: "researcher",
updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
});
const state = (agent.state ?? {}) as ResearchState;
return (
<View style={{ padding: 16, gap: 8 }} accessibilityLiveRegion="polite">
<Text style={{ fontWeight: "600" }}>
{state.status ?? (agent.isRunning ? "Working..." : "Idle")}
</Text>
<Text>
{state.completed ?? 0} of {state.total ?? "?"} complete
</Text>
{state.draft ? <Text>{state.draft}</Text> : null}
</View>
);
}updates picks which changes re-render the component. OnStateChanged fires on state changes, and OnRunStatusChanged fires when a run starts or ends, so agent.isRunning stays current. Leave updates out to re-render on messages too.
Render it next to your chat, under the same provider. The chat and ResearchProgress share one agent:
import { View } from "react-native";
import { CopilotKitProvider } from "@copilotkit/react-native/headless";
import { CopilotChat } from "@copilotkit/react-native/components";
import { ResearchProgress } from "./src/ResearchProgress";
const runtimeUrl = "http://localhost:8200/api/copilotkit";
export default function App() {
return (
<CopilotKitProvider runtimeUrl={runtimeUrl}>
<View style={{ flex: 1 }}>
<ResearchProgress />
<CopilotChat agentName="researcher" />
</View>
</CopilotKitProvider>
);
}To check it, ask the researcher agent to write a report. The status line and the counter change while the agent runs, and the draft grows as the agent updates draft in its state.
Inside the chat
The rendered CopilotChat has no slot for extra content between messages. To show state inside the conversation, build your own chat and add a row for it to your FlatList data. See Headless UI.
Treat state as untrusted
Treat agent state as external data. Validate it before you use it for a privileged action, and don't put secrets in state that is streamed to the device.
How is this guide?