neatlogs 1.0.3 → 1.0.5

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.
@@ -0,0 +1,373 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/anthropic.ts
21
+ var anthropic_exports = {};
22
+ __export(anthropic_exports, {
23
+ traceTool: () => traceTool,
24
+ wrapAnthropic: () => wrapAnthropic
25
+ });
26
+ module.exports = __toCommonJS(anthropic_exports);
27
+ var import_api = require("@opentelemetry/api");
28
+ var TRACER_NAME = "neatlogs.anthropic";
29
+ function wrapAnthropic(client) {
30
+ return wrapNamespace(client, []);
31
+ }
32
+ function traceTool(name, fn) {
33
+ return async function tracedTool(input) {
34
+ const tracer = import_api.trace.getTracer(TRACER_NAME);
35
+ return tracer.startActiveSpan(
36
+ `tool.${name}`,
37
+ {
38
+ attributes: {
39
+ "neatlogs.span.kind": "TOOL",
40
+ "neatlogs.tool.name": name,
41
+ "input.value": safeStringify(input)
42
+ }
43
+ },
44
+ import_api.context.active(),
45
+ async (span) => {
46
+ try {
47
+ const result = await fn(input);
48
+ span.setAttribute("output.value", safeStringify(result));
49
+ span.setStatus({ code: import_api.SpanStatusCode.OK });
50
+ return result;
51
+ } catch (err) {
52
+ recordError(span, err);
53
+ throw err;
54
+ } finally {
55
+ span.end();
56
+ }
57
+ }
58
+ );
59
+ };
60
+ }
61
+ function wrapNamespace(target, path) {
62
+ return new Proxy(target, {
63
+ get(obj, prop, receiver) {
64
+ const value = Reflect.get(obj, prop, receiver);
65
+ if (typeof prop === "symbol" || String(prop).startsWith("_")) return value;
66
+ const currentPath = [...path, String(prop)];
67
+ const pathStr = currentPath.join(".");
68
+ if (pathStr === "messages.create" && typeof value === "function") {
69
+ return tracedMessagesCreate(value.bind(obj));
70
+ }
71
+ if (pathStr === "messages.stream" && typeof value === "function") {
72
+ return tracedMessagesStream(value.bind(obj));
73
+ }
74
+ if (value && typeof value === "object" && !Array.isArray(value) && isNamespace(currentPath)) {
75
+ return wrapNamespace(value, currentPath);
76
+ }
77
+ return value;
78
+ }
79
+ });
80
+ }
81
+ function isNamespace(path) {
82
+ if (path.length > 3) return false;
83
+ const key = path[path.length - 1];
84
+ return ["messages", "beta"].includes(key);
85
+ }
86
+ function tracedMessagesCreate(original) {
87
+ return function(opts, ...rest) {
88
+ const tracer = import_api.trace.getTracer(TRACER_NAME);
89
+ const model = opts?.model ?? "";
90
+ const messages = opts?.messages ?? [];
91
+ const isStream = opts?.stream === true;
92
+ const span = tracer.startSpan("anthropic.messages.create", {
93
+ attributes: {
94
+ "neatlogs.span.kind": "LLM",
95
+ "neatlogs.llm.provider": "anthropic",
96
+ "neatlogs.llm.system": "anthropic",
97
+ "neatlogs.llm.model_name": model,
98
+ "neatlogs.llm.is_streaming": isStream
99
+ }
100
+ }, import_api.context.active());
101
+ setInputMessages(span, opts?.system, messages);
102
+ setTools(span, opts?.tools);
103
+ setInvocationParams(span, opts);
104
+ const ctx = import_api.trace.setSpan(import_api.context.active(), span);
105
+ const promise = import_api.context.with(ctx, () => original(opts, ...rest));
106
+ return promise.then(
107
+ (response) => {
108
+ if (isStream) {
109
+ return wrapStreamIterable(response, span);
110
+ }
111
+ finalizeMessageResponse(span, response);
112
+ return response;
113
+ },
114
+ (err) => {
115
+ recordError(span, err);
116
+ throw err;
117
+ }
118
+ );
119
+ };
120
+ }
121
+ function tracedMessagesStream(original) {
122
+ return function(opts, ...rest) {
123
+ const tracer = import_api.trace.getTracer(TRACER_NAME);
124
+ const model = opts?.model ?? "";
125
+ const messages = opts?.messages ?? [];
126
+ const span = tracer.startSpan("anthropic.messages.stream", {
127
+ attributes: {
128
+ "neatlogs.span.kind": "LLM",
129
+ "neatlogs.llm.provider": "anthropic",
130
+ "neatlogs.llm.system": "anthropic",
131
+ "neatlogs.llm.model_name": model,
132
+ "neatlogs.llm.is_streaming": true
133
+ }
134
+ }, import_api.context.active());
135
+ setInputMessages(span, opts?.system, messages);
136
+ setTools(span, opts?.tools);
137
+ setInvocationParams(span, opts);
138
+ const ctx = import_api.trace.setSpan(import_api.context.active(), span);
139
+ const messageStream = import_api.context.with(ctx, () => original(opts, ...rest));
140
+ return wrapMessageStream(messageStream, span);
141
+ };
142
+ }
143
+ function wrapStreamIterable(stream, span) {
144
+ const events = [];
145
+ const originalAsyncIterator = stream[Symbol.asyncIterator]?.bind(stream);
146
+ if (!originalAsyncIterator) {
147
+ span.setStatus({ code: import_api.SpanStatusCode.OK });
148
+ span.end();
149
+ return stream;
150
+ }
151
+ const wrapped = Object.create(Object.getPrototypeOf(stream));
152
+ Object.assign(wrapped, stream);
153
+ wrapped[Symbol.asyncIterator] = function() {
154
+ const iterator = originalAsyncIterator();
155
+ return {
156
+ async next() {
157
+ try {
158
+ const result = await iterator.next();
159
+ if (result.done) {
160
+ finalizeStreamEvents(span, events);
161
+ return result;
162
+ }
163
+ events.push(result.value);
164
+ return result;
165
+ } catch (err) {
166
+ recordError(span, err);
167
+ throw err;
168
+ }
169
+ },
170
+ async return(value) {
171
+ finalizeStreamEvents(span, events);
172
+ return iterator.return?.(value) ?? { done: true, value: void 0 };
173
+ },
174
+ async throw(err) {
175
+ recordError(span, err);
176
+ return iterator.throw?.(err) ?? { done: true, value: void 0 };
177
+ }
178
+ };
179
+ };
180
+ if (typeof stream.finalMessage === "function") {
181
+ const origFinal = stream.finalMessage.bind(stream);
182
+ wrapped.finalMessage = async function() {
183
+ return origFinal();
184
+ };
185
+ }
186
+ return wrapped;
187
+ }
188
+ function wrapMessageStream(messageStream, span) {
189
+ const origOn = messageStream.on?.bind(messageStream);
190
+ if (origOn) {
191
+ origOn("end", () => {
192
+ const finalMsg = messageStream._finalMessage ?? messageStream.currentMessage;
193
+ if (finalMsg) {
194
+ finalizeMessageResponse(span, finalMsg);
195
+ } else {
196
+ span.setStatus({ code: import_api.SpanStatusCode.OK });
197
+ span.end();
198
+ }
199
+ });
200
+ origOn("error", (err) => {
201
+ if (span.isRecording()) recordError(span, err);
202
+ });
203
+ }
204
+ if (typeof messageStream.finalMessage === "function") {
205
+ const origFinal = messageStream.finalMessage.bind(messageStream);
206
+ messageStream.finalMessage = async function() {
207
+ const result = await origFinal();
208
+ if (span.isRecording()) {
209
+ finalizeMessageResponse(span, result);
210
+ }
211
+ return result;
212
+ };
213
+ }
214
+ return messageStream;
215
+ }
216
+ function finalizeStreamEvents(span, events) {
217
+ const textParts = [];
218
+ const thinkingParts = [];
219
+ const toolCalls = [];
220
+ let currentToolInput = "";
221
+ let currentToolId = "";
222
+ let currentToolName = "";
223
+ let usage = null;
224
+ let model = "";
225
+ let stopReason = "";
226
+ for (const event of events) {
227
+ const type = event?.type ?? "";
228
+ if (type === "content_block_delta") {
229
+ const delta = event?.delta;
230
+ if (delta?.type === "text_delta" && delta.text) textParts.push(delta.text);
231
+ else if (delta?.type === "thinking_delta" && delta.thinking) thinkingParts.push(delta.thinking);
232
+ else if (delta?.type === "input_json_delta" && delta.partial_json) currentToolInput += delta.partial_json;
233
+ } else if (type === "content_block_start") {
234
+ const block = event?.content_block;
235
+ if (block?.type === "tool_use") {
236
+ currentToolId = block.id ?? "";
237
+ currentToolName = block.name ?? "";
238
+ currentToolInput = "";
239
+ }
240
+ } else if (type === "content_block_stop") {
241
+ if (currentToolName) {
242
+ toolCalls.push({ id: currentToolId, name: currentToolName, input: currentToolInput });
243
+ currentToolId = "";
244
+ currentToolName = "";
245
+ currentToolInput = "";
246
+ }
247
+ } else if (type === "message_start") {
248
+ const msg = event?.message;
249
+ if (msg?.model) model = msg.model;
250
+ if (msg?.usage) usage = msg.usage;
251
+ } else if (type === "message_delta") {
252
+ const delta = event?.delta;
253
+ if (delta?.stop_reason) stopReason = delta.stop_reason;
254
+ if (event?.usage) usage = { ...usage ?? {}, ...event.usage };
255
+ }
256
+ }
257
+ const fullText = textParts.join("");
258
+ if (fullText) {
259
+ span.setAttribute("neatlogs.llm.output_messages.0.role", "assistant");
260
+ span.setAttribute("neatlogs.llm.output_messages.0.content", fullText);
261
+ }
262
+ const thinking = thinkingParts.join("");
263
+ if (thinking) {
264
+ span.setAttribute("neatlogs.llm.output_messages.0.thinking", thinking);
265
+ }
266
+ for (let j = 0; j < toolCalls.length; j++) {
267
+ span.setAttribute(`neatlogs.llm.tool_calls.${j}.id`, toolCalls[j].id);
268
+ span.setAttribute(`neatlogs.llm.tool_calls.${j}.name`, toolCalls[j].name);
269
+ span.setAttribute(`neatlogs.llm.tool_calls.${j}.arguments`, toolCalls[j].input);
270
+ }
271
+ if (model) span.setAttribute("neatlogs.llm.model_name", model);
272
+ if (stopReason) span.setAttribute("neatlogs.llm.stop_reason", stopReason);
273
+ setUsageAttrs(span, usage);
274
+ span.setStatus({ code: import_api.SpanStatusCode.OK });
275
+ span.end();
276
+ }
277
+ function finalizeMessageResponse(span, response) {
278
+ const content = response?.content ?? [];
279
+ const textParts = [];
280
+ const thinkingParts = [];
281
+ const toolCalls = [];
282
+ for (const block of content) {
283
+ if (block.type === "text" && block.text) textParts.push(block.text);
284
+ else if (block.type === "thinking" && block.thinking) thinkingParts.push(block.thinking);
285
+ else if (block.type === "tool_use") {
286
+ toolCalls.push({
287
+ id: block.id ?? "",
288
+ name: block.name ?? "",
289
+ input: safeStringify(block.input ?? {})
290
+ });
291
+ }
292
+ }
293
+ if (textParts.length) {
294
+ span.setAttribute("neatlogs.llm.output_messages.0.role", "assistant");
295
+ span.setAttribute("neatlogs.llm.output_messages.0.content", textParts.join(""));
296
+ }
297
+ if (thinkingParts.length) {
298
+ span.setAttribute("neatlogs.llm.output_messages.0.thinking", thinkingParts.join(""));
299
+ }
300
+ for (let j = 0; j < toolCalls.length; j++) {
301
+ span.setAttribute(`neatlogs.llm.tool_calls.${j}.id`, toolCalls[j].id);
302
+ span.setAttribute(`neatlogs.llm.tool_calls.${j}.name`, toolCalls[j].name);
303
+ span.setAttribute(`neatlogs.llm.tool_calls.${j}.arguments`, toolCalls[j].input);
304
+ }
305
+ setUsageAttrs(span, response?.usage);
306
+ if (response?.model) span.setAttribute("neatlogs.llm.model_name", response.model);
307
+ if (response?.stop_reason) span.setAttribute("neatlogs.llm.stop_reason", response.stop_reason);
308
+ span.setStatus({ code: import_api.SpanStatusCode.OK });
309
+ span.end();
310
+ }
311
+ function setInputMessages(span, system, messages) {
312
+ let idx = 0;
313
+ if (system) {
314
+ const content = typeof system === "string" ? system : safeStringify(system);
315
+ span.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, "system");
316
+ span.setAttribute(`neatlogs.llm.input_messages.${idx}.content`, content);
317
+ idx++;
318
+ }
319
+ for (const msg of messages) {
320
+ span.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, msg.role ?? "");
321
+ if (typeof msg.content === "string") {
322
+ span.setAttribute(`neatlogs.llm.input_messages.${idx}.content`, msg.content);
323
+ } else if (msg.content) {
324
+ span.setAttribute(`neatlogs.llm.input_messages.${idx}.content`, safeStringify(msg.content));
325
+ }
326
+ idx++;
327
+ }
328
+ }
329
+ function setTools(span, tools) {
330
+ if (!tools) return;
331
+ for (let i = 0; i < tools.length; i++) {
332
+ const tool = tools[i];
333
+ span.setAttribute(`neatlogs.llm.tools.${i}.name`, tool.name ?? "");
334
+ if (tool.description) span.setAttribute(`neatlogs.llm.tools.${i}.description`, tool.description);
335
+ if (tool.input_schema) span.setAttribute(`neatlogs.llm.tools.${i}.input_schema`, safeStringify(tool.input_schema));
336
+ }
337
+ }
338
+ function setInvocationParams(span, opts) {
339
+ if (opts?.temperature != null) span.setAttribute("neatlogs.llm.temperature", opts.temperature);
340
+ if (opts?.top_p != null) span.setAttribute("neatlogs.llm.top_p", opts.top_p);
341
+ if (opts?.top_k != null) span.setAttribute("neatlogs.llm.top_k", opts.top_k);
342
+ if (opts?.max_tokens != null) span.setAttribute("neatlogs.llm.max_tokens", opts.max_tokens);
343
+ if (opts?.stop_sequences) span.setAttribute("neatlogs.llm.stop_sequences", safeStringify(opts.stop_sequences));
344
+ }
345
+ function setUsageAttrs(span, usage) {
346
+ if (!usage) return;
347
+ if (usage.input_tokens != null) span.setAttribute("neatlogs.llm.token_count.prompt", usage.input_tokens);
348
+ if (usage.output_tokens != null) span.setAttribute("neatlogs.llm.token_count.completion", usage.output_tokens);
349
+ if (usage.cache_read_input_tokens != null) span.setAttribute("neatlogs.llm.token_count.cache_read", usage.cache_read_input_tokens);
350
+ if (usage.cache_creation_input_tokens != null) span.setAttribute("neatlogs.llm.token_count.cache_write", usage.cache_creation_input_tokens);
351
+ }
352
+ function safeStringify(value) {
353
+ try {
354
+ return typeof value === "string" ? value : JSON.stringify(value);
355
+ } catch {
356
+ return "";
357
+ }
358
+ }
359
+ function recordError(span, err) {
360
+ if (err instanceof Error) {
361
+ span.setStatus({ code: import_api.SpanStatusCode.ERROR, message: err.message });
362
+ span.recordException(err);
363
+ } else {
364
+ span.setStatus({ code: import_api.SpanStatusCode.ERROR, message: String(err) });
365
+ }
366
+ span.end();
367
+ }
368
+ // Annotate the CommonJS export names for ESM import in node:
369
+ 0 && (module.exports = {
370
+ traceTool,
371
+ wrapAnthropic
372
+ });
373
+ //# sourceMappingURL=anthropic.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/anthropic.ts"],"sourcesContent":["/**\n * Neatlogs Anthropic wrapper — ES6 Proxy-based.\n *\n * Usage:\n * import { wrapAnthropic, traceTool } from 'neatlogs/anthropic';\n * import Anthropic from '@anthropic-ai/sdk';\n * const client = wrapAnthropic(new Anthropic());\n *\n * Intercepts:\n * - client.messages.create() — non-streaming and streaming (stream: true)\n * - client.messages.stream() — Anthropic's streaming helper (MessageStream)\n *\n * Also exports traceTool() to wrap user-defined tool functions with TOOL spans.\n * Handles thinking blocks, tool_use blocks, and cache tokens.\n */\n\nimport { trace, context as otelContext, SpanStatusCode, type Span } from '@opentelemetry/api';\n\nconst TRACER_NAME = 'neatlogs.anthropic';\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport function wrapAnthropic<T extends object>(client: T): T {\n return wrapNamespace(client, []) as T;\n}\n\n/**\n * Wrap a tool/function implementation to emit TOOL spans when executed.\n *\n * Usage:\n * const getWeather = traceTool('get_weather', async (input: { city: string }) => {\n * return `Weather in ${input.city}: sunny`;\n * });\n */\nexport function traceTool<TInput = any, TResult = any>(\n name: string,\n fn: (input: TInput) => TResult | Promise<TResult>,\n): (input: TInput) => Promise<TResult> {\n return async function tracedTool(input: TInput): Promise<TResult> {\n const tracer = trace.getTracer(TRACER_NAME);\n return tracer.startActiveSpan(\n `tool.${name}`,\n {\n attributes: {\n 'neatlogs.span.kind': 'TOOL',\n 'neatlogs.tool.name': name,\n 'input.value': safeStringify(input),\n },\n },\n otelContext.active(),\n async (span) => {\n try {\n const result = await fn(input);\n span.setAttribute('output.value', safeStringify(result));\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (err) {\n recordError(span, err);\n throw err;\n } finally {\n span.end();\n }\n },\n );\n };\n}\n\n// ---------------------------------------------------------------------------\n// Proxy wrapping\n// ---------------------------------------------------------------------------\n\nfunction wrapNamespace(target: any, path: string[]): any {\n return new Proxy(target, {\n get(obj, prop, receiver) {\n const value = Reflect.get(obj, prop, receiver);\n if (typeof prop === 'symbol' || String(prop).startsWith('_')) return value;\n\n const currentPath = [...path, String(prop)];\n const pathStr = currentPath.join('.');\n\n if (pathStr === 'messages.create' && typeof value === 'function') {\n return tracedMessagesCreate(value.bind(obj));\n }\n if (pathStr === 'messages.stream' && typeof value === 'function') {\n return tracedMessagesStream(value.bind(obj));\n }\n\n if (value && typeof value === 'object' && !Array.isArray(value) && isNamespace(currentPath)) {\n return wrapNamespace(value, currentPath);\n }\n\n return value;\n },\n });\n}\n\nfunction isNamespace(path: string[]): boolean {\n if (path.length > 3) return false;\n const key = path[path.length - 1];\n return ['messages', 'beta'].includes(key);\n}\n\n// ---------------------------------------------------------------------------\n// messages.create — non-streaming + streaming (stream: true)\n// ---------------------------------------------------------------------------\n\nfunction tracedMessagesCreate(original: (...args: any[]) => any) {\n return function (opts: any, ...rest: any[]): any {\n const tracer = trace.getTracer(TRACER_NAME);\n const model = opts?.model ?? '';\n const messages: any[] = opts?.messages ?? [];\n const isStream = opts?.stream === true;\n\n const span = tracer.startSpan('anthropic.messages.create', {\n attributes: {\n 'neatlogs.span.kind': 'LLM',\n 'neatlogs.llm.provider': 'anthropic',\n 'neatlogs.llm.system': 'anthropic',\n 'neatlogs.llm.model_name': model,\n 'neatlogs.llm.is_streaming': isStream,\n },\n }, otelContext.active());\n\n setInputMessages(span, opts?.system, messages);\n setTools(span, opts?.tools);\n setInvocationParams(span, opts);\n\n const ctx = trace.setSpan(otelContext.active(), span);\n const promise = otelContext.with(ctx, () => original(opts, ...rest));\n\n return promise.then(\n (response: any) => {\n if (isStream) {\n return wrapStreamIterable(response, span);\n }\n finalizeMessageResponse(span, response);\n return response;\n },\n (err: any) => {\n recordError(span, err);\n throw err;\n },\n );\n };\n}\n\n// ---------------------------------------------------------------------------\n// messages.stream() — returns a MessageStream object\n// ---------------------------------------------------------------------------\n\nfunction tracedMessagesStream(original: (...args: any[]) => any) {\n return function (opts: any, ...rest: any[]): any {\n const tracer = trace.getTracer(TRACER_NAME);\n const model = opts?.model ?? '';\n const messages: any[] = opts?.messages ?? [];\n\n const span = tracer.startSpan('anthropic.messages.stream', {\n attributes: {\n 'neatlogs.span.kind': 'LLM',\n 'neatlogs.llm.provider': 'anthropic',\n 'neatlogs.llm.system': 'anthropic',\n 'neatlogs.llm.model_name': model,\n 'neatlogs.llm.is_streaming': true,\n },\n }, otelContext.active());\n\n setInputMessages(span, opts?.system, messages);\n setTools(span, opts?.tools);\n setInvocationParams(span, opts);\n\n const ctx = trace.setSpan(otelContext.active(), span);\n const messageStream = otelContext.with(ctx, () => original(opts, ...rest));\n\n return wrapMessageStream(messageStream, span);\n };\n}\n\n// ---------------------------------------------------------------------------\n// Streaming: async iterable (stream: true returns events)\n// ---------------------------------------------------------------------------\n\nfunction wrapStreamIterable(stream: any, span: Span): any {\n const events: any[] = [];\n const originalAsyncIterator = stream[Symbol.asyncIterator]?.bind(stream);\n\n if (!originalAsyncIterator) {\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return stream;\n }\n\n const wrapped = Object.create(Object.getPrototypeOf(stream));\n Object.assign(wrapped, stream);\n\n wrapped[Symbol.asyncIterator] = function () {\n const iterator = originalAsyncIterator();\n return {\n async next(): Promise<IteratorResult<any>> {\n try {\n const result = await iterator.next();\n if (result.done) {\n finalizeStreamEvents(span, events);\n return result;\n }\n events.push(result.value);\n return result;\n } catch (err) {\n recordError(span, err);\n throw err;\n }\n },\n async return(value?: any): Promise<IteratorResult<any>> {\n finalizeStreamEvents(span, events);\n return iterator.return?.(value) ?? { done: true, value: undefined };\n },\n async throw(err?: any): Promise<IteratorResult<any>> {\n recordError(span, err);\n return iterator.throw?.(err) ?? { done: true, value: undefined };\n },\n };\n };\n\n if (typeof stream.finalMessage === 'function') {\n const origFinal = stream.finalMessage.bind(stream);\n wrapped.finalMessage = async function () {\n return origFinal();\n };\n }\n\n return wrapped;\n}\n\n// ---------------------------------------------------------------------------\n// Streaming: MessageStream (.on('end'), .finalMessage())\n// ---------------------------------------------------------------------------\n\nfunction wrapMessageStream(messageStream: any, span: Span): any {\n const origOn = messageStream.on?.bind(messageStream);\n if (origOn) {\n origOn('end', () => {\n const finalMsg = messageStream._finalMessage ?? messageStream.currentMessage;\n if (finalMsg) {\n finalizeMessageResponse(span, finalMsg);\n } else {\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n }\n });\n origOn('error', (err: any) => {\n if (span.isRecording()) recordError(span, err);\n });\n }\n\n if (typeof messageStream.finalMessage === 'function') {\n const origFinal = messageStream.finalMessage.bind(messageStream);\n messageStream.finalMessage = async function () {\n const result = await origFinal();\n if (span.isRecording()) {\n finalizeMessageResponse(span, result);\n }\n return result;\n };\n }\n\n return messageStream;\n}\n\n// ---------------------------------------------------------------------------\n// Stream event finalization\n// ---------------------------------------------------------------------------\n\nfunction finalizeStreamEvents(span: Span, events: any[]): void {\n const textParts: string[] = [];\n const thinkingParts: string[] = [];\n const toolCalls: Array<{ id: string; name: string; input: string }> = [];\n let currentToolInput = '';\n let currentToolId = '';\n let currentToolName = '';\n let usage: any = null;\n let model = '';\n let stopReason = '';\n\n for (const event of events) {\n const type = event?.type ?? '';\n\n if (type === 'content_block_delta') {\n const delta = event?.delta;\n if (delta?.type === 'text_delta' && delta.text) textParts.push(delta.text);\n else if (delta?.type === 'thinking_delta' && delta.thinking) thinkingParts.push(delta.thinking);\n else if (delta?.type === 'input_json_delta' && delta.partial_json) currentToolInput += delta.partial_json;\n } else if (type === 'content_block_start') {\n const block = event?.content_block;\n if (block?.type === 'tool_use') {\n currentToolId = block.id ?? '';\n currentToolName = block.name ?? '';\n currentToolInput = '';\n }\n } else if (type === 'content_block_stop') {\n if (currentToolName) {\n toolCalls.push({ id: currentToolId, name: currentToolName, input: currentToolInput });\n currentToolId = '';\n currentToolName = '';\n currentToolInput = '';\n }\n } else if (type === 'message_start') {\n const msg = event?.message;\n if (msg?.model) model = msg.model;\n if (msg?.usage) usage = msg.usage;\n } else if (type === 'message_delta') {\n const delta = event?.delta;\n if (delta?.stop_reason) stopReason = delta.stop_reason;\n if (event?.usage) usage = { ...(usage ?? {}), ...event.usage };\n }\n }\n\n const fullText = textParts.join('');\n if (fullText) {\n span.setAttribute('neatlogs.llm.output_messages.0.role', 'assistant');\n span.setAttribute('neatlogs.llm.output_messages.0.content', fullText);\n }\n\n const thinking = thinkingParts.join('');\n if (thinking) {\n span.setAttribute('neatlogs.llm.output_messages.0.thinking', thinking);\n }\n\n for (let j = 0; j < toolCalls.length; j++) {\n span.setAttribute(`neatlogs.llm.tool_calls.${j}.id`, toolCalls[j].id);\n span.setAttribute(`neatlogs.llm.tool_calls.${j}.name`, toolCalls[j].name);\n span.setAttribute(`neatlogs.llm.tool_calls.${j}.arguments`, toolCalls[j].input);\n }\n\n if (model) span.setAttribute('neatlogs.llm.model_name', model);\n if (stopReason) span.setAttribute('neatlogs.llm.stop_reason', stopReason);\n setUsageAttrs(span, usage);\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n}\n\n// ---------------------------------------------------------------------------\n// Non-streaming response finalization\n// ---------------------------------------------------------------------------\n\nfunction finalizeMessageResponse(span: Span, response: any): void {\n const content: any[] = response?.content ?? [];\n const textParts: string[] = [];\n const thinkingParts: string[] = [];\n const toolCalls: Array<{ id: string; name: string; input: string }> = [];\n\n for (const block of content) {\n if (block.type === 'text' && block.text) textParts.push(block.text);\n else if (block.type === 'thinking' && block.thinking) thinkingParts.push(block.thinking);\n else if (block.type === 'tool_use') {\n toolCalls.push({\n id: block.id ?? '',\n name: block.name ?? '',\n input: safeStringify(block.input ?? {}),\n });\n }\n }\n\n if (textParts.length) {\n span.setAttribute('neatlogs.llm.output_messages.0.role', 'assistant');\n span.setAttribute('neatlogs.llm.output_messages.0.content', textParts.join(''));\n }\n if (thinkingParts.length) {\n span.setAttribute('neatlogs.llm.output_messages.0.thinking', thinkingParts.join(''));\n }\n\n for (let j = 0; j < toolCalls.length; j++) {\n span.setAttribute(`neatlogs.llm.tool_calls.${j}.id`, toolCalls[j].id);\n span.setAttribute(`neatlogs.llm.tool_calls.${j}.name`, toolCalls[j].name);\n span.setAttribute(`neatlogs.llm.tool_calls.${j}.arguments`, toolCalls[j].input);\n }\n\n setUsageAttrs(span, response?.usage);\n if (response?.model) span.setAttribute('neatlogs.llm.model_name', response.model);\n if (response?.stop_reason) span.setAttribute('neatlogs.llm.stop_reason', response.stop_reason);\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n}\n\n// ---------------------------------------------------------------------------\n// Utilities\n// ---------------------------------------------------------------------------\n\nfunction setInputMessages(span: Span, system: any, messages: any[]): void {\n let idx = 0;\n if (system) {\n const content = typeof system === 'string' ? system : safeStringify(system);\n span.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, 'system');\n span.setAttribute(`neatlogs.llm.input_messages.${idx}.content`, content);\n idx++;\n }\n for (const msg of messages) {\n span.setAttribute(`neatlogs.llm.input_messages.${idx}.role`, msg.role ?? '');\n if (typeof msg.content === 'string') {\n span.setAttribute(`neatlogs.llm.input_messages.${idx}.content`, msg.content);\n } else if (msg.content) {\n span.setAttribute(`neatlogs.llm.input_messages.${idx}.content`, safeStringify(msg.content));\n }\n idx++;\n }\n}\n\nfunction setTools(span: Span, tools: any[] | undefined): void {\n if (!tools) return;\n for (let i = 0; i < tools.length; i++) {\n const tool = tools[i];\n span.setAttribute(`neatlogs.llm.tools.${i}.name`, tool.name ?? '');\n if (tool.description) span.setAttribute(`neatlogs.llm.tools.${i}.description`, tool.description);\n if (tool.input_schema) span.setAttribute(`neatlogs.llm.tools.${i}.input_schema`, safeStringify(tool.input_schema));\n }\n}\n\nfunction setInvocationParams(span: Span, opts: any): void {\n if (opts?.temperature != null) span.setAttribute('neatlogs.llm.temperature', opts.temperature);\n if (opts?.top_p != null) span.setAttribute('neatlogs.llm.top_p', opts.top_p);\n if (opts?.top_k != null) span.setAttribute('neatlogs.llm.top_k', opts.top_k);\n if (opts?.max_tokens != null) span.setAttribute('neatlogs.llm.max_tokens', opts.max_tokens);\n if (opts?.stop_sequences) span.setAttribute('neatlogs.llm.stop_sequences', safeStringify(opts.stop_sequences));\n}\n\nfunction setUsageAttrs(span: Span, usage: any): void {\n if (!usage) return;\n if (usage.input_tokens != null) span.setAttribute('neatlogs.llm.token_count.prompt', usage.input_tokens);\n if (usage.output_tokens != null) span.setAttribute('neatlogs.llm.token_count.completion', usage.output_tokens);\n if (usage.cache_read_input_tokens != null) span.setAttribute('neatlogs.llm.token_count.cache_read', usage.cache_read_input_tokens);\n if (usage.cache_creation_input_tokens != null) span.setAttribute('neatlogs.llm.token_count.cache_write', usage.cache_creation_input_tokens);\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return typeof value === 'string' ? value : JSON.stringify(value);\n } catch {\n return '';\n }\n}\n\nfunction recordError(span: Span, err: unknown): void {\n if (err instanceof Error) {\n span.setStatus({ code: SpanStatusCode.ERROR, message: err.message });\n span.recordException(err);\n } else {\n span.setStatus({ code: SpanStatusCode.ERROR, message: String(err) });\n }\n span.end();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,iBAAyE;AAEzE,IAAM,cAAc;AAMb,SAAS,cAAgC,QAAc;AAC5D,SAAO,cAAc,QAAQ,CAAC,CAAC;AACjC;AAUO,SAAS,UACd,MACA,IACqC;AACrC,SAAO,eAAe,WAAW,OAAiC;AAChE,UAAM,SAAS,iBAAM,UAAU,WAAW;AAC1C,WAAO,OAAO;AAAA,MACZ,QAAQ,IAAI;AAAA,MACZ;AAAA,QACE,YAAY;AAAA,UACV,sBAAsB;AAAA,UACtB,sBAAsB;AAAA,UACtB,eAAe,cAAc,KAAK;AAAA,QACpC;AAAA,MACF;AAAA,MACA,WAAAA,QAAY,OAAO;AAAA,MACnB,OAAO,SAAS;AACd,YAAI;AACF,gBAAM,SAAS,MAAM,GAAG,KAAK;AAC7B,eAAK,aAAa,gBAAgB,cAAc,MAAM,CAAC;AACvD,eAAK,UAAU,EAAE,MAAM,0BAAe,GAAG,CAAC;AAC1C,iBAAO;AAAA,QACT,SAAS,KAAK;AACZ,sBAAY,MAAM,G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AAK,UAAU;AAC1F,MAAI,MAAM,eAAgB,MAAK,aAAa,+BAA+B,cAAc,KAAK,cAAc,CAAC;AAC/G;AAEA,SAAS,cAAc,MAAY,OAAkB;AACnD,MAAI,CAAC,MAAO;AACZ,MAAI,MAAM,gBAAgB,KAAM,MAAK,aAAa,mCAAmC,MAAM,YAAY;AACvG,MAAI,MAAM,iBAAiB,KAAM,MAAK,aAAa,uCAAuC,MAAM,aAAa;AAC7G,MAAI,MAAM,2BAA2B,KAAM,MAAK,aAAa,uCAAuC,MAAM,uBAAuB;AACjI,MAAI,MAAM,+BAA+B,KAAM,MAAK,aAAa,wCAAwC,MAAM,2BAA2B;AAC5I;AAEA,SAAS,cAAc,OAAwB;AAC7C,MAAI;AACF,WAAO,OAAO,UAAU,WAAW,QAAQ,KAAK,UAAU,KAAK;AAAA,EACjE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,YAAY,MAAY,KAAoB;AACnD,MAAI,eAAe,OAAO;AACxB,SAAK,UAAU,EAAE,MAAM,0BAAe,OAAO,SAAS,IAAI,QAAQ,CAAC;AACnE,SAAK,gBAAgB,GAAG;AAAA,EAC1B,OAAO;AACL,SAAK,UAAU,EAAE,MAAM,0BAAe,OAAO,SAAS,OAAO,GAAG,EAAE,CAAC;AAAA,EACrE;AACA,OAAK,IAAI;AACX;","names":["otelContext"]}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Neatlogs Anthropic wrapper — ES6 Proxy-based.
3
+ *
4
+ * Usage:
5
+ * import { wrapAnthropic, traceTool } from 'neatlogs/anthropic';
6
+ * import Anthropic from '@anthropic-ai/sdk';
7
+ * const client = wrapAnthropic(new Anthropic());
8
+ *
9
+ * Intercepts:
10
+ * - client.messages.create() — non-streaming and streaming (stream: true)
11
+ * - client.messages.stream() — Anthropic's streaming helper (MessageStream)
12
+ *
13
+ * Also exports traceTool() to wrap user-defined tool functions with TOOL spans.
14
+ * Handles thinking blocks, tool_use blocks, and cache tokens.
15
+ */
16
+ declare function wrapAnthropic<T extends object>(client: T): T;
17
+ /**
18
+ * Wrap a tool/function implementation to emit TOOL spans when executed.
19
+ *
20
+ * Usage:
21
+ * const getWeather = traceTool('get_weather', async (input: { city: string }) => {
22
+ * return `Weather in ${input.city}: sunny`;
23
+ * });
24
+ */
25
+ declare function traceTool<TInput = any, TResult = any>(name: string, fn: (input: TInput) => TResult | Promise<TResult>): (input: TInput) => Promise<TResult>;
26
+
27
+ export { traceTool, wrapAnthropic };