Skip to main content

OpenAI (JS)

Instrument OpenAI in Node.js/TypeScript.

Auto-instrument the OpenAI Node.js SDK with a single function call.

Installation

npm install risicare openai

Quick Start

import { init } from 'risicare';
import { patchOpenAI } from 'risicare/openai';
import OpenAI from 'openai';
 
// Initialize Risicare
init();
 
// Wrap the OpenAI client
const openai = patchOpenAI(new OpenAI());
 
// All calls are now traced
const response = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Hello!' }],
});

Traced Methods

patchOpenAI() traces chat.completions.create, embeddings.create and the Responses API: responses.create (also with stream: true) and responses.parse. It also traces the stream helpers responses.stream(), chat.completions.stream() and beta.chat.completions.stream() (openai 4.x). See Stream helpers.

How It Works

patchOpenAI() returns an ES Proxy that wraps all OpenAI methods:

import { patchOpenAI } from 'risicare/openai';
 
// The original client is wrapped, not modified
const original = new OpenAI();
const traced = patchOpenAI(original);
 
// Both work, but only `traced` creates spans
await original.chat.completions.create(...); // Not traced
await traced.chat.completions.create(...);   // Traced

Captured Attributes

AttributeDescription
gen_ai.systemopenai (or detected provider for compatible APIs)
gen_ai.request.modelRequested model name
gen_ai.request.temperatureTemperature, when set on the request
gen_ai.request.max_tokensMax tokens, when set on the request. The value of max_completion_tokens when it is set, otherwise the value of max_tokens
gen_ai.request.top_ptop_p, when set on the request
gen_ai.request.tool_choicetool_choice, when set on the request
gen_ai.request.stop_sequencesThe stop of the request, when set
gen_ai.request.seedseed, when set on the request
gen_ai.request.has_toolsWhether the request carried tools
gen_ai.request.tool_countNumber of tools on the request
gen_ai.response.modelModel name returned by API
gen_ai.response.idResponse ID returned by API
gen_ai.response.finish_reasonsFinish reasons from the response
gen_ai.usage.prompt_tokensInput tokens
gen_ai.usage.completion_tokensOutput tokens
gen_ai.usage.total_tokensTotal tokens
gen_ai.usage.cache_read.input_tokensInput tokens that OpenAI read from its prompt cache (usage.prompt_tokens_details.cached_tokens), when the response gives them
gen_ai.usage.cache_write.input_tokensInput tokens that OpenAI wrote to its prompt cache (usage.prompt_tokens_details.cache_write_tokens), when the response gives them
gen_ai.usage.reasoning.output_tokensOutput tokens that the model used for reasoning (usage.completion_tokens_details.reasoning_tokens), when the response gives them
llm.cost.total_usdThe cost from the SDK's own table — emitted only when the response model is in that table; an unrecognized model name yields no cost attribute. The dashboard shows the server's cost for a model that the server's price table knows, and this cost for any other model

Attributes that differ between the SDKs

The two SDKs do not set the same attributes on an OpenAI span. For example, only Python sets gen_ai.latency_ms, and only JavaScript sets gen_ai.request.frequency_penalty and gen_ai.request.presence_penalty. Temperature, max_tokens, top_p, has_tools and response ID are captured by both — see the table above. For prompt and completion text, see Content Capture.

Streaming Support

A streaming call creates a span. The span ends when the stream ends, and it has stream.chunk_count and stream.end_reason. The token counts, the cache and reasoning counts and the cost come from the usage chunk of the stream, so set stream_options: { include_usage: true }. Without that option the span has no token counts, unless you set streamUsage: true (see below). Since npm 0.19.1, with content capture on, a streamed chat call also records the answer text (see Content Capture). It does record the tool calls of the answer, when you read the stream with the iterator (see Tool Calls).

const stream = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'Write a story' }],
  stream: true,
  stream_options: { include_usage: true },
});
 
// The token counts come from the usage chunk that stream_options asks for
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content || '');
}

Token counts with streamUsage. With init({ streamUsage: true }) (or RISICARE_STREAM_USAGE=true), when your call does not set stream_options, the SDK asks OpenAI for the token counts of the stream, on any host. Your code gets the same chunks. A host that refuses the field fails that one call, with one warning, and the SDK does not ask that host again. The default 'auto' does not ask, because asResponse(), toReadableStream() and tee() hand over the raw stream: with true, they show the extra usage chunk and usage: null.

Stream helpers

responses.stream(), chat.completions.stream() and beta.chat.completions.stream() (openai 4.x) are traced. A helper calls create on the client that patchOpenAI returns, so the create call of the helper is the span (stream: true), with the tool keys. The helper gives the same events, values, errors and abort as without Risicare.

  • A helper of another shape (openai 4.15 to 4.18, or a future version) runs as before, with no span. For a traced stream there, call create({ ..., stream: true }).
  • A break out of a helper loop, or its abort(), marks the span as cancelled (risicare.cancelled, risicare.cancel_type), with no error status.
  • The request of a helper goes out as the helper built it: streamUsage adds no stream_options.
  • To turn this off, set traceStreamHelpers: false in init() (or RISICARE_TRACE_STREAM_HELPERS=false). The helpers then run exactly as without Risicare, with no span. create({ stream: true }) stays traced.
  • runTools() and the other helpers are not traced. A frozen client (Object.freeze) is not traced either.

OpenAI-Compatible Providers

The proxy automatically detects OpenAI-compatible endpoints:

import { patchOpenAI } from 'risicare/openai';
import OpenAI from 'openai';
 
// Works with any OpenAI-compatible provider
const together = patchOpenAI(
  new OpenAI({
    baseURL: 'https://api.together.xyz/v1',
    apiKey: process.env.TOGETHER_API_KEY,
  })
);
 
// gen_ai.system is "together" (detected from baseURL); the span name stays
// openai.chat.completions.create
await together.chat.completions.create({
  model: 'meta-llama/Llama-3-70b-chat-hf',
  messages: [{ role: 'user', content: 'Hello!' }],
});

Supported Compatible Providers

ProviderBase URLAuto-detected
Together AIapi.together.xyzYes
Groqapi.groq.comYes
DeepSeekapi.deepseek.comYes
xAI (Grok)api.x.aiYes
Fireworksapi.fireworks.aiYes
Baseteninference.baseten.coYes
Novitaapi.novita.aiYes
BytePlusapi.byteplus.com, ark.cn-beijing.byteplus.comYes

Tool Calls

When a request includes tools, the LLM span records the tool calls of the answer as attributes. The JS OpenAI patch does not emit separate tool child-spans (no tool.name / tool.arguments): it annotates the parent LLM span. To make the function of yours that runs the tool a span of its own, see Trace your own tool function.

const response = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: [{ role: 'user', content: 'What is the weather?' }],
  tools: [
    {
      type: 'function',
      function: {
        name: 'get_weather',
        parameters: { type: 'object', properties: { location: { type: 'string' } } },
      },
    },
  ],
});
AttributeContent
gen_ai.request.has_toolstrue when the request carried tools
gen_ai.request.tool_countThe number of tools on the request
gen_ai.response.tool_call_countThe number of tool calls of the answer
gen_ai.completion.tool_callsThe number of tool calls
gen_ai.completion.tool_call.{j}.nameThe name of call j (the first 5)
gen_ai.completion.0.tool_calls.{j}.argumentsThe arguments of call j (the first 5). Content: the SDK sends it only with traceContent on, after your mask. Each text is cut at 10,000 code points
gen_ai.completion.finish_reasonWhy the answer ended (Responses: the status, or the reason of incomplete)
  • The number, the names and the finish reason are not content. The SDK sends them with content capture on or off, and no option turns them off.
  • To stop the arguments, turn off content capture: traceContent: false or RISICARE_TRACE_CONTENT=false. This turns off all content: the prompts, the completions and the tool arguments.
  • A stream that you read with the iterator records the same keys as an answer that is not a stream. The SDK collects the parts of a chat stream. A Responses stream gives its tool calls in its final event. A stream that you take another way (tee(), toReadableStream()) records no tool call.
  • The SDK reads the first choice only. At most 1,000 calls of one stream are counted.
  • A chat stream that ends early (you stop reading it, an error, an abort) records what it received, with no reason. A Responses stream records its tool calls only from its final event.
  • The id of a call is not on the span of the call that made it. With content capture on, it is on the span of the next call, in gen_ai.input.messages, when that list fits its cap.

Configuration

Content Capture

Content capture is on by default (traceContent: true, since npm 0.10.0). With it on (and the project's content setting on), patchOpenAI records the prompt and completion text (gen_ai.prompt.<n>.role, gen_ai.prompt.<n>.content, gen_ai.completion.content). Since npm 0.19.1, a streamed chat call records the answer text too: the delta.content text of choice 0, joined, in gen_ai.completion.content, cut at 10,000 code points. While the stream runs, the SDK keeps at most 20,000 UTF-16 units of the text, so the memory does not grow with the length of the stream. With content capture off, it keeps nothing. Your code gets the same chunks at the same time. Through npm 0.19.0, a streamed chat call recorded the prompt only. A Responses stream records the text of its final event, as before. To keep the text in your process, set traceContent: false or RISICARE_TRACE_CONTENT=false.

Request Capture

With content capture on, patchOpenAI also sends the whole request. It sends two more attributes, beside the older gen_ai.prompt.<n>.* keys. Those older keys hold the first 10 messages, each cut at 10,000 characters.

AttributeContentCap
gen_ai.tool.definitionsYour tools in one flat form (name, description, parameters)24,576 bytes
gen_ai.input.messagesYour whole messages list in the OpenTelemetry parts form, with each tool call and tool result paired by id49,152 bytes
  • A value above its cap is cut and stays valid JSON. The SDK cuts the longest strings first, and each cut string ends in ... [truncated]. Then a long list keeps its first and last items.
  • The SDK writes these keys last. It writes a key only if the strings on the span stay at or below 96,000 bytes. A key that does not fit is not written at all.
  • To raise the cap of the message list, set maxInputMessagesBytes in init(). The default is 49,152 bytes. The range is 1,024 to 65,535. Raise it if your prompts are long. The 96,000-byte limit of the span stays.
  • To stop it, set traceContent: false or RISICARE_TRACE_CONTENT=false. The SDK then does not build or send these keys.
  • The request parameters (top_p, tool_choice, stop_sequences, seed) go out with content capture on or off. The SDK does not send a parameter that you did not set.

With content capture off, the SDK also withholds the text of an error. See JS Configuration (errorText).

Custom Metadata

init({
  metadata: {
    feature: 'chat',
    team: 'platform',
  },
});

Next Steps