@traceloop/instrumentation-anthropic 0.17.0-otel-v1.1 → 0.17.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ var api = require('@opentelemetry/api');
5
5
  var instrumentation = require('@opentelemetry/instrumentation');
6
6
  var aiSemanticConventions = require('@traceloop/ai-semantic-conventions');
7
7
 
8
- var version = "0.17.0-otel-v1.1";
8
+ var version = "0.17.1";
9
9
 
10
10
  class AnthropicInstrumentation extends instrumentation.InstrumentationBase {
11
11
  constructor(config = {}) {
@@ -18,6 +18,7 @@ class AnthropicInstrumentation extends instrumentation.InstrumentationBase {
18
18
  this._diag.debug(`Patching @anthropic-ai/sdk manually`);
19
19
  this._wrap(module.Anthropic.Completions.prototype, "create", this.patchAnthropic("completion", module));
20
20
  this._wrap(module.Anthropic.Messages.prototype, "create", this.patchAnthropic("chat", module));
21
+ this._wrap(module.Anthropic.Beta.Messages.prototype, "create", this.patchAnthropic("chat", module));
21
22
  }
22
23
  init() {
23
24
  const module = new instrumentation.InstrumentationNodeModuleDefinition("@anthropic-ai/sdk", [">=0.9.1"], this.patch.bind(this), this.unpatch.bind(this));
@@ -27,12 +28,14 @@ class AnthropicInstrumentation extends instrumentation.InstrumentationBase {
27
28
  this._diag.debug(`Patching @anthropic-ai/sdk@${moduleVersion}`);
28
29
  this._wrap(moduleExports.Anthropic.Completions.prototype, "create", this.patchAnthropic("completion", moduleExports));
29
30
  this._wrap(moduleExports.Anthropic.Messages.prototype, "create", this.patchAnthropic("chat", moduleExports));
31
+ this._wrap(moduleExports.Anthropic.Beta.Messages.prototype, "create", this.patchAnthropic("chat", moduleExports));
30
32
  return moduleExports;
31
33
  }
32
34
  unpatch(moduleExports, moduleVersion) {
33
35
  this._diag.debug(`Unpatching @anthropic-ai/sdk@${moduleVersion}`);
34
36
  this._unwrap(moduleExports.Anthropic.Completions.prototype, "create");
35
37
  this._unwrap(moduleExports.Anthropic.Messages.prototype, "create");
38
+ this._unwrap(moduleExports.Anthropic.Beta.Messages.prototype, "create");
36
39
  }
37
40
  patchAnthropic(type, moduleExports) {
38
41
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -86,6 +89,13 @@ class AnthropicInstrumentation extends instrumentation.InstrumentationBase {
86
89
  attributes[aiSemanticConventions.SpanAttributes.LLM_REQUEST_TEMPERATURE] = params.temperature;
87
90
  attributes[aiSemanticConventions.SpanAttributes.LLM_REQUEST_TOP_P] = params.top_p;
88
91
  attributes[aiSemanticConventions.SpanAttributes.LLM_TOP_K] = params.top_k;
92
+ // Handle thinking parameters (for beta messages)
93
+ const betaParams = params;
94
+ if (betaParams.thinking && betaParams.thinking.type === "enabled") {
95
+ attributes["llm.request.thinking.type"] = betaParams.thinking.type;
96
+ attributes["llm.request.thinking.budget_tokens"] =
97
+ betaParams.thinking.budget_tokens;
98
+ }
89
99
  if (type === "completion") {
90
100
  attributes[aiSemanticConventions.SpanAttributes.LLM_REQUEST_MAX_TOKENS] =
91
101
  params.max_tokens_to_sample;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/instrumentation.ts"],"sourcesContent":["/*\n * Copyright Traceloop\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n context,\n trace,\n Span,\n Attributes,\n SpanKind,\n SpanStatusCode,\n} from \"@opentelemetry/api\";\nimport {\n InstrumentationBase,\n InstrumentationModuleDefinition,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from \"@opentelemetry/instrumentation\";\nimport {\n CONTEXT_KEY_ALLOW_TRACE_CONTENT,\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { AnthropicInstrumentationConfig } from \"./types\";\nimport { version } from \"../package.json\";\nimport type * as anthropic from \"@anthropic-ai/sdk\";\nimport type {\n CompletionCreateParamsNonStreaming,\n CompletionCreateParamsStreaming,\n Completion,\n} from \"@anthropic-ai/sdk/resources/completions\";\nimport type {\n MessageCreateParamsNonStreaming,\n MessageCreateParamsStreaming,\n Message,\n MessageStreamEvent,\n} from \"@anthropic-ai/sdk/resources/messages\";\nimport type { Stream } from \"@anthropic-ai/sdk/streaming\";\nimport type { APIPromise, BaseAnthropic } from \"@anthropic-ai/sdk\";\n\nexport class AnthropicInstrumentation extends InstrumentationBase {\n declare protected _config: AnthropicInstrumentationConfig;\n\n constructor(config: AnthropicInstrumentationConfig = {}) {\n super(\"@traceloop/instrumentation-anthropic\", version, config);\n }\n\n public override setConfig(config: AnthropicInstrumentationConfig = {}) {\n super.setConfig(config);\n }\n\n public manuallyInstrument(module: typeof anthropic) {\n this._diag.debug(`Patching @anthropic-ai/sdk manually`);\n\n this._wrap(\n module.Anthropic.Completions.prototype,\n \"create\",\n this.patchAnthropic(\"completion\", module),\n );\n this._wrap(\n module.Anthropic.Messages.prototype,\n \"create\",\n this.patchAnthropic(\"chat\", module),\n );\n }\n\n protected init(): InstrumentationModuleDefinition {\n const module = new InstrumentationNodeModuleDefinition(\n \"@anthropic-ai/sdk\",\n [\">=0.9.1\"],\n this.patch.bind(this),\n this.unpatch.bind(this),\n );\n return module;\n }\n\n private patch(moduleExports: typeof anthropic, moduleVersion?: string) {\n this._diag.debug(`Patching @anthropic-ai/sdk@${moduleVersion}`);\n\n this._wrap(\n moduleExports.Anthropic.Completions.prototype,\n \"create\",\n this.patchAnthropic(\"completion\", moduleExports),\n );\n this._wrap(\n moduleExports.Anthropic.Messages.prototype,\n \"create\",\n this.patchAnthropic(\"chat\", moduleExports),\n );\n return moduleExports;\n }\n\n private unpatch(\n moduleExports: typeof anthropic,\n moduleVersion?: string,\n ): void {\n this._diag.debug(`Unpatching @anthropic-ai/sdk@${moduleVersion}`);\n\n this._unwrap(moduleExports.Anthropic.Completions.prototype, \"create\");\n this._unwrap(moduleExports.Anthropic.Messages.prototype, \"create\");\n }\n\n private patchAnthropic(\n type: \"chat\" | \"completion\",\n moduleExports: typeof anthropic,\n ) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const plugin = this;\n // eslint-disable-next-line\n return (original: Function) => {\n return function method(this: any, ...args: unknown[]) {\n const span =\n type === \"chat\"\n ? plugin.startSpan({\n type,\n params: args[0] as MessageCreateParamsNonStreaming & {\n extraAttributes?: Record<string, any>;\n },\n })\n : plugin.startSpan({\n type,\n params: args[0] as CompletionCreateParamsNonStreaming & {\n extraAttributes?: Record<string, any>;\n },\n });\n\n const execContext = trace.setSpan(context.active(), span);\n const execPromise = safeExecuteInTheMiddle(\n () => {\n return context.with(execContext, () => {\n if ((args?.[0] as any)?.extraAttributes) {\n delete (args[0] as any).extraAttributes;\n }\n return original.apply(this, args);\n });\n },\n (e) => {\n if (e) {\n plugin._diag.error(\"Error in Anthropic instrumentation\", e);\n }\n },\n );\n\n if (\n (\n args[0] as\n | MessageCreateParamsStreaming\n | CompletionCreateParamsStreaming\n ).stream\n ) {\n return context.bind(\n execContext,\n plugin._streamingWrapPromise(this._client, moduleExports, {\n span,\n type,\n promise: execPromise,\n }),\n );\n }\n\n const wrappedPromise = plugin._wrapPromise(type, span, execPromise);\n\n return context.bind(execContext, wrappedPromise as any);\n };\n };\n }\n\n private startSpan({\n type,\n params,\n }:\n | {\n type: \"chat\";\n params: MessageCreateParamsNonStreaming & {\n extraAttributes?: Record<string, any>;\n };\n }\n | {\n type: \"completion\";\n params: CompletionCreateParamsNonStreaming & {\n extraAttributes?: Record<string, any>;\n };\n }): Span {\n const attributes: Attributes = {\n [SpanAttributes.LLM_SYSTEM]: \"Anthropic\",\n [SpanAttributes.LLM_REQUEST_TYPE]: type,\n };\n\n try {\n attributes[SpanAttributes.LLM_REQUEST_MODEL] = params.model;\n attributes[SpanAttributes.LLM_REQUEST_TEMPERATURE] = params.temperature;\n attributes[SpanAttributes.LLM_REQUEST_TOP_P] = params.top_p;\n attributes[SpanAttributes.LLM_TOP_K] = params.top_k;\n\n if (type === \"completion\") {\n attributes[SpanAttributes.LLM_REQUEST_MAX_TOKENS] =\n params.max_tokens_to_sample;\n } else {\n attributes[SpanAttributes.LLM_REQUEST_MAX_TOKENS] = params.max_tokens;\n }\n\n if (\n params.extraAttributes !== undefined &&\n typeof params.extraAttributes === \"object\"\n ) {\n Object.keys(params.extraAttributes).forEach((key: string) => {\n attributes[key] = params.extraAttributes![key];\n });\n }\n\n if (this._shouldSendPrompts()) {\n if (type === \"chat\") {\n let promptIndex = 0;\n\n // If a system prompt is provided, it should always be first\n if (\"system\" in params && params.system !== undefined) {\n attributes[`${SpanAttributes.LLM_PROMPTS}.0.role`] = \"system\";\n attributes[`${SpanAttributes.LLM_PROMPTS}.0.content`] =\n typeof params.system === \"string\"\n ? params.system\n : JSON.stringify(params.system);\n promptIndex += 1;\n }\n\n params.messages.forEach((message, index) => {\n const currentIndex = index + promptIndex;\n attributes[`${SpanAttributes.LLM_PROMPTS}.${currentIndex}.role`] =\n message.role;\n if (typeof message.content === \"string\") {\n attributes[\n `${SpanAttributes.LLM_PROMPTS}.${currentIndex}.content`\n ] = (message.content as string) || \"\";\n } else {\n attributes[\n `${SpanAttributes.LLM_PROMPTS}.${currentIndex}.content`\n ] = JSON.stringify(message.content);\n }\n });\n } else {\n attributes[`${SpanAttributes.LLM_PROMPTS}.0.role`] = \"user\";\n attributes[`${SpanAttributes.LLM_PROMPTS}.0.content`] = params.prompt;\n }\n }\n } catch (e) {\n this._diag.debug(e);\n this._config.exceptionLogger?.(e);\n }\n\n return this.tracer.startSpan(`anthropic.${type}`, {\n kind: SpanKind.CLIENT,\n attributes,\n });\n }\n\n private _streamingWrapPromise(\n client: BaseAnthropic,\n moduleExports: typeof anthropic,\n {\n span,\n type,\n promise,\n }:\n | {\n span: Span;\n type: \"chat\";\n promise: APIPromise<Stream<MessageStreamEvent>>;\n }\n | {\n span: Span;\n type: \"completion\";\n promise: APIPromise<Stream<Completion>>;\n },\n ) {\n async function* iterateStream(\n this: AnthropicInstrumentation,\n stream: Stream<MessageStreamEvent> | Stream<Completion>,\n ) {\n try {\n if (type === \"chat\") {\n const result: Message = {\n id: \"0\",\n type: \"message\",\n model: \"\",\n role: \"assistant\",\n stop_reason: null,\n stop_sequence: null,\n usage: {\n input_tokens: 0,\n output_tokens: 0,\n cache_creation_input_tokens: 0,\n cache_read_input_tokens: 0,\n server_tool_use: null,\n service_tier: null,\n },\n content: [],\n };\n\n for await (const chunk of stream) {\n yield chunk;\n\n try {\n switch (chunk.type) {\n case \"message_start\":\n result.id = chunk.message.id;\n result.model = chunk.message.model;\n Object.assign(result.usage, chunk.message.usage);\n break;\n case \"message_delta\":\n if (chunk.usage) {\n Object.assign(result.usage, chunk.usage);\n }\n break;\n case \"content_block_start\":\n if (result.content.length <= chunk.index) {\n result.content.push({ ...chunk.content_block });\n }\n break;\n\n case \"content_block_delta\":\n if (chunk.index < result.content.length) {\n const current = result.content[chunk.index];\n if (\n current.type === \"text\" &&\n chunk.delta.type === \"text_delta\"\n ) {\n result.content[chunk.index] = {\n type: \"text\",\n text: current.text + chunk.delta.text,\n citations: current.citations,\n };\n }\n }\n break;\n }\n } catch (e) {\n this._diag.debug(e);\n this._config.exceptionLogger?.(e);\n }\n }\n\n this._endSpan({ span, type, result });\n } else {\n const result: Completion = {\n id: \"0\",\n type: \"completion\",\n model: \"\",\n completion: \"\",\n stop_reason: null,\n };\n for await (const chunk of stream as Stream<Completion>) {\n yield chunk;\n\n try {\n result.id = chunk.id;\n result.model = chunk.model;\n\n if (chunk.stop_reason) {\n result.stop_reason = chunk.stop_reason;\n }\n if (chunk.model) {\n result.model = chunk.model;\n }\n if (chunk.completion) {\n result.completion += chunk.completion;\n }\n } catch (e) {\n this._diag.debug(e);\n this._config.exceptionLogger?.(e);\n }\n }\n\n this._endSpan({ span, type, result });\n }\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n span.recordException(error);\n span.end();\n throw error;\n }\n }\n\n return new moduleExports.APIPromise(\n client,\n (promise as any).responsePromise,\n async (client, props) => {\n const realStream = await (promise as any).parseResponse(client, props);\n\n // take the incoming stream, iterate it using our instrumented function, and wrap it in a new stream to keep the rich object type the same\n return new realStream.constructor(\n () => iterateStream.call(this, realStream),\n realStream.controller,\n );\n },\n ) as\n | APIPromise<Stream<MessageStreamEvent>>\n | APIPromise<Stream<Completion>>;\n }\n\n private _wrapPromise<T>(\n type: \"chat\" | \"completion\",\n span: Span,\n promise: Promise<T>,\n ): Promise<T> {\n return promise\n .then((result) => {\n if (type === \"chat\") {\n this._endSpan({\n type,\n span,\n result: result as Message,\n });\n } else {\n this._endSpan({\n type,\n span,\n result: result as Completion,\n });\n }\n\n return result;\n })\n .catch((error: Error) => {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n span.recordException(error);\n span.end();\n\n throw error;\n });\n }\n\n private _endSpan({\n span,\n type,\n result,\n }:\n | { span: Span; type: \"chat\"; result: Message }\n | {\n span: Span;\n type: \"completion\";\n result: Completion;\n }) {\n try {\n span.setAttribute(SpanAttributes.LLM_RESPONSE_MODEL, result.model);\n if (type === \"chat\" && result.usage) {\n span.setAttribute(\n SpanAttributes.LLM_USAGE_TOTAL_TOKENS,\n result.usage?.input_tokens + result.usage?.output_tokens,\n );\n span.setAttribute(\n SpanAttributes.LLM_USAGE_COMPLETION_TOKENS,\n result.usage?.output_tokens,\n );\n span.setAttribute(\n SpanAttributes.LLM_USAGE_PROMPT_TOKENS,\n result.usage?.input_tokens,\n );\n }\n\n if (result.stop_reason) {\n span.setAttribute(\n `${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`,\n result.stop_reason,\n );\n }\n\n if (this._shouldSendPrompts()) {\n if (type === \"chat\") {\n span.setAttribute(\n `${SpanAttributes.LLM_COMPLETIONS}.0.role`,\n \"assistant\",\n );\n span.setAttribute(\n `${SpanAttributes.LLM_COMPLETIONS}.0.content`,\n JSON.stringify(result.content),\n );\n } else {\n span.setAttribute(\n `${SpanAttributes.LLM_COMPLETIONS}.0.role`,\n \"assistant\",\n );\n span.setAttribute(\n `${SpanAttributes.LLM_COMPLETIONS}.0.content`,\n result.completion,\n );\n }\n }\n } catch (e) {\n this._diag.debug(e);\n this._config.exceptionLogger?.(e);\n }\n\n span.end();\n }\n\n private _shouldSendPrompts() {\n const contextShouldSendPrompts = context\n .active()\n .getValue(CONTEXT_KEY_ALLOW_TRACE_CONTENT);\n\n if (contextShouldSendPrompts !== undefined) {\n return contextShouldSendPrompts;\n }\n\n return this._config.traceContent !== undefined\n ? this._config.traceContent\n : true;\n }\n}\n"],"names":["InstrumentationBase","InstrumentationNodeModuleDefinition","trace","context","safeExecuteInTheMiddle","SpanAttributes","SpanKind","__asyncValues","__await","SpanStatusCode","__awaiter","CONTEXT_KEY_ALLOW_TRACE_CONTENT"],"mappings":";;;;;;;;;AAkDM,MAAO,wBAAyB,SAAQA,mCAAmB,CAAA;AAG/D,IAAA,WAAA,CAAY,SAAyC,EAAE,EAAA;AACrD,QAAA,KAAK,CAAC,sCAAsC,EAAE,OAAO,EAAE,MAAM,CAAC;IAChE;IAEgB,SAAS,CAAC,SAAyC,EAAE,EAAA;AACnE,QAAA,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC;IACzB;AAEO,IAAA,kBAAkB,CAAC,MAAwB,EAAA;AAChD,QAAA,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA,mCAAA,CAAqC,CAAC;QAEvD,IAAI,CAAC,KAAK,CACR,MAAM,CAAC,SAAS,CAAC,WAAW,CAAC,SAAS,EACtC,QAAQ,EACR,IAAI,CAAC,cAAc,CAAC,YAAY,EAAE,MAAM,CAAC,CAC1C;QACD,IAAI,CAAC,KAAK,CACR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BAAA,IAAI,CAAC,YAAY,CACf,CAAA,EAAGA,oCAAc,CAAC,eAAe,CAAA,UAAA,CAAY,EAC7C,MAAM,CAAC,UAAU,CAClB;gBACH;YACF;QACF;QAAE,OAAO,CAAC,EAAE;AACV,YAAA,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;YACnB,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,IAAI,CAAC,OAAO,EAAC,eAAe,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,MAAA,GAAA,EAAA,CAAA,IAAA,CAAA,EAAA,EAAG,CAAC,CAAC;QACnC;QAEA,IAAI,CAAC,GAAG,EAAE;IACZ;IAEQ,kBAAkB,GAAA;QACxB,MAAM,wBAAwB,GAAGF;AAC9B,aAAA,MAAM;aACN,QAAQ,CAACQ,qDAA+B,CAAC;AAE5C,QAAA,IAAI,wBAAwB,KAAK,SAAS,EAAE;AAC1C,YAAA,OAAO,wBAAwB;QACjC;AAEA,QAAA,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,KAAK;AACnC,cAAE,IAAI,CAAC,OAAO,CAAC;cACb,IAAI;IACV;AACD;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../src/instrumentation.ts"],"sourcesContent":["/*\n * Copyright Traceloop\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n context,\n trace,\n Span,\n Attributes,\n SpanKind,\n SpanStatusCode,\n} from \"@opentelemetry/api\";\nimport {\n InstrumentationBase,\n InstrumentationModuleDefinition,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from \"@opentelemetry/instrumentation\";\nimport {\n CONTEXT_KEY_ALLOW_TRACE_CONTENT,\n SpanAttributes,\n} from \"@traceloop/ai-semantic-conventions\";\nimport { AnthropicInstrumentationConfig } from \"./types\";\nimport { version } from \"../package.json\";\nimport type * as anthropic from \"@anthropic-ai/sdk\";\nimport type {\n CompletionCreateParamsNonStreaming,\n CompletionCreateParamsStreaming,\n Completion,\n} from \"@anthropic-ai/sdk/resources/completions\";\nimport type {\n MessageCreateParamsNonStreaming,\n MessageCreateParamsStreaming,\n Message,\n MessageStreamEvent,\n} from \"@anthropic-ai/sdk/resources/messages\";\nimport type { MessageCreateParamsNonStreaming as BetaMessageCreateParamsNonStreaming } from \"@anthropic-ai/sdk/resources/beta/messages\";\nimport type { Stream } from \"@anthropic-ai/sdk/streaming\";\nimport type { APIPromise, BaseAnthropic } from \"@anthropic-ai/sdk\";\n\nexport class AnthropicInstrumentation extends InstrumentationBase {\n declare protected _config: AnthropicInstrumentationConfig;\n\n constructor(config: AnthropicInstrumentationConfig = {}) {\n super(\"@traceloop/instrumentation-anthropic\", version, config);\n }\n\n public override setConfig(config: AnthropicInstrumentationConfig = {}) {\n super.setConfig(config);\n }\n\n public manuallyInstrument(module: typeof anthropic) {\n this._diag.debug(`Patching @anthropic-ai/sdk manually`);\n\n this._wrap(\n module.Anthropic.Completions.prototype,\n \"create\",\n this.patchAnthropic(\"completion\", module),\n );\n this._wrap(\n module.Anthropic.Messages.prototype,\n \"create\",\n this.patchAnthropic(\"chat\", module),\n );\n this._wrap(\n module.Anthropic.Beta.Messages.prototype,\n \"create\",\n this.patchAnthropic(\"chat\", module),\n );\n }\n\n protected init(): InstrumentationModuleDefinition {\n const module = new InstrumentationNodeModuleDefinition(\n \"@anthropic-ai/sdk\",\n [\">=0.9.1\"],\n this.patch.bind(this),\n this.unpatch.bind(this),\n );\n return module;\n }\n\n private patch(moduleExports: typeof anthropic, moduleVersion?: string) {\n this._diag.debug(`Patching @anthropic-ai/sdk@${moduleVersion}`);\n\n this._wrap(\n moduleExports.Anthropic.Completions.prototype,\n \"create\",\n this.patchAnthropic(\"completion\", moduleExports),\n );\n this._wrap(\n moduleExports.Anthropic.Messages.prototype,\n \"create\",\n this.patchAnthropic(\"chat\", moduleExports),\n );\n this._wrap(\n moduleExports.Anthropic.Beta.Messages.prototype,\n \"create\",\n this.patchAnthropic(\"chat\", moduleExports),\n );\n return moduleExports;\n }\n\n private unpatch(\n moduleExports: typeof anthropic,\n moduleVersion?: string,\n ): void {\n this._diag.debug(`Unpatching @anthropic-ai/sdk@${moduleVersion}`);\n\n this._unwrap(moduleExports.Anthropic.Completions.prototype, \"create\");\n this._unwrap(moduleExports.Anthropic.Messages.prototype, \"create\");\n this._unwrap(moduleExports.Anthropic.Beta.Messages.prototype, \"create\");\n }\n\n private patchAnthropic(\n type: \"chat\" | \"completion\",\n moduleExports: typeof anthropic,\n ) {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const plugin = this;\n // eslint-disable-next-line\n return (original: Function) => {\n return function method(this: any, ...args: unknown[]) {\n const span =\n type === \"chat\"\n ? plugin.startSpan({\n type,\n params: args[0] as MessageCreateParamsNonStreaming & {\n extraAttributes?: Record<string, any>;\n },\n })\n : plugin.startSpan({\n type,\n params: args[0] as CompletionCreateParamsNonStreaming & {\n extraAttributes?: Record<string, any>;\n },\n });\n\n const execContext = trace.setSpan(context.active(), span);\n const execPromise = safeExecuteInTheMiddle(\n () => {\n return context.with(execContext, () => {\n if ((args?.[0] as any)?.extraAttributes) {\n delete (args[0] as any).extraAttributes;\n }\n return original.apply(this, args);\n });\n },\n (e) => {\n if (e) {\n plugin._diag.error(\"Error in Anthropic instrumentation\", e);\n }\n },\n );\n\n if (\n (\n args[0] as\n | MessageCreateParamsStreaming\n | CompletionCreateParamsStreaming\n ).stream\n ) {\n return context.bind(\n execContext,\n plugin._streamingWrapPromise(this._client, moduleExports, {\n span,\n type,\n promise: execPromise,\n }),\n );\n }\n\n const wrappedPromise = plugin._wrapPromise(type, span, execPromise);\n\n return context.bind(execContext, wrappedPromise as any);\n };\n };\n }\n\n private startSpan({\n type,\n params,\n }:\n | {\n type: \"chat\";\n params: MessageCreateParamsNonStreaming & {\n extraAttributes?: Record<string, any>;\n };\n }\n | {\n type: \"completion\";\n params: CompletionCreateParamsNonStreaming & {\n extraAttributes?: Record<string, any>;\n };\n }): Span {\n const attributes: Attributes = {\n [SpanAttributes.LLM_SYSTEM]: \"Anthropic\",\n [SpanAttributes.LLM_REQUEST_TYPE]: type,\n };\n\n try {\n attributes[SpanAttributes.LLM_REQUEST_MODEL] = params.model;\n attributes[SpanAttributes.LLM_REQUEST_TEMPERATURE] = params.temperature;\n attributes[SpanAttributes.LLM_REQUEST_TOP_P] = params.top_p;\n attributes[SpanAttributes.LLM_TOP_K] = params.top_k;\n\n // Handle thinking parameters (for beta messages)\n const betaParams = params as BetaMessageCreateParamsNonStreaming;\n if (betaParams.thinking && betaParams.thinking.type === \"enabled\") {\n attributes[\"llm.request.thinking.type\"] = betaParams.thinking.type;\n attributes[\"llm.request.thinking.budget_tokens\"] =\n betaParams.thinking.budget_tokens;\n }\n\n if (type === \"completion\") {\n attributes[SpanAttributes.LLM_REQUEST_MAX_TOKENS] =\n params.max_tokens_to_sample;\n } else {\n attributes[SpanAttributes.LLM_REQUEST_MAX_TOKENS] = params.max_tokens;\n }\n\n if (\n params.extraAttributes !== undefined &&\n typeof params.extraAttributes === \"object\"\n ) {\n Object.keys(params.extraAttributes).forEach((key: string) => {\n attributes[key] = params.extraAttributes![key];\n });\n }\n\n if (this._shouldSendPrompts()) {\n if (type === \"chat\") {\n let promptIndex = 0;\n\n // If a system prompt is provided, it should always be first\n if (\"system\" in params && params.system !== undefined) {\n attributes[`${SpanAttributes.LLM_PROMPTS}.0.role`] = \"system\";\n attributes[`${SpanAttributes.LLM_PROMPTS}.0.content`] =\n typeof params.system === \"string\"\n ? params.system\n : JSON.stringify(params.system);\n promptIndex += 1;\n }\n\n params.messages.forEach((message, index) => {\n const currentIndex = index + promptIndex;\n attributes[`${SpanAttributes.LLM_PROMPTS}.${currentIndex}.role`] =\n message.role;\n if (typeof message.content === \"string\") {\n attributes[\n `${SpanAttributes.LLM_PROMPTS}.${currentIndex}.content`\n ] = (message.content as string) || \"\";\n } else {\n attributes[\n `${SpanAttributes.LLM_PROMPTS}.${currentIndex}.content`\n ] = JSON.stringify(message.content);\n }\n });\n } else {\n attributes[`${SpanAttributes.LLM_PROMPTS}.0.role`] = \"user\";\n attributes[`${SpanAttributes.LLM_PROMPTS}.0.content`] = params.prompt;\n }\n }\n } catch (e) {\n this._diag.debug(e);\n this._config.exceptionLogger?.(e);\n }\n\n return this.tracer.startSpan(`anthropic.${type}`, {\n kind: SpanKind.CLIENT,\n attributes,\n });\n }\n\n private _streamingWrapPromise(\n client: BaseAnthropic,\n moduleExports: typeof anthropic,\n {\n span,\n type,\n promise,\n }:\n | {\n span: Span;\n type: \"chat\";\n promise: APIPromise<Stream<MessageStreamEvent>>;\n }\n | {\n span: Span;\n type: \"completion\";\n promise: APIPromise<Stream<Completion>>;\n },\n ) {\n async function* iterateStream(\n this: AnthropicInstrumentation,\n stream: Stream<MessageStreamEvent> | Stream<Completion>,\n ) {\n try {\n if (type === \"chat\") {\n const result: Message = {\n id: \"0\",\n type: \"message\",\n model: \"\",\n role: \"assistant\",\n stop_reason: null,\n stop_sequence: null,\n usage: {\n input_tokens: 0,\n output_tokens: 0,\n cache_creation_input_tokens: 0,\n cache_read_input_tokens: 0,\n server_tool_use: null,\n service_tier: null,\n },\n content: [],\n };\n\n for await (const chunk of stream) {\n yield chunk;\n\n try {\n switch (chunk.type) {\n case \"message_start\":\n result.id = chunk.message.id;\n result.model = chunk.message.model;\n Object.assign(result.usage, chunk.message.usage);\n break;\n case \"message_delta\":\n if (chunk.usage) {\n Object.assign(result.usage, chunk.usage);\n }\n break;\n case \"content_block_start\":\n if (result.content.length <= chunk.index) {\n result.content.push({ ...chunk.content_block });\n }\n break;\n\n case \"content_block_delta\":\n if (chunk.index < result.content.length) {\n const current = result.content[chunk.index];\n if (\n current.type === \"text\" &&\n chunk.delta.type === \"text_delta\"\n ) {\n result.content[chunk.index] = {\n type: \"text\",\n text: current.text + chunk.delta.text,\n citations: current.citations,\n };\n }\n }\n break;\n }\n } catch (e) {\n this._diag.debug(e);\n this._config.exceptionLogger?.(e);\n }\n }\n\n this._endSpan({ span, type, result });\n } else {\n const result: Completion = {\n id: \"0\",\n type: \"completion\",\n model: \"\",\n completion: \"\",\n stop_reason: null,\n };\n for await (const chunk of stream as Stream<Completion>) {\n yield chunk;\n\n try {\n result.id = chunk.id;\n result.model = chunk.model;\n\n if (chunk.stop_reason) {\n result.stop_reason = chunk.stop_reason;\n }\n if (chunk.model) {\n result.model = chunk.model;\n }\n if (chunk.completion) {\n result.completion += chunk.completion;\n }\n } catch (e) {\n this._diag.debug(e);\n this._config.exceptionLogger?.(e);\n }\n }\n\n this._endSpan({ span, type, result });\n }\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n span.recordException(error);\n span.end();\n throw error;\n }\n }\n\n return new moduleExports.APIPromise(\n client,\n (promise as any).responsePromise,\n async (client, props) => {\n const realStream = await (promise as any).parseResponse(client, props);\n\n // take the incoming stream, iterate it using our instrumented function, and wrap it in a new stream to keep the rich object type the same\n return new realStream.constructor(\n () => iterateStream.call(this, realStream),\n realStream.controller,\n );\n },\n ) as\n | APIPromise<Stream<MessageStreamEvent>>\n | APIPromise<Stream<Completion>>;\n }\n\n private _wrapPromise<T>(\n type: \"chat\" | \"completion\",\n span: Span,\n promise: Promise<T>,\n ): Promise<T> {\n return promise\n .then((result) => {\n if (type === \"chat\") {\n this._endSpan({\n type,\n span,\n result: result as Message,\n });\n } else {\n this._endSpan({\n type,\n span,\n result: result as Completion,\n });\n }\n\n return result;\n })\n .catch((error: Error) => {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n span.recordException(error);\n span.end();\n\n throw error;\n });\n }\n\n private _endSpan({\n span,\n type,\n result,\n }:\n | { span: Span; type: \"chat\"; result: Message }\n | {\n span: Span;\n type: \"completion\";\n result: Completion;\n }) {\n try {\n span.setAttribute(SpanAttributes.LLM_RESPONSE_MODEL, result.model);\n if (type === \"chat\" && result.usage) {\n span.setAttribute(\n SpanAttributes.LLM_USAGE_TOTAL_TOKENS,\n result.usage?.input_tokens + result.usage?.output_tokens,\n );\n span.setAttribute(\n SpanAttributes.LLM_USAGE_COMPLETION_TOKENS,\n result.usage?.output_tokens,\n );\n span.setAttribute(\n SpanAttributes.LLM_USAGE_PROMPT_TOKENS,\n result.usage?.input_tokens,\n );\n }\n\n if (result.stop_reason) {\n span.setAttribute(\n `${SpanAttributes.LLM_COMPLETIONS}.0.finish_reason`,\n result.stop_reason,\n );\n }\n\n if (this._shouldSendPrompts()) {\n if (type === \"chat\") {\n span.setAttribute(\n `${SpanAttributes.LLM_COMPLETIONS}.0.role`,\n \"assistant\",\n );\n span.setAttribute(\n `${SpanAttributes.LLM_COMPLETIONS}.0.content`,\n JSON.stringify(result.content),\n );\n } else {\n span.setAttribute(\n `${SpanAttributes.LLM_COMPLETIONS}.0.role`,\n \"assistant\",\n );\n span.setAttribute(\n `${SpanAttributes.LLM_COMPLETIONS}.0.content`,\n result.completion,\n );\n }\n }\n } catch (e) {\n this._diag.debug(e);\n this._config.exceptionLogger?.(e);\n }\n\n span.end();\n }\n\n private _shouldSendPrompts() {\n const contextShouldSendPrompts = context\n .active()\n .getValue(CONTEXT_KEY_ALLOW_TRACE_CONTENT);\n\n if (contextShouldSendPrompts !== undefined) {\n return contextShouldSendPrompts;\n }\n\n return this._config.traceContent !== undefined\n ? this._config.traceContent\n : true;\n }\n}\n"],"names":["InstrumentationBase","InstrumentationNodeModuleDefinition","trace","context","safeExecuteInTheMiddle","SpanAttributes","SpanKind","__asyncValues","__await","SpanStatusCode","__awaiter","CONTEXT_KEY_ALLOW_TRACE_CONTENT"],"mappings":";;;;;;;;;AAmDM,MAAO,wBAAyB,SAAQA,mCAAmB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,CAAA,EAAGA,oCAAc,CAAC,eAAe,CAAA,UAAA,CAAY,EAC7C,MAAM,CAAC,UAAU,CAClB;gBACH;YACF;QACF;QAAE,OAAO,CAAC,EAAE;AACV,YAAA,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;YACnB,CAAA,EAAA,GAAA,CAAA,EAAA,GAAA,IAAI,CAAC,OAAO,EAAC,eAAe,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,MAAA,GAAA,EAAA,CAAA,IAAA,CAAA,EAAA,EAAG,CAAC,CAAC;QACnC;QAEA,IAAI,CAAC,GAAG,EAAE;IACZ;IAEQ,kBAAkB,GAAA;QACxB,MAAM,wBAAwB,GAAGF;AAC9B,aAAA,MAAM;aACN,QAAQ,CAACQ,qDAA+B,CAAC;AAE5C,QAAA,IAAI,wBAAwB,KAAK,SAAS,EAAE;AAC1C,YAAA,OAAO,wBAAwB;QACjC;AAEA,QAAA,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,KAAK;AACnC,cAAE,IAAI,CAAC,OAAO,CAAC;cACb,IAAI;IACV;AACD;;;;"}
package/dist/index.mjs CHANGED
@@ -3,7 +3,7 @@ import { trace, context, SpanKind, SpanStatusCode } from '@opentelemetry/api';
3
3
  import { InstrumentationBase, InstrumentationNodeModuleDefinition, safeExecuteInTheMiddle } from '@opentelemetry/instrumentation';
4
4
  import { SpanAttributes, CONTEXT_KEY_ALLOW_TRACE_CONTENT } from '@traceloop/ai-semantic-conventions';
5
5
 
6
- var version = "0.17.0-otel-v1.1";
6
+ var version = "0.17.1";
7
7
 
8
8
  class AnthropicInstrumentation extends InstrumentationBase {
9
9
  constructor(config = {}) {
@@ -16,6 +16,7 @@ class AnthropicInstrumentation extends InstrumentationBase {
16
16
  this._diag.debug(`Patching @anthropic-ai/sdk manually`);
17
17
  this._wrap(module.Anthropic.Completions.prototype, "create", this.patchAnthropic("completion", module));
18
18
  this._wrap(module.Anthropic.Messages.prototype, "create", this.patchAnthropic("chat", module));
19
+ this._wrap(module.Anthropic.Beta.Messages.prototype, "create", this.patchAnthropic("chat", module));
19
20
  }
20
21
  init() {
21
22
  const module = new InstrumentationNodeModuleDefinition("@anthropic-ai/sdk", [">=0.9.1"], this.patch.bind(this), this.unpatch.bind(this));
@@ -25,12 +26,14 @@ class AnthropicInstrumentation extends InstrumentationBase {
25
26
  this._diag.debug(`Patching @anthropic-ai/sdk@${moduleVersion}`);
26
27
  this._wrap(moduleExports.Anthropic.Completions.prototype, "create", this.patchAnthropic("completion", moduleExports));
27
28
  this._wrap(moduleExports.Anthropic.Messages.prototype, "create", this.patchAnthropic("chat", moduleExports));
29
+ this._wrap(moduleExports.Anthropic.Beta.Messages.prototype, "create", this.patchAnthropic("chat", moduleExports));
28
30
  return moduleExports;
29
31
  }
30
32
  unpatch(moduleExports, moduleVersion) {
31
33
  this._diag.debug(`Unpatching @anthropic-ai/sdk@${moduleVersion}`);
32
34
  this._unwrap(moduleExports.Anthropic.Completions.prototype, "create");
33
35
  this._unwrap(moduleExports.Anthropic.Messages.prototype, "create");
36
+ this._unwrap(moduleExports.Anthropic.Beta.Messages.prototype, "create");
34
37
  }
35
38
  patchAnthropic(type, moduleExports) {
36
39
  // eslint-disable-next-line @typescript-eslint/no-this-alias
@@ -84,6 +87,13 @@ class AnthropicInstrumentation extends InstrumentationBase {
84
87
  attributes[SpanAttributes.LLM_REQUEST_TEMPERATURE] = params.temperature;
85
88
  attributes[SpanAttributes.LLM_REQUEST_TOP_P] = params.top_p;
86
89
  attributes[SpanAttributes.LLM_TOP_K] = params.top_k;
90
+ // Handle thinking parameters (for beta messages)
91
+ const betaParams = params;
92
+ if (betaParams.thinking && betaParams.thinking.type === "enabled") {
93
+ attributes["llm.request.thinking.type"] = betaParams.thinking.type;
94
+ attributes["llm.request.thinking.budget_tokens"] =
95
+ betaParams.thinking.budget_tokens;
96
+ }
87
97
  if (type === "completion") {
88
98
  attributes[SpanAttributes.LLM_REQUEST_MAX_TOKENS] =
89
99
  params.max_tokens_to_sample;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@traceloop/instrumentation-anthropic",
3
- "version": "0.17.0-otel-v1.1",
3
+ "version": "0.17.1",
4
4
  "description": "Anthropic Instrumentaion",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -38,17 +38,17 @@
38
38
  "access": "public"
39
39
  },
40
40
  "dependencies": {
41
- "@opentelemetry/api": "^1.7.0",
42
- "@opentelemetry/core": "^1.30.1",
43
- "@opentelemetry/instrumentation": "^0.57.2",
41
+ "@opentelemetry/api": "^1.9.0",
42
+ "@opentelemetry/core": "^2.0.1",
43
+ "@opentelemetry/instrumentation": "^0.203.0",
44
44
  "@opentelemetry/semantic-conventions": "^1.36.0",
45
- "@traceloop/ai-semantic-conventions": "0.17.0-otel-v1.1",
45
+ "@traceloop/ai-semantic-conventions": "0.17.0",
46
46
  "tslib": "^2.8.1"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@anthropic-ai/sdk": "^0.56.0",
50
- "@opentelemetry/context-async-hooks": "^1.30.1",
51
- "@opentelemetry/sdk-trace-node": "^1.30.1",
50
+ "@opentelemetry/context-async-hooks": "^2.0.1",
51
+ "@opentelemetry/sdk-trace-node": "^2.0.1",
52
52
  "@pollyjs/adapter-fetch": "^6.0.7",
53
53
  "@pollyjs/adapter-node-http": "^6.0.6",
54
54
  "@pollyjs/core": "^6.0.6",
@@ -57,5 +57,5 @@
57
57
  "ts-mocha": "^11.1.0"
58
58
  },
59
59
  "homepage": "https://github.com/traceloop/openllmetry-js/tree/main/packages/instrumentation-anthropic",
60
- "gitHead": "5b7fe8fdb2ad614fea48e85da19002cab052134d"
60
+ "gitHead": "b5878c5eae9833f520d2b8a2e41d39f4a19f5006"
61
61
  }
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=instrumentation.test.d.ts.map