Send a span from a Node.js app or from the Node process of a VS Code or JetBrains extension. Your existing provider SDK or fetch still makes the LLM call with its own API key.
Checklist
- Create a Traces (send) key for the project and environment.
- Export to
https://getopentoken.com/api/otel/v1/traceswithAuthorization: Bearer <traces-key>. - Add a batch processor to your tracer provider and wrap the LLM stream in one span.
- Record the provider, model and token counts from the final usage chunk.
- Return the provider's shutdown promise from
deactivate()and check the trace in Open Token.
1. Create a traces key
Sign in at getopentoken.com. Open API keys → Create key, select Traces and Traces (send), and choose the environment and project that will receive the traces. Copy the key when it's shown. Load it from your secret manager as OT_INGEST_KEY in Node, or store it in the editor's secret storage.
Send POST https://getopentoken.com/api/otel/v1/traces with Authorization: Bearer <traces-key>. The endpoint accepts OTLP/HTTP protobuf (application/x-protobuf) and JSON (application/json). The Node example uses protobuf, and the curl test uses JSON.
For a distributed extension, let each installation supply its own scoped key or use an authenticated collector or relay that holds a shared key. Keep the key out of the bundle, workspace settings and logs.
2. Install and configure OpenTelemetry
Use Node.js 22+ for the runnable example and OpenTelemetry JS 2.x.
npm install @opentelemetry/api@^1.9 @opentelemetry/resources@^2.11 @opentelemetry/sdk-trace-node@^2.11 @opentelemetry/exporter-trace-otlp-proto@^0.222Use the full traces URL for the exporter's url option or OTEL_EXPORTER_OTLP_TRACES_ENDPOINT. The exporter appends /v1/traces only to the shared OTEL_EXPORTER_OTLP_ENDPOINT. Set the bearer header in headers or in OTEL_EXPORTER_OTLP_HEADERS, where %20 encodes the space. The protobuf package selects the transport in these examples.
The exporter reads environment variables when it's constructed. If your provider initializes at import time, set the variables before launching the extension host. For settings or secrets available only at activation, construct the exporter in activate() as shown below.
export OTEL_EXPORTER_OTLP_ENDPOINT="https://getopentoken.com/api/otel"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer%20${OT_INGEST_KEY}"
export OTEL_SERVICE_NAME="editor-llm"Save the shared helpers as telemetry.ts. Use createTelemetry() for a Node app that needs its own provider. An existing provider can use openTokenProcessor() and keep its resource, sampler and current processors.
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
import { SpanKind, SpanStatusCode, type Span } from "@opentelemetry/api";
import { resourceFromAttributes } from "@opentelemetry/resources";
import { BatchSpanProcessor, NodeTracerProvider } from "@opentelemetry/sdk-trace-node";
export type ChatResult = {
model?: string;
usage?: {
prompt_tokens: number;
completion_tokens: number;
prompt_tokens_details?: { cached_tokens?: number; cache_write_tokens?: number } | null;
} | null;
};
export function recordChatResult(span: Span, result: ChatResult) {
if (result.model) span.setAttribute("gen_ai.response.model", result.model);
if (!result.usage) return;
const { prompt_tokens, completion_tokens, prompt_tokens_details } = result.usage;
span.setAttribute("gen_ai.usage.input_tokens", prompt_tokens);
span.setAttribute("gen_ai.usage.output_tokens", completion_tokens);
const read = prompt_tokens_details?.cached_tokens;
const write = prompt_tokens_details?.cache_write_tokens;
if (read != null) span.setAttribute("gen_ai.usage.cache_read.input_tokens", read);
if (write != null) span.setAttribute("gen_ai.usage.cache_creation.input_tokens", write);
if (read != null || write != null) span.setAttribute("opentoken.usage.input_includes_cache", true);
}
export function openTokenProcessor(ingestKey?: string) {
const exporter = new OTLPTraceExporter(ingestKey ? {
url: "https://getopentoken.com/api/otel/v1/traces",
headers: { Authorization: "Bearer " + ingestKey },
} : {});
return new BatchSpanProcessor(exporter);
}
export function createTelemetry() {
const provider = new NodeTracerProvider({
resource: resourceFromAttributes({
"service.name": process.env.OTEL_SERVICE_NAME ?? "editor-llm",
}),
spanProcessors: [openTokenProcessor()],
});
const tracer = provider.getTracer("llm-calls");
async function traceChat<T extends ChatResult>(
vendor: string,
model: string,
call: () => Promise<T>,
) {
const span = tracer.startSpan("chat", {
kind: SpanKind.CLIENT,
attributes: {
"gen_ai.operation.name": "chat",
"gen_ai.provider.name": vendor,
"gen_ai.request.model": model,
},
});
try {
const response = await call();
recordChatResult(span, response);
return { response, traceId: span.spanContext().traceId };
} catch (error) {
span.setStatus({ code: SpanStatusCode.ERROR });
span.setAttribute("error.type", error instanceof Error ? error.name : "Error");
throw error;
} finally {
span.end();
}
}
return {
traceChat,
forceFlush: () => provider.forceFlush(),
shutdown: () => provider.shutdown(),
};
}Your app already has a tracer provider
In OpenTelemetry JS 2.x, pass all processors in the NodeTracerProvider constructor's spanProcessors array. The provider fans out to each processor. Replace your existing initialization with this pattern and keep a single registration. This version reads the exporter settings from the environment.
import { NodeTracerProvider, type NodeTracerConfig } from "@opentelemetry/sdk-trace-node";
import { openTokenProcessor } from "./telemetry";
// Use this at your existing provider's construction and registration site.
export function registerProvider(config: NodeTracerConfig) {
const provider = new NodeTracerProvider({
...config,
spanProcessors: [...(config.spanProcessors ?? []), openTokenProcessor()],
});
provider.register();
return provider;
}If the provider is created at import time but the key is available only later, include a forwarding processor in the same constructor. In VS Code, store the key from a password input with context.secrets.store("opentoken.ingestKey", key). During activate(), the forwarding processor gets its destination, constructed with the full URL and bearer header. Set it up before starting LLM work. The processor exports spans that end from then on.
import type { ExtensionContext } from "vscode";
import { NodeTracerProvider, type SpanProcessor } from "@opentelemetry/sdk-trace-node";
import { openTokenProcessor } from "./telemetry";
let destination: ReturnType<typeof openTokenProcessor> | undefined;
const openTokenSlot: SpanProcessor = {
onStart: (span, context) => destination?.onStart(span, context),
onEnd: (span) => destination?.onEnd(span),
async forceFlush() { await destination?.forceFlush(); },
async shutdown() { await destination?.shutdown(); },
};
export const provider = new NodeTracerProvider({
// Keep your existing resource, sampler and processors here.
spanProcessors: [openTokenSlot],
});
provider.register();
export async function activate(context: ExtensionContext) {
const ingestKey = await context.secrets.get("opentoken.ingestKey");
if (ingestKey) destination ??= openTokenProcessor(ingestKey);
}
export function deactivate() {
return provider.shutdown();
}addSpanProcessor() was removed in JS 2.x. If the provider is already built and has no forwarding processor, there is no supported way to attach one. Change its setup or point an existing configurable exporter at a collector that can fan out. A JetBrains extension with a Node sidecar can pass its secure settings to that process during startup.
3. Wrap one LLM call
Streaming in an editor extension
Inside your central async generator, use yield* traceStream(provider.getTracer("llm-calls"), vendor, model, openStream). Define openStream as a function that opens your existing provider stream. For OpenAI-compatible Chat Completions, send stream: true and stream_options: { include_usage: true } where supported. The last usage chunk can have empty choices. The wrapper records it before handing it to your consumer.
import { SpanKind, SpanStatusCode, type Attributes, type Tracer } from "@opentelemetry/api";
import { recordChatResult, type ChatResult } from "./telemetry";
export async function* traceStream<T extends ChatResult>(
tracer: Tracer,
vendor: string,
model: string,
openStream: () => AsyncIterable<T> | Promise<AsyncIterable<T>>,
dimensions: Attributes = {},
): AsyncGenerator<T> {
const span = tracer.startSpan("chat", {
kind: SpanKind.CLIENT,
attributes: {
...dimensions,
"gen_ai.operation.name": "chat",
"gen_ai.provider.name": vendor,
"gen_ai.request.model": model,
},
});
try {
for await (const chunk of await openStream()) {
recordChatResult(span, chunk);
yield chunk;
}
} catch (error) {
const type = error instanceof Error ? error.name : "Error";
if (type !== "AbortError") {
span.setStatus({ code: SpanStatusCode.ERROR });
span.setAttribute("error.type", type);
}
throw error;
} finally {
span.end();
}
}The span starts when iteration starts and ends in finally, on completion, cancellation or error. If the generator already creates a model span, apply this lifecycle to that span or replace its wrapper. Forward the caller's abort signal to your provider. If its SDK wraps user cancellation in a different error type, map that cancellation to AbortError before it leaves the stream.
Non-streaming in Node.js
Save the example as app.mts next to telemetry.ts. Set OPENAI_BASE_URL to the provider's OpenAI-compatible API base (for example, https://api.openai.com/v1), OPENAI_API_KEY to the provider key, CHAT_MODEL to the model and MODEL_VENDOR to its provider. Run npx tsx app.mts and copy the trace ID. You can pass an SDK call to traceChat instead of using fetch.
import { createTelemetry, type ChatResult } from "./telemetry.js";
const { OPENAI_BASE_URL, OPENAI_API_KEY, CHAT_MODEL, MODEL_VENDOR } = process.env;
if (!OPENAI_BASE_URL || !OPENAI_API_KEY || !CHAT_MODEL || !MODEL_VENDOR) {
throw new Error("Set OPENAI_BASE_URL, OPENAI_API_KEY, CHAT_MODEL and MODEL_VENDOR.");
}
const telemetry = createTelemetry();
try {
const { traceId } = await telemetry.traceChat(MODEL_VENDOR, CHAT_MODEL, async () => {
const url = OPENAI_BASE_URL.replace(/\/+$/, "") + "/chat/completions";
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: "Bearer " + OPENAI_API_KEY,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: CHAT_MODEL,
messages: [{ role: "user", content: "Reply with one word: hello." }],
}),
});
if (!response.ok) throw new Error("Model API returned HTTP " + response.status);
return await response.json() as ChatResult;
});
console.log("Trace ID:", traceId);
} finally {
await telemetry.shutdown();
}Flush and shut down. Unwind or finish active streams first. Return the existing provider's shutdown() promise from deactivate(), or await shutdown when the Node app or sidecar exits. Use forceFlush() after spans end to drain the queue while the provider stays active.
4. Send model, token and attribution metadata
Use current names in new code. The usage meter accepts these legacy fallbacks when the current field is absent.
| Purpose | Current attribute | Legacy fallback |
|---|---|---|
| Provider and pricing | gen_ai.provider.name | gen_ai.system |
| Input and output tokens | gen_ai.usage.input_tokens, gen_ai.usage.output_tokens | gen_ai.usage.prompt_tokens, gen_ai.usage.completion_tokens |
| Cached input reads | gen_ai.usage.cache_read.input_tokens | gen_ai.usage.cache_read_input_tokens |
| Cached input writes | gen_ai.usage.cache_creation.input_tokens | gen_ai.usage.cache_creation_input_tokens, gen_ai.usage.cache_write_input_tokens |
Set gen_ai.operation.name to chat and record gen_ai.request.model and gen_ai.response.model when known. The response model takes precedence for pricing, and the cost estimate uses reported units and the price catalog. Models without a matching price can show zero estimated cost. Use service.name on the resource and error.type with span status ERROR for failures.
For provider openrouter, Open Token treats the prompt total as including cache reads and writes. Report the returned vendor/model ID and the provider's counts. The helper sets opentoken.usage.input_includes_cache to true when it reports cache counts, so the inclusive total is handled even if you label the span with the underlying vendor. Change the flag to false if your provider counts cache tokens separately. A routing alias such as openrouter/auto may remain unpriced.
Add dimensions and group a conversation
Pass dimension attributes as the last argument to traceStream(), for example { "gen_ai.conversation.id": conversationId }.
- Customer and feature. Set
opentoken.customerto an opaque ID andopentoken.featureto a stable label. Cost explorer → Group by includes Customer and Feature. The customer dimension usesopentoken.customer;enduser.idalone leaves it unset. - Team, project and environment. A project-scoped ingest key determines the project, team and environment for usage. The usage meter reads
opentoken.projectas a project slug fallback andopentoken.environmentordeployment.environment.nameas an environment fallback when the key leaves that scope open.opentoken.teamis trace metadata and can become anot.teamusage tag for unscoped ingest. Traces filters by storage project and environment. Cost explorer groups by the resolved Team or Project and offers an environment filter for projects with multiple environments. - Conversation. Reuse the same opaque conversation ID on each call. Span attributes take precedence over resource attributes. On the same span,
opentoken.run_idtakes precedence, followed bygen_ai.conversation.idandsession.id. Traces → Threads groups stored traces by that run ID.
Other non-content span attributes can be stored on the span, subject to trace limits and redaction. Traces supports key=value search for keys indexed under Trace settings → Searchable keys. Arbitrary attributes become usage tags only when allowlisted. Keep prompts, outputs, tool arguments and credentials out of span attributes.
5. Verify in Open Token
In the dashboard, open Traces and select the project and environment associated with the key. Open the recent chat trace, or paste the printed ID into https://getopentoken.com/dashboard/traces/<trace-id> while signed in. Check the span's requested or returned model, duration, and input and output tokens. For estimated spend, open Cost explorer and select the same project and time range.
To test the connection independently of your app, run this curl command in a shell with OT_INGEST_KEY loaded and openssl installed. It sends a synthetic chat span and prints a fresh trace ID. On HTTP 200, {} means full success. If the response includes partialSuccess, check rejectedSpans and errorMessage.
now=$(date +%s)
trace_id=$(openssl rand -hex 16)
span_id=$(openssl rand -hex 8)
curl --silent --show-error --fail-with-body --write-out '\nHTTP %{http_code}\n' \
'https://getopentoken.com/api/otel/v1/traces' \
-H "Authorization: Bearer $OT_INGEST_KEY" -H 'Content-Type: application/json' \
--data-binary @- <<JSON && printf 'Trace ID: %s\n' "$trace_id"
{"resourceSpans":[{"resource":{"attributes":[{"key":"service.name","value":{"stringValue":"chat-smoke"}}]},
"scopeSpans":[{"spans":[{"traceId":"$trace_id","spanId":"$span_id",
"name":"chat","startTimeUnixNano":"${now}000000000","endTimeUnixNano":"${now}010000000",
"attributes":[
{"key":"gen_ai.operation.name","value":{"stringValue":"chat"}},
{"key":"gen_ai.provider.name","value":{"stringValue":"openai"}},
{"key":"gen_ai.request.model","value":{"stringValue":"gpt-4o-mini"}},
{"key":"gen_ai.usage.input_tokens","value":{"intValue":"8"}},
{"key":"gen_ai.usage.output_tokens","value":{"intValue":"2"}}
]}]}]}]}
JSONTroubleshooting
- 401 or 403. Check that the header is
Authorization: Bearer <traces-key>, that the key is valid, and that it has the Traces (send) scope. If your organization restricts ingest by IP, check the egress IP of the actual Node host or collector. - 404 or 415. Use
https://getopentoken.com/api/otelas the shared endpoint andhttps://getopentoken.com/api/otel/v1/tracesas the traces-specific URL. If the path ends in/v1/traces/v1/traces, the shared endpoint already had the suffix. Use the protobuf exporter for protobuf and the matching content type for JSON. - Nothing appears. Check project, environment, time range and sampling. Finish the stream and await
forceFlush()orshutdown(). With Only accept AI traces enabled, a trace without a recognized AI span is held rather than stored. Include agen_ai.*attribute on the model span. When ingest reports held spans, its OTLPpartialSuccess.errorMessageincludesNon-gen_ai spans are not stored. - Batch versus simple. Batch exports on a timer or when the batch fills. Simple starts sending each span when it ends. Await shutdown with either processor and use batching for a long-running extension or service.
- esbuild CJS. Inline OpenTelemetry with
bundle: true,platform: "node",format: "cjs"andexternal: ["vscode"]for VS Code. Use static imports or literal-stringimport()calls. Usenpm ls @opentelemetry/sdk-trace-base @opentelemetry/coreto check for one compatible copy of each across the exporter and SDK. Usenpm dedupeor compatible overrides if needed. Externalize OpenTelemetry only if you ship the requirednode_modules. - Corporate proxy or TLS. This Node exporter uses Node HTTP(S) with its own agent. It doesn't automatically honor
HTTPS_PROXYor use the agent configured for your LLMfetch. Installhttps-proxy-agent@^7and pass the exporter below toBatchSpanProcessor, or send OTLP to a local collector that can forward it. Use the organization's trusted CA and test from the extension host.
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-proto";
export function createProxiedExporter(ingestKey: string, proxyUrl: string) {
return new OTLPTraceExporter({
url: "https://getopentoken.com/api/otel/v1/traces",
headers: { Authorization: "Bearer " + ingestKey },
httpAgentOptions: async (_protocol) => {
const { HttpsProxyAgent } = await import("https-proxy-agent");
return new HttpsProxyAgent(proxyUrl);
},
});
}More examples
For framework integrations, see Observe a service and the Open Token SDK.
Python. For a streaming example with a tool, install with python -m pip install openai opentelemetry-sdk opentelemetry-exporter-otlp-proto-http. Set the provider variables from step 3 and OT_INGEST_KEY, save as app.py, and run python app.py. The example assumes the provider's prompt token total includes cached input.
import os
from contextlib import contextmanager
from datetime import datetime, timezone
from openai import OpenAI
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.trace import Status, StatusCode
provider = TracerProvider()
exporter = OTLPSpanExporter(
endpoint="https://getopentoken.com/api/otel/v1/traces",
headers={"Authorization": "Bearer " + os.environ["OT_INGEST_KEY"]},
timeout=3,
)
provider.add_span_processor(BatchSpanProcessor(
exporter, max_queue_size=512, max_export_batch_size=64,
))
tracer = provider.get_tracer("chat-app")
client = OpenAI() # OPENAI_BASE_URL and OPENAI_API_KEY
model = os.environ["CHAT_MODEL"]
@contextmanager
def traced(name, attrs):
with tracer.start_as_current_span(name, attributes=attrs, record_exception=False,
set_status_on_exception=False) as span:
try:
yield span
except BaseException as exc:
span.set_attribute("error.type", type(exc).__name__)
span.set_status(Status(StatusCode.ERROR))
raise
try:
with traced("answer", {}):
with traced("current_date", {"gen_ai.operation.name": "execute_tool",
"gen_ai.tool.name": "current_date"}):
today = datetime.now(timezone.utc).date().isoformat()
with traced("chat", {
"gen_ai.operation.name": "chat", "gen_ai.request.model": model,
"gen_ai.provider.name": os.environ["MODEL_VENDOR"],
"opentoken.usage.input_includes_cache": True,
}) as span:
with client.chat.completions.create(
model=model, messages=[{"role": "user", "content": f"What weekday is {today}?"}],
stream=True, stream_options={"include_usage": True},
) as stream:
for chunk in stream:
if chunk.model:
span.set_attribute("gen_ai.response.model", chunk.model)
if chunk.usage:
u = chunk.usage
span.set_attribute("gen_ai.usage.input_tokens", u.prompt_tokens)
span.set_attribute("gen_ai.usage.output_tokens", u.completion_tokens)
d = u.prompt_tokens_details
for field, key in [("cached_tokens", "cache_read"), ("cache_write_tokens", "cache_creation")]:
count = getattr(d, field, None)
if count is not None:
span.set_attribute(f"gen_ai.usage.{key}.input_tokens", count)
if chunk.choices:
print(chunk.choices[0].delta.content or "", end="", flush=True)
finally:
provider.shutdown()