# State Rendering

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

> **Not available for Langchain DeepAgents yet.** The code on this page comes from the showcase's `shared-state-streaming` demo, and Langchain DeepAgents doesn't have it yet. See this page for [CopilotKit's Built-in Agent](/generative-ui/state-rendering), [LangGraph (Python)](/langgraph-python/generative-ui/state-rendering), [LangGraph (TypeScript)](/langgraph-typescript/generative-ui/state-rendering).

## 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 shared state on your Deep Agent

    A Deep Agent declares its state through middleware. Add your field to a
    state schema, and pass that middleware to the agent together with the
    CopilotKit middleware. This example shares a `language` value.

    <Tabs groupId="agent_language" items={['Python', 'TypeScript']} persist>
      <Tab value="Python">
        ```python title="agent.py"
        from typing import Any, Literal, NotRequired

        from copilotkit import CopilotKitMiddleware, CopilotKitState
        from deepagents import create_deep_agent
        from langchain_openai import ChatOpenAI
        from langchain.agents.middleware import AgentMiddleware

        class AgentState(CopilotKitState):
            language: NotRequired[Literal["english", "spanish"]]

        class LanguageStateMiddleware(AgentMiddleware[AgentState, Any]):
            state_schema = AgentState

        agent = create_deep_agent(
            model=ChatOpenAI(model="gpt-6-luna", reasoning_effort="none"),
            middleware=[
                LanguageStateMiddleware(),
                CopilotKitMiddleware(expose_state=["language"]),
            ],
            system_prompt=(
                "You are a helpful assistant. Current agent state contains "
                "language. Always answer in that language."
            ),
        )
        ```
      </Tab>
      <Tab value="TypeScript">
        ```ts title="agent.ts"
        import { createMiddleware } from "langchain";
        import {
          createCopilotkitMiddleware,
          zodState,
        } from "@copilotkit/sdk-js/langgraph";
        import { createDeepAgent } from "deepagents";
        import { z } from "zod";

        // Define the state as a middleware. The default flows through automatically.
        export const languageStateMiddleware = createMiddleware({
          name: "AgentState",
          stateSchema: z.object({
            language: zodState(z.enum(["english", "spanish"]).default("english")),
          }),
        });

        export const agent = createDeepAgent({
          model: "openai:gpt-6-luna",
          middleware: [
            languageStateMiddleware,
            createCopilotkitMiddleware({ exposeState: ["language"] }),
          ],
          systemPrompt:
            "You are a helpful assistant. Current agent state contains " +
            "language. Always answer in that language.",
        });
        ```
      </Tab>
    </Tabs>

    In TypeScript, `zodState` keeps the field in the AG-UI state snapshots
    that reach the frontend.

  </Step>
  <Step>
    ### Expose the field to the model

    A value the UI writes with `agent.setState` reaches the agent's state, but
    the CopilotKit middleware does not show state to the model by default.
    List the fields the model should see in `expose_state` (`exposeState`),
    and say in the system prompt what they mean. Without the allowlist, the
    run succeeds and the model answers as if the UI had written nothing. Keep
    the allowlist narrow.

  </Step>
  <Step>
    ### Read and write the state in your UI

    Deep Agents has no live demo on this page yet, so the demo code below does
    not show for it. `useAgent` returns the agent, its reactive `state`, and
    `setState`:

    ```tsx title="ui/app/page.tsx"
    import { useAgent } from "@copilotkit/react-core/v2";

    function YourMainContent() {
      const { agent } = useAgent({
        agentId: "sample_agent",
      });

      const language = (agent.state.language as string) ?? "english";

      const toggleLanguage = () => {
        agent.setState({ language: language === "english" ? "spanish" : "english" });
      };

      return (
        // style excluded for brevity
        <div>
          <h1>Your main content</h1>
          <p>Language: {language}</p>
          <button onClick={toggleLanguage}>Toggle Language</button>
        </div>
      );
    }
    ```

  </Step>
</Steps>

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

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"]}
/>
