@telemetry-dev/anthropic 0.1.0
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/LICENSE +21 -0
- package/README.md +62 -0
- package/dist/index.d.mts +11 -0
- package/dist/index.mjs +430 -0
- package/package.json +59 -0
- package/src/index.ts +590 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 telemetry.dev
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# @telemetry-dev/anthropic
|
|
2
|
+
|
|
3
|
+
Anthropic SDK instrumentation for telemetry.dev. It wraps the Anthropic Messages API and emits OpenTelemetry GenAI spans through `@telemetry-dev/sdk`.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
pnpm add @telemetry-dev/sdk @telemetry-dev/anthropic @anthropic-ai/sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Set `TELEMETRY_DEV_API_KEY` for telemetry export and `ANTHROPIC_API_KEY` for Anthropic.
|
|
12
|
+
|
|
13
|
+
## Per-client wrapping
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import Anthropic from "@anthropic-ai/sdk";
|
|
17
|
+
import { init, shutdown } from "@telemetry-dev/sdk";
|
|
18
|
+
import { wrapAnthropic } from "@telemetry-dev/anthropic";
|
|
19
|
+
|
|
20
|
+
init({ serviceName: "anthropic-worker" });
|
|
21
|
+
|
|
22
|
+
const anthropic = wrapAnthropic(new Anthropic());
|
|
23
|
+
const response = await anthropic.messages.create({
|
|
24
|
+
model: "claude-sonnet-4-6",
|
|
25
|
+
max_tokens: 256,
|
|
26
|
+
messages: [{ role: "user", content: "Say hello." }],
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
await shutdown();
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
`wrapAnthropic(client)` mutates and returns that client. It is idempotent.
|
|
33
|
+
|
|
34
|
+
## Global instrumentation
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { instrumentAnthropic, uninstrumentAnthropic } from "@telemetry-dev/anthropic";
|
|
38
|
+
|
|
39
|
+
instrumentAnthropic();
|
|
40
|
+
// new Anthropic().messages.create(...) is now traced.
|
|
41
|
+
uninstrumentAnthropic();
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Global instrumentation patches `Messages.prototype.create`; call it once during process startup.
|
|
45
|
+
|
|
46
|
+
## Instrumented surfaces
|
|
47
|
+
|
|
48
|
+
- `client.messages.create(...)`, including `stream: true` responses.
|
|
49
|
+
- `client.messages.stream(...)` when the SDK helper is used.
|
|
50
|
+
- Anthropic, Bedrock, and Vertex clients. Provider attributes are emitted as `anthropic`, `aws.bedrock`, or `gcp.vertex_ai`.
|
|
51
|
+
|
|
52
|
+
Captured request fields include model, max tokens, temperature, top-p, stop sequences, system instructions, tools, and messages. Captured response fields include model, finish reason, content blocks, message id, and token usage including cache and thinking token details when Anthropic returns them.
|
|
53
|
+
|
|
54
|
+
## Streaming behavior
|
|
55
|
+
|
|
56
|
+
Streaming spans start when the request is made and end when the stream is consumed, closes early, or errors. The integration aggregates text, tool input JSON fragments, thinking deltas, signatures, usage, and the latest known stop reason before ending the span.
|
|
57
|
+
|
|
58
|
+
## Limitations
|
|
59
|
+
|
|
60
|
+
- `beta.messages`, `messages.countTokens`, and other non-Messages surfaces are not instrumented.
|
|
61
|
+
- `with_raw_response` and `with_streaming_response` helper namespaces are not patched directly.
|
|
62
|
+
- If application code never consumes or closes a stream, the span cannot finish until the stream is finalized by the runtime.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { SpanFields, SpanHandle, StartSpanOptions } from "@telemetry-dev/sdk";
|
|
2
|
+
|
|
3
|
+
//#region src/index.d.ts
|
|
4
|
+
interface AnthropicClient {
|
|
5
|
+
messages: object;
|
|
6
|
+
}
|
|
7
|
+
declare function wrapAnthropic<T extends AnthropicClient>(client: T): T;
|
|
8
|
+
declare function instrumentAnthropic(): void;
|
|
9
|
+
declare function uninstrumentAnthropic(): void;
|
|
10
|
+
//#endregion
|
|
11
|
+
export { type SpanFields, type SpanHandle, type StartSpanOptions, instrumentAnthropic, uninstrumentAnthropic, wrapAnthropic };
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,430 @@
|
|
|
1
|
+
import { startSpan } from "@telemetry-dev/sdk";
|
|
2
|
+
import { Stream } from "@anthropic-ai/sdk/core/streaming";
|
|
3
|
+
import { Messages } from "@anthropic-ai/sdk/resources/messages";
|
|
4
|
+
//#region src/index.ts
|
|
5
|
+
const WRAPPED = Symbol("telemetry.dev.anthropic.wrapped");
|
|
6
|
+
const WRAPPED_ORIGINAL = Symbol("telemetry.dev.anthropic.original");
|
|
7
|
+
const wrappedClients = /* @__PURE__ */ new WeakSet();
|
|
8
|
+
function asRecord(value) {
|
|
9
|
+
return value !== null && typeof value === "object" ? value : void 0;
|
|
10
|
+
}
|
|
11
|
+
function readString(value) {
|
|
12
|
+
return typeof value === "string" ? value : void 0;
|
|
13
|
+
}
|
|
14
|
+
function readNumber(value) {
|
|
15
|
+
return typeof value === "number" ? value : void 0;
|
|
16
|
+
}
|
|
17
|
+
function compactUsage(usage) {
|
|
18
|
+
if (!usage) return void 0;
|
|
19
|
+
return Object.values(usage).some((value) => value !== void 0) ? usage : void 0;
|
|
20
|
+
}
|
|
21
|
+
function stopSequences(value) {
|
|
22
|
+
if (typeof value === "string") return [value];
|
|
23
|
+
if (!Array.isArray(value)) return void 0;
|
|
24
|
+
const strings = value.filter((item) => typeof item === "string");
|
|
25
|
+
return strings.length > 0 ? strings : void 0;
|
|
26
|
+
}
|
|
27
|
+
function messagesRequest(body) {
|
|
28
|
+
const model = readString(body.model);
|
|
29
|
+
const input = body.tools !== void 0 || body.tool_choice !== void 0 ? {
|
|
30
|
+
messages: body.messages,
|
|
31
|
+
tools: body.tools,
|
|
32
|
+
tool_choice: body.tool_choice
|
|
33
|
+
} : body.messages;
|
|
34
|
+
return {
|
|
35
|
+
name: `chat ${model ?? "unknown"}`,
|
|
36
|
+
fields: {
|
|
37
|
+
type: "generation",
|
|
38
|
+
model,
|
|
39
|
+
input,
|
|
40
|
+
systemInstructions: body.system,
|
|
41
|
+
temperature: readNumber(body.temperature),
|
|
42
|
+
topP: readNumber(body.top_p),
|
|
43
|
+
topK: readNumber(body.top_k),
|
|
44
|
+
maxTokens: readNumber(body.max_tokens),
|
|
45
|
+
stopSequences: stopSequences(body.stop_sequences)
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
function messagesUsage(usage) {
|
|
50
|
+
const u = asRecord(usage);
|
|
51
|
+
const outputDetails = asRecord(u?.output_tokens_details);
|
|
52
|
+
return compactUsage({
|
|
53
|
+
inputTokens: readNumber(u?.input_tokens),
|
|
54
|
+
outputTokens: readNumber(u?.output_tokens),
|
|
55
|
+
cacheReadInputTokens: readNumber(u?.cache_read_input_tokens),
|
|
56
|
+
cacheCreationInputTokens: readNumber(u?.cache_creation_input_tokens),
|
|
57
|
+
reasoningOutputTokens: readNumber(outputDetails?.thinking_tokens)
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
function mergeUsage(current, incoming) {
|
|
61
|
+
if (!incoming) return current;
|
|
62
|
+
return compactUsage({
|
|
63
|
+
inputTokens: incoming.inputTokens ?? current?.inputTokens,
|
|
64
|
+
outputTokens: incoming.outputTokens ?? current?.outputTokens,
|
|
65
|
+
cacheReadInputTokens: incoming.cacheReadInputTokens ?? current?.cacheReadInputTokens,
|
|
66
|
+
cacheCreationInputTokens: incoming.cacheCreationInputTokens ?? current?.cacheCreationInputTokens,
|
|
67
|
+
reasoningOutputTokens: incoming.reasoningOutputTokens ?? current?.reasoningOutputTokens
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
function messagesResponse(response) {
|
|
71
|
+
const r = asRecord(response) ?? {};
|
|
72
|
+
const role = readString(r.role) ?? "assistant";
|
|
73
|
+
return {
|
|
74
|
+
responseModel: readString(r.model),
|
|
75
|
+
responseId: readString(r.id),
|
|
76
|
+
finishReason: readString(r.stop_reason),
|
|
77
|
+
output: r.content !== void 0 ? [{
|
|
78
|
+
role,
|
|
79
|
+
content: r.content
|
|
80
|
+
}] : void 0,
|
|
81
|
+
usage: messagesUsage(r.usage)
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
function constructorName(value) {
|
|
85
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return;
|
|
86
|
+
const ctor = value.constructor;
|
|
87
|
+
return typeof ctor === "function" ? ctor.name : void 0;
|
|
88
|
+
}
|
|
89
|
+
function providerForClient(client) {
|
|
90
|
+
switch (constructorName(client)) {
|
|
91
|
+
case "AnthropicBedrock":
|
|
92
|
+
case "AsyncAnthropicBedrock": return "aws.bedrock";
|
|
93
|
+
case "AnthropicVertex":
|
|
94
|
+
case "AsyncAnthropicVertex": return "gcp.vertex_ai";
|
|
95
|
+
default: return "anthropic";
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
function providerForResource(resource) {
|
|
99
|
+
return providerForClient(asRecord(resource)?._client);
|
|
100
|
+
}
|
|
101
|
+
function isWrapped(fn) {
|
|
102
|
+
if (typeof fn !== "function") return false;
|
|
103
|
+
return fn[WRAPPED] === true;
|
|
104
|
+
}
|
|
105
|
+
function markWrapped(fn, original) {
|
|
106
|
+
Object.defineProperty(fn, WRAPPED, { value: true });
|
|
107
|
+
Object.defineProperty(fn, WRAPPED_ORIGINAL, { value: original });
|
|
108
|
+
return fn;
|
|
109
|
+
}
|
|
110
|
+
function endOnce(span) {
|
|
111
|
+
let ended = false;
|
|
112
|
+
return (fields) => {
|
|
113
|
+
if (ended) return;
|
|
114
|
+
ended = true;
|
|
115
|
+
span.end(fields);
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function mapRawResponse(response) {
|
|
119
|
+
const requestId = response.headers.get("request-id");
|
|
120
|
+
return {
|
|
121
|
+
...requestId ? { responseId: requestId } : {},
|
|
122
|
+
attributes: { "http.response.status_code": response.status }
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
function finalizeParsedValue(value, ctx) {
|
|
126
|
+
if (ctx.streaming) {
|
|
127
|
+
const wrapped = wrapStream(value, ctx.span, ctx.startedAt, ctx.end);
|
|
128
|
+
if (wrapped !== value) return wrapped;
|
|
129
|
+
}
|
|
130
|
+
ctx.end(ctx.mapResponse(value));
|
|
131
|
+
return value;
|
|
132
|
+
}
|
|
133
|
+
function rejectMissing(method) {
|
|
134
|
+
return Promise.reject(/* @__PURE__ */ new TypeError(`wrapped result has no ${method}`));
|
|
135
|
+
}
|
|
136
|
+
function makeTracedPromise(inner, ctx) {
|
|
137
|
+
const source = inner;
|
|
138
|
+
const originalThen = source.then.bind(source);
|
|
139
|
+
const originalAsResponse = source.asResponse?.bind(source);
|
|
140
|
+
const originalThenUnwrap = source._thenUnwrap?.bind(source);
|
|
141
|
+
const handleError = (error) => {
|
|
142
|
+
ctx.end({ error });
|
|
143
|
+
throw error;
|
|
144
|
+
};
|
|
145
|
+
const onParsed = (value) => finalizeParsedValue(value, ctx);
|
|
146
|
+
const parsed = () => originalThen(onParsed, handleError);
|
|
147
|
+
const traced = constructorName(source) === "APIPromise" ? source : new Promise((resolve, reject) => {
|
|
148
|
+
parsed().then(resolve, reject);
|
|
149
|
+
});
|
|
150
|
+
if (traced === source) {
|
|
151
|
+
traced.then = ((onfulfilled, onrejected) => parsed().then(onfulfilled, onrejected));
|
|
152
|
+
traced.catch = ((onrejected) => parsed().catch(onrejected));
|
|
153
|
+
traced.finally = ((onfinally) => parsed().finally(onfinally));
|
|
154
|
+
}
|
|
155
|
+
traced.asResponse = () => {
|
|
156
|
+
if (!originalAsResponse) return rejectMissing("asResponse");
|
|
157
|
+
return originalAsResponse().then((response) => {
|
|
158
|
+
ctx.end(mapRawResponse(response));
|
|
159
|
+
return response;
|
|
160
|
+
}, handleError);
|
|
161
|
+
};
|
|
162
|
+
traced.withResponse = () => {
|
|
163
|
+
if (!originalAsResponse) return rejectMissing("withResponse");
|
|
164
|
+
return Promise.all([parsed(), originalAsResponse()]).then(([data, response]) => ({
|
|
165
|
+
data,
|
|
166
|
+
response,
|
|
167
|
+
request_id: response.headers.get("request-id")
|
|
168
|
+
}), handleError);
|
|
169
|
+
};
|
|
170
|
+
traced._thenUnwrap = (transform) => {
|
|
171
|
+
if (!originalThenUnwrap) return rejectMissing("_thenUnwrap");
|
|
172
|
+
return makeTracedPromise(originalThenUnwrap(transform), ctx);
|
|
173
|
+
};
|
|
174
|
+
return traced;
|
|
175
|
+
}
|
|
176
|
+
function isToolBlockState(value) {
|
|
177
|
+
return "data" in value && "inputJson" in value;
|
|
178
|
+
}
|
|
179
|
+
function setFirstStreamUpdate(span, startedAt, sawFirst, fields) {
|
|
180
|
+
if (sawFirst.value) return;
|
|
181
|
+
sawFirst.value = true;
|
|
182
|
+
span.update({
|
|
183
|
+
timeToFirstChunkMs: Date.now() - startedAt,
|
|
184
|
+
responseId: fields.responseId,
|
|
185
|
+
responseModel: fields.responseModel
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
function parseToolInput(inputJson) {
|
|
189
|
+
if (inputJson.length === 0) return {};
|
|
190
|
+
try {
|
|
191
|
+
return JSON.parse(inputJson);
|
|
192
|
+
} catch {
|
|
193
|
+
return inputJson;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
function finalizeBlock(block) {
|
|
197
|
+
if (!isToolBlockState(block)) return block;
|
|
198
|
+
const input = parseToolInput(block.inputJson);
|
|
199
|
+
if (block.data.input === void 0) return {
|
|
200
|
+
...block.data,
|
|
201
|
+
input
|
|
202
|
+
};
|
|
203
|
+
if (block.inputJson.length === 0) return block.data;
|
|
204
|
+
const existingInput = asRecord(block.data.input);
|
|
205
|
+
const parsedInput = asRecord(input);
|
|
206
|
+
return {
|
|
207
|
+
...block.data,
|
|
208
|
+
input: existingInput && parsedInput && !Array.isArray(existingInput) && !Array.isArray(parsedInput) ? {
|
|
209
|
+
...existingInput,
|
|
210
|
+
...parsedInput
|
|
211
|
+
} : input
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
function streamOutput(state) {
|
|
215
|
+
if (state.blocks.size === 0) return void 0;
|
|
216
|
+
return [{
|
|
217
|
+
role: "assistant",
|
|
218
|
+
content: [...state.blocks.entries()].sort(([left], [right]) => left - right).map(([, block]) => finalizeBlock(block))
|
|
219
|
+
}];
|
|
220
|
+
}
|
|
221
|
+
function streamPartialFields(state) {
|
|
222
|
+
return {
|
|
223
|
+
output: streamOutput(state),
|
|
224
|
+
usage: state.usage,
|
|
225
|
+
finishReason: state.finishReason
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
function recordContentBlockStart(event, state) {
|
|
229
|
+
const index = readNumber(event.index) ?? state.blocks.size;
|
|
230
|
+
const contentBlock = asRecord(event.content_block) ?? {};
|
|
231
|
+
const type = readString(contentBlock.type);
|
|
232
|
+
if (type === "text") {
|
|
233
|
+
state.blocks.set(index, {
|
|
234
|
+
type,
|
|
235
|
+
text: readString(contentBlock.text) ?? ""
|
|
236
|
+
});
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
if (type === "tool_use" || type === "server_tool_use") {
|
|
240
|
+
const data = {
|
|
241
|
+
...contentBlock,
|
|
242
|
+
type
|
|
243
|
+
};
|
|
244
|
+
state.blocks.set(index, {
|
|
245
|
+
data,
|
|
246
|
+
inputJson: ""
|
|
247
|
+
});
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
if (type === "thinking") {
|
|
251
|
+
state.blocks.set(index, {
|
|
252
|
+
type,
|
|
253
|
+
thinking: readString(contentBlock.thinking) ?? ""
|
|
254
|
+
});
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
state.blocks.set(index, { ...contentBlock });
|
|
258
|
+
}
|
|
259
|
+
function blockForDelta(index, deltaType, state) {
|
|
260
|
+
const existing = state.blocks.get(index);
|
|
261
|
+
if (existing) return existing;
|
|
262
|
+
if (deltaType === "input_json_delta") {
|
|
263
|
+
const block = {
|
|
264
|
+
data: { type: "tool_use" },
|
|
265
|
+
inputJson: ""
|
|
266
|
+
};
|
|
267
|
+
state.blocks.set(index, block);
|
|
268
|
+
return block;
|
|
269
|
+
}
|
|
270
|
+
const block = deltaType === "thinking_delta" ? {
|
|
271
|
+
type: "thinking",
|
|
272
|
+
thinking: ""
|
|
273
|
+
} : {
|
|
274
|
+
type: "text",
|
|
275
|
+
text: ""
|
|
276
|
+
};
|
|
277
|
+
state.blocks.set(index, block);
|
|
278
|
+
return block;
|
|
279
|
+
}
|
|
280
|
+
function appendStringField(target, key, value) {
|
|
281
|
+
if (value === void 0) return;
|
|
282
|
+
target[key] = `${readString(target[key]) ?? ""}${value}`;
|
|
283
|
+
}
|
|
284
|
+
function appendArrayField(target, key, value) {
|
|
285
|
+
if (value === void 0) return;
|
|
286
|
+
target[key] = [...Array.isArray(target[key]) ? target[key] : [], value];
|
|
287
|
+
}
|
|
288
|
+
function recordContentBlockDelta(event, state) {
|
|
289
|
+
const index = readNumber(event.index) ?? 0;
|
|
290
|
+
const delta = asRecord(event.delta) ?? {};
|
|
291
|
+
const deltaType = readString(delta.type);
|
|
292
|
+
const block = blockForDelta(index, deltaType, state);
|
|
293
|
+
if (deltaType === "input_json_delta") {
|
|
294
|
+
if (isToolBlockState(block)) block.inputJson += readString(delta.partial_json) ?? "";
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const data = isToolBlockState(block) ? block.data : block;
|
|
298
|
+
if (deltaType === "text_delta") appendStringField(data, "text", readString(delta.text));
|
|
299
|
+
if (deltaType === "citations_delta") appendArrayField(data, "citations", delta.citation);
|
|
300
|
+
if (deltaType === "thinking_delta") appendStringField(data, "thinking", readString(delta.thinking));
|
|
301
|
+
if (deltaType === "signature_delta" && delta.signature !== void 0) data.signature = delta.signature;
|
|
302
|
+
}
|
|
303
|
+
function recordStreamEvent(event, state) {
|
|
304
|
+
const e = asRecord(event) ?? {};
|
|
305
|
+
const type = readString(e.type);
|
|
306
|
+
const fields = {};
|
|
307
|
+
if (type === "message_start") {
|
|
308
|
+
const message = asRecord(e.message) ?? {};
|
|
309
|
+
fields.responseId = readString(message.id);
|
|
310
|
+
fields.responseModel = readString(message.model);
|
|
311
|
+
state.usage = mergeUsage(state.usage, messagesUsage(message.usage));
|
|
312
|
+
}
|
|
313
|
+
if (type === "content_block_start") recordContentBlockStart(e, state);
|
|
314
|
+
if (type === "content_block_delta") recordContentBlockDelta(e, state);
|
|
315
|
+
if (type === "message_delta") {
|
|
316
|
+
state.finishReason = readString((asRecord(e.delta) ?? {}).stop_reason) ?? state.finishReason;
|
|
317
|
+
state.usage = mergeUsage(state.usage, messagesUsage(e.usage));
|
|
318
|
+
}
|
|
319
|
+
return fields;
|
|
320
|
+
}
|
|
321
|
+
function isStreamLike(value) {
|
|
322
|
+
if (value === null || typeof value !== "object") return false;
|
|
323
|
+
const stream = value;
|
|
324
|
+
const signal = asRecord(stream.controller)?.signal;
|
|
325
|
+
return typeof stream[Symbol.asyncIterator] === "function" && signal !== void 0 && typeof asRecord(signal)?.addEventListener === "function";
|
|
326
|
+
}
|
|
327
|
+
function createObservedMessagesStream(source, span, startedAt, end) {
|
|
328
|
+
const state = { blocks: /* @__PURE__ */ new Map() };
|
|
329
|
+
let consumed = false;
|
|
330
|
+
const signal = source.controller.signal;
|
|
331
|
+
const endAborted = () => {
|
|
332
|
+
if (consumed) return;
|
|
333
|
+
end({
|
|
334
|
+
...streamPartialFields(state),
|
|
335
|
+
error: signal.reason ?? /* @__PURE__ */ new Error("Request aborted")
|
|
336
|
+
});
|
|
337
|
+
};
|
|
338
|
+
if (signal.aborted) endAborted();
|
|
339
|
+
else signal.addEventListener("abort", endAborted, { once: true });
|
|
340
|
+
async function* iterator() {
|
|
341
|
+
consumed = true;
|
|
342
|
+
const sawFirst = { value: false };
|
|
343
|
+
let terminalError;
|
|
344
|
+
try {
|
|
345
|
+
for await (const event of source) {
|
|
346
|
+
setFirstStreamUpdate(span, startedAt, sawFirst, recordStreamEvent(event, state));
|
|
347
|
+
yield event;
|
|
348
|
+
}
|
|
349
|
+
} catch (error) {
|
|
350
|
+
terminalError = error;
|
|
351
|
+
throw error;
|
|
352
|
+
} finally {
|
|
353
|
+
end({
|
|
354
|
+
...streamPartialFields(state),
|
|
355
|
+
...terminalError !== void 0 ? { error: terminalError } : {}
|
|
356
|
+
});
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
return new Stream(() => iterator(), source.controller);
|
|
360
|
+
}
|
|
361
|
+
function wrapStream(value, span, startedAt, end) {
|
|
362
|
+
if (!isStreamLike(value)) return value;
|
|
363
|
+
return createObservedMessagesStream(value, span, startedAt, end);
|
|
364
|
+
}
|
|
365
|
+
function wrapCreate(original, mapRequest, mapResponse, provider) {
|
|
366
|
+
if (isWrapped(original)) return original;
|
|
367
|
+
const wrapped = function(...args) {
|
|
368
|
+
const body = asRecord(args[0]) ?? {};
|
|
369
|
+
const streaming = body.stream === true;
|
|
370
|
+
const request = mapRequest(body);
|
|
371
|
+
const span = startSpan(request.name, {
|
|
372
|
+
...request.fields,
|
|
373
|
+
provider: provider(this)
|
|
374
|
+
});
|
|
375
|
+
const end = endOnce(span);
|
|
376
|
+
const startedAt = Date.now();
|
|
377
|
+
try {
|
|
378
|
+
return makeTracedPromise(original.apply(this, args), {
|
|
379
|
+
end,
|
|
380
|
+
span,
|
|
381
|
+
startedAt,
|
|
382
|
+
streaming,
|
|
383
|
+
mapResponse
|
|
384
|
+
});
|
|
385
|
+
} catch (error) {
|
|
386
|
+
end({ error });
|
|
387
|
+
throw error;
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
return markWrapped(wrapped, original);
|
|
391
|
+
}
|
|
392
|
+
function patchInstanceMethod(target, key, request, response, provider) {
|
|
393
|
+
const current = target[key];
|
|
394
|
+
if (isWrapped(current) && Object.hasOwn(target, key)) return;
|
|
395
|
+
const original = isWrapped(current) ? current[WRAPPED_ORIGINAL] : current;
|
|
396
|
+
if (typeof original !== "function") return;
|
|
397
|
+
target[key] = wrapCreate(original.bind(target), request, response, () => provider);
|
|
398
|
+
}
|
|
399
|
+
function patchPrototype(klass, key, request, response) {
|
|
400
|
+
const prototype = klass.prototype;
|
|
401
|
+
const original = prototype[key];
|
|
402
|
+
if (typeof original !== "function" || isWrapped(original)) return () => {};
|
|
403
|
+
prototype[key] = wrapCreate(original, request, response, providerForResource);
|
|
404
|
+
return () => {
|
|
405
|
+
prototype[key] = original;
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
let installed = false;
|
|
409
|
+
let restorePatches = [];
|
|
410
|
+
function wrapAnthropic(client) {
|
|
411
|
+
if (wrappedClients.has(client)) return client;
|
|
412
|
+
const provider = providerForClient(client);
|
|
413
|
+
const messages = asRecord(client.messages);
|
|
414
|
+
if (messages) patchInstanceMethod(messages, "create", messagesRequest, messagesResponse, provider);
|
|
415
|
+
wrappedClients.add(client);
|
|
416
|
+
return client;
|
|
417
|
+
}
|
|
418
|
+
function instrumentAnthropic() {
|
|
419
|
+
if (installed) return;
|
|
420
|
+
restorePatches = [patchPrototype(Messages, "create", messagesRequest, messagesResponse)];
|
|
421
|
+
installed = true;
|
|
422
|
+
}
|
|
423
|
+
function uninstrumentAnthropic() {
|
|
424
|
+
if (!installed) return;
|
|
425
|
+
for (const restore of restorePatches.reverse()) restore();
|
|
426
|
+
restorePatches = [];
|
|
427
|
+
installed = false;
|
|
428
|
+
}
|
|
429
|
+
//#endregion
|
|
430
|
+
export { instrumentAnthropic, uninstrumentAnthropic, wrapAnthropic };
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@telemetry-dev/anthropic",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Anthropic SDK instrumentation for telemetry.dev: wraps the Messages API and emits OpenTelemetry GenAI spans.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"anthropic",
|
|
7
|
+
"claude",
|
|
8
|
+
"genai",
|
|
9
|
+
"llm",
|
|
10
|
+
"observability",
|
|
11
|
+
"opentelemetry",
|
|
12
|
+
"telemetry",
|
|
13
|
+
"tracing"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://telemetry.dev",
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/telemetry-dev/telemetry.dev.git",
|
|
20
|
+
"directory": "packages/anthropic"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"src"
|
|
25
|
+
],
|
|
26
|
+
"type": "module",
|
|
27
|
+
"exports": {
|
|
28
|
+
".": {
|
|
29
|
+
"types": "./dist/index.d.mts",
|
|
30
|
+
"import": "./dist/index.mjs",
|
|
31
|
+
"default": "./dist/index.mjs"
|
|
32
|
+
},
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@anthropic-ai/sdk": "0.110.0",
|
|
40
|
+
"@opentelemetry/sdk-logs": "^0.218.0",
|
|
41
|
+
"@opentelemetry/sdk-metrics": "^2.7.1",
|
|
42
|
+
"@opentelemetry/sdk-trace-base": "^2.7.1",
|
|
43
|
+
"@types/node": "^24",
|
|
44
|
+
"typescript": "^5",
|
|
45
|
+
"vite-plus": "0.1.20",
|
|
46
|
+
"vitest": "npm:@voidzero-dev/vite-plus-test@0.1.20",
|
|
47
|
+
"@telemetry-dev/sdk": "0.1.0"
|
|
48
|
+
},
|
|
49
|
+
"peerDependencies": {
|
|
50
|
+
"@anthropic-ai/sdk": ">=0.110.0 <1",
|
|
51
|
+
"@telemetry-dev/sdk": "^0.1.0"
|
|
52
|
+
},
|
|
53
|
+
"scripts": {
|
|
54
|
+
"build": "pnpm exec vp pack",
|
|
55
|
+
"dev": "pnpm exec vp pack --watch",
|
|
56
|
+
"test": "vp test",
|
|
57
|
+
"check": "vp check"
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
import {
|
|
2
|
+
startSpan,
|
|
3
|
+
type SpanFields,
|
|
4
|
+
type SpanHandle,
|
|
5
|
+
type StartSpanOptions,
|
|
6
|
+
} from "@telemetry-dev/sdk";
|
|
7
|
+
import { Stream } from "@anthropic-ai/sdk/core/streaming";
|
|
8
|
+
import { Messages } from "@anthropic-ai/sdk/resources/messages";
|
|
9
|
+
|
|
10
|
+
export type { SpanFields, SpanHandle, StartSpanOptions } from "@telemetry-dev/sdk";
|
|
11
|
+
|
|
12
|
+
const WRAPPED = Symbol("telemetry.dev.anthropic.wrapped");
|
|
13
|
+
const WRAPPED_ORIGINAL = Symbol("telemetry.dev.anthropic.original");
|
|
14
|
+
const wrappedClients = new WeakSet<object>();
|
|
15
|
+
|
|
16
|
+
type UnknownRecord = Record<string, unknown>;
|
|
17
|
+
type WrappedFunction = ((...args: unknown[]) => unknown) & {
|
|
18
|
+
[WRAPPED]?: true;
|
|
19
|
+
[WRAPPED_ORIGINAL]?: (...args: never[]) => unknown;
|
|
20
|
+
};
|
|
21
|
+
type ProviderResolver = (resource: unknown) => string;
|
|
22
|
+
|
|
23
|
+
interface AnthropicClient {
|
|
24
|
+
messages: object;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
interface RequestMapping {
|
|
28
|
+
name: string;
|
|
29
|
+
fields: StartSpanOptions;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface WrappedResponse<T> {
|
|
33
|
+
data: T;
|
|
34
|
+
response: Response;
|
|
35
|
+
request_id: string | null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface ToolBlockState {
|
|
39
|
+
data: UnknownRecord;
|
|
40
|
+
inputJson: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface StreamState {
|
|
44
|
+
blocks: Map<number, UnknownRecord | ToolBlockState>;
|
|
45
|
+
usage?: SpanFields["usage"];
|
|
46
|
+
finishReason?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function asRecord(value: unknown): UnknownRecord | undefined {
|
|
50
|
+
return value !== null && typeof value === "object" ? (value as UnknownRecord) : undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function readString(value: unknown): string | undefined {
|
|
54
|
+
return typeof value === "string" ? value : undefined;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function readNumber(value: unknown): number | undefined {
|
|
58
|
+
return typeof value === "number" ? value : undefined;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function compactUsage(usage: SpanFields["usage"]): SpanFields["usage"] {
|
|
62
|
+
if (!usage) return undefined;
|
|
63
|
+
return Object.values(usage).some((value) => value !== undefined) ? usage : undefined;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function stopSequences(value: unknown): string[] | undefined {
|
|
67
|
+
if (typeof value === "string") return [value];
|
|
68
|
+
if (!Array.isArray(value)) return undefined;
|
|
69
|
+
const strings = value.filter((item): item is string => typeof item === "string");
|
|
70
|
+
return strings.length > 0 ? strings : undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function messagesRequest(body: UnknownRecord): RequestMapping {
|
|
74
|
+
const model = readString(body.model);
|
|
75
|
+
const input =
|
|
76
|
+
body.tools !== undefined || body.tool_choice !== undefined
|
|
77
|
+
? { messages: body.messages, tools: body.tools, tool_choice: body.tool_choice }
|
|
78
|
+
: body.messages;
|
|
79
|
+
return {
|
|
80
|
+
name: `chat ${model ?? "unknown"}`,
|
|
81
|
+
fields: {
|
|
82
|
+
type: "generation",
|
|
83
|
+
model,
|
|
84
|
+
input,
|
|
85
|
+
systemInstructions: body.system,
|
|
86
|
+
temperature: readNumber(body.temperature),
|
|
87
|
+
topP: readNumber(body.top_p),
|
|
88
|
+
topK: readNumber(body.top_k),
|
|
89
|
+
maxTokens: readNumber(body.max_tokens),
|
|
90
|
+
stopSequences: stopSequences(body.stop_sequences),
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function messagesUsage(usage: unknown): SpanFields["usage"] {
|
|
96
|
+
const u = asRecord(usage);
|
|
97
|
+
const outputDetails = asRecord(u?.output_tokens_details);
|
|
98
|
+
return compactUsage({
|
|
99
|
+
inputTokens: readNumber(u?.input_tokens),
|
|
100
|
+
outputTokens: readNumber(u?.output_tokens),
|
|
101
|
+
cacheReadInputTokens: readNumber(u?.cache_read_input_tokens),
|
|
102
|
+
cacheCreationInputTokens: readNumber(u?.cache_creation_input_tokens),
|
|
103
|
+
reasoningOutputTokens: readNumber(outputDetails?.thinking_tokens),
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function mergeUsage(
|
|
108
|
+
current: SpanFields["usage"],
|
|
109
|
+
incoming: SpanFields["usage"],
|
|
110
|
+
): SpanFields["usage"] {
|
|
111
|
+
if (!incoming) return current;
|
|
112
|
+
return compactUsage({
|
|
113
|
+
inputTokens: incoming.inputTokens ?? current?.inputTokens,
|
|
114
|
+
outputTokens: incoming.outputTokens ?? current?.outputTokens,
|
|
115
|
+
cacheReadInputTokens: incoming.cacheReadInputTokens ?? current?.cacheReadInputTokens,
|
|
116
|
+
cacheCreationInputTokens:
|
|
117
|
+
incoming.cacheCreationInputTokens ?? current?.cacheCreationInputTokens,
|
|
118
|
+
reasoningOutputTokens: incoming.reasoningOutputTokens ?? current?.reasoningOutputTokens,
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function messagesResponse(response: unknown): SpanFields {
|
|
123
|
+
const r = asRecord(response) ?? {};
|
|
124
|
+
const role = readString(r.role) ?? "assistant";
|
|
125
|
+
return {
|
|
126
|
+
responseModel: readString(r.model),
|
|
127
|
+
responseId: readString(r.id),
|
|
128
|
+
finishReason: readString(r.stop_reason),
|
|
129
|
+
output: r.content !== undefined ? [{ role, content: r.content }] : undefined,
|
|
130
|
+
usage: messagesUsage(r.usage),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function constructorName(value: unknown): string | undefined {
|
|
135
|
+
if (value === null || (typeof value !== "object" && typeof value !== "function")) {
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
const ctor = value.constructor;
|
|
139
|
+
return typeof ctor === "function" ? ctor.name : undefined;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function providerForClient(client: unknown): string {
|
|
143
|
+
switch (constructorName(client)) {
|
|
144
|
+
case "AnthropicBedrock":
|
|
145
|
+
case "AsyncAnthropicBedrock":
|
|
146
|
+
return "aws.bedrock";
|
|
147
|
+
case "AnthropicVertex":
|
|
148
|
+
case "AsyncAnthropicVertex":
|
|
149
|
+
return "gcp.vertex_ai";
|
|
150
|
+
default:
|
|
151
|
+
return "anthropic";
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function providerForResource(resource: unknown): string {
|
|
156
|
+
return providerForClient(asRecord(resource)?._client);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function isWrapped(fn: unknown): fn is WrappedFunction {
|
|
160
|
+
if (typeof fn !== "function") return false;
|
|
161
|
+
const wrapped = fn as WrappedFunction;
|
|
162
|
+
return wrapped[WRAPPED] === true;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function markWrapped<T extends WrappedFunction>(fn: T, original: (...args: never[]) => unknown): T {
|
|
166
|
+
Object.defineProperty(fn, WRAPPED, { value: true });
|
|
167
|
+
Object.defineProperty(fn, WRAPPED_ORIGINAL, { value: original });
|
|
168
|
+
return fn;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function endOnce(span: SpanHandle): (fields?: SpanFields) => void {
|
|
172
|
+
let ended = false;
|
|
173
|
+
return (fields?: SpanFields) => {
|
|
174
|
+
if (ended) return;
|
|
175
|
+
ended = true;
|
|
176
|
+
span.end(fields);
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
type TracedResult<T> = Promise<T> & {
|
|
181
|
+
asResponse(): Promise<Response>;
|
|
182
|
+
withResponse(): Promise<WrappedResponse<T>>;
|
|
183
|
+
_thenUnwrap<U>(transform: (data: T, ...args: unknown[]) => U): TracedResult<U>;
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
interface TracePromiseContext {
|
|
187
|
+
end: (fields?: SpanFields) => void;
|
|
188
|
+
span: SpanHandle;
|
|
189
|
+
startedAt: number;
|
|
190
|
+
streaming: boolean;
|
|
191
|
+
mapResponse: (response: unknown) => SpanFields;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
interface StreamLike<T> extends AsyncIterable<T> {
|
|
195
|
+
controller: AbortController;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
type InnerAPIPromise = {
|
|
199
|
+
then: Promise<unknown>["then"];
|
|
200
|
+
catch: Promise<unknown>["catch"];
|
|
201
|
+
finally: Promise<unknown>["finally"];
|
|
202
|
+
asResponse?: () => Promise<Response>;
|
|
203
|
+
withResponse?: () => Promise<WrappedResponse<unknown>>;
|
|
204
|
+
_thenUnwrap?: <U>(transform: (data: unknown, ...args: unknown[]) => U) => InnerAPIPromise;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
function mapRawResponse(response: Response): SpanFields {
|
|
208
|
+
const requestId = response.headers.get("request-id");
|
|
209
|
+
return {
|
|
210
|
+
...(requestId ? { responseId: requestId } : {}),
|
|
211
|
+
attributes: { "http.response.status_code": response.status },
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function finalizeParsedValue(value: unknown, ctx: TracePromiseContext): unknown {
|
|
216
|
+
if (ctx.streaming) {
|
|
217
|
+
const wrapped = wrapStream(value, ctx.span, ctx.startedAt, ctx.end);
|
|
218
|
+
if (wrapped !== value) return wrapped;
|
|
219
|
+
}
|
|
220
|
+
ctx.end(ctx.mapResponse(value));
|
|
221
|
+
return value;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function rejectMissing(method: string): Promise<never> {
|
|
225
|
+
return Promise.reject(new TypeError(`wrapped result has no ${method}`));
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function makeTracedPromise<T>(inner: unknown, ctx: TracePromiseContext): TracedResult<T> {
|
|
229
|
+
const source = inner as InnerAPIPromise;
|
|
230
|
+
const originalThen = source.then.bind(source);
|
|
231
|
+
const originalAsResponse = source.asResponse?.bind(source);
|
|
232
|
+
const originalThenUnwrap = source._thenUnwrap?.bind(source);
|
|
233
|
+
const handleError = (error: unknown): never => {
|
|
234
|
+
ctx.end({ error });
|
|
235
|
+
throw error;
|
|
236
|
+
};
|
|
237
|
+
const onParsed = (value: unknown) => finalizeParsedValue(value, ctx) as T;
|
|
238
|
+
const parsed = () => originalThen(onParsed, handleError);
|
|
239
|
+
const traced =
|
|
240
|
+
constructorName(source) === "APIPromise"
|
|
241
|
+
? (source as TracedResult<T>)
|
|
242
|
+
: (new Promise<T>((resolve, reject) => {
|
|
243
|
+
parsed().then(resolve, reject);
|
|
244
|
+
}) as TracedResult<T>);
|
|
245
|
+
if (traced === source) {
|
|
246
|
+
// oxlint-disable-next-line unicorn/no-thenable -- preserve Anthropic APIPromise subclass contract.
|
|
247
|
+
traced.then = ((onfulfilled, onrejected) =>
|
|
248
|
+
parsed().then(onfulfilled, onrejected)) as TracedResult<T>["then"];
|
|
249
|
+
traced.catch = ((onrejected) => parsed().catch(onrejected)) as TracedResult<T>["catch"];
|
|
250
|
+
traced.finally = ((onfinally) => parsed().finally(onfinally)) as TracedResult<T>["finally"];
|
|
251
|
+
}
|
|
252
|
+
traced.asResponse = () => {
|
|
253
|
+
if (!originalAsResponse) return rejectMissing("asResponse");
|
|
254
|
+
return originalAsResponse().then((response) => {
|
|
255
|
+
ctx.end(mapRawResponse(response));
|
|
256
|
+
return response;
|
|
257
|
+
}, handleError);
|
|
258
|
+
};
|
|
259
|
+
traced.withResponse = () => {
|
|
260
|
+
if (!originalAsResponse) return rejectMissing("withResponse");
|
|
261
|
+
return Promise.all([parsed(), originalAsResponse()]).then(
|
|
262
|
+
([data, response]) => ({
|
|
263
|
+
data,
|
|
264
|
+
response,
|
|
265
|
+
request_id: response.headers.get("request-id"),
|
|
266
|
+
}),
|
|
267
|
+
handleError,
|
|
268
|
+
);
|
|
269
|
+
};
|
|
270
|
+
traced._thenUnwrap = <U>(transform: (data: T, ...args: unknown[]) => U): TracedResult<U> => {
|
|
271
|
+
if (!originalThenUnwrap) return rejectMissing("_thenUnwrap") as unknown as TracedResult<U>;
|
|
272
|
+
return makeTracedPromise(
|
|
273
|
+
originalThenUnwrap(transform as (data: unknown, ...args: unknown[]) => U),
|
|
274
|
+
ctx,
|
|
275
|
+
);
|
|
276
|
+
};
|
|
277
|
+
return traced;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function isToolBlockState(value: UnknownRecord | ToolBlockState): value is ToolBlockState {
|
|
281
|
+
return "data" in value && "inputJson" in value;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function setFirstStreamUpdate(
|
|
285
|
+
span: SpanHandle,
|
|
286
|
+
startedAt: number,
|
|
287
|
+
sawFirst: { value: boolean },
|
|
288
|
+
fields: SpanFields,
|
|
289
|
+
): void {
|
|
290
|
+
if (sawFirst.value) return;
|
|
291
|
+
sawFirst.value = true;
|
|
292
|
+
span.update({
|
|
293
|
+
timeToFirstChunkMs: Date.now() - startedAt,
|
|
294
|
+
responseId: fields.responseId,
|
|
295
|
+
responseModel: fields.responseModel,
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function parseToolInput(inputJson: string): unknown {
|
|
300
|
+
if (inputJson.length === 0) return {};
|
|
301
|
+
try {
|
|
302
|
+
return JSON.parse(inputJson) as unknown;
|
|
303
|
+
} catch {
|
|
304
|
+
return inputJson;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function finalizeBlock(block: UnknownRecord | ToolBlockState): UnknownRecord {
|
|
309
|
+
if (!isToolBlockState(block)) return block;
|
|
310
|
+
const input = parseToolInput(block.inputJson);
|
|
311
|
+
if (block.data.input === undefined) return { ...block.data, input };
|
|
312
|
+
if (block.inputJson.length === 0) return block.data;
|
|
313
|
+
const existingInput = asRecord(block.data.input);
|
|
314
|
+
const parsedInput = asRecord(input);
|
|
315
|
+
return {
|
|
316
|
+
...block.data,
|
|
317
|
+
input:
|
|
318
|
+
existingInput && parsedInput && !Array.isArray(existingInput) && !Array.isArray(parsedInput)
|
|
319
|
+
? { ...existingInput, ...parsedInput }
|
|
320
|
+
: input,
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function streamOutput(state: StreamState): UnknownRecord[] | undefined {
|
|
325
|
+
if (state.blocks.size === 0) return undefined;
|
|
326
|
+
return [
|
|
327
|
+
{
|
|
328
|
+
role: "assistant",
|
|
329
|
+
content: [...state.blocks.entries()]
|
|
330
|
+
.sort(([left], [right]) => left - right)
|
|
331
|
+
.map(([, block]) => finalizeBlock(block)),
|
|
332
|
+
},
|
|
333
|
+
];
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function streamPartialFields(state: StreamState): SpanFields {
|
|
337
|
+
return {
|
|
338
|
+
output: streamOutput(state),
|
|
339
|
+
usage: state.usage,
|
|
340
|
+
finishReason: state.finishReason,
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
function recordContentBlockStart(event: UnknownRecord, state: StreamState): void {
|
|
345
|
+
const index = readNumber(event.index) ?? state.blocks.size;
|
|
346
|
+
const contentBlock = asRecord(event.content_block) ?? {};
|
|
347
|
+
const type = readString(contentBlock.type);
|
|
348
|
+
if (type === "text") {
|
|
349
|
+
state.blocks.set(index, { type, text: readString(contentBlock.text) ?? "" });
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
if (type === "tool_use" || type === "server_tool_use") {
|
|
353
|
+
const data: UnknownRecord = { ...contentBlock, type };
|
|
354
|
+
state.blocks.set(index, { data, inputJson: "" });
|
|
355
|
+
return;
|
|
356
|
+
}
|
|
357
|
+
if (type === "thinking") {
|
|
358
|
+
state.blocks.set(index, { type, thinking: readString(contentBlock.thinking) ?? "" });
|
|
359
|
+
return;
|
|
360
|
+
}
|
|
361
|
+
state.blocks.set(index, { ...contentBlock });
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function blockForDelta(
|
|
365
|
+
index: number,
|
|
366
|
+
deltaType: string | undefined,
|
|
367
|
+
state: StreamState,
|
|
368
|
+
): UnknownRecord | ToolBlockState {
|
|
369
|
+
const existing = state.blocks.get(index);
|
|
370
|
+
if (existing) return existing;
|
|
371
|
+
if (deltaType === "input_json_delta") {
|
|
372
|
+
const block = { data: { type: "tool_use" }, inputJson: "" };
|
|
373
|
+
state.blocks.set(index, block);
|
|
374
|
+
return block;
|
|
375
|
+
}
|
|
376
|
+
const block =
|
|
377
|
+
deltaType === "thinking_delta"
|
|
378
|
+
? { type: "thinking", thinking: "" }
|
|
379
|
+
: { type: "text", text: "" };
|
|
380
|
+
state.blocks.set(index, block);
|
|
381
|
+
return block;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function appendStringField(target: UnknownRecord, key: string, value: string | undefined): void {
|
|
385
|
+
if (value === undefined) return;
|
|
386
|
+
const existing = readString(target[key]) ?? "";
|
|
387
|
+
target[key] = `${existing}${value}`;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function appendArrayField(target: UnknownRecord, key: string, value: unknown): void {
|
|
391
|
+
if (value === undefined) return;
|
|
392
|
+
const existing = Array.isArray(target[key]) ? (target[key] as unknown[]) : [];
|
|
393
|
+
target[key] = [...existing, value];
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function recordContentBlockDelta(event: UnknownRecord, state: StreamState): void {
|
|
397
|
+
const index = readNumber(event.index) ?? 0;
|
|
398
|
+
const delta = asRecord(event.delta) ?? {};
|
|
399
|
+
const deltaType = readString(delta.type);
|
|
400
|
+
const block = blockForDelta(index, deltaType, state);
|
|
401
|
+
if (deltaType === "input_json_delta") {
|
|
402
|
+
if (isToolBlockState(block)) block.inputJson += readString(delta.partial_json) ?? "";
|
|
403
|
+
return;
|
|
404
|
+
}
|
|
405
|
+
const data = isToolBlockState(block) ? block.data : block;
|
|
406
|
+
if (deltaType === "text_delta") appendStringField(data, "text", readString(delta.text));
|
|
407
|
+
if (deltaType === "citations_delta") appendArrayField(data, "citations", delta.citation);
|
|
408
|
+
if (deltaType === "thinking_delta") {
|
|
409
|
+
appendStringField(data, "thinking", readString(delta.thinking));
|
|
410
|
+
}
|
|
411
|
+
if (deltaType === "signature_delta" && delta.signature !== undefined)
|
|
412
|
+
data.signature = delta.signature;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function recordStreamEvent(event: unknown, state: StreamState): SpanFields {
|
|
416
|
+
const e = asRecord(event) ?? {};
|
|
417
|
+
const type = readString(e.type);
|
|
418
|
+
const fields: SpanFields = {};
|
|
419
|
+
if (type === "message_start") {
|
|
420
|
+
const message = asRecord(e.message) ?? {};
|
|
421
|
+
fields.responseId = readString(message.id);
|
|
422
|
+
fields.responseModel = readString(message.model);
|
|
423
|
+
state.usage = mergeUsage(state.usage, messagesUsage(message.usage));
|
|
424
|
+
}
|
|
425
|
+
if (type === "content_block_start") recordContentBlockStart(e, state);
|
|
426
|
+
if (type === "content_block_delta") recordContentBlockDelta(e, state);
|
|
427
|
+
if (type === "message_delta") {
|
|
428
|
+
const delta = asRecord(e.delta) ?? {};
|
|
429
|
+
state.finishReason = readString(delta.stop_reason) ?? state.finishReason;
|
|
430
|
+
state.usage = mergeUsage(state.usage, messagesUsage(e.usage));
|
|
431
|
+
}
|
|
432
|
+
return fields;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
function isStreamLike(value: unknown): value is StreamLike<unknown> {
|
|
436
|
+
if (value === null || typeof value !== "object") return false;
|
|
437
|
+
const stream = value as Partial<StreamLike<unknown>>;
|
|
438
|
+
const signal = asRecord(stream.controller)?.signal;
|
|
439
|
+
return (
|
|
440
|
+
typeof stream[Symbol.asyncIterator] === "function" &&
|
|
441
|
+
signal !== undefined &&
|
|
442
|
+
typeof asRecord(signal)?.addEventListener === "function"
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function createObservedMessagesStream(
|
|
447
|
+
source: StreamLike<unknown>,
|
|
448
|
+
span: SpanHandle,
|
|
449
|
+
startedAt: number,
|
|
450
|
+
end: (fields?: SpanFields) => void,
|
|
451
|
+
): Stream<unknown> {
|
|
452
|
+
const state: StreamState = { blocks: new Map() };
|
|
453
|
+
// The iterator's finally block never runs when iteration never starts, so an
|
|
454
|
+
// abort on an unconsumed stream must end the span here. Once iteration begins,
|
|
455
|
+
// the finally block owns the span end (the SDK aborts the controller as normal
|
|
456
|
+
// cleanup when the caller stops early, which is not an error).
|
|
457
|
+
let consumed = false;
|
|
458
|
+
const signal = source.controller.signal;
|
|
459
|
+
const endAborted = () => {
|
|
460
|
+
if (consumed) return;
|
|
461
|
+
end({ ...streamPartialFields(state), error: signal.reason ?? new Error("Request aborted") });
|
|
462
|
+
};
|
|
463
|
+
if (signal.aborted) endAborted();
|
|
464
|
+
else signal.addEventListener("abort", endAborted, { once: true });
|
|
465
|
+
async function* iterator() {
|
|
466
|
+
consumed = true;
|
|
467
|
+
const sawFirst = { value: false };
|
|
468
|
+
let terminalError: unknown;
|
|
469
|
+
try {
|
|
470
|
+
for await (const event of source) {
|
|
471
|
+
const fields = recordStreamEvent(event, state);
|
|
472
|
+
setFirstStreamUpdate(span, startedAt, sawFirst, fields);
|
|
473
|
+
yield event;
|
|
474
|
+
}
|
|
475
|
+
} catch (error) {
|
|
476
|
+
terminalError = error;
|
|
477
|
+
throw error;
|
|
478
|
+
} finally {
|
|
479
|
+
end({
|
|
480
|
+
...streamPartialFields(state),
|
|
481
|
+
...(terminalError !== undefined ? { error: terminalError } : {}),
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return new Stream(() => iterator(), source.controller);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function wrapStream(
|
|
489
|
+
value: unknown,
|
|
490
|
+
span: SpanHandle,
|
|
491
|
+
startedAt: number,
|
|
492
|
+
end: (fields?: SpanFields) => void,
|
|
493
|
+
): unknown {
|
|
494
|
+
if (!isStreamLike(value)) return value;
|
|
495
|
+
return createObservedMessagesStream(value, span, startedAt, end);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function wrapCreate<Fn extends (...args: never[]) => unknown>(
|
|
499
|
+
original: Fn,
|
|
500
|
+
mapRequest: (body: UnknownRecord) => RequestMapping,
|
|
501
|
+
mapResponse: (response: unknown) => SpanFields,
|
|
502
|
+
provider: ProviderResolver,
|
|
503
|
+
): Fn {
|
|
504
|
+
if (isWrapped(original)) return original;
|
|
505
|
+
const wrapped = function (this: unknown, ...args: unknown[]): unknown {
|
|
506
|
+
const body = asRecord(args[0]) ?? {};
|
|
507
|
+
const streaming = body.stream === true;
|
|
508
|
+
const request = mapRequest(body);
|
|
509
|
+
const span = startSpan(request.name, { ...request.fields, provider: provider(this) });
|
|
510
|
+
const end = endOnce(span);
|
|
511
|
+
const startedAt = Date.now();
|
|
512
|
+
|
|
513
|
+
try {
|
|
514
|
+
const result = original.apply(this, args as never[]);
|
|
515
|
+
return makeTracedPromise(result, { end, span, startedAt, streaming, mapResponse });
|
|
516
|
+
} catch (error) {
|
|
517
|
+
end({ error });
|
|
518
|
+
throw error;
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
return markWrapped(wrapped as WrappedFunction, original) as unknown as Fn;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function patchInstanceMethod<T extends UnknownRecord>(
|
|
525
|
+
target: T,
|
|
526
|
+
key: keyof T,
|
|
527
|
+
request: (body: UnknownRecord) => RequestMapping,
|
|
528
|
+
response: (value: unknown) => SpanFields,
|
|
529
|
+
provider: string,
|
|
530
|
+
): void {
|
|
531
|
+
const current = target[key];
|
|
532
|
+
// An inherited wrapper (from the global prototype patch) is not an own wrapper:
|
|
533
|
+
// install one over the original so the client keeps emitting spans after
|
|
534
|
+
// uninstrumentAnthropic().
|
|
535
|
+
if (isWrapped(current) && Object.hasOwn(target, key)) return;
|
|
536
|
+
const original = isWrapped(current) ? current[WRAPPED_ORIGINAL] : current;
|
|
537
|
+
if (typeof original !== "function") return;
|
|
538
|
+
target[key] = wrapCreate(
|
|
539
|
+
original.bind(target) as (...args: never[]) => unknown,
|
|
540
|
+
request,
|
|
541
|
+
response,
|
|
542
|
+
() => provider,
|
|
543
|
+
) as T[keyof T];
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function patchPrototype(
|
|
547
|
+
klass: { prototype: object },
|
|
548
|
+
key: string,
|
|
549
|
+
request: (body: UnknownRecord) => RequestMapping,
|
|
550
|
+
response: (value: unknown) => SpanFields,
|
|
551
|
+
): () => void {
|
|
552
|
+
const prototype = klass.prototype as UnknownRecord;
|
|
553
|
+
const original = prototype[key];
|
|
554
|
+
if (typeof original !== "function" || isWrapped(original)) return () => {};
|
|
555
|
+
prototype[key] = wrapCreate(
|
|
556
|
+
original as (...args: never[]) => unknown,
|
|
557
|
+
request,
|
|
558
|
+
response,
|
|
559
|
+
providerForResource,
|
|
560
|
+
);
|
|
561
|
+
return () => {
|
|
562
|
+
prototype[key] = original;
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
let installed = false;
|
|
567
|
+
let restorePatches: Array<() => void> = [];
|
|
568
|
+
|
|
569
|
+
export function wrapAnthropic<T extends AnthropicClient>(client: T): T {
|
|
570
|
+
if (wrappedClients.has(client)) return client;
|
|
571
|
+
const provider = providerForClient(client);
|
|
572
|
+
const messages = asRecord(client.messages);
|
|
573
|
+
if (messages)
|
|
574
|
+
patchInstanceMethod(messages, "create", messagesRequest, messagesResponse, provider);
|
|
575
|
+
wrappedClients.add(client);
|
|
576
|
+
return client;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
export function instrumentAnthropic(): void {
|
|
580
|
+
if (installed) return;
|
|
581
|
+
restorePatches = [patchPrototype(Messages, "create", messagesRequest, messagesResponse)];
|
|
582
|
+
installed = true;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
export function uninstrumentAnthropic(): void {
|
|
586
|
+
if (!installed) return;
|
|
587
|
+
for (const restore of restorePatches.reverse()) restore();
|
|
588
|
+
restorePatches = [];
|
|
589
|
+
installed = false;
|
|
590
|
+
}
|