I’ve been building AI‑augmented products for a handful of years now, and the moment I realized I was spending more time wiring UI plumbing than actually delivering value was the day I first ran into the AG‑UI protocol. It’s an emerging, open‑source contract that describes how a front‑end component talks to an “agent” – a piece of LLM‑powered logic – in a way that’s language‑agnostic, versionable, and, most importantly for us senior engineers, testable. In this post I’ll walk you through how to adopt the protocol in a modern React / Next.js stack, keep the codebase maintainable, and stay flexible enough to swap out the underlying model without rewriting the UI.


Why a Protocol Matters for AI Agent UIs

The pain points we’ve hit

When I first prototyped an AI assistant inside a Next.js app, I used a naïve fetch‑and‑render loop:

// src/components/ChatBox.tsx
const [messages, setMessages] = useState<string[]>([]);
const [input, setInput] = useState("");

async function send() {
  const res = await fetch("/api/chat", {
    method: "POST",
    body: JSON.stringify({ prompt: input }),
  });
  const { reply } = await res.json();
  setMessages([...messages, input, reply]);
  setInput("");
}

It worked, but every new feature—function calling, streaming, multi‑modal inputs—required me to sprinkle ad‑hoc flags and custom payload shapes throughout the codebase. The result was a brittle “chat glue” that broke whenever the back‑end model changed its JSON schema or when we tried to reuse the component in a different product.

The core issues were:

  1. No shared contract – the front‑end assumed a response shape that the back‑end could silently evolve.
  2. Hard‑coded transport – we were locked into a single /api/chat endpoint, making it difficult to move to edge functions or serverless providers.
  3. Testing nightmare – unit tests had to mock the entire LLM response, and any change in the schema required a cascade of test updates.

What AG‑UI promises

The AG‑UI protocol (Agent‑Generated UI) defines three things:

Piece Description
Message envelope A JSON wrapper that carries type, payload, metadata and optional stream_id.
Capability schema A JSON‑Schema document that enumerates the agent’s functions, required parameters, and UI hints (e.g., button labels, input types).
Version negotiation A protocol_version field that lets the client and server agree on a contract version before any payload exchange.

By adhering to this contract, you get:

  • Interoperability – any AG‑UI‑compliant back‑end (OpenAI, Anthropic, self‑hosted Llama) can be swapped without touching the UI.
  • Testability – you can validate the schema once and reuse it across unit, integration, and contract tests.
  • Future‑proofing – version negotiation lets you evolve the protocol without breaking existing clients.

Verification note: The AG‑UI protocol is currently a community‑driven specification hosted on GitHub (https://github.com/ag-ui/spec). Its stability and versioning policy are still evolving, so treat it as “beta‑grade” for production use.


Getting Started: Adding the AG‑UI SDK to a Next.js Project

Install the package

The reference implementation lives under the @ag-ui/react NPM scope. In a fresh Next.js 14 app (app router) run:

npm i @ag-ui/react@latest @ag-ui/core@latest
# or with pnpm
pnpm add @ag-ui/react @ag-ui/core

Both packages are pure TypeScript and have peer dependencies on react@^18.2.0 and next@^14.0.0. The SDK ships with a tiny runtime that handles envelope serialization, version negotiation, and a React hook (useAgent) that abstracts the fetch logic.

Bootstrap a minimal UI

Create a new component under src/components/AgentUI.tsx:

import { useAgent } from "@ag-ui/react";
import type { AgentMessage } from "@ag-ui/core";

export default function AgentUI() {
  const { send, messages, isLoading } = useAgent({
    endpoint: "/api/agent",
    protocolVersion: "1.0",
  });

  const [input, setInput] = useState("");

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await send({ type: "user_message", payload: { text: input } });
    setInput("");
  };

  return (
    <div className="max-w-xl mx-auto p-4">
      <ul className="space-y-2">
        {messages.map((msg: AgentMessage, i) => (
          <li key={i} className={msg.type === "assistant" ? "text-blue-600" : ""}>
            {msg.payload?.text ?? JSON.stringify(msg.payload)}
          </li>
        ))}
      </ul>

      <form onSubmit={handleSubmit} className="mt-4 flex gap-2">
        <input
          className="flex-1 p-2 border rounded"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask me anything…"
          disabled={isLoading}
        />
        <button type="submit" className="px-4 py-2 bg-indigo-600 text-white rounded" disabled={isLoading}>
          Send
        </button>
      </form>
    </div>
  );
}

The useAgent hook does three things for you:

  1. Negotiates the protocol version with the server (via a GET /api/agent/version call).
  2. Serializes outgoing messages into the AG‑UI envelope.
  3. Deserializes incoming envelopes and pushes them into the messages array.

All of this is hidden behind a tiny API surface, which means you can replace the hook with a custom implementation later without touching the UI markup.


Defining Agent Capabilities with the AG‑UI Schema

TypeScript definitions

The protocol encourages you to keep a capability schema alongside your front‑end code. In src/agent/agent-schema.json you might have:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://example.com/agent-schema.json",
  "title": "Customer Support Agent",
  "type": "object",
  "properties": {
    "functions": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "name": { "type": "string" },
          "description": { "type": "string" },
          "parameters": {
            "type": "object",
            "additionalProperties": { "$ref": "#/definitions/parameter" }
          },
          "ui": {
            "type": "object",
            "properties": {
              "buttonLabel": { "type": "string" },
              "inputHints": { "type": "object", "additionalProperties": { "type": "string" } }
            },
            "required": ["buttonLabel"]
          }
        },
        "required": ["name", "description", "parameters"]
      }
    }
  },
  "required": ["functions"],
  "definitions": {
    "parameter": {
      "type": "object",
      "properties": {
        "type": { "enum": ["string", "number", "boolean"] },
        "description": { "type": "string" },
        "enum": { "type": "array", "items": { "type": "string" } }
      },
      "required": ["type"]
    }
  }
}

This JSON‑Schema tells the UI exactly which functions the agent can invoke (e.g., lookupOrder, scheduleCallback) and provides UI hints such as button labels. The SDK ships a helper loadAgentSchema that you can call in a useEffect to expose the schema to your components:

import { loadAgentSchema } from "@ag-ui/react";

useEffect(() => {
  loadAgentSchema("/agent/agent-schema.json")
    .then(setSchema)
    .catch(console.error);
}, []);

Now you can render dynamic UI elements based on the schema, keeping the front‑end declarative and data‑driven.

Example: Rendering a function button

function FunctionBar({ schema }: { schema: AgentSchema }) {
  return (
    <div className="flex gap-2 mt-2">
      {schema.functions.map((fn) => (
        <button
          key={fn.name}
          className="px-3 py-1 bg-gray-200 rounded"
          onClick={() => send({ type: "function_call", payload: { name: fn.name } })}
        >
          {fn.ui?.buttonLabel ?? fn.name}
        </button>
      ))}
    </div>
  );
}

Because the UI is driven by the schema, adding a new function on the back‑end is as simple as updating agent-schema.json and redeploying—no component code changes required.


Wiring the UI to LLM Backends

Serverless API route in Next.js

Next.js lets you expose an edge‑compatible route with a single file under src/app/api/agent/route.ts. Below is a minimal implementation that respects the AG‑UI contract:

// src/app/api/agent/route.ts
import { NextResponse } from "next/server";
import { parseEnvelope, createEnvelope } from "@ag-ui/core";
import { getModelResponse } from "@/lib/llm";

export async function GET() {
  // Respond with the protocol version the server supports
  return NextResponse.json({ protocol_version: "1.0" });
}

export async function POST(req: Request) {
  const raw = await req.json();
  const envelope = parseEnvelope(raw);

  // Simple routing based on envelope.type
  if (envelope.type === "user_message") {
    const llmReply = await getModelResponse(envelope.payload.text);
    const replyEnvelope = createEnvelope({
      type: "assistant",
      payload: { text: llmReply },
      metadata: { timestamp: Date.now() },
    });
    return NextResponse.json(replyEnvelope);
  }

  // Fallback for unsupported types
  return NextResponse.json(
    createEnvelope({
      type: "error",
      payload: { message: "Unsupported message type" },
    }),
    { status: 400 }
  );
}

A few notes:

  • Edge runtime – By placing the file under src/app/api, Next.js automatically treats it as an Edge Function (if you set "runtime": "edge" in next.config.js). This reduces latency for chat‑like interactions.
  • Streaming – If you need token‑by‑token streaming, replace NextResponse.json with new TransformStream() and pipe the LLM’s streaming output into AG‑UI envelopes. The SDK’s useAgent hook can handle EventSource streams out of the box.

Streaming responses with Edge Functions

// src/app/api/agent/route.ts (streaming variant)
export async function POST(req: Request) {
  const raw = await req.json();
  const envelope = parseEnvelope(raw);
  if (envelope.type !== "user_message") {
    return NextResponse.json(
      createEnvelope({ type: "error", payload: { message: "Invalid type" } }),
      { status: 400 }
    );
  }

  const { readable, writable } = new TransformStream();
  const writer = writable.getWriter();

  // Assume getStreamingResponse returns an async iterator of strings
  (async () => {
    for await (const token of getStreamingResponse(envelope.payload.text)) {
      const chunk = createEnvelope({
        type: "assistant",
        payload: { text: token },
        stream_id: envelope.id,
      });
      await writer.write(JSON.stringify(chunk) + "\n");
    }
    await writer.close();
  })();

  return new Response(readable, {
    headers: { "Content-Type": "text/event-stream" },
  });
}

The front‑end can now listen to the stream via the SDK’s useAgent hook, which parses each line as a separate envelope and appends it to the message list.


State Management & Interoperability

Using React Context + Zustand

While the SDK maintains an internal message buffer, most production apps need a global store to share conversation state across pages (e.g., a “history” view). I prefer Zustand for its minimal boilerplate and TypeScript friendliness.

// src/store/agentStore.ts
import { create } from "zustand";
import type { AgentMessage } from "@ag-ui/core";

type AgentState = {
  conversations: Record<string, AgentMessage[]>;
  activeId: string;
  addMessage: (conversationId: string, msg: AgentMessage) => void;
  setActive: (id: string) => void;
};

export const useAgentStore = create<AgentState>((set) => ({
  conversations: {},
  activeId: "default",
  addMessage: (cid, msg) =>
    set((s) => ({
      conversations: {
        ...s.conversations,
        [cid]: [...(s.conversations[cid] ?? []), msg],
      },
    })),
  setActive: (id) => set({ activeId: id }),
}));

Now you can wire the useAgent hook to push messages into the store:

const { send, messages } = useAgent({ endpoint: "/api/agent", protocolVersion: "1.0" });
const activeId = useAgentStore((s) => s.activeId);
const addMessage = useAgentStore((s) => s.addMessage);

useEffect(() => {
  messages.forEach((msg) => addMessage(activeId, msg));
}, [messages, activeId, addMessage]);

Because the store is decoupled from the UI component, you can render the same conversation in a separate /history/[id] page without re‑fetching from the back‑end.

Persisting conversation state across pages

Next.js 14’s app router supports server components that can read from a shared cache. To keep the conversation alive after a full page reload, I store the active conversation ID in a signed HTTP‑only cookie:

// src/app/api/agent/session/route.ts
import { NextResponse } from "next/server";

export async function GET() {
  const cookie = req.headers.get("cookie") ?? "";
  const match = cookie.match(/conversation_id=([^;]+)/);
  const id = match ? match[1] : crypto.randomUUID();

  const res = NextResponse.json({ conversation_id: id });
  res.headers.set(
    "Set-Cookie",
    `conversation_id=${id}; HttpOnly; Path=/; Max-Age=86400; SameSite=Lax`
  );
  return res;
}

On the client side, read the cookie once during app initialization and feed it into the store:

useEffect(() => {
  fetch("/api/agent/session")
    .then((r) => r.json())
    .then(({ conversation_id }) => useAgentStore.getState().setActive(conversation_id));
}, []);

Now every page that uses useAgentStore automatically syncs to the same conversation, regardless of navigation method.


Testing and Versioning the UI Contract

Contract tests with Jest and @open-wc/testing

Because the AG‑UI envelope is a pure JSON object, you can validate it against the schema using the ajv library. I keep a contract test in tests/agent-contract.test.ts:

import Ajv from "ajv";
import schema from "../src/agent/agent-schema.json";
import { createEnvelope, parseEnvelope } from "@ag-ui/core";

const ajv = new Ajv({ allErrors: true });
const validate = ajv.compile(schema);

test("assistant envelope conforms to schema", () => {
  const envelope = createEnvelope({
    type: "assistant",
    payload: { text: "Hello world" },
  });

  const parsed = parseEnvelope(envelope);
  const valid = validate(parsed);
  expect(valid).toBe(true);
  if (!valid) console.error(validate.errors);
});

Running this test on every CI build guarantees that any change to the envelope generation logic stays compatible with the declared capabilities.

Version bump strategy (semantic)

The protocol version lives in two places:

  1. Server – GET /api/agent/version returns { protocol_version: "1.0" }.
  2. Client – useAgent({ protocolVersion: "1.0" }).

When you introduce a breaking change to the envelope (e.g., rename payload.text to payload.message), bump the server version to 2.0. The client should then be updated to request 2.0. To avoid accidental mismatches, I enforce a runtime guard:

// src/lib/protocolGuard.ts
export async function ensureProtocolMatch(endpoint: string, clientVersion: string) {
  const res = await fetch(`${endpoint}/version`);
  const { protocol_version } = await res.json();
  if (protocol_version !== clientVersion) {
    throw new Error(
      `Protocol version mismatch: server ${protocol_version}, client ${clientVersion}`
    );
  }
}

Call this guard inside useAgent’s initialization. If the versions diverge, the UI fails fast, prompting a coordinated rollout.


Deploying and Observability

Edge runtime considerations

When you deploy to Vercel or Cloudflare Workers, the Edge runtime imposes limits on cold start time and memory. The AG‑UI SDK is lightweight (< 15 KB gzipped), but the LLM call can dominate latency. To keep the edge function snappy:

  • Cache the model response for identical prompts using a KV store (e.g., Vercel Edge Config or Cloudflare Workers KV).
  • Set Cache-Control: s-maxage=60 on successful responses so downstream CDN nodes can serve repeated queries without hitting the LLM again.
return NextResponse.json(replyEnvelope, {
  headers: { "Cache-Control": "s-maxage=60, stale-while-revalidate=30" },
});

Logging and tracing with OpenTelemetry

Observability is crucial when you have multiple agents and streaming responses. I instrument the API route with OpenTelemetry’s Node.js SDK:

import { trace } from "@opentelemetry/api";
import { getNodeTracerProvider } from "@opentelemetry/sdk-node";

const provider = getNodeTracerProvider();
provider.register();

const tracer = trace.getTracer("ag-ui-server");

export async function POST(req: Request) {
  return tracer.startActiveSpan("agent-request", async (span) => {
    try {
      const raw = await req.json();
      const envelope = parseEnvelope(raw);
      // ...process...
      span.setAttribute("agui.message.type", envelope.type);
      return NextResponse.json(replyEnvelope);
    } catch (err) {
      span.recordException(err);
      throw err;
    } finally {
      span.end();
    }
  });
}

When paired with a backend like Honeycomb or Datadog, you get a per‑request trace that shows the negotiation, LLM call latency, and any streaming chunks. This visibility helps you spot bottlenecks before they surface in production.


Common Gotchas and When to Pull Back

Browser compatibility

The AG‑UI protocol itself is just JSON, but the SDK’s streaming support relies on EventSource (Server‑Sent Events) or ReadableStream. Older browsers (IE11, early Safari) lack native support. If you need to support them, polyfill with eventsource-polyfill and avoid the edge‑only streaming path.

Rate limiting and token budgeting

Because the UI can trigger arbitrary function calls, it’s easy to unintentionally hammer the LLM endpoint. I recommend:

  • Debounce user input – only send a request after a 300 ms pause.
  • Enforce a per‑conversation token budget – track metadata.tokens_used in each envelope and stop further calls once a threshold (e.g., 4 k tokens) is reached.
  • Expose a “reset” button that clears the conversation and token counter.

Verification note: The exact token‑budget field (metadata.tokens_used) is a convention used by many AG‑UI implementations but is not mandated by the official spec.


Wrap‑up: When to Adopt AG‑UI and When to Roll Your Own

If you’re building a single‑purpose chatbot that talks to a fixed OpenAI model, the overhead of a full protocol may feel unnecessary. A simple fetch‑loop can be sufficient, and you’ll avoid the extra dependency surface.

However, in the scenarios where I’ve found the AG‑UI protocol indispensable:

  • Multiple agents (e.g., a support bot, a code‑assistant, a data‑retrieval agent) share the same UI shell.
  • Cross‑team ownership – front‑end and back‑end squads evolve independently; a contract prevents accidental breakage.
  • Regulatory or audit requirements – the envelope’s metadata field lets you inject request IDs, user IDs, and compliance tags without touching business logic.
  • Future model swaps – moving from GPT‑4 to a self‑hosted Llama 3 model becomes a one‑line config change.

Adopting the AG‑UI protocol is not a silver bullet; it introduces a small learning curve and a dependency on the community spec. But for most mid‑size to large teams that need maintainable, interoperable AI agent interfaces, the trade‑off is worth it. Start with the minimal SDK integration shown above, lock down the schema early, and let the contract guide your evolution. When the spec stabilizes, you’ll thank yourself for having a version‑negotiated contract instead of a spaghetti‑coded fetch loop.

If you want a concrete example of embedding an agent with AG‑UI in a Next.js app, check out our related post on that topic: /blog/embed-ai-agents-react-nextjs-ag-ui. For deeper patterns around AI‑driven code review pipelines, see /blog/ai-agent-code-review-patterns.

Conclusion

AG-UI is worth adopting when more than one interface will talk to the same agents, because the contract is what saves you from rewriting each one. It is not worth adopting for a single chat widget you could build in a day. The deciding question is whether the UI contract will outlive the UI.

The protocol is only half of the integration: embedding AI agents in React and Next.js covers the streaming and state side, and AI agent development is where I build these contracts for a living. The specification itself lives at docs.ag-ui.com. If you are deciding between this and a custom contract, tell me what your agents need to do.

Frequently asked questions

Do I need AG-UI to build an AI agent interface in React?

No. A single chat panel can talk to your own endpoint with a typed request and a streamed response. AG-UI pays for itself when several interfaces share the same agents, or when the agent and the UI are built by different people, because then the protocol is the contract between them.

Does the AG-UI protocol keep my API keys out of the browser?

The protocol does not do that on its own. Secrets stay server-side because the agent runs behind a server endpoint, which is a deployment decision. If a client calls a model provider directly, no protocol will hide the key it sent.

How do I test an AG-UI integration?

Treat the message envelope as a schema and test against it: assert the shape of what the agent emits, and replay recorded envelopes against the UI. That catches the breakage you care about when the specification or your agent changes.

What happens if the AG-UI specification changes?

Pin the version you build against and keep the translation in one module, so a specification change touches that module rather than every component. The specification is still moving, so plan for one migration rather than assuming stability.