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 state with state_schema

Pass a state_schema to AgentFrameworkAgent. The adapter adds the current shared state to the model's context on every turn, so values the UI writes with agent.setState(...) reach the model. Without a state_schema, the agent never sees those writes.

src/agents/shared_state_read_write_agent.py
STATE_SCHEMA: dict[str, object] = {
    "preferences": {
        "type": "object",
        "description": (
            "User-supplied preferences. Adapt every response to match. "
            "Address the user by name when appropriate."
        ),
        "properties": {
            "name": {"type": "string"},
            "tone": {"type": "string"},
            "language": {"type": "string"},
            "interests": {"type": "array", "items": {"type": "string"}},
        },
    },
    "notes": {
        "type": "array",
        "items": {"type": "string"},
        "description": (
            "Short notes the agent has chosen to remember about the "
            "user. Updated by calling `set_notes` with the FULL list."
        ),
    },
}

Write state from a tool with predict_state_config

The agent writes state through a tool call. predict_state_config maps a tool argument to a state key, and the adapter sends the new value to the UI. The tool itself only returns a string for the model:

src/agents/shared_state_read_write_agent.py
from typing import Annotated

from agent_framework import Agent, BaseChatClient, tool
from agent_framework_ag_ui import AgentFrameworkAgent
from pydantic import Field

PREDICT_STATE_CONFIG: dict[str, dict[str, str]] = {
    "notes": {
        "tool": "set_notes",
        "tool_argument": "notes",
    },
}


@tool(
    name="set_notes",
    description=(
        "Replace the notes array in shared state with the full updated "
        "list. Always pass the FULL list of short note strings "
        "(existing notes + any new ones), not a diff. Keep each note "
        "short (< 120 chars)."
    ),
)
def set_notes(
    notes: Annotated[
        list[str],
        Field(
            description=(
                "The complete updated list of short note strings. "
                "Must include every existing note you want to keep "
                "plus any new ones."
            )
        ),
    ],
) -> str:
    """Push the agent-authored notes into AG-UI shared state."""
    return f"Notes updated. Tracking {len(notes)} note(s)."


def create_shared_state_read_write_agent(
    chat_client: BaseChatClient,
) -> AgentFrameworkAgent:
    base_agent = Agent(
        client=chat_client,
        name="shared_state_read_write_agent",
        instructions=SYSTEM_PROMPT,  # tells the model to call set_notes
        tools=[set_notes],
    )

    return AgentFrameworkAgent(
        agent=base_agent,
        name="CopilotKitMSAgentSharedStateReadWriteAgent",
        description=(
            "Bidirectional shared-state demo. Reads UI-written "
            "`preferences` from shared state every turn and writes "
            "agent-authored `notes` back via the `set_notes` tool."
        ),
        state_schema=STATE_SCHEMA,
        predict_state_config=PREDICT_STATE_CONFIG,
        require_confirmation=False,
    )

The mapped value replaces the state key, so have the tool take the whole value (the full notes list), not a diff. Tell the model the same thing in its instructions.

  1. 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.
  2. On the frontend, subscribe to the agent's state with useAgent. Each time the state changes, your component renders again with the latest value.
  3. Read the keys from agent.state and render them.
src/ResearchProgress.tsx
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:

App.tsx
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?