> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agnost.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# CopilotKit

> Capture CopilotKit runtime agent runs with session, user, model, and tool data

## Choose a setup method

| Method | Use it when |
| - | - |
| **Agnost AI skill** | You want your coding agent to inspect the app, make the change, and verify it. |
| **Agnost AI SDK** | You want explicit control over the interaction boundaries and fields. |
| **OpenTelemetry** | The framework already emits useful spans or you operate an OTel pipeline. |

Start with one method for a call path. Combining SDK tracking with framework
OpenTelemetry on the same call can create duplicate interactions.

## Recommended: Agnost AI skill

> [!NOTE]
>
> **Recommended.** Choose this path when you want your coding agent to inspect the
> project, select a supported transport, make the smallest instrumentation change,
> send a test event, and verify that it reached Agnost AI.

Install the skill once in your coding-agent environment:

```bash theme={null}
npx skills add AgnostAI/skills --skill agnost-ai
```

Run the framework-specific prompt below from the application root. Review the
resulting diff before deploying it.

```text theme={null}
Use the agnost-ai skill to add Agnost AI analytics to this CopilotKit application.
Org ID: your-org-id
Instrument the real CopilotRuntime agent run (BuiltInAgent factory) and verify one fresh interaction.
```

This guide covers the CopilotKit v2 runtime (`@copilotkit/runtime/v2`) with a
`BuiltInAgent` in factory mode, where your code owns the `streamText()` call.
If your `CopilotRuntime` fronts an agent built with another framework, such as
[LangGraph](https://docs.agnost.ai/langchain.md), [Mastra](https://docs.agnost.ai/mastra.md), [CrewAI](https://docs.agnost.ai/crewai.md), [Agno](https://docs.agnost.ai/agno.md),
or [Pydantic AI](https://docs.agnost.ai/pydantic-ai.md), instrument that agent with its own guide.

## Manual setup: Agnost AI SDK

Record one event per agent run. The CopilotKit thread becomes the Agnost AI
conversation.

```bash theme={null}
npm install agnostai @copilotkit/runtime ai@^6 @ai-sdk/anthropic@^3
```

```typescript theme={null}
import * as agnost from 'agnostai';
import {
  BuiltInAgent,
  CopilotRuntime,
  InMemoryAgentRunner,
  convertMessagesToVercelAISDKMessages,
  convertToolsToVercelAITools,
} from '@copilotkit/runtime/v2';
import { anthropic } from '@ai-sdk/anthropic';
import { stepCountIs, streamText } from 'ai';

agnost.init(process.env.AGNOST_ORG_ID!);

// Replace with your own auth lookup (session cookie, JWT, ...).
async function getUserId(request: Request) {
  return request.headers.get('x-user-id') ?? 'anonymous';
}

function createAgent(userId: string) {
  return new BuiltInAgent({
    type: 'aisdk',
    factory: ({ input, abortSignal }) => {
      const lastUser = [...input.messages].reverse().find((m) => m.role === 'user');
      const prompt = typeof lastUser?.content === 'string' ? lastUser.content : JSON.stringify(lastUser?.content ?? '');

      const interaction = agnost.begin({
        userId,
        agentName: 'copilotkit-agent',
        input: prompt,
        conversationId: input.threadId, // one CopilotKit thread = one conversation
      });
      if (!interaction) throw new Error('Agnost is not initialized. Call agnost.init() first.');

      return streamText({
        model: anthropic('claude-haiku-4-5'),
        system: 'You are a helpful assistant.',
        messages: convertMessagesToVercelAISDKMessages(input.messages),
        tools: convertToolsToVercelAITools(input.tools),
        stopWhen: stepCountIs(5),
        abortSignal,
        onFinish: ({ steps }) => {
          interaction.end(steps.map((step) => step.text).filter(Boolean).join('\n'));
        },
        onError: ({ error }) => {
          interaction.end(String(error), false);
        },
        onAbort: () => {
          interaction.end('Run aborted', false);
        },
      });
    },
  });
}

export const runtime = new CopilotRuntime({
  agents: async ({ request }) => ({ default: createAgent(await getUserId(request)) }),
  runner: new InMemoryAgentRunner(),
});
```

The `agents` factory runs once per request, so each run knows the signed-in
user. Serve `runtime` with your usual CopilotKit endpoint, for example
`createCopilotRuntimeHandler`, `createCopilotNodeListener`, or the Express and
Hono adapters.

Call `await agnost.shutdown()` once when the application exits, not after each request.

## Manual setup: OpenTelemetry

The Vercel AI SDK inside a factory-mode `BuiltInAgent` emits `ai.*` spans for
each run, model step, and tool call. Send them to Agnost AI and put the
CopilotKit `threadId` and your user ID in the telemetry metadata.

### Install

`@copilotkit/runtime` 1.90 depends on `ai` 6.x. Install the same major so your
factory and the runtime share one copy of the AI SDK.

**Already have `@opentelemetry/sdk-node` and an OTLP exporter?** Install only the
CopilotKit and AI SDK packages.

**No OTel set up yet?**

```bash theme={null}
npm install @copilotkit/runtime ai@^6 @ai-sdk/anthropic@^3 zod \
  @opentelemetry/sdk-node @opentelemetry/sdk-trace @opentelemetry/exporter-trace-otlp-proto
```

### Setup

**1. Start the OTel SDK before the runtime loads** (for example in Next.js
`instrumentation.ts`, or the first import of your server entry file):

```typescript theme={null}
import { NodeSDK } from '@opentelemetry/sdk-node';
import { BatchSpanProcessor } from '@opentelemetry/sdk-trace';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';

export const otelSdk = new NodeSDK({
  serviceName: 'my-copilotkit-runtime',
  spanProcessors: [
    new BatchSpanProcessor({
      exporter: new OTLPTraceExporter({
        url: 'https://otel.agnost.ai/v1/traces',
        headers: { 'X-Agnost-Org-ID': process.env.AGNOST_ORG_ID! },
      }),
    }),
  ],
});
otelSdk.start();
```

**Already exporting OTel?** Add the Agnost AI `BatchSpanProcessor` above to the
`spanProcessors` array of your existing `NodeSDK` or tracer provider.

**2. Turn on AI SDK telemetry in the factory:**

```typescript theme={null}
import {
  BuiltInAgent,
  CopilotRuntime,
  InMemoryAgentRunner,
  convertMessagesToVercelAISDKMessages,
  convertToolsToVercelAITools,
} from '@copilotkit/runtime/v2';
import { anthropic } from '@ai-sdk/anthropic';
import { stepCountIs, streamText, tool } from 'ai';
import { z } from 'zod';

// Replace with your own auth lookup (session cookie, JWT, ...).
async function getUserId(request: Request) {
  return request.headers.get('x-user-id') ?? 'anonymous';
}

const getWeather = tool({
  description: 'Get the weather for a city',
  inputSchema: z.object({ city: z.string() }),
  execute: async ({ city }) => ({ city, forecast: 'sunny', celsius: 22 }),
});

function createAgent(userId: string) {
  return new BuiltInAgent({
    type: 'aisdk',
    factory: ({ input, abortSignal }) =>
      streamText({
        model: anthropic('claude-haiku-4-5'),
        system: 'You are a helpful assistant.',
        messages: convertMessagesToVercelAISDKMessages(input.messages),
        tools: { ...convertToolsToVercelAITools(input.tools), getWeather },
        stopWhen: stepCountIs(5),
        abortSignal,
        experimental_telemetry: {
          isEnabled: true,
          functionId: 'copilotkit-agent',
          metadata: { sessionId: input.threadId, userId },
        },
      }),
  });
}

export const runtime = new CopilotRuntime({
  agents: async ({ request }) => ({ default: createAgent(await getUserId(request)) }),
  runner: new InMemoryAgentRunner(),
});
```

`metadata.sessionId` and `metadata.userId` become `ai.telemetry.metadata.sessionId`
and `ai.telemetry.metadata.userId` on every span. Agnost AI uses them for
conversation grouping and user attribution. `convertToolsToVercelAITools(input.tools)`
passes the frontend tools registered in the browser; server tools such as
`getWeather` run on the server and show up as tool events.

### What appears in Agnost AI

* **Conversations** grouped by the CopilotKit `threadId`.
* **User-level analytics** grouped by the user ID you put in `metadata`.
* **Events** for each run (`ai.streamText`), each model step (`ai.streamText.doStream`), and each server tool call (named after the tool).

### Verify

Send one chat message through your CopilotKit UI, then open **Conversations**
in Agnost AI. Confirm the conversation uses the thread ID, has your user ID,
and shows the user message and assistant reply. If the agent called a server
tool, confirm a tool event with its arguments and result.

### Troubleshooting

* Start the OTel SDK before `@copilotkit/runtime` and `ai` are imported. Spans created before `otelSdk.start()` are not exported.
* Use `BuiltInAgent` with `type: 'aisdk'`. The classic config (`model: 'openai/...'`) calls `streamText()` without telemetry, so no `ai.*` spans are created.
* Keep `ai` on the major version that `@copilotkit/runtime` depends on (6.x for 1.90). AI SDK 7 uses a different telemetry API.
* Confirm `X-Agnost-Org-ID` is set on the exporter and the URL ends in `/v1/traces`.
* In short-lived scripts, call `await otelSdk.shutdown()` before exit so the batch is flushed.

### References

* [CopilotKit: use your own LLM backend (factory mode)](https://docs.copilotkit.ai/backend/custom-agent)
* [AI SDK 6 telemetry](https://github.com/vercel/ai/blob/release-v6.0/content/docs/03-ai-sdk-core/60-telemetry.mdx)
* [Agnost AI OpenTelemetry](https://docs.agnost.ai/otel.md)

## Next steps

* [Conversations](https://docs.agnost.ai/using-conversations.md): review each CopilotKit thread as one conversation.
* [Events](https://docs.agnost.ai/using-events.md): inspect model steps and tool calls.
* [Patterns](https://docs.agnost.ai/using-patterns.md): organize production conversations by what users wanted.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.