Back to Copilotkit

Reading agent state

showcase/shell-docs/src/content/docs/integrations/ag2/shared-state/read.mdx

1.57.05.6 KB
Original Source

<video src="https://cdn.copilotkit.ai/docs/copilotkit/videos/coagents/shared-state.mp4" className="rounded-lg shadow-xl" loop playsInline controls autoPlay muted /> <Callout> This video shows the result of npx copilotkit@latest init with the implementation section applied to it. </Callout>

What is this?

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

<Callout type="info"> CopilotKit consumes AG-UI protocol events streamed by AG2 over{" "} <code>/chat</code>. See the{" "} <a href="https://docs.ag2.ai/latest/docs/user-guide/ag-ui/" target="_blank"> AG2 AG-UI integration docs </a> . </Callout>

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

<Steps> <Step> ### Run and connect your agent Start your AG2 backend and connect your CopilotKit frontend to the AG-UI `/chat` endpoint. </Step> <Step> ### Define the Agent State
Create your AG2 backend with `ContextVariables` and emit `StateSnapshotEvent` whenever the state changes:

```python title="agent.py"
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",
    )
```
</Step> <Step> ### Use the `useAgent` Hook With your agent connected and running all that is left is to call the [useAgent](/reference/v1/hooks/useAgent) hook, pass the agent's ID, and optionally provide an initial state.
```tsx title="ui/app/page.tsx"

// 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>
      <p>Language: {agent.state.language}</p>
    </div>
  );
}
```

<Callout type="warn" title="Important">
  The `agentId` parameter must exactly match the agent name you defined in your CopilotRuntime configuration (e.g., `my_agent` from the quickstart).
</Callout>

<Callout type="info">
  The `agent.state` in `useAgent` is reactive and will automatically update when the agent's state changes.
</Callout>
</Step> <Step> ### 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. </Step> </Steps>

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.

tsx
// 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>;
    },
  });
  // ...
}
<Callout type="warn" title="Important"> The `name` parameter must exactly match the agent name you defined in your CopilotRuntime configuration (e.g., `my_agent` from the quickstart). </Callout> <Callout type="info"> The `agent.state` in `useAgent` is reactive and will automatically update when the agent's state changes. </Callout>

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.