930aaeb
CopilotKitDocs
  • Docs
  • Integrations
  • Reference
Get Started
QuickstartCoding Agents
Concepts
ArchitectureGenerative UI OverviewOSS vs Enterprise
Agentic Protocols
OverviewAG-UIAG-UI MiddlewareMCPA2A
Build Chat UIs
Prebuilt Components
CopilotChatCopilotSidebarCopilotPopup
Custom Look and Feel
CSS CustomizationSlots (Subcomponents)Fully Headless UIReasoning Messages
Multimodal AttachmentsVoice
Build Generative UI
Controlled
Tool-based Generative UITool RenderingState RenderingReasoning
Your Components
Display ComponentsInteractive Components
Declarative
A2UIDynamic Schema A2UIFixed Schema A2UI
Open-Ended
MCP Apps
Adding Agent Powers
Frontend ToolsShared State
Human-in-the-Loop
HITL OverviewPausing the Agent for InputHeadless Interrupts
Sub-AgentsAgent ConfigProgrammatic Control
Agents & Backends
Built-in Agent
Backend
Copilot RuntimeFactory ModeAG-UI
Runtime Server AdapterAuthentication
AG2
Shared state
Reading agent stateWriting agent state
Readables
Observe & Operate
InspectorVS Code Extension
Troubleshooting
Common Copilot IssuesError Debugging & ObservabilityDebug ModeAG-UI Event InspectorHook ExplorerError Observability Connectors
Enterprise
CopilotKit PremiumHow the Enterprise Intelligence Platform WorksHow Threads & Persistence WorkObservabilitySelf-Hosting IntelligenceThreads
Deploy
AWS AgentCore
What's New
Full MCP Apps SupportLangGraph Deep Agents in CopilotKitA2UI Launches with full AG-UI SupportCopilotKit v1.50Generative UI Spec SupportA2A and MCP Handshake
Migrate
Migrate to V2Migrate to 1.8.2
Other
Contributing
Code ContributionsDocumentation Contributions
Anonymous Telemetry
AG2Shared StateRead

Reading agent state

Read the realtime agent state in your native application.

Info

This video shows the result of npx copilotkit@latest init with the implementation section applied to it.

What is this?#

You can easily use the realtime agent state not only in the chat UI, but also in the native application UX.

Info

CopilotKit consumes AG-UI protocol events streamed by AG2 over /chat. See the

AG2 AG-UI integration docs

.

When should I use this?#

You can use this when you want to provide the user with feedback about your agent's state. As your agent's state updates, you can reflect these updates natively in your application.

Implementation#

Run and connect your agent#

Start your AG2 backend and connect your CopilotKit frontend to the AG-UI /chat endpoint.

Define the Agent State#

Create your AG2 backend with ContextVariables and emit StateSnapshotEvent whenever the state changes:

from typing import Annotated

from ag_ui.core import EventType, StateSnapshotEvent
from fastapi import FastAPI, Header
from fastapi.responses import StreamingResponse
from autogen import ContextVariables, ConversableAgent, LLMConfig
from autogen.ag_ui import AGUIStream, RunAgentInput

def read_state(context: ContextVariables) -> dict:
    return context.get("agent_state", {"language": "english"})

def write_state(context: ContextVariables, state: dict) -> StateSnapshotEvent:
    context["agent_state"] = state
    return StateSnapshotEvent(type=EventType.STATE_SNAPSHOT, snapshot=state)

agent = ConversableAgent(
    name="assistant",
    system_message=(
        "You are a helpful assistant for tracking language. "
        "Always respond in the current language."
    ),
    llm_config=LLMConfig({"model": "gpt-5.4-mini"}),
)

@agent.register_for_llm(description="Update the language in shared state.")
def set_language(
    context: ContextVariables,
    language: Annotated[str, "language such as english or spanish"],
) -> StateSnapshotEvent:
    return write_state(context, {"language": language.lower()})

agent.register_for_execution(name="set_language")(set_language)

stream = AGUIStream(agent)
app = FastAPI()

@app.post("/chat")
async def run_agent(
    message: RunAgentInput,
accept: str | None = Header(None),
):
    return StreamingResponse(
        stream.dispatch(message, accept=accept),
        media_type=accept or "text/event-stream",
    )

Use the useAgent Hook#

With your agent connected and running all that is left is to call the useAgent hook, pass the agent's ID, and optionally provide an initial state.


// Define the agent state type, should match the actual state of your agent
type AgentState = {
language: "english" | "spanish";
}

function YourMainContent() {
  // [!code highlight:4]
  const { agent } = useAgent({
    agentId: "my_agent", // MUST match the agent name in CopilotRuntime
    initialState: { language: "english" }  // optionally provide an initial state
  });

  // ...

  return (
    // style excluded for brevity
    <div>
      <h1>Your main content</h1>
      {/* [!code highlight:1] */}
      <p>Language: {agent.state.language}</p>
    </div>
  );
}
Important

The agentId parameter must exactly match the agent name you defined in your CopilotRuntime configuration (e.g., my_agent from the quickstart).

Info

The agent.state in useAgent is reactive and will automatically update when the agent's state changes.

Give it a try#

As the agent state updates, your state variable will automatically update with it. In this case, you'll see the language set to "english" as that's the initial state we set.

Rendering agent state in the chat#

You can also render the agent's state in the chat UI. This is useful for informing the user about the agent's state in a more in-context way. To do this, you can use the useAgent hook with a render function.

// Define the agent state type, should match the actual state of your agent
type AgentState = {
  language: "english" | "spanish";
};

function YourMainContent() {
  // ...
  // [!code highlight:7]
  useAgent({
    agentId: "my_agent",
    render: ({ state }) => {
      if (!state.language) return null;
      return <div>Language: {state.language}</div>;
    },
  });
  // ...
}
Important

The name parameter must exactly match the agent name you defined in your CopilotRuntime configuration (e.g., my_agent from the quickstart).

Info

The agent.state in useAgent is reactive and will automatically update when the agent's state changes.

Intermediately Stream and Render Agent State#

By default, AG2 state updates are visible to CopilotKit whenever your backend emits StateSnapshotEvent. For smoother long-running workflows, emit additional intermediate snapshots from your backend tools.

On this page
What is this?When should I use this?ImplementationRendering agent state in the chatIntermediately Stream and Render Agent State