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, LangGraph (Python), LangGraph (TypeScript).

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

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.

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."
    ),
)

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

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.

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:

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>
  );
}
  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, import useAgent from @copilotkit/react-core/v2:

    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:

    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:

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

Free course: See this pattern built end-to-end in 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).

How is this guide?