aispendbook 0.0.0-stage → 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 +145 -2
- package/dist/cjs/client.d.ts +48 -0
- package/dist/cjs/client.js +197 -0
- package/dist/cjs/config.d.ts +80 -0
- package/dist/cjs/config.js +59 -0
- package/dist/cjs/context.d.ts +22 -0
- package/dist/cjs/context.js +28 -0
- package/dist/cjs/index.d.ts +26 -0
- package/dist/cjs/index.js +53 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/transport.d.ts +61 -0
- package/dist/cjs/transport.js +231 -0
- package/dist/cjs/types.d.ts +51 -0
- package/dist/cjs/types.js +7 -0
- package/dist/cjs/usage.d.ts +16 -0
- package/dist/cjs/usage.js +110 -0
- package/dist/cjs/vercel.d.ts +30 -0
- package/dist/cjs/vercel.js +130 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/wrappers/anthropic.d.ts +9 -0
- package/dist/cjs/wrappers/anthropic.js +106 -0
- package/dist/cjs/wrappers/google.d.ts +9 -0
- package/dist/cjs/wrappers/google.js +74 -0
- package/dist/cjs/wrappers/openai.d.ts +10 -0
- package/dist/cjs/wrappers/openai.js +136 -0
- package/dist/cjs/wrappers/span.d.ts +60 -0
- package/dist/cjs/wrappers/span.js +190 -0
- package/dist/esm/client.d.ts +48 -0
- package/dist/esm/client.js +187 -0
- package/dist/esm/config.d.ts +80 -0
- package/dist/esm/config.js +54 -0
- package/dist/esm/context.d.ts +22 -0
- package/dist/esm/context.js +23 -0
- package/dist/esm/index.d.ts +26 -0
- package/dist/esm/index.js +19 -0
- package/dist/esm/transport.d.ts +61 -0
- package/dist/esm/transport.js +226 -0
- package/dist/esm/types.d.ts +51 -0
- package/dist/esm/types.js +4 -0
- package/dist/esm/usage.d.ts +16 -0
- package/dist/esm/usage.js +103 -0
- package/dist/esm/vercel.d.ts +30 -0
- package/dist/esm/vercel.js +125 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/wrappers/anthropic.d.ts +9 -0
- package/dist/esm/wrappers/anthropic.js +102 -0
- package/dist/esm/wrappers/google.d.ts +9 -0
- package/dist/esm/wrappers/google.js +70 -0
- package/dist/esm/wrappers/openai.d.ts +10 -0
- package/dist/esm/wrappers/openai.js +132 -0
- package/dist/esm/wrappers/span.d.ts +60 -0
- package/dist/esm/wrappers/span.js +179 -0
- package/package.json +85 -4
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anthropic (`@anthropic-ai/sdk`): `messages.create`, streamed or not. `messages.stream()` calls
|
|
3
|
+
* `create({ stream: true })` on the wrapped resource, so it is recorded through the same path.
|
|
4
|
+
* Provider is `bedrock` for AnthropicBedrock, `vertex` for AnthropicVertex, else `anthropic`.
|
|
5
|
+
*/
|
|
6
|
+
import { n, anthropicUsage } from "../usage.js";
|
|
7
|
+
import { isAsyncIterable, observeResult, observeStream, startSpan, str, wrapPath } from "./span.js";
|
|
8
|
+
export function detectAnthropicProvider(client) {
|
|
9
|
+
const name = client?.constructor?.name ?? "";
|
|
10
|
+
if (/bedrock/i.test(name))
|
|
11
|
+
return "bedrock";
|
|
12
|
+
if (/vertex/i.test(name))
|
|
13
|
+
return "vertex";
|
|
14
|
+
return "anthropic";
|
|
15
|
+
}
|
|
16
|
+
function finishMessage(span, message) {
|
|
17
|
+
const usage = message?.usage;
|
|
18
|
+
span.finish({
|
|
19
|
+
usage: anthropicUsage(usage),
|
|
20
|
+
model: str(message?.model),
|
|
21
|
+
requestId: str(message?._request_id),
|
|
22
|
+
serviceTier: str(usage?.service_tier),
|
|
23
|
+
metadata: usage ? undefined : { usage_missing: true },
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/** `message_start` carries input/cache tokens; `message_delta.usage` carries cumulative output. */
|
|
27
|
+
class AnthropicStreamObserver {
|
|
28
|
+
requestId;
|
|
29
|
+
model;
|
|
30
|
+
startUsage;
|
|
31
|
+
deltaUsage;
|
|
32
|
+
constructor(requestId) {
|
|
33
|
+
this.requestId = requestId;
|
|
34
|
+
}
|
|
35
|
+
observe(event) {
|
|
36
|
+
if (event?.type === "message_start") {
|
|
37
|
+
this.model = str(event.message?.model) ?? this.model;
|
|
38
|
+
this.startUsage = event.message?.usage;
|
|
39
|
+
}
|
|
40
|
+
else if (event?.type === "message_delta" && event.usage) {
|
|
41
|
+
this.deltaUsage = event.usage;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
finish() {
|
|
45
|
+
const usage = anthropicUsage(this.startUsage);
|
|
46
|
+
const d = this.deltaUsage;
|
|
47
|
+
if (d) {
|
|
48
|
+
if (d.output_tokens !== undefined)
|
|
49
|
+
usage.outputTokens = n(d.output_tokens);
|
|
50
|
+
if (d.input_tokens != null)
|
|
51
|
+
usage.inputTokens = n(d.input_tokens);
|
|
52
|
+
if (d.cache_read_input_tokens != null)
|
|
53
|
+
usage.cacheReadTokens = n(d.cache_read_input_tokens);
|
|
54
|
+
if (d.cache_creation_input_tokens != null)
|
|
55
|
+
usage.cacheWriteTokens = n(d.cache_creation_input_tokens);
|
|
56
|
+
if (usage.cacheWrite1hTokens > usage.cacheWriteTokens)
|
|
57
|
+
usage.cacheWrite1hTokens = usage.cacheWriteTokens;
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
usage,
|
|
61
|
+
model: this.model,
|
|
62
|
+
requestId: this.requestId,
|
|
63
|
+
serviceTier: str(this.startUsage?.service_tier),
|
|
64
|
+
metadata: this.startUsage ? undefined : { usage_missing: true },
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** Return a proxy of an `Anthropic` / `AnthropicBedrock` / `AnthropicVertex` client whose calls are recorded. */
|
|
69
|
+
export function wrapAnthropic(client, opts = {}) {
|
|
70
|
+
const provider = opts.provider ?? detectAnthropicProvider(client);
|
|
71
|
+
const create = (original, thisArg) => function wrapped(...args) {
|
|
72
|
+
const params = args[0];
|
|
73
|
+
const streamed = Boolean(params?.stream);
|
|
74
|
+
const span = startSpan(opts, provider, params, streamed);
|
|
75
|
+
if (!span)
|
|
76
|
+
return original.apply(thisArg, args);
|
|
77
|
+
let result;
|
|
78
|
+
try {
|
|
79
|
+
result = original.apply(thisArg, args);
|
|
80
|
+
}
|
|
81
|
+
catch (err) {
|
|
82
|
+
span.fail(err);
|
|
83
|
+
throw err;
|
|
84
|
+
}
|
|
85
|
+
return observeResult(result, span, (value) => {
|
|
86
|
+
if (streamed && isAsyncIterable(value)) {
|
|
87
|
+
let requestId;
|
|
88
|
+
try {
|
|
89
|
+
requestId = str(value.response?.headers?.get?.("request-id"));
|
|
90
|
+
}
|
|
91
|
+
catch {
|
|
92
|
+
requestId = undefined;
|
|
93
|
+
}
|
|
94
|
+
observeStream(value, new AnthropicStreamObserver(requestId), span);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
finishMessage(span, value);
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
};
|
|
101
|
+
return wrapPath(client, { messages: { create } });
|
|
102
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Gen AI (`@google/genai`): `models.generateContent` and `models.generateContentStream`.
|
|
3
|
+
* Provider is `vertex` when the client was created with `vertexai: true`, else `google`.
|
|
4
|
+
* Stream chunks carry cumulative `usageMetadata`; the last one seen is recorded.
|
|
5
|
+
*/
|
|
6
|
+
import { type WrapOptions } from "./span.js";
|
|
7
|
+
export declare function detectGoogleProvider(client: unknown): string;
|
|
8
|
+
/** Return a proxy of a `GoogleGenAI` client whose `models` calls are recorded. */
|
|
9
|
+
export declare function wrapGoogleGenAI<T extends object>(client: T, opts?: WrapOptions): T;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google Gen AI (`@google/genai`): `models.generateContent` and `models.generateContentStream`.
|
|
3
|
+
* Provider is `vertex` when the client was created with `vertexai: true`, else `google`.
|
|
4
|
+
* Stream chunks carry cumulative `usageMetadata`; the last one seen is recorded.
|
|
5
|
+
*/
|
|
6
|
+
import { geminiUsage } from "../usage.js";
|
|
7
|
+
import { observeResult, observeStream, startSpan, str, wrapPath } from "./span.js";
|
|
8
|
+
export function detectGoogleProvider(client) {
|
|
9
|
+
const c = client;
|
|
10
|
+
return c?.vertexai === true || c?.apiClient?.clientOptions?.vertexai === true ? "vertex" : "google";
|
|
11
|
+
}
|
|
12
|
+
function finishResponse(span, response) {
|
|
13
|
+
const md = response?.usageMetadata;
|
|
14
|
+
span.finish({
|
|
15
|
+
usage: geminiUsage(md),
|
|
16
|
+
model: str(response?.modelVersion),
|
|
17
|
+
requestId: str(response?.responseId),
|
|
18
|
+
metadata: md ? undefined : { usage_missing: true },
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
class GeminiStreamObserver {
|
|
22
|
+
model;
|
|
23
|
+
requestId;
|
|
24
|
+
usage;
|
|
25
|
+
observe(chunk) {
|
|
26
|
+
this.model = str(chunk?.modelVersion) ?? this.model;
|
|
27
|
+
this.requestId = str(chunk?.responseId) ?? this.requestId;
|
|
28
|
+
if (chunk?.usageMetadata)
|
|
29
|
+
this.usage = chunk.usageMetadata;
|
|
30
|
+
}
|
|
31
|
+
finish() {
|
|
32
|
+
return {
|
|
33
|
+
usage: geminiUsage(this.usage),
|
|
34
|
+
model: this.model,
|
|
35
|
+
requestId: this.requestId,
|
|
36
|
+
metadata: this.usage ? undefined : { usage_missing: true },
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function method(opts, provider, streamed) {
|
|
41
|
+
return (original, thisArg) => function wrapped(...args) {
|
|
42
|
+
const span = startSpan(opts, provider, args[0], streamed);
|
|
43
|
+
if (!span)
|
|
44
|
+
return original.apply(thisArg, args);
|
|
45
|
+
let result;
|
|
46
|
+
try {
|
|
47
|
+
result = original.apply(thisArg, args);
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
span.fail(err);
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
return observeResult(result, span, (value) => {
|
|
54
|
+
if (streamed)
|
|
55
|
+
observeStream(value, new GeminiStreamObserver(), span);
|
|
56
|
+
else
|
|
57
|
+
finishResponse(span, value);
|
|
58
|
+
});
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
/** Return a proxy of a `GoogleGenAI` client whose `models` calls are recorded. */
|
|
62
|
+
export function wrapGoogleGenAI(client, opts = {}) {
|
|
63
|
+
const provider = opts.provider ?? detectGoogleProvider(client);
|
|
64
|
+
return wrapPath(client, {
|
|
65
|
+
models: {
|
|
66
|
+
generateContent: method(opts, provider, false),
|
|
67
|
+
generateContentStream: method(opts, provider, true),
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI (`openai` npm package): `chat.completions.create` and `responses.create`, streamed or not.
|
|
3
|
+
* Streamed chat completions only carry usage when the request sets
|
|
4
|
+
* `stream_options: { include_usage: true }`; without it the event is recorded with zero tokens and
|
|
5
|
+
* `metadata.usage_missing = true` (never guessed).
|
|
6
|
+
*/
|
|
7
|
+
import { type WrapOptions } from "./span.js";
|
|
8
|
+
export declare function detectOpenAIProvider(client: unknown): string;
|
|
9
|
+
/** Return a proxy of an `OpenAI` / `AzureOpenAI` client whose calls are recorded. */
|
|
10
|
+
export declare function wrapOpenAI<T extends object>(client: T, opts?: WrapOptions): T;
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI (`openai` npm package): `chat.completions.create` and `responses.create`, streamed or not.
|
|
3
|
+
* Streamed chat completions only carry usage when the request sets
|
|
4
|
+
* `stream_options: { include_usage: true }`; without it the event is recorded with zero tokens and
|
|
5
|
+
* `metadata.usage_missing = true` (never guessed).
|
|
6
|
+
*/
|
|
7
|
+
import { openaiChatUsage, openaiResponsesUsage } from "../usage.js";
|
|
8
|
+
import { isAsyncIterable, observeResult, observeStream, startSpan, str, wrapPath } from "./span.js";
|
|
9
|
+
export function detectOpenAIProvider(client) {
|
|
10
|
+
const name = client?.constructor?.name ?? "";
|
|
11
|
+
return /azure/i.test(name) ? "azure_openai" : "openai";
|
|
12
|
+
}
|
|
13
|
+
function headerRequestId(stream) {
|
|
14
|
+
try {
|
|
15
|
+
return str(stream?.response?.headers?.get?.("x-request-id"));
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function finishChat(span, completion) {
|
|
22
|
+
const usage = completion?.usage;
|
|
23
|
+
span.finish({
|
|
24
|
+
usage: openaiChatUsage(usage),
|
|
25
|
+
model: str(completion?.model),
|
|
26
|
+
requestId: str(completion?._request_id),
|
|
27
|
+
serviceTier: str(completion?.service_tier),
|
|
28
|
+
metadata: usage ? undefined : { usage_missing: true },
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function finishResponse(span, response) {
|
|
32
|
+
const usage = response?.usage;
|
|
33
|
+
const failed = response?.status === "failed";
|
|
34
|
+
span.finish({
|
|
35
|
+
status: failed ? "error" : "success",
|
|
36
|
+
errorType: failed ? "ResponseFailed" : undefined,
|
|
37
|
+
usage: openaiResponsesUsage(usage),
|
|
38
|
+
model: str(response?.model),
|
|
39
|
+
requestId: str(response?._request_id),
|
|
40
|
+
serviceTier: str(response?.service_tier),
|
|
41
|
+
metadata: usage ? undefined : { usage_missing: true },
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
class ChatStreamObserver {
|
|
45
|
+
requestId;
|
|
46
|
+
model;
|
|
47
|
+
serviceTier;
|
|
48
|
+
usage;
|
|
49
|
+
constructor(requestId) {
|
|
50
|
+
this.requestId = requestId;
|
|
51
|
+
}
|
|
52
|
+
observe(chunk) {
|
|
53
|
+
this.model = this.model ?? str(chunk?.model);
|
|
54
|
+
this.serviceTier = str(chunk?.service_tier) ?? this.serviceTier;
|
|
55
|
+
if (chunk?.usage)
|
|
56
|
+
this.usage = chunk.usage;
|
|
57
|
+
}
|
|
58
|
+
finish() {
|
|
59
|
+
return {
|
|
60
|
+
usage: openaiChatUsage(this.usage),
|
|
61
|
+
model: this.model,
|
|
62
|
+
requestId: this.requestId,
|
|
63
|
+
serviceTier: this.serviceTier,
|
|
64
|
+
metadata: this.usage ? undefined : { usage_missing: true },
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
class ResponsesStreamObserver {
|
|
69
|
+
requestId;
|
|
70
|
+
model;
|
|
71
|
+
final;
|
|
72
|
+
finalType;
|
|
73
|
+
constructor(requestId) {
|
|
74
|
+
this.requestId = requestId;
|
|
75
|
+
}
|
|
76
|
+
observe(event) {
|
|
77
|
+
const type = event?.type;
|
|
78
|
+
if (["response.created", "response.in_progress", "response.completed", "response.incomplete", "response.failed"].includes(type)) {
|
|
79
|
+
this.model = str(event?.response?.model) ?? this.model;
|
|
80
|
+
if (type !== "response.created" && type !== "response.in_progress") {
|
|
81
|
+
this.final = event.response;
|
|
82
|
+
this.finalType = type;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
finish() {
|
|
87
|
+
const usage = this.final?.usage;
|
|
88
|
+
const failed = this.finalType === "response.failed";
|
|
89
|
+
return {
|
|
90
|
+
usage: openaiResponsesUsage(usage),
|
|
91
|
+
model: this.model,
|
|
92
|
+
requestId: this.requestId,
|
|
93
|
+
serviceTier: str(this.final?.service_tier),
|
|
94
|
+
status: failed ? "error" : undefined,
|
|
95
|
+
errorType: failed ? "ResponseFailed" : undefined,
|
|
96
|
+
metadata: usage ? undefined : { usage_missing: true },
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function method(opts, provider, finish, Observer) {
|
|
101
|
+
return (original, thisArg) => function wrapped(...args) {
|
|
102
|
+
const params = args[0];
|
|
103
|
+
const streamed = Boolean(params?.stream);
|
|
104
|
+
const span = startSpan(opts, provider, params, streamed);
|
|
105
|
+
if (!span)
|
|
106
|
+
return original.apply(thisArg, args);
|
|
107
|
+
let result;
|
|
108
|
+
try {
|
|
109
|
+
result = original.apply(thisArg, args);
|
|
110
|
+
}
|
|
111
|
+
catch (err) {
|
|
112
|
+
span.fail(err);
|
|
113
|
+
throw err;
|
|
114
|
+
}
|
|
115
|
+
return observeResult(result, span, (value) => {
|
|
116
|
+
if (streamed && isAsyncIterable(value)) {
|
|
117
|
+
observeStream(value, new Observer(headerRequestId(value)), span);
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
finish(span, value);
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/** Return a proxy of an `OpenAI` / `AzureOpenAI` client whose calls are recorded. */
|
|
126
|
+
export function wrapOpenAI(client, opts = {}) {
|
|
127
|
+
const provider = opts.provider ?? detectOpenAIProvider(client);
|
|
128
|
+
return wrapPath(client, {
|
|
129
|
+
chat: { completions: { create: method(opts, provider, finishChat, ChatStreamObserver) } },
|
|
130
|
+
responses: { create: method(opts, provider, finishResponse, ResponsesStreamObserver) },
|
|
131
|
+
});
|
|
132
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared wrapper machinery. Every helper swallows its own errors so telemetry can never change
|
|
3
|
+
* the behaviour of the host application's provider call.
|
|
4
|
+
*/
|
|
5
|
+
import { type SpendbookClient } from "../client.js";
|
|
6
|
+
import type { EventStatus, MetaValue, Usage } from "../types.js";
|
|
7
|
+
export interface WrapOptions {
|
|
8
|
+
/** Client to record with. Defaults to the global client from `init()` at call time. */
|
|
9
|
+
client?: SpendbookClient;
|
|
10
|
+
/** Provider name to report (e.g. `azure_openai`, `bedrock`, `vertex`); auto-detected when omitted. */
|
|
11
|
+
provider?: string;
|
|
12
|
+
}
|
|
13
|
+
export interface FinishInput {
|
|
14
|
+
status?: EventStatus;
|
|
15
|
+
usage?: Usage;
|
|
16
|
+
model?: string;
|
|
17
|
+
requestId?: string;
|
|
18
|
+
serviceTier?: string;
|
|
19
|
+
errorType?: string;
|
|
20
|
+
metadata?: Record<string, MetaValue>;
|
|
21
|
+
}
|
|
22
|
+
export declare class CallSpan {
|
|
23
|
+
private readonly client;
|
|
24
|
+
private readonly provider;
|
|
25
|
+
private readonly requestModel;
|
|
26
|
+
private readonly streamed;
|
|
27
|
+
private readonly started;
|
|
28
|
+
private readonly occurredAt;
|
|
29
|
+
private readonly attribution;
|
|
30
|
+
done: boolean;
|
|
31
|
+
constructor(client: SpendbookClient, provider: string, requestModel: string | undefined, streamed: boolean);
|
|
32
|
+
finish(input?: FinishInput): void;
|
|
33
|
+
fail(err: unknown): void;
|
|
34
|
+
}
|
|
35
|
+
export declare function str(value: unknown): string | undefined;
|
|
36
|
+
export declare function startSpan(opts: WrapOptions, provider: string, params: unknown, streamed: boolean): CallSpan | null;
|
|
37
|
+
export declare function safe(fn: () => void): void;
|
|
38
|
+
/**
|
|
39
|
+
* Observe a call's result without replacing it: the original promise (e.g. an OpenAI APIPromise
|
|
40
|
+
* with `.withResponse()`) is returned unchanged. Our `then` runs before the caller's, so a stream
|
|
41
|
+
* is instrumented before the caller iterates it.
|
|
42
|
+
*/
|
|
43
|
+
export declare function observeResult(result: unknown, span: CallSpan, onValue: (value: unknown) => void): unknown;
|
|
44
|
+
export declare function isAsyncIterable(value: unknown): boolean;
|
|
45
|
+
export interface StreamObserver {
|
|
46
|
+
observe(item: unknown): void;
|
|
47
|
+
finish(): FinishInput;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Instrument an async-iterable stream in place (same object returned to the caller): records
|
|
51
|
+
* success when iteration completes, error when it throws, cancelled on early `return()`.
|
|
52
|
+
*/
|
|
53
|
+
export declare function observeStream(stream: unknown, observer: StreamObserver, span: CallSpan): void;
|
|
54
|
+
type Factory = (original: (...args: unknown[]) => unknown, thisArg: unknown) => (...args: unknown[]) => unknown;
|
|
55
|
+
export interface WrapSpec {
|
|
56
|
+
[key: string]: WrapSpec | Factory;
|
|
57
|
+
}
|
|
58
|
+
/** Proxy `target` so the methods named in `spec` (nested by property path) are wrapped. */
|
|
59
|
+
export declare function wrapPath<T extends object>(target: T, spec: WrapSpec): T;
|
|
60
|
+
export {};
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared wrapper machinery. Every helper swallows its own errors so telemetry can never change
|
|
3
|
+
* the behaviour of the host application's provider call.
|
|
4
|
+
*/
|
|
5
|
+
import { getClient } from "../client.js";
|
|
6
|
+
import { getContext } from "../context.js";
|
|
7
|
+
export class CallSpan {
|
|
8
|
+
client;
|
|
9
|
+
provider;
|
|
10
|
+
requestModel;
|
|
11
|
+
streamed;
|
|
12
|
+
started = Date.now();
|
|
13
|
+
occurredAt = new Date();
|
|
14
|
+
attribution = getContext();
|
|
15
|
+
done = false;
|
|
16
|
+
constructor(client, provider, requestModel, streamed) {
|
|
17
|
+
this.client = client;
|
|
18
|
+
this.provider = provider;
|
|
19
|
+
this.requestModel = requestModel;
|
|
20
|
+
this.streamed = streamed;
|
|
21
|
+
}
|
|
22
|
+
finish(input = {}) {
|
|
23
|
+
if (this.done)
|
|
24
|
+
return;
|
|
25
|
+
this.done = true;
|
|
26
|
+
try {
|
|
27
|
+
const record = {
|
|
28
|
+
provider: this.provider,
|
|
29
|
+
model: input.model || this.requestModel,
|
|
30
|
+
occurredAt: this.occurredAt,
|
|
31
|
+
completedAt: new Date(),
|
|
32
|
+
latencyMs: Date.now() - this.started,
|
|
33
|
+
status: input.status ?? "success",
|
|
34
|
+
errorType: input.errorType,
|
|
35
|
+
requestId: input.requestId,
|
|
36
|
+
serviceTier: input.serviceTier,
|
|
37
|
+
streamed: this.streamed,
|
|
38
|
+
metadata: input.metadata,
|
|
39
|
+
attribution: this.attribution,
|
|
40
|
+
...(input.usage ?? {}),
|
|
41
|
+
};
|
|
42
|
+
this.client.record(record);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// never surface telemetry errors
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
fail(err) {
|
|
49
|
+
const name = err?.name;
|
|
50
|
+
const aborted = name === "AbortError" || name === "APIUserAbortError";
|
|
51
|
+
this.finish({
|
|
52
|
+
status: aborted ? "cancelled" : "error",
|
|
53
|
+
errorType: typeof name === "string" ? name : "Error",
|
|
54
|
+
requestId: str(err?.requestID ?? err?.request_id),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
export function str(value) {
|
|
59
|
+
return typeof value === "string" && value ? value : undefined;
|
|
60
|
+
}
|
|
61
|
+
export function startSpan(opts, provider, params, streamed) {
|
|
62
|
+
try {
|
|
63
|
+
const client = opts.client ?? getClient();
|
|
64
|
+
if (!client?.active)
|
|
65
|
+
return null;
|
|
66
|
+
const model = params?.model;
|
|
67
|
+
return new CallSpan(client, opts.provider ?? provider, typeof model === "string" ? model : undefined, streamed);
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
export function safe(fn) {
|
|
74
|
+
try {
|
|
75
|
+
fn();
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// ignore
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function isThenable(value) {
|
|
82
|
+
return Boolean(value) && typeof value.then === "function";
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Observe a call's result without replacing it: the original promise (e.g. an OpenAI APIPromise
|
|
86
|
+
* with `.withResponse()`) is returned unchanged. Our `then` runs before the caller's, so a stream
|
|
87
|
+
* is instrumented before the caller iterates it.
|
|
88
|
+
*/
|
|
89
|
+
export function observeResult(result, span, onValue) {
|
|
90
|
+
if (isThenable(result)) {
|
|
91
|
+
result.then((value) => safe(() => onValue(value)), (err) => safe(() => span.fail(err)));
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
safe(() => onValue(result));
|
|
95
|
+
return result;
|
|
96
|
+
}
|
|
97
|
+
export function isAsyncIterable(value) {
|
|
98
|
+
return Boolean(value) && typeof value[Symbol.asyncIterator] === "function";
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Instrument an async-iterable stream in place (same object returned to the caller): records
|
|
102
|
+
* success when iteration completes, error when it throws, cancelled on early `return()`.
|
|
103
|
+
*/
|
|
104
|
+
export function observeStream(stream, observer, span) {
|
|
105
|
+
const target = stream;
|
|
106
|
+
const original = target?.[Symbol.asyncIterator];
|
|
107
|
+
if (typeof original !== "function") {
|
|
108
|
+
span.finish({ metadata: { usage_missing: true } });
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
const end = (status, errorType) => {
|
|
112
|
+
if (span.done)
|
|
113
|
+
return;
|
|
114
|
+
let input = {};
|
|
115
|
+
safe(() => {
|
|
116
|
+
input = observer.finish();
|
|
117
|
+
});
|
|
118
|
+
span.finish({ ...input, status: status === "success" ? input.status ?? "success" : status, errorType: errorType ?? input.errorType });
|
|
119
|
+
};
|
|
120
|
+
Object.defineProperty(target, Symbol.asyncIterator, {
|
|
121
|
+
configurable: true,
|
|
122
|
+
writable: true,
|
|
123
|
+
value: function observed() {
|
|
124
|
+
const inner = original.call(this);
|
|
125
|
+
const wrapped = {
|
|
126
|
+
async next(...args) {
|
|
127
|
+
try {
|
|
128
|
+
const res = await inner.next(...args);
|
|
129
|
+
if (res.done)
|
|
130
|
+
end("success");
|
|
131
|
+
else
|
|
132
|
+
safe(() => observer.observe(res.value));
|
|
133
|
+
return res;
|
|
134
|
+
}
|
|
135
|
+
catch (err) {
|
|
136
|
+
const name = err?.name;
|
|
137
|
+
end(name === "AbortError" || name === "APIUserAbortError" ? "cancelled" : "error", typeof name === "string" ? name : "Error");
|
|
138
|
+
throw err;
|
|
139
|
+
}
|
|
140
|
+
},
|
|
141
|
+
async return(value) {
|
|
142
|
+
end("cancelled");
|
|
143
|
+
return inner.return ? inner.return(value) : { done: true, value };
|
|
144
|
+
},
|
|
145
|
+
async throw(err) {
|
|
146
|
+
end("error", err?.name ?? "Error");
|
|
147
|
+
if (inner.throw)
|
|
148
|
+
return inner.throw(err);
|
|
149
|
+
throw err;
|
|
150
|
+
},
|
|
151
|
+
};
|
|
152
|
+
return wrapped;
|
|
153
|
+
},
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
/** Proxy `target` so the methods named in `spec` (nested by property path) are wrapped. */
|
|
157
|
+
export function wrapPath(target, spec) {
|
|
158
|
+
const cache = new Map();
|
|
159
|
+
return new Proxy(target, {
|
|
160
|
+
get(obj, prop, receiver) {
|
|
161
|
+
const value = Reflect.get(obj, prop, receiver);
|
|
162
|
+
const entry = typeof prop === "string" ? spec[prop] : undefined;
|
|
163
|
+
if (!entry || value === null || value === undefined)
|
|
164
|
+
return value;
|
|
165
|
+
const cached = cache.get(prop);
|
|
166
|
+
if (cached && cached.src === value)
|
|
167
|
+
return cached.out;
|
|
168
|
+
let out = value;
|
|
169
|
+
if (typeof entry === "function" && typeof value === "function") {
|
|
170
|
+
out = entry(value, obj);
|
|
171
|
+
}
|
|
172
|
+
else if (typeof entry === "object" && typeof value === "object") {
|
|
173
|
+
out = wrapPath(value, entry);
|
|
174
|
+
}
|
|
175
|
+
cache.set(prop, { src: value, out });
|
|
176
|
+
return out;
|
|
177
|
+
},
|
|
178
|
+
});
|
|
179
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,87 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "aispendbook",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "AI Spendbook tracking SDK for Node.js: attribute OpenAI, Anthropic and Google Gemini token usage to customers and features.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "AI Spendbook",
|
|
7
|
+
"homepage": "https://aispendbook.com",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"llm",
|
|
10
|
+
"openai",
|
|
11
|
+
"anthropic",
|
|
12
|
+
"gemini",
|
|
13
|
+
"vercel-ai-sdk",
|
|
14
|
+
"finops",
|
|
15
|
+
"cost",
|
|
16
|
+
"telemetry"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"main": "./dist/cjs/index.js",
|
|
20
|
+
"module": "./dist/esm/index.js",
|
|
21
|
+
"types": "./dist/esm/index.d.ts",
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"import": {
|
|
25
|
+
"types": "./dist/esm/index.d.ts",
|
|
26
|
+
"default": "./dist/esm/index.js"
|
|
27
|
+
},
|
|
28
|
+
"require": {
|
|
29
|
+
"types": "./dist/cjs/index.d.ts",
|
|
30
|
+
"default": "./dist/cjs/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"README.md",
|
|
38
|
+
"LICENSE"
|
|
39
|
+
],
|
|
40
|
+
"sideEffects": false,
|
|
41
|
+
"engines": {
|
|
42
|
+
"node": ">=18"
|
|
43
|
+
},
|
|
44
|
+
"scripts": {
|
|
45
|
+
"clean": "node scripts/clean.cjs",
|
|
46
|
+
"build": "npm run clean && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && node scripts/cjs-package.cjs",
|
|
47
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
48
|
+
"test": "vitest run",
|
|
49
|
+
"prepublishOnly": "npm run build && npm test",
|
|
50
|
+
"prepare": "npm run build"
|
|
51
|
+
},
|
|
52
|
+
"peerDependencies": {
|
|
53
|
+
"@anthropic-ai/sdk": "*",
|
|
54
|
+
"@google/genai": "*",
|
|
55
|
+
"ai": "*",
|
|
56
|
+
"openai": "*"
|
|
57
|
+
},
|
|
58
|
+
"peerDependenciesMeta": {
|
|
59
|
+
"@anthropic-ai/sdk": {
|
|
60
|
+
"optional": true
|
|
61
|
+
},
|
|
62
|
+
"@google/genai": {
|
|
63
|
+
"optional": true
|
|
64
|
+
},
|
|
65
|
+
"ai": {
|
|
66
|
+
"optional": true
|
|
67
|
+
},
|
|
68
|
+
"openai": {
|
|
69
|
+
"optional": true
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
"devDependencies": {
|
|
73
|
+
"@types/node": "^22.20.5",
|
|
74
|
+
"typescript": "^6.0.3",
|
|
75
|
+
"vitest": "^3.2.4"
|
|
76
|
+
},
|
|
77
|
+
"publishConfig": {
|
|
78
|
+
"access": "public"
|
|
79
|
+
},
|
|
80
|
+
"repository": {
|
|
81
|
+
"type": "git",
|
|
82
|
+
"url": "git+https://github.com/AISpendbook/aispendbook-node.git"
|
|
83
|
+
},
|
|
84
|
+
"bugs": {
|
|
85
|
+
"url": "https://github.com/AISpendbook/aispendbook-node/issues"
|
|
86
|
+
}
|
|
87
|
+
}
|