State Rendering
Render your agent's state with custom UI 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 progresses through nodes and emits state updates, your frontend renders those changes, showing progress, drafts, or intermediate results.
When should I use this?
Use state rendering when you want to:
- Show real-time progress (e.g. "Researching... 2/5 complete")
- Display drafts that update as the agent works
- Build dashboards that reflect agent state
- Render structured output outside of the chat
How it works in code
On the frontend, subscribe to the agent's state. Each time the backend forwards a fresh value, your component re-renders with the latest partial output. useAgent returns an agent ref; read agent.value?.state in script or let templates unwrap the ref. Keep the provider in an ancestor SFC.
<script setup lang="ts">
import { computed } from "vue";
import { useAgent, UseAgentUpdate } from "@copilotkit/vue/v2";
type ResearchState = { status?: string; draft?: string; completed?: number; total?: number };
const { agent } = useAgent({
agentId: "researcher",
updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
});
const state = computed(() => (agent.value?.state ?? {}) as ResearchState);
</script>
<template>
<section aria-live="polite">
<p>{{ state.status ?? "Idle" }}</p>
<progress :value="state.completed ?? 0" :max="state.total ?? 1" />
<article v-if="state.draft">{{ state.draft }}</article>
</section>
</template><script setup lang="ts">
import { CopilotChat, CopilotKitProvider } from "@copilotkit/vue/v2";
import ResearchProgress from "./components/ResearchProgress.vue";
</script>
<template>
<CopilotKitProvider runtime-url="/api/copilotkit">
<ResearchProgress />
<CopilotChat agent-id="researcher" />
</CopilotKitProvider>
</template>On the backend, a state-streaming mapping forwards a tool argument into a state key while the model writes it. Some frameworks provide that as middleware. Direct SDK adapters can emit STATE_SNAPSHOT events from their streaming loop. Either way, the UI can watch the answer assemble token-by-token rather than appearing in one burst between checkpoints.
Install the CrewAI AG-UI package
pip install ag-ui-crewai litellmDeclare the state key
from ag_ui_crewai import CopilotKitState
class SharedStateStreamingState(CopilotKitState):
document: str = ""Map the tool argument to the state key
Call copilotkit_predict_state with one StateItem before the model
call. While the model streams write_document, CopilotKit copies the
partial document argument into the document state key. Wrap the call
in copilotkit_stream, or nothing streams until the turn ends.
from crewai.flow.flow import Flow, start
from litellm import acompletion
from ag_ui_crewai import StateItem, copilotkit_predict_state, copilotkit_stream
class SharedStateStreamingFlow(Flow[SharedStateStreamingState]):
@start()
async def write(self) -> None:
await copilotkit_predict_state(
[
StateItem(
state_key="document",
tool="write_document",
tool_argument="document",
)
]
)
tools = [*self.state.copilotkit.actions, WRITE_DOCUMENT_TOOL]
response = await copilotkit_stream(
await acompletion(
reasoning_effort="none",
allowed_openai_params=["reasoning_effort"],
model="openai/gpt-6-luna",
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
*self.state.messages,
],
tools=tools,
parallel_tool_calls=False,
stream=True,
)
)WRITE_DOCUMENT_TOOL is a plain OpenAI-format tool schema with one
required document string argument.
Persist the final value
When a Flow method finishes, its state becomes the single source of
truth. The streamed predictions are not written to self.state, so
assign the final value yourself. Otherwise it is overwritten when the
method completes.
# Still inside write(), after the model call (needs `import json`)
message = response.choices[0].message
self.state.messages.append(message)
calls = message.get("tool_calls") or []
write_call = next(
(
call
for call in calls
if call.get("function", {}).get("name") == "write_document"
),
None,
)
if write_call is None:
return
arguments = json.loads(
write_call.get("function", {}).get("arguments") or "{}"
)
document = arguments.get("document")
self.state.document = document if isinstance(document, str) else ""The showcase Flow then appends a role: "tool" message, calls
copilotkit_emit_tool_result, and asks the model for a one-line
confirmation. See src/agents/shared_state_streaming.py.
Emit progress without a tool argument
To show progress that is not a tool argument, assign the value and call
copilotkit_emit_state after each sub-step:
from ag_ui_crewai import copilotkit_emit_state
for step in steps:
self.state.observed_steps = [*self.state.observed_steps, step]
await copilotkit_emit_state(self.state)
await asyncio.sleep(1)class SharedStateStreamingState(CopilotKitState):
document: str = ""
class SharedStateStreamingFlow(Flow[SharedStateStreamingState]):
"""Predict write_document arguments into state, then persist the result."""
@start()
async def write(self) -> None:
await copilotkit_predict_state(
[
StateItem(
state_key="document",
tool="write_document",
tool_argument="document",
)
]
)Ask the researcher agent to write a report. The status line and the progress bar change while the agent runs, and the draft text grows as the tokens arrive.
Treat agent state as untrusted external data. Validate it before using it for privileged actions, and avoid putting secrets in state that is streamed to the browser.
How is this guide?