State Rendering

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

State Streaming

Waking up the demo

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

Map JSON content to a state snapshot

A .NET agent publishes state as a DataContent update with the application/json media type. The MapContent mapping on AGUIStreamOptions is what turns that content into a STATE_SNAPSHOT event for the frontend. Register it next to AddAGUIServer:

Program.cs
using System.Text.Json;
using AGUI.Abstractions;
using AGUI.Server;
using Microsoft.Extensions.AI;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAGUIServer();
// Turn the wrapper's JSON DataContent into a STATE_SNAPSHOT event
builder.Services.Configure<AGUIStreamOptions>(options => options.MapContent(content =>
{
    if (content is not DataContent { MediaType: "application/json" } data) return null;
    try
    {
        using var document = JsonDocument.Parse(data.Data);
        return [new StateSnapshotEvent { Snapshot = document.RootElement.Clone() }];
    }
    catch (JsonException)
    {
        return null;
    }
}));
var app = builder.Build();

Read and write state in an agent wrapper

Wrap your agent in a DelegatingAIAgent. The state the UI sent arrives on the AG-UI request, which TryGetRunAgentInput recovers from the chat options. To update the UI, yield the new state as JSON DataContent:

Program.cs (excerpt)
internal sealed class StateStreamingAgent : DelegatingAIAgent
{
    // ...

    protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingAsync(
        IEnumerable<AIChatMessage> messages,
        AgentSession? session = null,
        AgentRunOptions? options = null,
        [EnumeratorCancellation] CancellationToken cancellationToken = default)
    {
        // Recover the state sent in the AG-UI request
        JsonElement? currentState = null;
        if (options is ChatClientAgentRunOptions { ChatOptions: { } chatOptions } &&
            chatOptions.TryGetRunAgentInput(out RunAgentInput? input) &&
            input?.State is { ValueKind: JsonValueKind.Object } state)
        {
            currentState = state;
        }

        // ... run the inner agent and build the new state snapshot

        byte[] stateBytes = JsonSerializer.SerializeToUtf8Bytes(
            parsedStateSnapshot,
            this._jsonSerializerOptions.GetTypeInfo(typeof(JsonElement)));

        // Emit state snapshot as DataContent
        yield return new AgentResponseUpdate
        {
            Contents = [new DataContent(stateBytes, "application/json")]
        };
    }
}

For a full agent that does this, see SharedStateAgent.cs, or the SharedStateAgent sample in the Agent Framework repository.

  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:

    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:

    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?