> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.runtype.com/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.runtype.com/_mcp/server.

# Instrument a supported framework

> Send OpenTelemetry traces from a supported agent framework to Runtype with a telemetry API key or framework adapter.

Follow this guide to send telemetry by hand from an agent that runs outside Runtype. Use it when you already have a Runtype agent ID, or when your framework isn't the Vercel AI SDK, LangGraph, the OpenAI Agents SDK, Pydantic AI, or plain OpenTelemetry. Your agent keeps using its own model provider and credentials, and Runtype displays each imported run on the receiving agent's **Runs** view.

> **Tip**
>
> To connect a repository with a product ingest key instead of creating an agent and telemetry API key by hand, open **Connect an agent** in the dashboard. It gives you `npx @runtypelabs/connect` to run in your repository root and a prompt for your coding agent. For the walkthrough, see [Connect a repository](/connect/connect-a-repository) and [Send a first trace](/connect/send-a-first-trace).

Choose the setup path for your framework in the following table:

| Framework                                                    | Setup path                                 | Where to start                                                                    |
| ------------------------------------------------------------ | ------------------------------------------ | --------------------------------------------------------------------------------- |
| Flue                                                         | Runtype adapter and OpenTelemetry exporter | [Instrument a Flue agent](/connect/instrument-a-flue-agent)                       |
| Vercel AI SDK, LangGraph, OpenAI Agents SDK, Mastra          | OpenTelemetry exporter                     | [Send traces from a supported framework](#send-traces-from-a-supported-framework) |
| OpenClaw                                                     | Runtype adapter                            | [OpenClaw adapter](#openclaw-adapter)                                             |
| Hermes                                                       | Runtype adapter                            | [Hermes adapter](#hermes-adapter)                                                 |
| Pi                                                           | Runtype adapter                            | [Pi adapter](#pi-adapter)                                                         |
| Pydantic AI                                                  | Runtype adapter                            | [Pydantic AI adapter](#pydantic-ai-adapter)                                       |
| Cloudflare Agents SDK (retryable per-request delivery, beta) | Runtype adapter                            | [Cloudflare Agents SDK adapter](#cloudflare-agents-sdk-adapter)                   |
| Cloudflare Agents SDK (no code, Workers Observability)       | Cloudflare dashboard                       | [Cloudflare Agents SDK](#cloudflare-agents-sdk)                                   |

If your agent is authored in Runtype and self-hosted with `@runtypelabs/runtime`, configure `telemetry` with `enabled: true` and `apiKey` instead. For details, see [Self-hosting (BYOC)](https://platform-docs.runtype.com/developer-guides/guides/self-hosting).

## Before you begin

Before you configure your exporter or adapter, confirm that you have the following:

* A Runtype agent that receives the runs. Create one on the **Agents** page (**New agent**) or through the API, and copy its `agent_...` ID. Runtype rejects a trace that names no agent.
* An API key with the `TELEMETRY:WRITE` scope (`AGENTS:WRITE` also works). For setup steps, see [Create a telemetry API key](#create-a-telemetry-api-key).
* An OpenTelemetry SDK with an OpenTelemetry Protocol (OTLP) over HTTP trace exporter, unless you use a Runtype adapter that includes one or Cloudflare Workers Observability.

## Create a telemetry API key

Create a telemetry API key on the **API keys** page in **Settings**. Select the **Telemetry Ingest** permission group, which grants the `TELEMETRY:WRITE` scope.

To request a telemetry-only key from the `runtype` CLI and approve it in your browser, install `@runtypelabs/cli` (`npm i -g @runtypelabs/cli`), sign in with `runtype login`, and run a command similar to the following:

**`Request a telemetry key`**

```bash title="Request a telemetry key"
runtype keys request --name "Support agent telemetry" --scopes TELEMETRY:WRITE --env test --reason "Send Support agent traces to Runtype" --inline
```

Use a key that can only send telemetry, because it often ends up in collector files and shared environments. Each framework section names the environment variable or header that stores the key.

## Configure the OTLP/HTTP exporter

For a framework that uses an OpenTelemetry SDK, set the base OTLP endpoint, headers, and protocol:

**`Environment variables`**

```bash title="Environment variables"
OTEL_EXPORTER_OTLP_ENDPOINT=https://api.runtype.com/v1/otel
OTEL_EXPORTER_OTLP_HEADERS=authorization=Bearer rt_YOUR_TELEMETRY_KEY,x-runtype-agent-id=agent_YOUR_AGENT_ID
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
```

Replace the following:

* `rt_YOUR_TELEMETRY_KEY`: your telemetry API key.
* `agent_YOUR_AGENT_ID`: the ID of the Runtype agent that receives the runs.

OpenTelemetry adds `/v1/traces` to this base URL. Runtype accepts OTLP over HTTP, not gRPC.

Restart your agent after you set these variables. The next exported run appears on the receiving agent's **Runs** view.

## Configure the exporter in code

If your application builds its OpenTelemetry pipeline in code, configure the HTTP trace exporter with the full traces URL.

For a Node.js application, configure `NodeSDK` and `OTLPTraceExporter` in TypeScript:

**`TypeScript SDK`**

```typescript title="TypeScript SDK"
import { NodeSDK } from '@opentelemetry/sdk-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'

const sdk = new NodeSDK({
  traceExporter: new OTLPTraceExporter({
    url: 'https://api.runtype.com/v1/otel/v1/traces',
    headers: {
      authorization: `Bearer ${process.env.RUNTYPE_API_KEY}`,
      'x-runtype-agent-id': 'agent_YOUR_AGENT_ID',
    },
  }),
})
sdk.start()

process.once('beforeExit', () => void sdk.shutdown().catch(console.error))
```

Replace `agent_YOUR_AGENT_ID` with the ID of the receiving Runtype agent, and set `RUNTYPE_API_KEY` to your telemetry API key.

For a Python application, install `opentelemetry-exporter-otlp-proto-http` and configure `OTLPSpanExporter`:

**`Python SDK`**

```python title="Python SDK"
import os

from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

exporter = OTLPSpanExporter(
  endpoint="https://api.runtype.com/v1/otel/v1/traces",
  headers={
    "authorization": f"Bearer {os.environ['RUNTYPE_API_KEY']}",
    "x-runtype-agent-id": "agent_YOUR_AGENT_ID",
  },
)
provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(exporter))
trace.set_tracer_provider(provider)
```

Replace `agent_YOUR_AGENT_ID` with the ID of the receiving Runtype agent, and set `RUNTYPE_API_KEY` to your telemetry API key.

## Flush before the process exits

A batch span processor sends spans every few seconds. If your process exits first, the run's closing span is lost and the run stays in progress. Short-lived processes, such as CLI commands and serverless handlers, drop the closing span unless you flush before exit.

In a Node.js `instrumentation.ts` file that owns the SDK or tracer provider, register the `beforeExit` shutdown hook shown in [Configure the exporter in code](#configure-the-exporter-in-code). For specific frameworks and runtimes, flush as follows:

* **Mastra**: call `await mastra.shutdown()` inside a `finally` block so failed runs also flush their closing span.
* **Serverless handlers**: call `await provider.forceFlush()` before the handler returns, because a frozen invocation never emits `beforeExit`.
* **LangGraph and OpenAI Agents SDK**: call `provider.force_flush()` before a short-lived script exits.
* **Pydantic AI**: in tests or short-lived handlers that check for a run right away, call `force_flush()` on the handle that `instrument()` returns.

Catch errors from `forceFlush` in a `finally` block so a telemetry failure doesn't fail the response:

**`Flush in a serverless handler`**

```typescript title="Flush in a serverless handler"
export async function handler(request: Request): Promise<Response> {
  try {
    return await runAgent(request)
  } finally {
    await provider.forceFlush().catch((error) => {
      console.error('Telemetry flush failed', error)
    })
  }
}
```

In this example, `runAgent` is your agent code and `provider` is the tracer provider you registered.

## Verify that runs arrive

To test the traces endpoint, your API key, and the content type before running your agent, send an empty OTLP/JSON export:

**`cURL smoke test`**

```bash title="cURL smoke test"
curl -X POST https://api.runtype.com/v1/otel/v1/traces \
  -H "Authorization: Bearer rt_YOUR_TELEMETRY_KEY" \
  -H "Content-Type: application/json" \
  -d '{"resourceSpans": []}'
```

Replace `rt_YOUR_TELEMETRY_KEY` with your telemetry API key. Runtype returns `HTTP 200` with `{}` when it accepts the request.

After your agent finishes a run, open the receiving agent's **Runs** view in the dashboard to inspect the imported run. For API and MCP queries over imported runs, see [Read traces and runs](/analyze/read-traces-and-runs).

## Send traces from a supported framework

Each framework in the following table needs an OpenTelemetry tracer provider and OTLP/HTTP exporter behind its instrumentation. Instrumentation without an exporter emits spans that never reach Runtype.

| Framework         | What to install                                                                                                                             | What to enable                                                         |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| Flue              | `@flue/runtime`, `@runtypelabs/flue-otel`, `@opentelemetry/api`, `@opentelemetry/sdk-trace-node`, `@opentelemetry/exporter-trace-otlp-http` | `instrument(createRuntypeFlueInstrumentation())`                       |
| Vercel AI SDK     | `@opentelemetry/sdk-node`, `@opentelemetry/exporter-trace-otlp-proto`                                                                       | `experimental_telemetry: { isEnabled: true, functionId: 'my-agent' }`  |
| LangGraph         | `openinference-instrumentation-langchain`, `opentelemetry-exporter-otlp-proto-http`                                                         | `LangChainInstrumentor().instrument(tracer_provider=provider)`         |
| OpenAI Agents SDK | `openinference-instrumentation-openai-agents`, `opentelemetry-exporter-otlp-proto-http`                                                     | `OpenAIAgentsInstrumentor().instrument(tracer_provider=provider)`      |
| Mastra            | `@mastra/core`, `@mastra/observability`, `@mastra/otel-exporter`, `@opentelemetry/exporter-trace-otlp-proto`                                | An `OtelExporter` on the `Mastra` constructor's `observability` config |

Load your instrumentation file before the agent runs. For example, import `instrumentation.ts` (Flue or the Vercel AI SDK) or `instrumentation.py` (LangGraph or the OpenAI Agents SDK) at the top of your entry point. The Vercel AI SDK turns telemetry on per `generateText` or `streamText` call. With a product ingest key, `functionId` names the agent. For Mastra, configure `OtelExporter` in your `Mastra` constructor and call `mastra.shutdown()` after your agent run.

Mastra's `OtelExporter` ignores the `OTEL_EXPORTER_OTLP_*` variables, so pass the full traces URL and headers to it directly. Set `RUNTYPE_AGENT_ID` and `RUNTYPE_API_KEY` in your `.env` file:

**`Mastra environment`**

```bash title="Mastra environment"
RUNTYPE_AGENT_ID=agent_YOUR_AGENT_ID
RUNTYPE_API_KEY=rt_YOUR_TELEMETRY_KEY
```

Replace the following:

* `agent_YOUR_AGENT_ID`: the ID of the receiving Runtype agent.
* `rt_YOUR_TELEMETRY_KEY`: your telemetry API key.

Import `Observability` from `@mastra/observability` and pass the exporter in `observability.configs.otel.exporters`:

**`Mastra`**

```typescript title="Mastra"
observability: new Observability({
  configs: {
    otel: {
      exporters: [
        new OtelExporter({
          provider: {
            custom: {
              endpoint: 'https://api.runtype.com/v1/otel/v1/traces',
              headers: {
                authorization: `Bearer ${process.env.RUNTYPE_API_KEY}`,
                'x-runtype-agent-id': process.env.RUNTYPE_AGENT_ID,
              },
              protocol: 'http/protobuf',
            },
          },
        }),
      ],
    },
  },
})
```

Install `@opentelemetry/exporter-trace-otlp-proto` alongside `@mastra/otel-exporter`, because `@mastra/otel-exporter` doesn't install it.

For conversation content rules across frameworks, see [Control what content is sent](/connect/control-what-content-is-sent).

### OpenClaw adapter

The OpenClaw plugin uses Gateway hooks to send one trace per agent turn, with the model call and each completed tool call. You don't need a separate OpenTelemetry provider.

Review the plugin and its requested capabilities before granting conversation access. To install and enable `@runtypelabs/openclaw-adapter`, run these commands:

**`OpenClaw CLI`**

```bash title="OpenClaw CLI"
openclaw plugins install @runtypelabs/openclaw-adapter
openclaw plugins enable runtype
openclaw config set plugins.entries.runtype.hooks.allowConversationAccess true --strict-json
```

The last command lets the plugin read conversation content.

Set these environment variables on the OpenClaw Gateway process (the plugin doesn't read a project `.env` file):

**`Gateway environment`**

```bash title="Gateway environment"
RUNTYPE_AGENT_ID=agent_YOUR_AGENT_ID
RUNTYPE_API_KEY=rt_YOUR_TELEMETRY_KEY
RUNTYPE_CAPTURE_CONTENT=true
```

Replace the following:

* `agent_YOUR_AGENT_ID`: the ID of the receiving Runtype agent.
* `rt_YOUR_TELEMETRY_KEY`: a `TELEMETRY:WRITE` API key.

The adapter posts to `https://api.runtype.com/v1/otel/v1/traces` by default. To send traces to another URL, set `RUNTYPE_OTLP_URL` to the full OTLP traces URL.

Restart the Gateway to load the plugin and verify its runtime hooks:

**`Check OpenClaw plugin`**

```bash title="Check OpenClaw plugin"
openclaw gateway restart
openclaw plugins inspect runtype --runtime
```

Content capture is off by default. Set `RUNTYPE_CAPTURE_CONTENT=true` to send bounded prompt, answer, system-instruction, and tool content (up to 32 KiB per value) for transcripts and eval capture. Omit that line for metadata-only traces. The plugin redacts `RUNTYPE_API_KEY` and environment variable values whose names match secret patterns. That filter can't identify every secret in free-form content.

Send an OpenClaw message after restarting the Gateway, then open the receiving agent's **Runs** view. Telemetry errors don't fail the agent turn, and a failed export isn't retried.

### Hermes adapter

The Hermes plugin sends one OTLP trace per observed agent turn. You don't need a separate OpenTelemetry provider.

Install and enable the plugin from its public repository:

**`Hermes CLI`**

```bash title="Hermes CLI"
hermes plugins install runtypelabs/hermes-runtype-otel --enable
```

The plugin doesn't read a project `.env` file. Set these variables in the Hermes gateway or CLI process environment, or in its profile `.env` file:

**`Hermes environment`**

```bash title="Hermes environment"
RUNTYPE_AGENT_ID=agent_YOUR_AGENT_ID
RUNTYPE_OTEL_API_KEY=rt_YOUR_TELEMETRY_KEY
RUNTYPE_OTEL_ENDPOINT=https://api.runtype.com/v1/otel/v1/traces
RUNTYPE_OTEL_CAPTURE_CONTENT=true
```

Replace the following:

* `agent_YOUR_AGENT_ID`: the ID of the receiving Runtype agent.
* `rt_YOUR_TELEMETRY_KEY`: a `TELEMETRY:WRITE` API key.

Set `RUNTYPE_OTEL_CAPTURE_CONTENT=true` to send conversation content for transcripts and eval capture, or set `RUNTYPE_OTEL_CAPTURE_CONTENT=false` for metadata-only traces.

Restart a running gateway with `hermes gateway restart`, then send a message. Each exported turn appears on the receiving agent's **Runs** view.

### Pi adapter

`@runtypelabs/pi-otel` reports [Pi](https://pi.dev) agent runs directly over OTLP/JSON, so you don't need a separate OpenTelemetry provider. It exposes one binding for each Pi runtime:

* `@runtypelabs/pi-otel/coding-agent`: an extension for the Pi coding agent (`@earendil-works/pi-coding-agent`).
* `@runtypelabs/pi-otel/durable`: an observer for a `pi-durable` harness (`@earendil-works/pi-durable` `1.x`), including Cloudflare `PiHarness`.

Each Pi run becomes one Runtype run and shows a cost estimate. Report each Pi run through one producer only, because sending the same run through two producers duplicates spans, tokens, and cost.

#### Pi coding agent

Install the package with the Pi package manager:

**`Pi CLI`**

```bash title="Pi CLI"
pi install npm:@runtypelabs/pi-otel
```

Set these variables in the shell that starts Pi:

**`Shell environment`**

```bash title="Shell environment"
export RUNTYPE_AGENT_ID=agent_YOUR_AGENT_ID
export RUNTYPE_API_KEY=rt_YOUR_TELEMETRY_KEY
export RUNTYPE_CAPTURE_CONTENT=true
```

Replace the following:

* `agent_YOUR_AGENT_ID`: the ID of the receiving Runtype agent.
* `rt_YOUR_TELEMETRY_KEY`: a `TELEMETRY:WRITE` API key.

The extension posts to `https://api.runtype.com/v1/otel/v1/traces` by default. To send traces to another URL, set `RUNTYPE_OTLP_URL` to the full OTLP traces URL.

Content capture is off by default because coding sessions often carry source code. Set `RUNTYPE_CAPTURE_CONTENT=true` to send prompts, answers, system prompts, and tool content, or omit that line for metadata-only traces.

Start `pi` in the same shell and send a prompt. Each prompt becomes one run and appears on the receiving agent's **Runs** view after Pi finishes answering. Without `RUNTYPE_API_KEY` or `RUNTYPE_AGENT_ID`, the extension stays inactive. Set `RUNTYPE_DEBUG=true` to log diagnostics to stderr.

#### pi-durable and PiHarness

Install the package next to `@earendil-works/pi-durable`:

**`Terminal`**

```bash title="Terminal"
npm install @runtypelabs/pi-otel
```

Call `observePiDurable` right after opening the harness and await `recover` before work resumes. With Cloudflare `PiHarness`, run both inside the harness factory before returning the harness:

**`PiHarness factory`**

```ts title="PiHarness factory"
import { observePiDurable } from '@runtypelabs/pi-otel/durable'

harness: async ({ storage, context }) => {
  const pi = await Harness.open(storage, { models, registry }, context)
  this.telemetry = observePiDurable(pi, {
    agentId: this.env.RUNTYPE_AGENT_ID,
    apiKey: this.env.RUNTYPE_API_KEY,
    harnessId: this.ctx.id.toString(),
  })
  await this.telemetry.recover(context)
  return pi
}
```

Set `harnessId` to a stable ID for the harness's storage, such as `this.ctx.id.toString()` in a Durable Object. Call `recover()` so a run interrupted by a restart finishes as the same run. Attach before the harness resumes work, not through `this.harness.pi()`.

Each input submission becomes one run, and Runtype records a submission that ends `unanswered` as a failed run. In a Worker, pass `this.telemetry.flush()` to `ctx.waitUntil` after each prompt. In Node.js, call `await observer.flush()` before exiting.

The durable binding sends content by default. Pass `content: false` for metadata-only traces, set an individual kind to `false` (for example, `content: { systemInstructions: false }`), or pass a `redact` function to rewrite or omit values before export. For all options, see the [@runtypelabs/pi-otel README](https://www.npmjs.com/package/@runtypelabs/pi-otel).

### Pydantic AI adapter

`runtype-pydantic-ai` reports [Pydantic AI](https://ai.pydantic.dev) agent runs. It supports `pydantic-ai` 1.90 and later, including 2.x, and includes its own exporter. Each top-level agent run becomes one run in Runtype.

To configure the adapter, follow these steps:

1. Install the package:

   **`Terminal`**

   ```bash title="Terminal"
   pip install runtype-pydantic-ai
   ```

2. Set the telemetry API key and receiving agent ID in your shell or deployment environment:

   **`Shell environment`**

   ```bash title="Shell environment"
   export RUNTYPE_API_KEY=rt_YOUR_TELEMETRY_KEY
   export RUNTYPE_AGENT_ID=agent_YOUR_AGENT_ID
   ```

   Replace `rt_YOUR_TELEMETRY_KEY` with a `TELEMETRY:WRITE` API key and `agent_YOUR_AGENT_ID` with the receiving agent's ID. The adapter posts to `https://api.runtype.com/v1/otel/v1/traces` by default. To send traces to another URL, set `RUNTYPE_OTLP_URL` to the full OTLP traces URL.

3. Call `instrument()` once at startup, before the first agent run:

   **`Your entry point`**

   ```python title="Your entry point"
   import runtype_pydantic_ai

   runtype_pydantic_ai.instrument()
   ```

   Every `Agent` in the process is now traced, and each run appears on the receiving agent's **Runs** view a few seconds after it ends.

If your application uses Logfire, call `instrument()` after `logfire.configure()` so the adapter joins Logfire's tracer provider. You can also pass the span processor to Logfire directly:

**`With Logfire`**

```python title="With Logfire"
import logfire
import runtype_pydantic_ai

logfire.configure(additional_span_processors=[runtype_pydantic_ai.span_processor()])
logfire.instrument_pydantic_ai(include_content=True, version=5)
```

Logfire keeps receiving its spans unchanged.

To route several Pydantic AI agents to different Runtype agents, map them by name with `instrument(agent_ids={"support": "agent_YOUR_AGENT_ID"})`, or wrap a call in `with runtype_pydantic_ai.runtype_agent("agent_YOUR_AGENT_ID"):`. A sub-agent called from a tool stays part of the outer run.

The adapter sends the transcript, system instructions, tool arguments, and tool results by default, including any personal data in your prompts. Pass `content=False` for metadata-only traces, or pass `ContentOptions` to disable individual content kinds or redact values before export. Exception messages and stack traces never reach Runtype. Failed runs report the exception class name only. For all options, see the [runtype-pydantic-ai package page](https://pypi.org/project/runtype-pydantic-ai/).

### Cloudflare Agents SDK adapter

`@runtypelabs/cloudflare-agents` is a beta npm package for Cloudflare Agents SDK Workers that need to record each user request even when the connection drops. Choose this adapter for reliable per-request delivery. Choose [Cloudflare Agents SDK](#cloudflare-agents-sdk) for a no-code Workers Observability setup. The adapter is validated against `agents@0.22.0`, `@cloudflare/ai-chat@0.11.0`, and `ai@6.0.277`.

The adapter stores each request in a Durable Object in your Worker (`RuntypeOtlpOutbox`) and sends it to Runtype directly.

Configure the following server-side Worker bindings alongside your `AIChatAgent`:

* `RUNTYPE_AGENT_ID`: the ID of the receiving Runtype agent.
* `RUNTYPE_API_KEY`: a `TELEMETRY:WRITE` key stored with `wrangler secret put`.
* `RUNTYPE_BASE_URL`: `https://api.runtype.com`.

Keep all three bindings server-side. Never send `RUNTYPE_API_KEY` to a browser, WebSocket frame, or client bundle. Export `RuntypeOtlpOutbox` from your Worker module and add its binding and SQLite migration in `wrangler.jsonc`:

**`wrangler.jsonc`**

```jsonc title="wrangler.jsonc"
{
  "durable_objects": {
    "bindings": [{ "name": "AdapterTelemetryOutbox", "class_name": "RuntypeOtlpOutbox" }],
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["RuntypeOtlpOutbox"] }],
}
```

Pass a stable application submission ID per user request, a separate conversation ID for attribution, and the Agents SDK request ID as `exchangeId`. Generate a new `submissionId` for an explicit rerun, and reuse the same `submissionId` for transport retries and reconnects. Don't derive these IDs from message content or position.

The following example wraps a `streamText` call inside an `AIChatAgent`:

**`Cloudflare Agents SDK adapter`**

```ts title="Cloudflare Agents SDK adapter"
import { AIChatAgent } from '@cloudflare/ai-chat'
import { streamText } from 'ai'
import {
  createDurableObserver,
  createRunIdentity,
  observeStreamTextOptions,
} from '@runtypelabs/cloudflare-agents'
import { RuntypeOtlpOutbox } from '@runtypelabs/cloudflare-agents/durable-object'

export { RuntypeOtlpOutbox }

interface Env {
  RUNTYPE_AGENT_ID: string
  RUNTYPE_API_KEY: string
  RUNTYPE_BASE_URL: string
  AdapterTelemetryOutbox: DurableObjectNamespace<RuntypeOtlpOutbox>
}

class SupportAgent extends AIChatAgent<Env> {
  async onChatMessage(onFinish, options) {
    const turn = {
      submissionId: readStableSubmissionId(options?.body),
      conversationId: readConversationId(options?.body),
      exchangeId: readStableExchangeId(options?.requestId),
      continuation: options?.continuation === true,
    }
    const identity = await createRunIdentity({
      agentId: this.env.RUNTYPE_AGENT_ID,
      submissionId: turn.submissionId,
      conversationId: turn.conversationId,
    })
    const outbox = this.env.AdapterTelemetryOutbox.get(
      this.env.AdapterTelemetryOutbox.idFromName(identity.traceId)
    )
    const stream = await observeStreamTextOptions(
      {
        model: myModel,
        system: 'Answer customer support questions concisely.',
        messages: await toModelMessages(this.messages),
        tools: myServerTools,
        abortSignal: options?.abortSignal,
        onFinish,
      },
      {
        turn,
        content: {
          messages: true,
          instructions: true,
          tools: false,
          errors: false,
        },
        observer: createDurableObserver(outbox),
      }
    )
    return streamText(stream).toUIMessageStreamResponse()
  }
}
```

In this example, `readStableSubmissionId`, `readConversationId`, `readStableExchangeId`, `myModel`, `toModelMessages`, and `myServerTools` belong to your application. Validate the IDs before calling the adapter, and keep your `streamText(...).toUIMessageStreamResponse()` call and your `abortSignal`, `onFinish`, `onError`, and `prepareStep` callbacks. The wrapper doesn't consume the response stream and runs its callbacks alongside yours.

The adapter records no content by default. Each `content` option enables one category:

* `messages`: user and assistant messages.
* `instructions`: system and developer messages, including effective instructions after `prepareStep`.
* `tools`: tool arguments and results. Tool names and durations are always recorded.
* `errors`: error text.

If you set `messages: true` and omit `instructions`, the adapter also records instructions. To record messages without instructions, set `instructions: false`.

To rewrite or drop values before storage or export, pass a `redact(kind, value)` function in `content` and return `undefined` to omit a value. After redaction, the adapter omits any value larger than 32 KiB. To lower that cap, set `maxBytes` in `content`.

A run that never reaches a final result shows as incomplete. Telemetry failures don't fail the user's response.

The adapter doesn't support approval continuations, client tools, automatic subagent trees, linking to Cloudflare traces, or approving and resuming from Runtype.

### Cloudflare Agents SDK

Use Cloudflare Workers Observability when you want a no-code setup with content off by default. For reliable per-request delivery, use the [Cloudflare Agents SDK adapter](#cloudflare-agents-sdk-adapter) instead.

A plain `AIChatAgent` that calls `streamText` emits no GenAI spans. Wrap the AI SDK once at module scope and call the wrapped namespace from `onChatMessage`:

**`Instrument the native AI SDK trace`**

```typescript title="Instrument the native AI SDK trace"
import * as ai from 'ai'
import { wrapAISDK } from 'agents/observability/ai'

export const tracedAI = wrapAISDK(ai, { storeMessages: true, storeTools: true })
```

Content recording is off unless you pass `storeMessages: true` and `storeTools: true`. Without them, the run has no transcript and you can't capture it as an eval case.

Configure the export as a Workers Observability **Traces** destination in the Cloudflare dashboard, set its endpoint and headers there, and reference the destination name in `wrangler.jsonc`. The `OTEL_EXPORTER_*` environment variables don't configure Workers Observability. Follow the destination steps in [Flue on Cloudflare Workers, no code](https://platform-docs.runtype.com/developer-guides/guides/bring-your-own-agent#flue-on-cloudflare-workers-no-code). Exporting traces requires a Cloudflare Workers Paid plan.

Keep these behaviors in mind when using Workers Observability:

* One run doesn't always equal one user request because Cloudflare can group several turns into one trace or split one request across traces.
* A cancelled or very slow turn might not create a run.
* Approval requests and decisions appear as read-only history. You can't approve or resume them from Runtype.

## Next steps

* [Control what content is sent](/connect/control-what-content-is-sent): manage conversation capture, redaction, and logging privacy.
* [Instrument a Flue agent](/connect/instrument-a-flue-agent): configure `@runtypelabs/flue-otel` options, attribution, and redaction.
* [Instrument a custom agent loop](/connect/instrument-a-custom-agent-loop): emit hand-written OpenTelemetry spans, route several services through one collector, or use product ingest keys.
* [Trace attributes](/reference/trace-attributes): inspect every span and resource attribute that Runtype reads.
* [Troubleshooting](/reference/troubleshooting): fix ingest errors and missing traces.
* [Limits and pricing](/reference/limits-and-pricing): check span limits and retention by plan.