Skip to content

The Open Standard for Generative UI

4.7 KB
Raw Blame
---
title: "AG-UI"
---

<Example
  prompt="Compare the weather in Tokyo, London and New York right now."
  image="/integrations/examples/ag-ui"
  width={1600}
  height={1050}
  alt="An AG-UI agent answering a request to compare the weather in three cities. The tool calls arrive as AG-UI events, and OpenUI renders a card for each city and a table of temperatures and conditions."
  href="https://github.com/thesysdev/openui/tree/main/examples/agent-frameworks/google-adk"
>

OpenUI renders any AG-UI stream the same way. This screenshot comes from the Google ADK example: its route turns ADK events into AG-UI events, and `agUIAdapter()` reads them in the browser. Its `get_weather` tool returns sample data. The steps below build the same kind of endpoint without a framework, following the self-hosting guide's Anthropic recipe.

```bash title="Terminal"
cd examples/agent-frameworks/google-adk
pnpm install --ignore-workspace
pnpm generate:apiKey   # writes THESYS_API_KEY to .env.local
pnpm dev
```

</Example>

<Steps>

<Step title="Prompt your agent for OpenUI Lang" source="https://www.openui.com/docs/build-agents/ui-generation">

Generate the system prompt from the same component library the client renders, so the agent's text output is OpenUI Lang the renderer understands.

```ts title="server.ts"
import { generateSystemPrompt, type LibrarySpec } from "@openuidev/lang-core";
// Your component library's spec, written by `openui generate --spec`.
import library from "./lib/openui.spec.json";

// The complete prompt, ready to send to any model.
const openuiInstructions = generateSystemPrompt({
  library: library as LibrarySpec,
});
```

</Step>

<Step title="Serve AG-UI events" source="https://www.openui.com/docs/agent/reference/self-hosting">

Expose the agent as a server-sent events endpoint whose `data:` lines are AG-UI events: `TEXT_MESSAGE_*` for text, `TOOL_CALL_*` and `TOOL_CALL_RESULT` for tools, and `RUN_ERROR` for failures. Closing the stream ends the run. This route translates Anthropic's stream; an agent framework that already emits AG-UI events can replace it.

```ts title="app/api/chat/route.ts"
import Anthropic from "@anthropic-ai/sdk";

const anthropic = new Anthropic(); // Reads ANTHROPIC_API_KEY from the environment.
const encoder = new TextEncoder();

export async function POST(req: Request) {
  const { messages } = await req.json(); // { role, content } turns (openAIMessageFormat)
  const stream = new ReadableStream({
    async start(controller) {
      // Each AG-UI event goes out as one SSE "data:" line.
      const send = (event: object) =>
        controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
      const messageId = crypto.randomUUID();
      try {
        const reply = anthropic.beta.messages.stream({
          model: "claude-opus-5-5",
          max_tokens: 64000,
          // If the model declines, Anthropic re-runs the request on a fallback model.
          betas: ["server-side-fallback-2026-07-01"],
          fallbacks: "default",
          system: openuiInstructions, // The OpenUI Lang prompt from step 1.
          messages: messages.filter((m: { role: string }) => m.role !== "system"),
        });
        send({ type: "TEXT_MESSAGE_START", messageId });
        for await (const chunk of reply) {
          if (chunk.type === "content_block_delta" && chunk.delta.type === "text_delta") {
            send({ type: "TEXT_MESSAGE_CONTENT", messageId, delta: chunk.delta.text });
          }
        }
        send({ type: "TEXT_MESSAGE_END", messageId });
      } catch (err) {
        send({ type: "RUN_ERROR", message: (err as Error).message });
      }
      controller.close(); // Closing the stream ends the run in the UI.
    },
  });
  return new Response(stream, { headers: { "Content-Type": "text/event-stream" } });
}
```

</Step>

<Step title="Connect the adapter" source="https://www.openui.com/docs/agent/reference/self-hosting">

Point `fetchLLM`, or your own `ChatLLM` implementation, at the endpoint with `agUIAdapter()` as the stream adapter. Then pass it to `AgentInterface` for a ready-made chat app, or to `ChatProvider` from `@openuidev/react-headless` for your own UI.

```tsx title="app/page.tsx"
"use client";

import { AgentInterface, agUIAdapter, fetchLLM, openAIMessageFormat } from "@openuidev/react-ui";
// Your component library: the one step 1's spec was generated from.
import { library } from "@/lib/openui";

const llm = fetchLLM({
  url: "/api/chat",
  streamAdapter: agUIAdapter(),
  // Sends OpenAI-style { role, content } turns, which the route forwards to Anthropic.
  messageFormat: openAIMessageFormat,
});

export default function Page() {
  return <AgentInterface llm={llm} componentLibrary={library} />;
}
```

</Step>

</Steps>