> 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 custom agent loop

> Instrument a custom agent loop with OpenTelemetry GenAI spans, configure product ingest keys or shared collectors, or send runs without OpenTelemetry.

Instrument a custom agent loop so its OpenTelemetry generative AI (GenAI) spans appear as runs in Runtype.

## Before you begin

Before you instrument your loop, prepare the following:

* An OpenTelemetry SDK with an OpenTelemetry Protocol (OTLP) over HTTP trace exporter, unless you use compatibility ingest. For exporter setup, flushing before process exit, and creating a telemetry API key, see [Instrument a supported framework](/connect/instrument-a-supported-framework).
* A product ingest key or a telemetry API key:
  * **Product ingest key**: sends OTLP traces only to one product and creates agents by name from traces. Run `runtype-connect init` when you [connect a repository](/connect/connect-a-repository) to create one.
  * **Telemetry API key**: sends OTLP traces or compatibility ingest batches to existing agents that you name by ID (`TELEMETRY:WRITE` or `AGENTS:WRITE` scope). Open **Agents** in the dashboard, click **New agent**, and copy its `agent_` ID.

## Emit OpenTelemetry GenAI spans

Emit spans that follow the OpenTelemetry GenAI semantic conventions. Runtype creates a run for any trace that contains a GenAI operation or model telemetry. A trace without either stays in **Logs** as a diagnostic and creates no run.

The following table lists the span attributes that Runtype reads for a custom loop:

| Span             | Attribute                                                                          | Effect on the run                                         |
| ---------------- | ---------------------------------------------------------------------------------- | --------------------------------------------------------- |
| Agent invocation | `gen_ai.operation.name` set to `invoke_agent`                                      | Opens and closes the run. Its end time completes the run. |
| Agent invocation | `gen_ai.agent.name`                                                                | Sets the agent name shown on the run.                     |
| Agent invocation | `gen_ai.conversation.id`                                                           | Groups runs that belong to the same conversation.         |
| Agent invocation | `user.id`                                                                          | Sets the end-user ID.                                     |
| Model call       | `gen_ai.operation.name` set to `chat`, `generate_content`, or `text_completion`    | Records one model call.                                   |
| Model call       | `gen_ai.request.model`, `gen_ai.response.model`                                    | Identifies the model and prices the call.                 |
| Model call       | `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`                          | Records token counts and calculates the cost estimate.    |
| Model call       | `gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.cache_creation.input_tokens` | Records prompt-cache token counts.                        |
| Model call       | `gen_ai.input.messages`, `gen_ai.output.messages`                                  | Records prompts and model replies for the run transcript. |
| Tool call        | `gen_ai.operation.name` set to `execute_tool`                                      | Records one tool call.                                    |
| Tool call        | `gen_ai.tool.name`, `gen_ai.tool.call.id`                                          | Sets the tool name and call ID.                           |
| Tool call        | `gen_ai.tool.call.arguments`, `gen_ai.tool.call.result`                            | Records tool inputs and outputs.                          |

To mark a run as failed, set the `invoke_agent` span's status to `ERROR`.

The following TypeScript sample opens an `invoke_agent` span with one child `chat` span and one child `execute_tool` span:

**`Custom agent loop`**

```typescript title="Custom agent loop"
import { trace, SpanStatusCode } from '@opentelemetry/api'

const tracer = trace.getTracer('support-agent')

await tracer.startActiveSpan(
  'invoke_agent support-agent',
  async (agentSpan) => {
    agentSpan.setAttributes({
      'gen_ai.operation.name': 'invoke_agent',
      'gen_ai.agent.name': 'support-agent',
      'gen_ai.conversation.id': conversationId,
      'user.id': userId,
    })
    try {
      const reply = await tracer.startActiveSpan(
        'chat claude-sonnet-5',
        async (chatSpan) => {
          try {
            const response = await callModel(messages)
            chatSpan.setAttributes({
              'gen_ai.operation.name': 'chat',
              'gen_ai.request.model': 'claude-sonnet-5',
              'gen_ai.usage.input_tokens': response.usage.inputTokens,
              'gen_ai.usage.output_tokens': response.usage.outputTokens,
              'gen_ai.input.messages': JSON.stringify(messages),
              'gen_ai.output.messages': JSON.stringify(response.messages),
            })
            return response
          } finally {
            chatSpan.end()
          }
        }
      )
      await tracer.startActiveSpan(
        'execute_tool lookup_order',
        async (toolSpan) => {
          try {
            toolSpan.setAttributes({
              'gen_ai.operation.name': 'execute_tool',
              'gen_ai.tool.name': 'lookup_order',
              'gen_ai.tool.call.id': reply.toolCallId,
              'gen_ai.tool.call.arguments': JSON.stringify(
                reply.toolArguments
              ),
            })
            const result = await lookupOrder(reply.toolArguments)
            toolSpan.setAttribute(
              'gen_ai.tool.call.result',
              JSON.stringify(result)
            )
          } finally {
            toolSpan.end()
          }
        }
      )
    } catch (error) {
      agentSpan.recordException(error as Error)
      agentSpan.setStatus({ code: SpanStatusCode.ERROR })
      throw error
    } finally {
      agentSpan.end()
    }
  }
)
```

In this sample, `conversationId`, `userId`, `messages`, `callModel`, and `lookupOrder` belong to your application. Use opaque values for `gen_ai.conversation.id` and `user.id`, not personally identifiable information (PII) or credentials. Runtype stores these values as you send them. It replaces a value with a stable digest only when scrubbing or PII redaction would change the value, or when the value exceeds 256 bytes. For system instructions (`gen_ai.system_instructions`), tool definitions (`gen_ai.tool.definitions`), and content redaction, see [Control what content is sent](/connect/control-what-content-is-sent).

Run your agent once. Then open the receiving agent's **Runs** view in Runtype to confirm that the run shows its model calls and tool calls.

## Send traces with a product ingest key

The `runtype-connect init` command creates a product ingest key that can send traces only to one product. It writes `RUNTYPE_INGEST_KEY`, `RUNTYPE_OTLP_URL` (`https://api.runtype.com/v1/otel/v1/traces`), and `RUNTYPE_ENVIRONMENT` (default `development`) to `.env`.

Configure your OTLP HTTP exporter to read the `.env` values written by `runtype-connect init`:

**`Exporter options`**

```typescript title="Exporter options"
const exporterOptions = {
  url: process.env.RUNTYPE_OTLP_URL,
  headers: {
    authorization: `Bearer ${process.env.RUNTYPE_INGEST_KEY}`,
  },
}
```

Set the `deployment.environment.name` resource attribute from `process.env.RUNTYPE_ENVIRONMENT`.

If your OpenTelemetry SDK reads standard `OTEL_` environment variables instead, set the following:

**`Environment variables`**

```bash title="Environment variables"
OTEL_EXPORTER_OTLP_ENDPOINT=https://api.runtype.com/v1/otel
OTEL_EXPORTER_OTLP_HEADERS=authorization=Bearer rt_YOUR_INGEST_KEY
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=development
```

Replace `rt_YOUR_INGEST_KEY` with your product ingest key.

With a product ingest key, Runtype resolves the agent for each trace in the following order:

1. A `runtype.agent.id` attribute on the resource, `invoke_agent` span, or root span wins over any agent name. The agent must be in that product or not in any product.
2. Otherwise, Runtype reads the agent name and creates an agent of that name in the product the first time that name appears. Later traces with the same name reuse that agent.
3. The `x-runtype-agent-id` header applies only when the trace names no agent.

For the agent-name fallback order and every attribute Runtype reads, see [Trace attributes](/reference/trace-attributes).

A product can create at most 50 agents from traces. Runtype refuses a trace that names a 51st agent with `agent_limit_reached`.

When a span names a different agent from its enclosing agent span, Runtype creates a separate run under that agent. The parent run records the handoff as a `subagent` tool call. One trace can hold at most 20 runs, and Runtype refuses a trace that needs more with `run_limit_reached`.

If a trace never names an agent and the resource sets a custom `service.name`, Runtype uses `service.name` after the trace is idle for 10 minutes.

Set the environment on the `deployment.environment.name` resource attribute. Runtype treats `production` and `prod` as production, regardless of case, and treats any other value or an absent attribute as development. Trace queries and the first-trace check keep production and development runs apart.

For monthly span limits and plan quotas, see [Limits and pricing](/reference/limits-and-pricing).

## Send several services through one collector

When an OpenTelemetry Collector exports several services in one request with a telemetry API key, identify each service with a `runtype.agent.id` resource attribute:

**`Per-service attribution`**

```bash title="Per-service attribution"
OTEL_RESOURCE_ATTRIBUTES=runtype.agent.id=agent_YOUR_AGENT_ID
```

Replace `agent_YOUR_AGENT_ID` with the ID of the Runtype agent for that service.

For each trace, Runtype resolves the receiving agent in the following order:

1. The `runtype.agent.id` resource attribute.
2. The `x-runtype-agent-id` HTTP header.
3. The `runtype.agent.id` attribute on the `invoke_agent` span or root span.

### Run several agents in one process

If one process runs several agents with a telemetry API key, set `runtype.agent.id` on the `invoke_agent` span that opens each run:

**`Per-run attribution`**

```typescript title="Per-run attribution"
span.setAttribute('runtype.agent.id', 'agent_YOUR_AGENT_ID')
```

Replace `agent_YOUR_AGENT_ID` with the ID of the Runtype agent for that run.

Leave both the `x-runtype-agent-id` header and the `runtype.agent.id` resource attribute unset in that process. Either one takes precedence over the span attribute and routes every run to the agent it names.

If two `invoke_agent` spans in one trace name different agents without a resource or header agent ID, Runtype rejects the trace as `ambiguous_agent_attribution`.

When agents delegate inside one trace, set the agent on the resource or header, or export each invocation as its own trace. To give each agent in a handoff its own run, use a product ingest key instead.

## Use compatibility ingest without OpenTelemetry

Use OTLP when your code already emits OpenTelemetry spans. Use compatibility ingest when it doesn't.

Send a `POST` request to the compatibility ingest endpoint with a telemetry API key (`TELEMETRY:WRITE` or `AGENTS:WRITE` scope). A product ingest key can't call this endpoint and returns `403`.

The following `curl` request sends a minimal completed run to the compatibility ingest endpoint:

**`cURL`**

```bash title="cURL"
curl -X POST https://api.runtype.com/v1/executions/ingest \
  -H "Authorization: Bearer rt_YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "executionId": "YOUR_EXECUTION_ID",
    "agentId": "agent_YOUR_AGENT_ID",
    "inputMessages": [
      { "role": "user", "content": "Where is order 1042?" }
    ],
    "events": [
      {
        "type": "execution_start",
        "executionId": "YOUR_EXECUTION_ID",
        "seq": 0,
        "kind": "agent",
        "startedAt": "2026-01-01T00:00:00Z"
      },
      {
        "type": "execution_complete",
        "executionId": "YOUR_EXECUTION_ID",
        "seq": 1,
        "kind": "agent",
        "success": true
      }
    ]
  }'
```

Replace the following:

* `rt_YOUR_API_KEY`: your telemetry API key.
* `agent_YOUR_AGENT_ID`: the ID of the receiving Runtype agent.
* `YOUR_EXECUTION_ID`: a unique ID for the run.

The following table describes the request body fields:

| Field           | Required | Description                                                                                                |
| --------------- | -------- | ---------------------------------------------------------------------------------------------------------- |
| `executionId`   | Yes      | The run's ID, up to 255 characters. Can't start with `otel-`.                                              |
| `agentId`       | Yes      | The receiving agent's ID, up to 255 characters.                                                            |
| `agentName`     | No       | The agent name shown on the run, up to 255 characters.                                                     |
| `inputMessages` | No       | Up to 500 `{ "role", "content" }` objects that form the run's transcript.                                  |
| `events`        | Yes      | 1 to 500 events. Each event needs a `type`, the same `executionId`, and a `seq` integer of `0` or greater. |

To send more than 500 events, send several batches with the same `executionId`. A later batch updates the run, for example to complete a run or a tool call that an earlier batch opened.

Runtype accepts updates for eight days after it first receives the run. After that, the endpoint returns `409`. Don't retry that execution ID. For the full event schema, see the [API Reference](/api-reference/overview).

The endpoint returns `202` with a body similar to the following:

**`202 response`**

```json title="202 response"
{
  "accepted": 2,
  "executionId": "YOUR_EXECUTION_ID",
  "execution": "created",
  "toolCalls": 0,
  "status": "completed"
}
```

Errors use the same status codes as the OTLP endpoint. A `500` response means Runtype couldn't store the batch, so retry it. For status codes and fixes, see [Troubleshooting](/reference/troubleshooting).

Runs from compatibility ingest appear in the receiving agent's **Runs** view and eval capture, with a transcript when you send `inputMessages`.

## Next steps

Continue with one of these guides:

* [Send a first trace](/connect/send-a-first-trace): run your instrumented agent and verify its spans with the first-trace check.
* [Read traces and runs](/analyze/read-traces-and-runs): count runs and inspect individual run details.
* [Working with runs](https://platform-docs.runtype.com/user-guide/logs/working-with-runs): inspect imported runs in the dashboard.