# 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>
    ### 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.

    ```python title="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."
            ),
        },
    }
    ```

  </Step>
  <Step>
    ### 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:

    ```python title="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.

  </Step>
</Steps>

1. On the backend, write the value to a key in the
   [agent state](/ms-agent-python/shared-state). To stream a tool argument into a state key
   token by token, see [State Streaming](/ms-agent-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"]}
/>
