# State Rendering

> Render your agent's state with custom UI components in real-time.

<!-- interactive demo: shared-state-streaming -->

## What is this? [#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? [#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 [#how-it-works-in-code]

<Steps>
  <Step>
    ### Put shared state in the system prompt and tools

    The demo exposes frontend preferences to Claude and gives the agent a tool
    for writing notes back into CopilotKit state. Keep the state contract small,
    typed, and mirrored by the UI components that read the same values.

~~~~python title="shared_state_read_write_agent.py"
SYSTEM_PROMPT = dedent("""
    You are a helpful, concise assistant.

    The user's preferences are supplied via shared state and added at the
    start of every turn — always respect them. Address the user by name
    when known, match the requested tone, and respond in the requested
    language.

    When the user asks you to "remember" something, or you observe
    something worth surfacing in the UI's notes panel, call the
    ``set_notes`` tool with the FULL updated list of short notes
    (existing notes + new ones, not a diff). Keep each note short
    (< 120 characters). After updating notes, briefly acknowledge what
    you remembered.
""").strip()


SET_NOTES_TOOL: dict[str, Any] = {
    "name": "set_notes",
    "description": (
        "Replace the notes array in shared state with the FULL updated "
        "list. Always include every existing note plus any new ones, "
        "not a diff. Keep each note short (< 120 chars)."
    ),
    "input_schema": {
        "type": "object",
        "properties": {
            "notes": {
                "type": "array",
                "items": {"type": "string"},
                "description": "Full list of short note strings to persist.",
            },
        },
        "required": ["notes"],
    },
}


def build_preferences_block(prefs: dict[str, Any] | None) -> str | None:
    """Render the user-supplied preferences as an injectable prompt block.

    Returns ``None`` when no recognised keys are present so the system
    prompt is left untouched.
    """
    if not isinstance(prefs, dict) or not prefs:
        return None
    lines = ["The user has shared these preferences with you:"]
    if prefs.get("name"):
        lines.append(f"- Name: {prefs['name']}")
    if prefs.get("tone"):
        lines.append(f"- Preferred tone: {prefs['tone']}")
    if prefs.get("language"):
        lines.append(f"- Preferred language: {prefs['language']}")
    interests = prefs.get("interests") or []
    if isinstance(interests, list) and interests:
        lines.append(f"- Interests: {', '.join(str(i) for i in interests)}")
    if len(lines) == 1:
        # No recognised fields — don't emit a header with no content.
        return None
    lines.append(
        "Tailor every response to these preferences. Address the user "
        "by name when appropriate."
    )
    return "\n".join(lines)


def _state_dict(state: dict[str, Any]) -> dict[str, Any]:
    """Coerce the AG-UI raw state envelope into the slots we care about."""
    return {
        "preferences": state.get("preferences") or {},
        "notes": list(state.get("notes") or []),
    }


~~~~

  </Step>

  <Step>
    ### Register `set_notes` with Claude

    This dedicated demo uses the Anthropic Messages API directly. Pass the
    schema to `client.messages.stream` so Claude can call `set_notes`.

~~~~python title="shared_state_read_write_agent.py"
        stream_request = client.messages.stream(
            model=normalize_claude_model(
                os.getenv("ANTHROPIC_MODEL", DEFAULT_ANTHROPIC_MODEL)
            ),
            max_tokens=2048,
            system=system,
            messages=messages,
            tools=[SET_NOTES_TOOL],
        )
~~~~

  </Step>

  <Step>
    ### Write the tool result back to shared state

    When Claude calls `set_notes`, replace the notes array, emit a
    `StateSnapshotEvent` for the UI, and return a `ToolCallResultEvent` to
    Claude before the loop continues.

~~~~python title="shared_state_read_write_agent.py"
        # Execute set_notes by mutating shared state and emitting a
        # StateSnapshotEvent so the UI re-renders the agent-authored
        # notes. This is the agent-side half of the WRITE direction.
        tool_results: list[dict[str, Any]] = []
        for tc in tool_calls:
            if tc["name"] == "set_notes":
                notes = tc["input"].get("notes") or []
                if isinstance(notes, list):
                    state["notes"] = [str(n) for n in notes]
                result_text = json.dumps({"status": "ok", "count": len(state["notes"])})
                yield encoder.encode(
                    StateSnapshotEvent(type=EventType.STATE_SNAPSHOT, snapshot=state)
                )
            else:
                result_text = json.dumps({"error": f"unknown tool {tc['name']}"})

            yield encoder.encode(
                ToolCallResultEvent(
                    type=EventType.TOOL_CALL_RESULT,
                    tool_call_id=tc["id"],
                    message_id=f"{msg_id}-tool-result-{tc['id']}",
                    content=result_text,
                )
            )
            tool_results.append(
                {
                    "type": "tool_result",
                    "tool_use_id": tc["id"],
                    "content": result_text,
                }
            )
        messages.append({"role": "user", "content": tool_results})
~~~~

  </Step>

  <Step>
    ### Serve the shared-state loop

    Mount the dedicated runner on `/shared-state-read-write` and return its
    AG-UI events as a streaming response.

~~~~python title="agent_server.py"
@app.post("/shared-state-read-write")
async def shared_state_read_write_endpoint(request: Request) -> StreamingResponse:
    """Bidirectional shared state demo — UI writes preferences, agent writes notes.

    Uses its own streaming loop (not the shared sales-assistant
    ``run_agent``) because the state schema, tools, and prompt-injection
    middleware are all demo-specific.
    """
    body = await request.json()
    input_data = RunAgentInput(**body)

    async def event_stream() -> AsyncIterator[str]:
        async for chunk in run_shared_state_read_write_agent(input_data):
            yield chunk

    return StreamingResponse(
        event_stream(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "X-Accel-Buffering": "no",
        },
    )


~~~~

  </Step>
</Steps>

<Callout type="info">
  This Python route intentionally uses its own Messages API loop. It does not
  use `ClaudeAgentAdapter` or an MCP server.
</Callout>

1. On the backend, write the value to a key in the
   [agent state](/claude-sdk-python/shared-state). To stream a tool argument into a state key
   token by token, see [State Streaming](/claude-sdk-python/shared-state/streaming).
2. On the frontend, import `useAgent` from `@copilotkit/react-core/v2`:

   ```tsx
   import { useAgent, UseAgentUpdate } from "@copilotkit/react-core/v2";
   ```

3. Subscribe to the agent state. Each time the state changes, your component
   renders again with the latest value:

   ```typescript title="src/app/demos/shared-state-streaming/page.tsx"
     // Subscribe to BOTH state changes and run-status changes. The former
     // drives the per-token document rerender; the latter toggles the
     // "LIVE" badge when the agent starts / stops.
     const { agent } = useAgent({
       agentId: "shared-state-streaming",
       updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
     });
   ```

4. Read the key from `agent.state` and render it:

   ```tsx
   const document = (agent.state as { document?: string }).document ?? "";
   ```

To check it, ask the agent to write a short poem. Your component renders the
poem each time the agent updates `document` in its state.

To render the state inside the chat instead, pass a `children` function to
the chat's `messageView` slot and add your UI next to the messages. For
example, to list the searches an agent keeps in a `searches` key:

```tsx
<CopilotChat
  agentId="sample_agent"
  messageView={{
    children: ({ messageElements, interruptElement }) => (
      <div>
        {messageElements}
        {state.searches?.map((search, index) => (
          <div key={index}>{search.done ? "✅" : "❌"} {search.query}</div>
        ))}
        {interruptElement}
      </div>
    ),
  }}
/>
```

Here `state` is `agent.state` from `useAgent`.

<Callout type="info">
  **Free course:** See this pattern built end-to-end in [Build Interactive Agents with Generative UI](https://www.deeplearning.ai/short-courses/build-interactive-agents-with-generative-ui/). This free DeepLearning.AI short course is taught by CopilotKit's CEO. It covers the full Generative UI spectrum (Controlled, Declarative, and Open-Ended).
</Callout>

<IntegrationGrid
  path="generative-ui/state-rendering"
  exclude={["agno", "agent-spec"]}
/>
