Skip to content

OpenTelemetry ​

Spectra can export AI request data to external observability platforms over the OpenTelemetry Protocol (OTLP), so you see your AI calls next to the rest of your monitoring. Each tracked AI request becomes a span in your distributed tracing system, with its provider, model, token usage, cost, latency, and status.

What Is OpenTelemetry? ​

OpenTelemetry (often abbreviated as OTel) is an open-source, vendor-neutral observability framework maintained by the Cloud Native Computing Foundation (CNCF). It defines a standard format for telemetry data (traces, metrics, and logs), and virtually every major observability platform supports it.

In practice, a trace is the full journey of a request through your system. Each step in that journey is a span. Spectra creates a span for every tracked AI request, with attributes for the provider name, model identifier, token counts, calculated cost, latency, and HTTP status code.

The main benefit of OpenTelemetry is portability. You export your traces in OTLP format once, and you can send them to any compatible backend: Jaeger, Grafana Tempo, Datadog, New Relic, Honeycomb, or dozens of others. If you switch observability vendors later, you change the endpoint configuration, not your application code.

When to Use OpenTelemetry ​

The OpenTelemetry integration is most useful when you already use an observability platform and want AI request data in the same place as the rest of your telemetry. Typical uses:

  • Correlating AI calls with other services in a distributed system to understand end-to-end request flow.
  • Setting up alerts on AI request latency, error rates, or cost thresholds through your existing alerting infrastructure.
  • Building unified dashboards that combine AI metrics with application performance metrics.
  • Meeting enterprise monitoring requirements that mandate centralized observability with retention policies and access controls.

If you only need AI observability and don't already have tracing infrastructure, the built-in Spectra dashboard may be all you need.

Setup ​

Enable the integration in config/spectra.php and provide the OTLP endpoint for your collector or backend:

php
'integrations' => [
    'opentelemetry' => [
        'enabled' => env('SPECTRA_OTEL_ENABLED', false),
        'endpoint' => env('SPECTRA_OTEL_ENDPOINT', 'http://localhost:4318/v1/traces'),
        'headers' => [],
        'service_version' => env('SPECTRA_OTEL_SERVICE_VERSION', '1.0.0'),
        'resource_attributes' => [],
        'timeout' => (int) env('SPECTRA_OTEL_TIMEOUT', 10),
    ],
],

Then set the environment variables:

ini
SPECTRA_OTEL_ENABLED=true
SPECTRA_OTEL_ENDPOINT=http://localhost:4318/v1/traces

Configuration Options ​

OptionDefaultDescription
enabledfalseWhether to export traces to the configured OTLP endpoint.
endpointhttp://localhost:4318/v1/tracesThe OTLP HTTP endpoint for your collector or observability backend.
headers[]Custom HTTP headers sent with each export request. Typically used for authentication tokens or API keys.
service_version1.0.0A version string included in trace metadata. Useful for identifying which deployment generated a given trace.
resource_attributes[]Key-value pairs added to every exported trace. Used for deployment region, Kubernetes namespace, service tier, or other infrastructure context.
timeout10HTTP timeout in seconds for OTLP export requests. Increase this if your backend is remote or slow to respond.

Compatible Backends ​

Spectra exports traces in standard OTLP HTTP format, which all major observability platforms support:

BackendTypeEndpoint Example
JaegerOpen sourcehttp://localhost:4318/v1/traces
ZipkinOpen sourcehttp://localhost:9411/api/v2/spans
Grafana TempoOpen sourcehttp://tempo:4318/v1/traces
Datadog APMCloudhttps://trace.agent.datadoghq.com/v1/traces
New RelicCloudhttps://otlp.nr-data.net:4318/v1/traces
AWS X-RayCloudVia OpenTelemetry Collector
Google Cloud TraceCloudVia OpenTelemetry Collector
HoneycombCloudhttps://api.honeycomb.io/v1/traces
LightstepCloudhttps://ingest.lightstep.com:443/traces/otlp/v0.9

TIP

The easiest way to test the OpenTelemetry integration locally is with Jaeger. Start a Jaeger instance with Docker:

shell
docker run -d --name jaeger \
  -p 16686:16686 \
  -p 4318:4318 \
  jaegertracing/all-in-one:latest

Set SPECTRA_OTEL_ENDPOINT=http://localhost:4318/v1/traces and open http://localhost:16686 to view traces in the Jaeger UI.

Authentication ​

Most cloud backends require authentication headers. Add them to the headers array in the configuration. The exact header depends on your provider:

php
'opentelemetry' => [
    'headers' => [
        // Bearer token (New Relic, Honeycomb, etc.)
        'Authorization' => 'Bearer ' . env('OTEL_AUTH_TOKEN'),

        // API key (Datadog, etc.)
        'x-api-key' => env('OTEL_API_KEY'),

        // Honeycomb-specific team key
        'x-honeycomb-team' => env('HONEYCOMB_API_KEY'),
    ],
],

Resource Attributes ​

Resource attributes are key-value pairs added to every exported trace. They describe the environment the trace came from, such as the deployment region, Kubernetes namespace, service tier, and similar infrastructure metadata. Use them to filter and group traces in your observability backend:

php
'opentelemetry' => [
    'resource_attributes' => [
        'deployment.environment' => 'production',
        'deployment.region' => 'us-east-1',
        'k8s.namespace' => 'ai-services',
        'service.team' => 'platform',
    ],
],

Export Timing ​

OpenTelemetry export follows the same persistence mode as request storage, controlled by the queue configuration:

Queue ConfigExport Behavior
queue.enabled: trueDispatched as an ExportTrackedRequestJob on your configured queue
queue.after_response: trueExported after the HTTP response is sent to the client (no added latency for the user)
Both false (default)Exported synchronously after the AI response completes

INFO

In non-HTTP contexts such as console commands and queue workers, after_response has no effect. Traces are always exported synchronously in those contexts unless queue mode is enabled.

Trace Correlation ​

Spectra assigns a trace_id to each tracked request. The same id appears in the Spectra dashboard and in the exported OpenTelemetry spans, so you can follow a single user action across multiple AI calls and external services.

Automatic Trace Ids ​

All AI calls of the same HTTP request, queued job, or Artisan command share one trace id. A queued job dispatched during a request keeps the request's trace id. Each exported span is a separate span inside that trace, so your backend shows the calls of one request together. See Traces.

Joining an Incoming Trace ​

When the incoming HTTP request has a W3C traceparent header, Spectra uses its trace id and sets the caller's span as the parent of each AI span. Your gateway, proxy, or calling service then shows the AI calls nested under its own span.

The header's 32-character trace id is stored as a UUID in the trace_id column (the same 128 bits), and the parent span id in the parent_span_id column. The exported span uses the original hex value, so it matches the caller's trace.

Turn this off with SPECTRA_USE_TRACEPARENT=false.

Spans and Parents ​

Each AI call is exported with its own stored span id, and with the span it ran in as its parent: a Spectra::span() block, or the request, job or command it ran in (see Spans). Those spans are exported too, as INTERNAL spans (SERVER for a request, CONSUMER for a job), with their attributes, so your backend shows the same tree as the dashboard. A tool is exported as execute_tool {name} with gen_ai.operation.name set to execute_tool, as the GenAI conventions name tool runs. The outermost span's parent is the incoming traceparent span.

A custom exporter receives AI calls through RequestExporter::export(). To receive the other spans as well, also implement Spectra\Contracts\ExportsSpans:

php
use Spectra\Contracts\ExportsSpans;
use Spectra\Contracts\RequestExporter;

class MyExporter implements ExportsSpans, RequestExporter
{
    public function exportSpan(array $span): void
    {
        // trace_id, span_id, parent_span_id, name, kind, origin,
        // started_at, ended_at, duration_ms, status, error_message, attributes
    }

    // export() and exportBatch() from RequestExporter
}

Custom Trace Ids ​

You can provide your own trace id to integrate with an existing tracing system. Use a UUID, or a 32-character hex OpenTelemetry trace id written as a UUID. Set it for the rest of the request or job with Spectra::withTraceId($traceId), or for one call:

php
$result = Spectra::track('openai', 'gpt-4o', function ($ctx) use ($myTraceId) {
    return OpenAI::chat()->create([
        'model' => 'gpt-4o',
        'messages' => $messages,
    ]);
}, ['trace_id' => $myTraceId]);

Where Trace Ids Appear ​

SystemLocation
Spectra DashboardThe Trace card on the request page, and the requests list filter
OpenTelemetryThe span's trace_id attribute, visible in your backend's trace view

This gives you end-to-end tracing. A user clicks "Generate Summary", which triggers an API route that calls an AI model, writes to the database, and dispatches a queue job. All of these steps share one trace id, which you can see in both Spectra and your observability platform.

Span Name and Attributes ​

The default span builder follows the current OpenTelemetry GenAI semantic conventions for client inference spans. You can read them in the semantic conventions repository.

The span name is {operation} {model}, for example chat gpt-4o. The operation (gen_ai.operation.name) is one of chat, embeddings, generate_content, text_completion, rerank, or transcription. The model is the provider's model id (the snapshot column). Spectra stores it for every request it can name, even when the response echoes the model you asked for.

Every span has these attributes:

AttributeValue
gen_ai.operation.nameThe operation, as above
gen_ai.provider.nameThe provider (openai, anthropic, ...; gcp.gemini for Google, x_ai for xAI)
gen_ai.request.modelThe model, as in the span name
gen_ai.usage.input_tokensPrompt tokens (the full prompt, including cache reads and writes)
gen_ai.usage.output_tokensCompletion tokens (the full output, including reasoning)
http.response.status_codeThe HTTP status code
spectra.trace_id, spectra.request_idSpectra's trace id and request id
spectra.modelThe model name Spectra stored
spectra.cost_centsThe total cost, in cents
spectra.latency_msThe latency, in milliseconds

These attributes are added when they have a value:

AttributeValue
gen_ai.response.modelThe model id the provider returned
gen_ai.response.idThe provider's response id
gen_ai.response.finish_reasonsThe finish reason, as an array
gen_ai.usage.cache_read.input_tokensPrompt tokens read from the cache
gen_ai.usage.cache_write.input_tokensPrompt tokens written to the cache
gen_ai.usage.reasoning.output_tokensReasoning tokens
gen_ai.request.streamtrue for streamed requests
gen_ai.conversation.idThe conversation id
error.typeThe error class (or the status code) of a failed request
spectra.endpointThe API endpoint path
spectra.model_type, spectra.pricing_tier, spectra.currencyModel type, pricing tier, and the currency of the cost
spectra.trackable.type, spectra.trackable.idThe trackable (user, team, ...)
spectra.reasoning_effort, spectra.has_tool_callsReasoning effort and tool use
spectra.time_to_first_token_ms, spectra.tokens_per_second, spectra.duration_secondsStreaming and media metrics

A failed request has the error status, with the provider's error message.

Changes from 1.x ​

The attribute names follow the current conventions since Spectra 2.0. If your dashboards or alerts use the 1.x names, see OpenTelemetry Attribute Names in the upgrade guide for the old and new names, and how to keep the old ones.

Customizing Spans ​

You can customize how spans are built by providing your own SpanBuilder implementation.

Extending the Default Builder ​

The easiest approach is to extend DefaultSpanBuilder and override only the methods you want to change. Apart from build(), its methods are protected, so you can override them one at a time:

php
use Spectra\Integrations\OpenTelemetry\DefaultSpanBuilder;

class MySpanBuilder extends DefaultSpanBuilder
{
    protected function spanName(array $data): string
    {
        return "myapp.ai.{$data['provider']}.{$data['model']}";
    }

    protected function attributes(array $data): array
    {
        $attrs = parent::attributes($data);

        // Add custom attributes
        $attrs[] = ['key' => 'myapp.team', 'value' => ['stringValue' => 'ml-platform']];

        // Remove attributes you don't want exported
        $attrs = array_filter($attrs, fn ($a) => $a['key'] !== 'spectra.cost_cents');

        return $attrs;
    }
}

Register it in config/spectra.php:

php
'opentelemetry' => [
    'span_builder' => \App\Telemetry\MySpanBuilder::class,
],

Building Spans from Scratch ​

For full control, implement the SpanBuilder contract directly. The build() method receives a data array (produced by RequestTransformer) and must return an OTLP-compatible span array:

php
use Spectra\Contracts\SpanBuilder;

class MinimalSpanBuilder implements SpanBuilder
{
    public function build(array $data): array
    {
        return [
            'traceId' => str_replace('-', '', $data['trace_id'] ?? ''),
            'spanId' => bin2hex(random_bytes(8)),
            'parentSpanId' => '',
            'name' => "llm.{$data['model']}",
            'kind' => 3,
            'startTimeUnixNano' => (string) ((int) $data['started_at']->getPreciseTimestamp(6) * 1000),
            'endTimeUnixNano' => (string) ((int) $data['completed_at']->getPreciseTimestamp(6) * 1000),
            'attributes' => [
                ['key' => 'model', 'value' => ['stringValue' => $data['model']]],
                ['key' => 'tokens', 'value' => ['intValue' => $data['total_tokens']]],
                ['key' => 'cost_cents', 'value' => ['doubleValue' => $data['total_cost_in_cents']]],
            ],
            'status' => ['code' => $data['is_failed'] ? 2 : 1],
            'events' => [],
            'links' => [],
        ];
    }
}

Available Data ​

The $data array passed to SpanBuilder::build() holds the stored request columns (without the raw request and response payloads). The main fields are:

FieldTypeDescription
idstringUnique request id
trace_id?stringTrace id for correlation
response_id?stringProvider's response id
conversation_id?stringConversation id, if set
conversation_turn?intTurn number in the conversation
providerstringProvider name (for example, openai)
modelstringThe catalog display name of the requested model (for example, GPT-4o), or its id when the catalog doesn't know it
snapshot?stringThe provider's model id: the one the response returned, or the requested id when the response didn't name one
model_type?stringClassification: text, embedding, image, tts, stt, video
endpoint?stringAPI endpoint path
pricing_tier?stringPricing tier used
prompt_tokensintInput tokens (the full prompt)
completion_tokensintOutput tokens (the full output)
cached_tokensintPrompt tokens read from the cache
cache_write_tokensintPrompt tokens written to the cache
reasoning_tokensintReasoning/thinking tokens
total_tokensintSum of prompt + completion tokens
prompt_costfloatPrompt cost in cents
completion_costfloatCompletion cost in cents
total_cost_in_centsfloatTotal cost in cents
currency?stringThe currency of the costs (for example, USD)
latency_ms?intRequest latency in milliseconds
time_to_first_token_ms?intTime to the first token (streaming)
status_code?intHTTP status code
is_failedboolWhether the request failed
error_type?stringError class of a failed request
error_message?stringThe provider's error message
finish_reason?stringModel's finish reason
is_reasoningboolWhether reasoning was used
is_streamingboolWhether the request was streamed
has_tool_callsboolWhether tools were called
tool_call_counts?arrayTool calls by type
trackable_type?stringTrackable morph type
trackable_id?stringTrackable id
request_source?stringweb, api, or console
started_atCarbonRequest start time
completed_atCarbonRequest completion time
metadata?arrayCustom metadata

Request Transformer ​

The RequestTransformer class controls how SpectraRequest models are converted into the data arrays that integrations and events receive. The default transformer extracts all relevant fields. Extend it to add, remove, or change fields:

php
use Spectra\Support\RequestTransformer;
use Spectra\Models\SpectraRequest;

class MyTransformer extends RequestTransformer
{
    public function transform(SpectraRequest $request): array
    {
        $data = parent::transform($request);

        // Add custom fields
        $data['environment'] = config('app.env');
        $data['team'] = 'ml-platform';

        // Remove sensitive fields
        unset($data['trackable_type'], $data['trackable_id']);

        return $data;
    }
}

Register it in config/spectra.php:

php
'integrations' => [
    'request_transformer' => \App\Telemetry\MyTransformer::class,
],

Events ​

Spectra dispatches a RequestTracked event after every AI request is persisted. The event carries the same data array the RequestTransformer produces, so you can build your own integrations without changing Spectra itself.

Listening to the Event ​

Register a listener in your EventServiceProvider or use a closure:

php
use Spectra\Events\RequestTracked;

// In EventServiceProvider
protected $listen = [
    RequestTracked::class => [
        \App\Listeners\SendToDatadog::class,
        \App\Listeners\AlertOnHighCost::class,
    ],
];

Listener Example ​

php
use Spectra\Events\RequestTracked;

class AlertOnHighCost
{
    public function handle(RequestTracked $event): void
    {
        $data = $event->request;

        if ($data['total_cost_in_cents'] > 100) {
            // Send a Slack alert, log, or trigger a notification
            logger()->warning('High-cost AI request', [
                'model' => $data['model'],
                'cost_cents' => $data['total_cost_in_cents'],
                'tokens' => $data['total_tokens'],
            ]);
        }
    }
}

Available Event Data ​

The $event->request array contains the same fields listed in the Available Data table above. The data is produced by the configured RequestTransformer.

Released under the MIT License.