Skip to navigation

Instrument a custom agent loop

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.
  • 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 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:

SpanAttributeEffect on the run
Agent invocationgen_ai.operation.name set to invoke_agentOpens and closes the run. Its end time completes the run.
Agent invocationgen_ai.agent.nameSets the agent name shown on the run.
Agent invocationgen_ai.conversation.idGroups runs that belong to the same conversation.
Agent invocationuser.idSets the end-user ID.
Model callgen_ai.operation.name set to chat, generate_content, or text_completionRecords one model call.
Model callgen_ai.request.model, gen_ai.response.modelIdentifies the model and prices the call.
Model callgen_ai.usage.input_tokens, gen_ai.usage.output_tokensRecords token counts and calculates the cost estimate.
Model callgen_ai.usage.cache_read.input_tokens, gen_ai.usage.cache_creation.input_tokensRecords prompt-cache token counts.
Model callgen_ai.input.messages, gen_ai.output.messagesRecords prompts and model replies for the run transcript.
Tool callgen_ai.operation.name set to execute_toolRecords one tool call.
Tool callgen_ai.tool.name, gen_ai.tool.call.idSets the tool name and call ID.
Tool callgen_ai.tool.call.arguments, gen_ai.tool.call.resultRecords 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
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.

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
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
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.

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.

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
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
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
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:

FieldRequiredDescription
executionIdYesThe run’s ID, up to 255 characters. Can’t start with otel-.
agentIdYesThe receiving agent’s ID, up to 255 characters.
agentNameNoThe agent name shown on the run, up to 255 characters.
inputMessagesNoUp to 500 { "role", "content" } objects that form the run’s transcript.
eventsYes1 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.

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

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.

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: