State Rendering

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

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

On the frontend, subscribe to the agent's state. Each time the backend forwards a fresh value, your component re-renders with the latest partial output. useAgent returns an agent ref; read agent.value?.state in script or let templates unwrap the ref. Keep the provider in an ancestor SFC.

src/components/ResearchProgress.vue
<script setup lang="ts">
import { computed } from "vue";
import { useAgent, UseAgentUpdate } from "@copilotkit/vue/v2";

type ResearchState = { status?: string; draft?: string; completed?: number; total?: number };

const { agent } = useAgent({
  agentId: "researcher",
  updates: [UseAgentUpdate.OnStateChanged, UseAgentUpdate.OnRunStatusChanged],
});

const state = computed(() => (agent.value?.state ?? {}) as ResearchState);
</script>

<template>
  <section aria-live="polite">
    <p>{{ state.status ?? "Idle" }}</p>
    <progress :value="state.completed ?? 0" :max="state.total ?? 1" />
    <article v-if="state.draft">{{ state.draft }}</article>
  </section>
</template>
src/App.vue
<script setup lang="ts">
import { CopilotChat, CopilotKitProvider } from "@copilotkit/vue/v2";
import ResearchProgress from "./components/ResearchProgress.vue";
</script>

<template>
  <CopilotKitProvider runtime-url="/api/copilotkit">
    <ResearchProgress />
    <CopilotChat agent-id="researcher" />
  </CopilotKitProvider>
</template>

On the backend, a state-streaming mapping forwards a tool argument into a state key while the model writes it. Some frameworks provide that as middleware. Direct SDK adapters can emit STATE_SNAPSHOT events from their streaming loop. Either way, the UI can watch the answer assemble token-by-token rather than appearing in one burst between checkpoints.

Map the tool call to a state snapshot

AGUIStreamOptions.MapCall maps a tool call to AG-UI events. Return a StateSnapshotEvent built from the tool's arguments, and attach the options to the endpoint with WithMetadata:

Program.cs
using System.ComponentModel;
using System.Text.Json;
using AGUI.Abstractions;
using AGUI.Server;
#pragma warning disable OPENAI001
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Hosting.AGUI.AspNetCore;
using Microsoft.Extensions.AI;
using OpenAI;
using OpenAI.Chat;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAGUIServer();
var app = builder.Build();

string openAiApiKey = builder.Configuration["OPENAI_API_KEY"]
    ?? throw new InvalidOperationException("Set OPENAI_API_KEY");

// Define a tool the LLM may call to report its progress
[Description("Report current step progress.")]
static string StepProgress([Description("Steps completed so far")] string[] steps)
    => "Progress received.";

AITool stepProgress = AIFunctionFactory.Create(StepProgress, name: "step_progress");
var agent = new OpenAIClient(openAiApiKey)
    .GetChatClient("gpt-6-luna")
    .AsIChatClient().AsBuilder()
    .ConfigureOptions(options => options.RawRepresentationFactory = _ =>
        new OpenAI.Chat.ChatCompletionOptions { ReasoningEffortLevel = new("none") })
    .Build()
    .AsAIAgent(
        name: "AGUIAssistant",
        instructions: "You are a helpful assistant that may call the 'step_progress' tool to report intermediate steps.",
        tools: [stepProgress]);

// Map the completed tool arguments to a shared-state snapshot
AGUIStreamOptions streamOptions = new AGUIStreamOptions()
    .MapCall("step_progress", call =>
    {
        if (call.Arguments?.TryGetValue("steps", out object? steps) is not true)
        {
            return [];
        }

        JsonElement snapshot = JsonSerializer.SerializeToElement(
            new { observed_steps = steps });
        return [new StateSnapshotEvent { Snapshot = snapshot }];
    });

app.MapAGUIServer("/", agent).WithMetadata(streamOptions);
await app.RunAsync();

Know what streams and what does not

MapCall runs on the completed FunctionCallContent, so the state key updates once, when the tool call finishes. It does not grow token by token while the model writes the arguments. To stream partial arguments into state, register a provider-specific extractor with MapStreamingToolCallArguments.

Ask the researcher agent to write a report. The status line and the progress bar change while the agent runs, and the draft text grows as the tokens arrive.

Treat agent state as untrusted external data. Validate it before using it for privileged actions, and avoid putting secrets in state that is streamed to the browser.

How is this guide?