Skip to content

CopilotKit Quickstart

Run an AG2 agent behind an AG-UI 1.0 endpoint and connect a CopilotKit UI to it. The AG2 weather sample contains the Python server and the Next.js app used below, and shows sub-agents, human approval and shared state next to a plain chat.

Prerequisites#

  • Python 3.11–3.15 and uv
  • Node.js 20.9 or newer and pnpm
  • An OpenAI API key for the sample agent

The backend depends on ag2[ag-ui,openai]>=1.1.2,<2; the UI on @copilotkit/react-core and @copilotkit/runtime 1.76.0 and @ag-ui/client 1.0.1.

Run the sample#

The sample serves the agent only to a signed-in user, so both processes share a secret that signs and verifies the user's access token. Generate any long random string and use the same value for both.

Clone the sample and start its AG2 backend from the repository root:

git clone https://github.com/ag2ai/ag2-samples.git
cd ag2-samples
uv sync
export OPENAI_API_KEY="your-openai-api-key"
export AUTH_SECRET="a-long-random-string"
uv run python -m backend

The server listens on port 8000. Its AG-UI endpoint is /weather/ in this sample. The basic server example uses /chat instead; use the URL configured by the server you actually start.

In another terminal, from the repository root, start the UI with the same secret:

cd ui
pnpm install
AUTH_SECRET="a-long-random-string" pnpm dev

Open http://localhost:3000, enter a name to sign in, and ask for the weather in a city. The UI sends the run to the Python endpoint and renders its streamed AG-UI events. You can also ask about your location if you allow browser location access.

The sign-in is a demonstration

The sample accepts any name and keeps the token in localStorage. Replace verify_access_token in backend/auth.py and the token route in the UI before reusing the pattern. See Authentication for protecting the AG2 endpoint.

Starting from a generated project

Run npx copilotkit@latest init, select AG2 in the prompts, then use the install and start commands it prints. The generated project's layout and endpoint may differ from the weather sample.

What the sample shows#

AG-UI 1.0 feature Backend Frontend Try it
Delegations (SUBAGENT_* events) ClothingAdvisor and TripPlanner, wrapped with Agent.as_tool() agent.subscribe(...) in a side panel "What should I wear in Oslo?"
Interrupts save_favorite_city is held by ApprovalRequired useInterrupt renders Approve and Reject, and resolve(true) or resolve(false) answers "Save Lisbon to my favorites"
Shared state (STATE_SNAPSHOT) context.variables useAgent reads agent.state Save a city, then watch the panel
Capabilities GET /weather/ returns stream.capabilities() curl localhost:8000/weather/
Frontend tools useFrontendTool registers getUserLocation "What's the weather here?"

Connect your own AG2 agent#

Serve the agent with AGUIStream, as shown in the AG-UI overview. Then register an HttpAgent pointed at that endpoint in your CopilotKit runtime. The sample's runtime route (ui/app/api/copilotkit/route.ts) is the whole wiring:

ui/app/api/copilotkit/route.ts
import { HttpAgent } from "@ag-ui/client";
import { NextRequest } from "next/server";
import {
  CopilotRuntime,
  createCopilotRuntimeHandler,
} from "@copilotkit/runtime/v2";

export const POST = async (req: NextRequest) => {
  const runtime = new CopilotRuntime({
    agents: {
      agenticChatAgent: new HttpAgent({
        url: "http://localhost:8000/weather/",
        headers: { Authorization: req.headers.get("authorization") ?? "" },
      }),
    },
  });

  return createCopilotRuntimeHandler({
    runtime,
    basePath: "/api/copilotkit",
    mode: "single-route",
  })(req);
};

The agent is built per request so the caller's Authorization header can be forwarded to the AG2 server. If your endpoint needs no credentials, create the runtime once at module level and drop headers.

On the page, wrap the chat in the CopilotKit provider and name the same agent:

import { CopilotKit } from "@copilotkit/react-core/v2";

<CopilotKit agent="agenticChatAgent" runtimeUrl="/api/copilotkit">
  {children}
</CopilotKit>

Hooks such as useAgent, useInterrupt, useFrontendTool and useRenderTool come from @copilotkit/react-core/v2 as well. CopilotKit's route and component APIs differ across major versions; use the CopilotKit AG2 integration guide for the version you install.

The backend and CopilotKit runtime are separate processes. Both routes need protecting as appropriate for your deployment.

Interrupts that require resume proof

useInterrupt().resolve() and .cancel() send no metadata in the resume entry. That is enough for a gated tool call like the sample's save_favorite_city, but not for a server running with require_resume_proof=True. See Asking the human a question.

Check the connection#

If chat does not stream, check these in order:

  1. The AG2 backend is running and the configured HttpAgent URL points to its AG-UI endpoint.
  2. The endpoint responds to a valid POST with Content-Type: text/event-stream.
  3. The Next.js runtime route can reach the backend; check its server logs for connection errors.
  4. If the backend answers 401, the access token is missing or was signed with a different AUTH_SECRET than the backend's.
  5. If the browser calls AG2 directly, allow the frontend origin and required headers in the backend's CORS settings.

For frontend tools, shared state, and human input, see Backend deep dive, Shared state, and Asking the human a question. A client that resumes an AG2 interrupt on a server with require_resume_proof=True must copy the interrupt's metadata into its resume entry.