Skip to main content

OpenAI

Auto-instrumentation for OpenAI API.

Risicare automatically instruments the OpenAI Python SDK.

Installation

pip install risicare openai

Basic Usage

import risicare
from openai import OpenAI
 
risicare.init()
 
client = OpenAI()
 
# Automatically traced
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the capital of France?"}
    ]
)

Supported Methods

MethodTraced
chat.completions.createYes (sync + async), with and without stream=True
chat.completions.parse (structured outputs)Yes (sync + async). It is beta.chat.completions.parse before openai 1.92
chat.completions.stream()Yes
responses.createYes (sync + async), with and without stream=True
responses.parseYes (sync + async)
responses.stream()Yes (the helper calls create(stream=True))
embeddings.createYes (sync + async)

A call through with_raw_response has the tokens and the model of its answer on its span. So has a with_streaming_response call that is not a stream: its span stays open until your parse(), and takes them from your answer.

Streaming

A streaming response is traced:

stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Write a poem"}],
    stream=True
)
 
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="")

The traced stream is a proxy of the OpenAI stream object, so with client.chat.completions.create(..., stream=True) as stream: and stream.response work as without the SDK. The span completes when the stream is fully consumed. A stream that you stop reading and drop, or never read, still sends a span, with status ok and no token counts.

A streamed answer records its tool calls, with the same keys as an answer that is not a stream. See Function Calling.

Token counts of a stream. The OpenAI API sends the token counts of a streamed call only when the request asks for them (stream_options={"include_usage": True}). When your call does not set stream_options, the SDK asks for them. The option stream_usage of init() (or RISICARE_STREAM_USAGE) sets where: "auto" (the default) asks on a call to https://api.openai.com, True on any host, False never. Your code gets the same chunks as without the SDK: the SDK reads the extra usage chunk and does not pass it on. A host that refuses the field fails that one call, with one WARNING, and the SDK does not ask that host again. One exception: code that reads the transport of an already parsed stream (stream.response.iter_lines(), iter_bytes(), iter_text()), stream._iterator or copy.copy(stream) sees the usage field and the extra usage event. Set stream_usage=False for such code.

Async Support

Async clients are automatically instrumented:

from openai import AsyncOpenAI
 
client = AsyncOpenAI()
 
async def main():
    response = await client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Hello!"}]
    )

Function Calling

The span of a call records the tool calls of the answer. A streamed answer records the same keys as an answer that is not a stream: create(stream=True) (sync and async) and the chat.completions.stream() helper.

This records that the model asked for a tool. It does not trace the function of yours that runs the tool. To make that function a span of its own, see Trace your own tool function.

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What's the weather?"}],
    tools=[{
        "type": "function",
        "function": {
            "name": "get_weather",
            "parameters": {"type": "object", "properties": {}}
        }
    }]
)
AttributeContent
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 content capture on, after your mask. Each text is cut at 10,000 characters
gen_ai.completion.finish_reasonWhy the answer ended
  • 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: trace_content=False or RISICARE_TRACE_CONTENT=false. This turns off all content: the prompts, the completions and the tool arguments.
  • The SDK reads the first choice only. It joins the parts of a streamed call as the openai library joins them. At most 1,000 calls of one stream are counted.
  • A stream that ends early (you stop reading it, an error, a cancel) records what it received, with no finish reason.
  • 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 (the tool call and its result, paired by id), when that list fits its cap. With capture off, no span has the id.
  • The tool definitions (tools) are captured with content capture on. See Request Capture.

Captured Attributes

AttributeDescription
gen_ai.systemopenai (or detected provider for compatible APIs)
gen_ai.request.modelRequested model name
gen_ai.response.modelModel name returned by API
gen_ai.response.idResponse ID
gen_ai.request.temperatureSampling temperature
gen_ai.request.max_tokensMax output tokens. The value of max_completion_tokens when you set it, otherwise the value of max_tokens
gen_ai.request.top_ptop_p, when you set it
gen_ai.request.tool_choicetool_choice, when you set it
gen_ai.request.stop_sequencesThe stop of the call, when you set it
gen_ai.request.seedseed, when you set it
gen_ai.request.streamWhether streaming was requested
gen_ai.request.has_toolsWhether tools were provided
gen_ai.usage.prompt_tokensInput tokens. The count includes the cached 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)
gen_ai.usage.cache_write.input_tokensInput tokens that OpenAI wrote to its prompt cache (usage.prompt_tokens_details.cache_write_tokens)
gen_ai.usage.reasoning.output_tokensOutput tokens that the model used for reasoning (usage.completion_tokens_details.reasoning_tokens)
gen_ai.completion.tool_callsNumber of tool calls made
gen_ai.completion.tool_call.{j}.nameName of tool call j (the first 5)
gen_ai.completion.0.tool_calls.{j}.argumentsArguments of tool call j (the first 5). Content: only with content capture on
gen_ai.completion.finish_reasonStop reason
gen_ai.latency_msRequest latency in milliseconds

The SDK sends a cache or reasoning key only when the response gives an integer for its field. A real 0 is sent. A stream gives the three counts only in its usage chunk. The SDK asks for that chunk when your call does not (see Streaming). These keys are not content: trace_content=False keeps them. The SDK sends the request parameters (top_p, tool_choice, stop_sequences, seed) with content capture on or off. It does not send a parameter that you did not set.

For embedding calls (embeddings.create), Risicare also captures:

AttributeDescription
gen_ai.operationembeddings
gen_ai.input.countNumber of input texts
gen_ai.response.embeddingsNumber of embeddings returned
gen_ai.response.dimensionsEmbedding dimensions

Cost Tracking

Costs are automatically calculated:

ModelInput (per 1M)Output (per 1M)
gpt-4o$2.50$10.00
gpt-4o-mini$0.15$0.60
gpt-4-turbo$10.00$30.00
gpt-3.5-turbo$0.50$1.50

Content Capture

Prompt and completion content is on by default (since Python 0.7.0). To keep it in your process:

risicare.init(trace_content=False)

You can also set RISICARE_TRACE_CONTENT=false.

Request Capture

With content capture on, a call to chat.completions.create sends the whole request. The patch sends two more attributes, beside the older gen_ai.prompt.{i}.role and gen_ai.prompt.{i}.content 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 max_input_messages_bytes 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 trace_content=False or RISICARE_TRACE_CONTENT=false. The SDK then does not build or send these keys.
  • The Responses API writes the same keys: instructions is a system message, and input gives the other messages (a function_call item is a tool call, a function_call_output item a tool result).

With content capture off, the SDK also withholds the text of an error. See Production & Failure Modes.

Next Steps