Skip to main content

Anthropic

Auto-instrumentation for Anthropic API.

Risicare automatically instruments the Anthropic Python SDK.

Installation

pip install risicare anthropic

Basic Usage

from anthropic import Anthropic
import risicare
 
risicare.init()
 
client = Anthropic()
 
# Automatically traced
response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "What is the capital of France?"}
    ]
)

Supported Methods

MethodTraced
messages.createYes (sync + async), with and without stream=True
messages.stream()Yes (sync + async). See Streaming
messages.parseYes
beta.messages.create, beta.messages.stream(), beta.messages.parseYes

A call through with_raw_response has the tokens and the model of its answer on its span.

Streaming

A streaming response is traced via the stream=True parameter:

stream = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Write a poem"}],
    stream=True
)
 
for event in stream:
    if event.type == "content_block_delta":
        print(event.delta.text, end="")

The client.messages.stream() helper is traced too. The stream manager and the MessageStream that you get are the library's own: events, text_stream, get_final_message() and until_done() work as without the SDK. The span opens when the helper sends the request (at with) and ends when the stream ends, fails or is closed (the block exit closes it). It has the tokens and the cache counts of the stream.

On anthropic 0.30 and 0.40, the SDK traces the helper from the enter to the exit of the block, with the tokens of current_message_snapshot. get_instrumented_modules()["anthropic"]["state"] is then partially_instrumented, with a WARNING. With RISICARE_STRICT_INSTRUMENTATION=1, this partial state raises InstrumentationError.

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

Async Support

Async clients are automatically instrumented:

import asyncio
from anthropic import AsyncAnthropic
 
client = AsyncAnthropic()
 
async def main():
    response = await client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=1024,
        messages=[{"role": "user", "content": "Hello!"}]
    )
 
asyncio.run(main())

Tool Use

The span of a call records the tool use blocks 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 messages.stream() helper (anthropic 0.50 and later). On anthropic 0.30 and 0.40, the span of the helper reads the final message of the stream.

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.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    messages=[{"role": "user", "content": "What's the weather in Paris?"}],
    tools=[{
        "name": "get_weather",
        "description": "Get current weather",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {"type": "string"}
            }
        }
    }]
)
AttributeContent
gen_ai.completion.tool_usesThe number of tool use blocks
gen_ai.completion.tool_use.{j}.nameThe name of block j (the first 5)
gen_ai.completion.0.tool_calls.{j}.argumentsThe input of block j (the first 5), as JSON text. Content: the SDK sends it only with content capture on, after your mask. Each text is cut at 10,000 characters
gen_ai.response.stop_reasonWhy the answer ended
  • The number, the names and the stop reason are not content. The SDK sends them with content capture on or off, and no option turns them off.
  • To stop the inputs, turn off content capture: trace_content=False or RISICARE_TRACE_CONTENT=false. This turns off all content: the prompts, the completions and the tool inputs.
  • The SDK writes the input of a streamed call as json.dumps writes the input of an answer that is not a stream.
  • A stream that ends early (you stop reading it, an error, a cancel) records what it received, with no stop reason.
  • The id of a block 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 use and its result, paired by id), when that list fits its cap.
  • A failed tool. The tool_call_response part of an Anthropic tool_result keeps the is_error flag of the block (only a real boolean), so you can tell a failed tool from a tool that answered. The part is in gen_ai.input.messages, a content key: trace_content=False turns it off.
  • The tool definitions (tools) are captured with content capture on. See Request Capture.

Captured Attributes

AttributeDescription
gen_ai.systemanthropic
gen_ai.request.modelRequested model name
gen_ai.response.modelModel name returned by API
gen_ai.response.idResponse ID
gen_ai.request.max_tokensMax output tokens
gen_ai.request.temperatureSampling temperature (null when the request does not pass it). anthropic 1.11.0 does not accept temperature or top_p: the call raises TypeError before any request, so only its error span carries the value
gen_ai.request.top_ptop_p, when you set it. See the note on temperature: anthropic 1.11.0 refuses it, so only an error span carries the value
gen_ai.request.tool_choicetool_choice, when you set it
gen_ai.request.stop_sequencesstop_sequences, 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 Anthropic input_tokens does not include the cache tokens, and the SDK sends it unchanged
gen_ai.usage.completion_tokensOutput tokens
gen_ai.usage.total_tokensTotal tokens
gen_ai.usage.cache_read.input_tokensInput tokens that Anthropic read from its prompt cache (usage.cache_read_input_tokens)
gen_ai.usage.cache_write.input_tokensInput tokens that Anthropic wrote to its prompt cache (usage.cache_creation_input_tokens)
gen_ai.usage.reasoning.output_tokensOutput tokens that the model used for thinking (usage.output_tokens_details.thinking_tokens)
gen_ai.response.stop_reasonStop reason
gen_ai.completion.tool_usesNumber of tool use blocks
gen_ai.completion.tool_use.{j}.nameName of tool use block j (the first 5)
gen_ai.completion.0.tool_calls.{j}.argumentsInput of tool use block j (the first 5), as JSON text. Content: only with content capture on
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 counts in message_start and in message_delta. The counts of message_delta are cumulative, so a count there replaces the count of message_start. These keys are not content: trace_content=False keeps them. The SDK sends the request parameters (top_p, tool_choice, stop_sequences) with content capture on or off. It does not send a parameter that you did not set.

Cost Tracking

The cost in the dashboard comes from the server's price table. See Cost Tracking.

System Prompts

System prompts are captured separately (with content capture on):

response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=1024,
    system="You are a helpful assistant.",
    messages=[{"role": "user", "content": "Hello!"}]
)

The whole system prompt, a string or a list of blocks, is in gen_ai.system_instructions. The older gen_ai.system_prompt key holds the first 5,000 characters of a string system, and nothing for a list.

Request Capture

Prompt and completion content is on by default (since Python 0.7.0). To keep it in your process, set trace_content=False or RISICARE_TRACE_CONTENT=false.

With content capture on, a call to messages.create sends the whole request. The patch sends three 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.system_instructionsThe system prompt, a string or a list of blocks, kept whole16,384 bytes
gen_ai.input.messagesYour whole messages list in the OpenTelemetry parts form, with each tool call and tool result paired by id. A tool result keeps its is_error flag49,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.

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

Next Steps