Skip to main content

Anthropic (JS)

Instrument Anthropic in Node.js/TypeScript.

Auto-instrument the Anthropic Node.js SDK.

Installation

npm install risicare @anthropic-ai/sdk

Quick Start

import { init } from 'risicare';
import { patchAnthropic } from 'risicare/anthropic';
import Anthropic from '@anthropic-ai/sdk';
 
// Initialize Risicare
init();
 
// Wrap the Anthropic client
const anthropic = patchAnthropic(new Anthropic());
 
// All calls are now traced
const response = await anthropic.messages.create({
  model: 'claude-sonnet-5-5',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Hello!' }],
});

How It Works

patchAnthropic() intercepts messages.create calls:

import { patchAnthropic } from 'risicare/anthropic';
 
const original = new Anthropic();
const traced = patchAnthropic(original);
 
// Only traced client creates spans
await traced.messages.create({...}); // Traced

Captured Attributes

AttributeDescription
gen_ai.system"anthropic"
gen_ai.request.modelModel name (claude-sonnet-5-5, etc.)
gen_ai.response.modelActual model used
gen_ai.usage.prompt_tokensInput tokens (from Anthropic's input_tokens)
gen_ai.usage.completion_tokensOutput tokens (from Anthropic's output_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), when the response gives them
gen_ai.usage.cache_write.input_tokensInput tokens that Anthropic wrote to its prompt cache (usage.cache_creation_input_tokens), when the response gives them
gen_ai.usage.reasoning.output_tokensOutput tokens that the model used for thinking (usage.output_tokens_details.thinking_tokens), when the response gives them
gen_ai.request.tool_choicetool_choice, when set on the request
gen_ai.request.stop_sequencesstop_sequences, when set on the request
llm.cost.total_usdThe cost from the SDK's own table. The dashboard shows the server's cost for a model that the server's price table knows, and this cost for any other model

Streaming Support

What a stream gives

A streaming call creates a span with llm.stream set. The SDK reads the model, the response id, the stop reason and the token counts from the message_start and message_delta events of the stream. This includes the cache and thinking counts. The counts of message_delta are cumulative, so a count there replaces the count of message_start. Since npm 0.19.1, with content capture on, the SDK also records the text of a streamed answer (see Content Capture). It records the tool use blocks of the answer, when you read the stream with the iterator (see Tool Use).

const stream = await anthropic.messages.create({
  model: 'claude-sonnet-5-5',
  max_tokens: 1024,
  messages: [{ role: 'user', content: 'Write a poem' }],
  stream: true,
});
 
for await (const event of stream) {
  if (event.type === 'content_block_delta') {
    process.stdout.write(event.delta.text);
  }
}

Tool Use

The span of a call records the tool use blocks of the answer, also for a stream that you read with the iterator. A stream that you take another way (tee(), toReadableStream()) records no tool call. To make the function of yours that runs the tool a span of its own, see Trace your own tool function.

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 traceContent on, after your mask. Each text is cut at 10,000 code points
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: traceContent: false or RISICARE_TRACE_CONTENT=false. This turns off all content: the prompts, the completions and the tool inputs.
  • The SDK writes the input as JSON.stringify writes it. The Python SDK writes the same value with json.dumps, so the two texts can differ in spacing and in the escapes of non-ASCII characters: parse them. A number that JavaScript cannot hold exactly (an integer above 2^53) changes in the parse, and an input cut at 10,000 code points does not parse.
  • At most 1,000 calls of one stream are counted. A stream that ends early (you stop reading it, an error, an abort) records what it received, with no 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, 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: traceContent: false turns it off.

The request is traced as a standard LLM span (model, tokens, cost, finish reason). With content capture on, gen_ai.input.messages holds the tool-use, tool-result and thinking blocks of the request messages.

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), patchAnthropic records the prompt and completion text (gen_ai.prompt.<n>.role, gen_ai.prompt.<n>.content, gen_ai.completion.content). The older gen_ai.system_prompt key holds the first 5,000 characters of a string system. Since npm 0.19.1, a streamed call records the answer text too: the text of the text_delta events, 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 events at the same time. Through npm 0.19.0, a streamed call recorded the prompt only. To keep the text in your process, set traceContent: false or RISICARE_TRACE_CONTENT=false.

Request Capture

With content capture on, patchAnthropic also sends the whole request. It sends three more attributes, beside the older keys. The older gen_ai.prompt.<n>.* 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 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) 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).

Next Steps