Skip to navigation

Instrument a Flue agent

@runtypelabs/flue-otel is OpenTelemetry instrumentation from Runtype for Flue agents. Register it with Flue’s instrument() function and configure an OpenTelemetry Protocol (OTLP) exporter to send each run to Runtype. In the dashboard, you can inspect each run’s model, token usage, cost, loop iterations, tool calls, and stop reason.

Choose a path

The shortest way to connect a Flue agent depends on where it runs and what you need from Runtype. The following table compares the available paths:

Your agentUse
Deployed to Cloudflare WorkersNo code. Export Workers traces to Runtype. See Deploy on Cloudflare Workers.
On Node@runtypelabs/flue-otel, covered in this guide. It sends the transcript, system prompt, and tool content by default so you can capture runs as eval cases. Unlike a generic exporter, it reports the exact iteration count, a run-level stop reason, and the run’s total token usage.
On Node, stock instrumentation only@flue/opentelemetry. It exports conversation content by default, so runs carry a transcript and you can capture them as eval cases. Runtype derives loop structure from Flue’s own attributes. The exact iteration count and run-level stop reason are unavailable.
Called by RuntypeRegister an external agent with a runtype-stream endpoint. See Implement a runtype-stream endpoint. Combine with either telemetry path.

Before you begin

Make sure that you have the following:

  • Node 22 or later.
  • A Flue runtime (1.0.0-beta.9 or later, or Flue 2.x).
  • A Runtype agent to receive the runs, and its agent ID.
  • A telemetry API key with the Telemetry Ingest permission group (TELEMETRY:WRITE), or a key with AGENTS:WRITE.

To create the receiving agent in the dashboard, click Primitives to open Agents, then click New agent. Click Start with an empty agent, enter a name, and click Create Agent. The dashboard opens the agent at /agents/agent_YOUR_AGENT_ID, where agent_YOUR_AGENT_ID is the agent ID. To create the agent from the runtype CLI instead, run runtype agents create --name "Support agent". The command prints the agent ID.

To create a telemetry API key in the dashboard, open Settings and select API keys. Click Create API key, enter a name, select Telemetry Ingest under Permission template (optional), and click Create API key. For more information, see Create a telemetry API key.

If you ran npx @runtypelabs/connect and already have a product ingest key (RUNTYPE_INGEST_KEY), you can use it instead of a telemetry API key and omit the agent ID. Runtype accepts the trace and creates the agent from gen_ai.agent.name.

Install and start

Install @runtypelabs/flue-otel and the OpenTelemetry API:

Install
npm install @runtypelabs/flue-otel @opentelemetry/api

Register the instrumentation with Flue:

Register the instrumentation
import { instrument } from '@flue/runtime'
import { createRuntypeFlueInstrumentation } from '@runtypelabs/flue-otel'
const stopInstrumenting = instrument(createRuntypeFlueInstrumentation())

instrument() returns a disposer (stopInstrumenting). Call it to stop instrumenting. It doesn’t flush spans, so flush your provider yourself.

The package doesn’t include an OpenTelemetry SDK or exporter. Use your own, or follow Set up an OpenTelemetry pipeline. If your application already configures OpenTelemetry, add the agent resource attributes with runtypeFlueResourceAttributes({ agentId }). For attribution rules, see Attribution.

The following table lists the options that createRuntypeFlueInstrumentation() accepts:

OptionPurpose
agentNameSets the agent name that each run carries. Pass a string or a function that returns a name. See Name the agent.
agentsMaps each agent name to a Runtype agent ID. See Run several agents in one process.
tracerSets the OpenTelemetry tracer that receives spans. Defaults to the tracer of the globally registered provider. Pass a tracer to send spans for Runtype through a separate provider.
contentControls which content the spans carry. All kinds are on by default. Pass false to send no content. See Control what content is sent.

Set up an OpenTelemetry pipeline

If your application doesn’t have an OpenTelemetry pipeline, install @opentelemetry/sdk-trace-node, @opentelemetry/exporter-trace-otlp-http, and @opentelemetry/resources.

Configure the provider, exporter, and instrumentation with the following code:

Full pipeline
import { NodeTracerProvider, BatchSpanProcessor } from '@opentelemetry/sdk-trace-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { resourceFromAttributes } from '@opentelemetry/resources'
import { instrument } from '@flue/runtime'
import {
createRuntypeFlueInstrumentation,
runtypeFlueResourceAttributes,
} from '@runtypelabs/flue-otel'
const provider = new NodeTracerProvider({
resource: resourceFromAttributes({
'service.name': 'my-agent',
...runtypeFlueResourceAttributes({ agentId: process.env.RUNTYPE_AGENT_ID }),
}),
spanProcessors: [
new BatchSpanProcessor(
new OTLPTraceExporter({
url: 'https://api.runtype.com/v1/otel/v1/traces',
headers: { Authorization: `Bearer ${process.env.RUNTYPE_API_KEY}` },
}),
{ maxExportBatchSize: 32 }
),
],
})
provider.register()
const stopInstrumenting = instrument(createRuntypeFlueInstrumentation())
process.once('beforeExit', () => void provider.shutdown().catch(console.error))

Set the required environment variables before you start the process:

.env
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 Runtype agent that receives the runs.
  • rt_YOUR_TELEMETRY_KEY: your telemetry API key.

maxExportBatchSize keeps each export request small while content is on. For the reason, see Size limits.

Register the provider. Without provider.register(), each span starts its own trace and the run breaks apart.

Flush before the process exits. Otherwise, the run’s closing span is lost and the run stays in progress. In a serverless handler, run await provider.forceFlush().catch(console.error) before returning.

Verify the run

To confirm that runs reach Runtype, follow these steps:

  1. Run your agent once and let the process exit or flush.
  2. In the dashboard, open the agent and select the Runs tab.
  3. Open the run and check the iteration count, the stop reason, and the transcript.

If you set up Connect in this repository, you can also run npx @runtypelabs/connect check to verify the trace. For details, see Run the agent and check the first trace.

If the run stays in progress, the closing span didn’t arrive. Check that your application calls forceFlush() or shutdown() on the provider. If no run appears, see Troubleshooting.

Attribution: which Runtype agent owns the run

Runtype resolves the agent for each trace in this order:

  1. The runtype.agent.id resource attribute, set by runtypeFlueResourceAttributes({ agentId }).
  2. The x-runtype-agent-id request header that your exporter sends.
  3. The runtype.agent.id attribute on the run’s invoke_agent span, set by the agents option.

Use the resource attribute or request header when one process runs one Runtype agent.

Name the agent

Every run’s spans carry gen_ai.agent.name. If a trace names no agent, Runtype doesn’t record it as a run. The package takes the name from the first of these sources that is set:

  1. The agentName option.
  2. The Flue agent’s name.
  3. The workflow’s name, for a Flue 1.x workflow whose agent reports no name.
  4. flue-agent, so every run has a name.

Pass a string to give every run the same name, or pass a function that receives { agentName, workflowName } and returns a name. If the function returns undefined, the package falls through to the preceding order. The following examples configure both forms:

Name the agent
createRuntypeFlueInstrumentation({ agentName: 'onboarding' })
createRuntypeFlueInstrumentation({
agentName: ({ agentName, workflowName }) =>
workflowName === 'review' ? 'reviewer' : agentName,
})

A sub-agent that a run delegates to keeps its own name. Its flue.task span, model calls, and tool calls carry the sub-agent’s name. In a workflow that runs several agents, each agent’s spans carry that agent’s name.

Run several agents in one process

The agents keys match the name that each run carries, as described in Name the agent. When one process runs several agents, map each agent name to a Runtype agent ID with the agents option:

Per agent attribution
createRuntypeFlueInstrumentation({
agents: {
triage: 'YOUR_TRIAGE_AGENT_ID',
billing: 'YOUR_BILLING_AGENT_ID',
},
})

Replace the following:

  • YOUR_TRIAGE_AGENT_ID: the Runtype agent ID for the triage agent.
  • YOUR_BILLING_AGENT_ID: the Runtype agent ID for the billing agent.

A delegated sub-agent appears as a tool call on the parent run, not as its own run. The sub-agent’s own spans carry the sub-agent’s name.

Keep one agent invocation per trace. Spans inherit the active OpenTelemetry context. If an enclosing span remains active when two agent invocations run, both land in the same trace. An HTTP server span from auto-instrumentation commonly causes this. When two invocations share a trace, Runtype merges them into one run or rejects the trace (ambiguous_agent_attribution).

To run several agent invocations in one request or job, start each invocation in its own trace. A separate process per agent lets you set the resource attribute instead. A dispatch() call might join the caller’s trace when your application registers a trace-context propagator. To keep each dispatched invocation in its own trace, start it outside any active span.

What it emits

The instrumentation emits the following spans:

  • One run (invoke_agent) per agent invocation, with gen_ai.agent.name, model details, summed token usage, iteration count, and stop reason.
  • One model call (chat) per model turn, with gen_ai.agent.name, gen_ai.tool.definitions, provider, model, finish reason, and per-turn usage. For details on tool definitions, see Tool definitions.
  • One tool call (execute_tool) per model-requested tool call, with gen_ai.agent.name, tool name, and call ID.
  • Bookkeeping spans for delegation, compaction, and host shell calls.

When the package can identify how the run ended, it sets runtype.stop_reason to end_turn, length, content_filter, error, or unknown. A run that ends during a tool call reports unknown.

For the full list of span and resource attributes that Runtype reads, see Trace attributes.

Compose with other instrumentations

Flue’s instrument() supports multiple subscribers, so you can register this package alongside @flue/opentelemetry.

Send one Flue instrumentation to each Runtype endpoint. If this package and @flue/opentelemetry export to the same endpoint, Runtype receives two invoke_agent spans for one run and counts token usage and cost twice. You can send them to different backends.

If you already export Flue traces to Runtype with @flue/opentelemetry, replace it with this package for that endpoint.

If your application exports to another backend, pass a tracer from a separate provider that exports only to Runtype. Spans for Runtype then leave through that provider, and the rest of the process keeps its own exporter.

Control what content is sent

By default, the package sends the conversation, the final output, the system prompt, the tools offered to the model, and each tool’s arguments and result. Each kind has a switch that defaults to on. Runs need the conversation to show a transcript and to be captured as eval cases.

To send shape and cost only, with no content of any kind, pass content: false:

No content
instrument(createRuntypeFlueInstrumentation({ content: false }))

Message content

Pass these switches under content to control what the run’s invoke_agent span carries:

Message content switches
instrument(
createRuntypeFlueInstrumentation({
content: {
inputMessages: true,
outputMessages: true,
systemInstructions: false,
},
})
)

The following options control message content:

  • inputMessages: the conversation that the run’s last model turn received. Runtype shows it as the run’s transcript and uses it when you capture the run as an eval case.
  • outputMessages: the final assistant text of the run. Runtype shows it as the run’s final output.
  • systemInstructions: the system prompt. Turn it off to keep spans small.

Messages carry text only.

Tool content

Each execute_tool span carries the tool’s arguments and result, shown on the tool’s card in the trace view. To drop either, switch it off:

Tool content switches
instrument(
createRuntypeFlueInstrumentation({
content: {
toolArguments: true,
toolResults: false,
},
})
)

A delegation to a sub-agent is a tool call whose arguments carry the prompt handed to that sub-agent. To omit that prompt from the export, return undefined from redact for the delegation tool, as shown in Redact content.

Tool definitions

Each chat span carries the tools offered to the model in gen_ai.tool.definitions, with each tool’s name, description, and JSON Schema parameters. Tool definitions follow these rules:

  • toolDefinitions covers every tool offered to the model, including tools that Flue adds itself, such as read, bash, and task.
  • The package sends each distinct tool set once per run, on the first model call that offers it.
  • The package caps the value at 32 KiB. Over 32 KiB, the package drops parameter schemas first, then descriptions, then the last tools, so the value stays valid JSON.
  • redact doesn’t run on tool definitions.

To omit tool definitions, set toolDefinitions to false:

No tool definitions
instrument(
createRuntypeFlueInstrumentation({
content: { toolDefinitions: false },
})
)

Size limits

maxChars sets the longest value sent (default 64 KiB, at most 256 KiB), including the truncation marker. Each tool argument value and tool result is capped at 192 KiB. Each message value and the system prompt are capped at 128 KiB.

When a value exceeds its limit, the package shortens it:

  • A result is cut and ends with …[truncated N chars].
  • Arguments are replaced by { "truncated": "..." }, which holds the start of the JSON and the same marker so they stay a valid object.
  • A message list drops its oldest messages first, so the newest survive.

Runtype also limits the total content of one trace and drops content past that limit. For per-span and per-trace caps, see Content size limits.

One export request can carry at most 8 MiB. Set maxExportBatchSize to 16 to 32 for tool-heavy agents, or 64 for short runs.

Redact content

redact runs on every content value before encoding and truncation. It receives the value and a context object whose kind identifies the content:

kindValue it receivesWhat to return
arguments, resultThe raw tool payload (context.toolName names the tool).The value, or a replacement.
input_messages, output_messagesAn array of { role, parts: [{ type: 'text', content }] } objects.The array, or a replacement array of that shape.
system_instructionsThe system prompt as a string.A string or text parts. Anything else sends none.

Return undefined to drop that attribute. If redact throws, the package drops that attribute and sends the rest of the span.

The following example masks email addresses in the conversation and drops the prompt that a delegate tool hands to a sub-agent:

Redact content
import { instrument } from '@flue/runtime'
import {
createRuntypeFlueInstrumentation,
type FlueContentMessage,
} from '@runtypelabs/flue-otel'
const EMAIL = /[^\s@]+@[^\s@]+\.[^\s@]+/g
instrument(
createRuntypeFlueInstrumentation({
content: {
redact: (value, context) => {
if (context.kind === 'arguments' && context.toolName === 'delegate') return undefined
if (context.kind !== 'input_messages') return value
return (value as FlueContentMessage[]).map((message) => ({
...message,
parts: message.parts.map((part) => ({
...part,
content: part.content.replace(EMAIL, '[email]'),
})),
}))
},
},
})
)

What it does not send

Whatever you set, the package never sends error messages or stack traces, a failed tool’s result, shell output from the host, or thinking and image parts.

With content: false, the package sends only identifiers, structure, metrics, model IDs, token counts, durations, tool names, correlation IDs, error types, and exception class names for failed spans. This has two consequences:

  • Runs have no transcript. You can inspect timing, cost, iteration counts, and the tool call sequence, but not the exchanged text.
  • Eval capture is unavailable. Capturing an external run into an eval suite requires the transcript.

The standard @flue/opentelemetry instrumentation exports content by default. Review its exporter configuration before sending traces to a third-party backend.

Deploy on Cloudflare Workers

On Cloudflare Workers, a Flue 2 agent built with @flue/vite is traced automatically, conversation content included. You don’t install this package or an OpenTelemetry SDK. Export the Workers traces to Runtype instead.

To export Workers traces to Runtype, follow these steps:

  1. In the Cloudflare dashboard, open Workers Observability and add a Traces destination with the endpoint https://api.runtype.com/v1/otel/v1/traces and two custom headers: Authorization: Bearer rt_YOUR_TELEMETRY_KEY and x-runtype-agent-id: agent_YOUR_AGENT_ID. Replace rt_YOUR_TELEMETRY_KEY with your telemetry API key and agent_YOUR_AGENT_ID with the ID of the Runtype agent that receives the runs. Exporting Workers traces to an OTLP destination requires a Workers Paid plan.

  2. Reference the destination in wrangler.jsonc:

    wrangler.jsonc
    {
    "observability": {
    "traces": {
    "enabled": true,
    "destinations": ["runtype"],
    "head_sampling_rate": 1,
    },
    },
    }
  3. Run npx vite build && npx wrangler deploy and start a conversation. Each successful response appears under the agent’s Runs tab with a transcript, so you can capture it as an eval case.

Each response becomes its own run. A canceled response might not complete a run.

To omit content, register instrument(createCloudflareTracing({ content: false })) from @flue/runtime/cloudflare at module scope in app.ts. Runs then lose eval capture as well.

Troubleshooting

The following table lists common export problems:

SymptomCauseFix
The exporter reports 401The key is missing, invalid, or revoked.Send a valid telemetry API key in the Authorization header.
The exporter reports 403The credential isn’t a Runtype API key, or the key has neither TELEMETRY:WRITE nor AGENTS:WRITE.Send a Runtype API key with TELEMETRY:WRITE or AGENTS:WRITE.
The exporter reports 400No agent ID resolves the trace, or its invocations report different agent IDs.Set the resource attribute or the x-runtype-agent-id header. See Attribution.
The exporter reports 404The key can’t reach the agent ID that the trace names.Check the agent ID, and use a key from the organization that owns the agent.
The exporter reports 413The export request or trace is too large.Lower maxExportBatchSize or maxChars. If one trace is too large, keep one agent invocation per trace. See Size limits.
Some runs are missing, with no errorRuntype answers 200 with a partial_success body that names each rejected trace.Log the response body or check ingest health.
A run stays in progressThe closing invoke_agent span never arrived.Call forceFlush() or shutdown() on the provider before the process exits.

To check what Runtype received for a trace, see Inspect ingest health.

Next steps

Continue with these guides: