OpenAI
Auto-instrumentation for OpenAI API.
Risicare automatically instruments the OpenAI Python SDK.
Installation
pip install risicare openaiBasic 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
| Method | Traced |
|---|---|
chat.completions.create | Yes (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.create | Yes (sync + async), with and without stream=True |
responses.parse | Yes (sync + async) |
responses.stream() | Yes (the helper calls create(stream=True)) |
embeddings.create | Yes (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": {}}
}
}]
)| Attribute | Content |
|---|---|
gen_ai.completion.tool_calls | The number of tool calls |
gen_ai.completion.tool_call.{j}.name | The name of call j (the first 5) |
gen_ai.completion.0.tool_calls.{j}.arguments | The 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_reason | Why 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=FalseorRISICARE_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
openailibrary 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
| Attribute | Description |
|---|---|
gen_ai.system | openai (or detected provider for compatible APIs) |
gen_ai.request.model | Requested model name |
gen_ai.response.model | Model name returned by API |
gen_ai.response.id | Response ID |
gen_ai.request.temperature | Sampling temperature |
gen_ai.request.max_tokens | Max output tokens. The value of max_completion_tokens when you set it, otherwise the value of max_tokens |
gen_ai.request.top_p | top_p, when you set it |
gen_ai.request.tool_choice | tool_choice, when you set it |
gen_ai.request.stop_sequences | The stop of the call, when you set it |
gen_ai.request.seed | seed, when you set it |
gen_ai.request.stream | Whether streaming was requested |
gen_ai.request.has_tools | Whether tools were provided |
gen_ai.usage.prompt_tokens | Input tokens. The count includes the cached tokens |
gen_ai.usage.completion_tokens | Output tokens |
gen_ai.usage.total_tokens | Total tokens |
gen_ai.usage.cache_read.input_tokens | Input tokens that OpenAI read from its prompt cache (usage.prompt_tokens_details.cached_tokens) |
gen_ai.usage.cache_write.input_tokens | Input tokens that OpenAI wrote to its prompt cache (usage.prompt_tokens_details.cache_write_tokens) |
gen_ai.usage.reasoning.output_tokens | Output tokens that the model used for reasoning (usage.completion_tokens_details.reasoning_tokens) |
gen_ai.completion.tool_calls | Number of tool calls made |
gen_ai.completion.tool_call.{j}.name | Name of tool call j (the first 5) |
gen_ai.completion.0.tool_calls.{j}.arguments | Arguments of tool call j (the first 5). Content: only with content capture on |
gen_ai.completion.finish_reason | Stop reason |
gen_ai.latency_ms | Request 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:
| Attribute | Description |
|---|---|
gen_ai.operation | embeddings |
gen_ai.input.count | Number of input texts |
gen_ai.response.embeddings | Number of embeddings returned |
gen_ai.response.dimensions | Embedding dimensions |
Cost Tracking
Costs are automatically calculated:
| Model | Input (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.
| Attribute | Content | Cap |
|---|---|---|
gen_ai.tool.definitions | Your tools in one flat form (name, description, parameters) | 24,576 bytes |
gen_ai.input.messages | Your whole messages list in the OpenTelemetry parts form, with each tool call and tool result paired by id | 49,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_bytesininit(). 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=FalseorRISICARE_TRACE_CONTENT=false. The SDK then does not build or send these keys. - The Responses API writes the same keys:
instructionsis a system message, andinputgives the other messages (afunction_callitem is a tool call, afunction_call_outputitem a tool result).
With content capture off, the SDK also withholds the text of an error. See Production & Failure Modes.