@nestjs/observe 0.3.19 → 0.3.21
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 +105 -22
- package/NOTICE +31 -0
- package/README.md +97 -8
- package/dist/agent/observe-agent.worker.js +8 -7
- package/dist/instrument/create-instance-decorator.instrument.js +134 -88
- package/dist/interfaces/observe-options.interface.d.ts +18 -2
- package/dist/interfaces/trace-events.interfaces.d.ts +11 -5
- package/dist/observe.constants.d.ts +5 -5
- package/dist/observe.constants.js +5 -5
- package/dist/observe.module.js +12 -0
- package/dist/outgoing/http.integration.js +4 -0
- package/dist/outgoing/llm/llm-fetch.integration.d.ts +56 -0
- package/dist/outgoing/llm/llm-fetch.integration.js +236 -0
- package/dist/outgoing/llm/llm-providers.d.ts +25 -0
- package/dist/outgoing/llm/llm-providers.js +96 -0
- package/dist/outgoing/llm/llm-usage.d.ts +67 -0
- package/dist/outgoing/llm/llm-usage.js +263 -0
- package/dist/outgoing/outgoing-observe-agent.service.d.ts +1 -0
- package/dist/outgoing/outgoing-observe-agent.service.js +12 -0
- package/dist/outgoing/outgoing-span.recorder.d.ts +9 -0
- package/dist/outgoing/outgoing-span.recorder.js +55 -6
- package/dist/protocols/deferred-trace-completion.d.ts +13 -2
- package/dist/protocols/deferred-trace-completion.js +27 -4
- package/dist/protocols/graphql-observe-agent.service.js +1 -1
- package/dist/protocols/http-observe-agent.service.js +20 -28
- package/dist/protocols/job-trace-runner.js +2 -2
- package/dist/protocols/rpc-observe-agent.service.js +19 -10
- package/dist/protocols/ws-observe-agent.service.js +1 -1
- package/dist/services/collapse-repeated-spans.util.js +41 -37
- package/dist/services/operation-trace.registry.d.ts +15 -9
- package/dist/services/operation-trace.registry.js +79 -25
- package/dist/utils/uuid-v7.util.js +53 -15
- package/package.json +5 -3
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { OutgoingHttpOptions } from "../outgoing/http.integration.js";
|
|
2
|
+
import type { OutgoingLlmOptions } from "../outgoing/llm/llm-fetch.integration.js";
|
|
2
3
|
import type { HttpCaptureOptions } from "../utils/capture-request.util.js";
|
|
3
4
|
import { FactoryProvider, ModuleMetadata, Provider, Type } from "@nestjs/common";
|
|
4
5
|
import { BaseRpcContext, Transport } from "@nestjs/microservices";
|
|
@@ -79,7 +80,9 @@ export interface CreateObserveModuleOptions {
|
|
|
79
80
|
*
|
|
80
81
|
* Nest's own `Reflector` is never instrumented, whatever this returns: its
|
|
81
82
|
* metadata lookups run several times a request and say nothing a
|
|
82
|
-
* waterfall is for.
|
|
83
|
+
* waterfall is for. Nor are the `mongodb` driver's `MongoClient` and
|
|
84
|
+
* `Db`: their command spans come from the mongodb integration, and a
|
|
85
|
+
* proxied client fails the driver's session identity checks.
|
|
83
86
|
*
|
|
84
87
|
* Runs before the built-in checks, so it also shields providers that
|
|
85
88
|
* cannot even be inspected safely: some libraries (nestjs-cls proxy
|
|
@@ -180,7 +183,8 @@ export interface ObserveOptions {
|
|
|
180
183
|
* One setting for telemetry and profiles both, so the two can never point at
|
|
181
184
|
* different places. Defaults to the hosted collector; set `OBSERVE_ENDPOINT`
|
|
182
185
|
* in the environment to override that without touching this config, which is
|
|
183
|
-
* how a
|
|
186
|
+
* how a proxy or gateway that forwards to NestJS Observe is usually pointed
|
|
187
|
+
* at.
|
|
184
188
|
*
|
|
185
189
|
* @default 'https://observe-api.nestjs.com'
|
|
186
190
|
*/
|
|
@@ -602,6 +606,18 @@ export interface ObserveOptions {
|
|
|
602
606
|
database?: boolean;
|
|
603
607
|
/** @default true */
|
|
604
608
|
http?: boolean | OutgoingHttpOptions;
|
|
609
|
+
/**
|
|
610
|
+
* Model calls: for a `fetch` to a model provider (OpenAI, Anthropic,
|
|
611
|
+
* Gemini, Bedrock, Mistral and others), the model and the tokens its
|
|
612
|
+
* response reports, read as the response passes through to the
|
|
613
|
+
* caller. Prompts and completions are never read into the report.
|
|
614
|
+
* Needs `http`; calls made through `node:http` (axios) keep their
|
|
615
|
+
* plain span. Off, the global `fetch` is left as it was: `forRoot`
|
|
616
|
+
* puts the original back, and `forRootAsync` does when the agent
|
|
617
|
+
* starts.
|
|
618
|
+
* @default true
|
|
619
|
+
*/
|
|
620
|
+
llm?: boolean | OutgoingLlmOptions;
|
|
605
621
|
};
|
|
606
622
|
/**
|
|
607
623
|
* WebSocket gateway configuration options for the Observe APM.
|
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { TraceSpan } from "./trace-span.interface.js";
|
|
2
2
|
export interface OngoingTraceEventNode extends TraceSpan {
|
|
3
|
-
|
|
3
|
+
/**
|
|
4
|
+
* `"start"` while the call runs, `"end"` once it has returned. A node that
|
|
5
|
+
* has ended keeps its other fields where they are - `startTime`, an empty
|
|
6
|
+
* `children` - until its trace is handed off, when the tree is rebuilt into
|
|
7
|
+
* `CompleteTraceEventNode`s holding only what is shipped.
|
|
8
|
+
*/
|
|
9
|
+
type: "start" | "end";
|
|
4
10
|
/**
|
|
5
11
|
* Represents the host class name, which is the class where the method being traced is defined.
|
|
6
12
|
*/
|
|
@@ -17,9 +23,9 @@ export interface OngoingTraceEventNode extends TraceSpan {
|
|
|
17
23
|
/**
|
|
18
24
|
* Milliseconds between the start of the trace root and the start of this span.
|
|
19
25
|
*
|
|
20
|
-
* Captured when the span opens and carried through to the completed node,
|
|
21
|
-
*
|
|
22
|
-
*
|
|
26
|
+
* Captured when the span opens and carried through to the completed node,
|
|
27
|
+
* which has no `startTime`. Undefined when the parent snapshot has already
|
|
28
|
+
* been cleaned up.
|
|
23
29
|
*/
|
|
24
30
|
startOffset?: number;
|
|
25
31
|
/**
|
|
@@ -31,7 +37,7 @@ export interface OngoingTraceEventNode extends TraceSpan {
|
|
|
31
37
|
children: Array<CompleteTraceEventNode | OngoingTraceEventNode>;
|
|
32
38
|
/**
|
|
33
39
|
* Optional parent node for ongoing trace events.
|
|
34
|
-
* Undefined for root nodes.
|
|
40
|
+
* Undefined for root nodes, and once the node has ended.
|
|
35
41
|
*/
|
|
36
42
|
parent?: OngoingTraceEventNode;
|
|
37
43
|
}
|
|
@@ -3,11 +3,11 @@ export declare const CALLER_METADATA_KEY = "#caller";
|
|
|
3
3
|
/**
|
|
4
4
|
* Where a store keeps the registry key when it differs from the trace id.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
6
|
+
* Queued jobs and RPC calls can share the trace id of the operation that
|
|
7
|
+
* dispatched them, including one still open in this process. The registry is
|
|
8
|
+
* keyed per execution, so each gets a key of its own here while `traceIdKey`
|
|
9
|
+
* keeps the id everything user-facing reads: logs, `currentTraceId()`, the
|
|
10
|
+
* snapshot.
|
|
11
11
|
*/
|
|
12
12
|
export declare const TRACE_REGISTRY_KEY = "#registryKey";
|
|
13
13
|
/**
|
|
@@ -3,11 +3,11 @@ export const CALLER_METADATA_KEY = "#caller";
|
|
|
3
3
|
/**
|
|
4
4
|
* Where a store keeps the registry key when it differs from the trace id.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
6
|
+
* Queued jobs and RPC calls can share the trace id of the operation that
|
|
7
|
+
* dispatched them, including one still open in this process. The registry is
|
|
8
|
+
* keyed per execution, so each gets a key of its own here while `traceIdKey`
|
|
9
|
+
* keeps the id everything user-facing reads: logs, `currentTraceId()`, the
|
|
10
|
+
* snapshot.
|
|
11
11
|
*/
|
|
12
12
|
export const TRACE_REGISTRY_KEY = "#registryKey";
|
|
13
13
|
/**
|
package/dist/observe.module.js
CHANGED
|
@@ -21,6 +21,7 @@ import { CALLER_METADATA_KEY, OBSERVE_OPTIONS } from "./observe.constants.js";
|
|
|
21
21
|
import { GraphQLObserveAgentService } from "./protocols/graphql-observe-agent.service.js";
|
|
22
22
|
import { HttpObserveAgentService } from "./protocols/http-observe-agent.service.js";
|
|
23
23
|
import { OutgoingObserveAgentService } from "./outgoing/outgoing-observe-agent.service.js";
|
|
24
|
+
import { installLlmFetchObserver, llmCallsOff, uninstallLlmFetchObserver, } from "./outgoing/llm/llm-fetch.integration.js";
|
|
24
25
|
import { BullObserveAgentService } from "./protocols/bull-observe-agent.service.js";
|
|
25
26
|
import { QueueObserveAgentService } from "./protocols/queue-observe-agent.service.js";
|
|
26
27
|
import { RpcObserveAgentService } from "./protocols/rpc-observe-agent.service.js";
|
|
@@ -125,6 +126,9 @@ export function createObserveModule(options = {}) {
|
|
|
125
126
|
options.attachTraceIdToLogs ??= true;
|
|
126
127
|
options.traceIdGenerator ??= defaultTraceIdGenerator;
|
|
127
128
|
options.skipInstrumentation ??= () => false;
|
|
129
|
+
// Inert until the agent starts with `outgoing.llm` on - see the function.
|
|
130
|
+
// `forRoot` puts the original back if its options turn model calls off.
|
|
131
|
+
installLlmFetchObserver();
|
|
128
132
|
const asyncLocalStorage = new AsyncLocalStorage();
|
|
129
133
|
const operationTraceRegistry = new OperationTraceRegistry(asyncLocalStorage, options.sourceContext);
|
|
130
134
|
let ObserveModule = ObserveModule_1 = class ObserveModule {
|
|
@@ -138,6 +142,14 @@ export function createObserveModule(options = {}) {
|
|
|
138
142
|
this.options = options;
|
|
139
143
|
}
|
|
140
144
|
static forRoot(observeOpts) {
|
|
145
|
+
// Options that turn model calls off give `fetch` back now, before the
|
|
146
|
+
// application's clients are constructed around the wrapper.
|
|
147
|
+
if (llmCallsOff(observeOpts.outgoing)) {
|
|
148
|
+
uninstallLlmFetchObserver();
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
installLlmFetchObserver();
|
|
152
|
+
}
|
|
141
153
|
return {
|
|
142
154
|
global: true,
|
|
143
155
|
module: ObserveModule_1,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { subscribe, unsubscribe } from "diagnostics_channel";
|
|
2
2
|
import { redactUrlQuery } from "../utils/redact-url-query.js";
|
|
3
|
+
import { attachLlmSpan } from "./llm/llm-fetch.integration.js";
|
|
3
4
|
const TRACE_HEADER = "x-request-id";
|
|
4
5
|
/**
|
|
5
6
|
* Spans for outbound HTTP, from the diagnostics channels Node publishes on its
|
|
@@ -48,6 +49,9 @@ getRedactor = () => null) {
|
|
|
48
49
|
});
|
|
49
50
|
if (span) {
|
|
50
51
|
spans.set(request, span);
|
|
52
|
+
// A no-op unless this request is a model call the fetch observer is
|
|
53
|
+
// reading - see `llm-fetch.integration.ts`.
|
|
54
|
+
attachLlmSpan(span);
|
|
51
55
|
}
|
|
52
56
|
return true;
|
|
53
57
|
};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
2
|
+
import type { ObserveOptions } from "../../interfaces/observe-options.interface.js";
|
|
3
|
+
import { OpenOutgoingSpan, OutgoingSpanRecorder } from "../outgoing-span.recorder.js";
|
|
4
|
+
export interface OutgoingLlmOptions {
|
|
5
|
+
/**
|
|
6
|
+
* More hosts to read as model providers - a gateway in front of them, a
|
|
7
|
+
* self-hosted model with an OpenAI-compatible API - as `host` or
|
|
8
|
+
* `host:port`. Their calls are tagged with the provider `custom`.
|
|
9
|
+
* @example ['llm-gateway.internal:4000']
|
|
10
|
+
*/
|
|
11
|
+
hosts?: string[];
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* What one observed `fetch` call learns from the outbound span undici opens
|
|
15
|
+
* for it: the span, held open until the response has been read.
|
|
16
|
+
*/
|
|
17
|
+
interface LlmFetchHolder {
|
|
18
|
+
span?: OpenOutgoingSpan;
|
|
19
|
+
release?: () => void;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Carries a holder from the `fetch` call into undici's request-create channel,
|
|
23
|
+
* which runs inside the call's async context. That is how the span the HTTP
|
|
24
|
+
* integration opens is found again here, without a header or a lookup table.
|
|
25
|
+
*/
|
|
26
|
+
export declare const llmFetchContext: AsyncLocalStorage<LlmFetchHolder>;
|
|
27
|
+
/** Called by the HTTP integration for every span it opens. */
|
|
28
|
+
export declare function attachLlmSpan(span: OpenOutgoingSpan | undefined): void;
|
|
29
|
+
/**
|
|
30
|
+
* Whether an `outgoing` option turns model calls off. They are read off the
|
|
31
|
+
* HTTP spans, so turning those off turns model calls off with them.
|
|
32
|
+
*/
|
|
33
|
+
export declare function llmCallsOff(outgoing: ObserveOptions["outgoing"]): boolean;
|
|
34
|
+
/**
|
|
35
|
+
* Wraps the global `fetch` once, inert until `activateLlmFetchObserver`.
|
|
36
|
+
*
|
|
37
|
+
* Wrapped as early as the module is created rather than when the agent
|
|
38
|
+
* starts: a client that captures `fetch` when it is constructed - the
|
|
39
|
+
* official OpenAI and Anthropic SDKs do - and is constructed before Nest
|
|
40
|
+
* instantiates the agent would otherwise keep the unwrapped one. Calls to
|
|
41
|
+
* any other host go straight to the original. An application that turns
|
|
42
|
+
* model calls off gets the original back - see `uninstallLlmFetchObserver`.
|
|
43
|
+
*/
|
|
44
|
+
export declare function installLlmFetchObserver(): void;
|
|
45
|
+
/**
|
|
46
|
+
* Puts the original `fetch` back, for an application that turned model calls
|
|
47
|
+
* off: with them off, nothing of this should sit in its calls' path.
|
|
48
|
+
*
|
|
49
|
+
* Only while the wrapper is still the global one. Something that wrapped
|
|
50
|
+
* `fetch` again on top of it would be unwrapped too, so in that case the
|
|
51
|
+
* wrapper stays where it is, inert - a straight pass-through.
|
|
52
|
+
*/
|
|
53
|
+
export declare function uninstallLlmFetchObserver(): void;
|
|
54
|
+
/** Starts reading model calls; the returned function stops it again. */
|
|
55
|
+
export declare function activateLlmFetchObserver(recorder: OutgoingSpanRecorder, options?: OutgoingLlmOptions): () => void;
|
|
56
|
+
export {};
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
2
|
+
import { llmProviderForHost, modelFromRequestBody, modelFromUrlPath, } from "./llm-providers.js";
|
|
3
|
+
import { JsonUsageReader, mergeUsage, SseUsageReader, } from "./llm-usage.js";
|
|
4
|
+
/**
|
|
5
|
+
* Carries a holder from the `fetch` call into undici's request-create channel,
|
|
6
|
+
* which runs inside the call's async context. That is how the span the HTTP
|
|
7
|
+
* integration opens is found again here, without a header or a lookup table.
|
|
8
|
+
*/
|
|
9
|
+
export const llmFetchContext = new AsyncLocalStorage();
|
|
10
|
+
/** Called by the HTTP integration for every span it opens. */
|
|
11
|
+
export function attachLlmSpan(span) {
|
|
12
|
+
const holder = llmFetchContext.getStore();
|
|
13
|
+
if (!holder || !span || holder.span) {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
holder.span = span;
|
|
17
|
+
// Taken now, before undici can end the span: a small response can arrive
|
|
18
|
+
// whole, and end its span, before the caller's `await` sees it.
|
|
19
|
+
holder.release = span.hold?.();
|
|
20
|
+
}
|
|
21
|
+
const INSTALLED = Symbol.for("@nestjs/observe:llm-fetch");
|
|
22
|
+
let active;
|
|
23
|
+
/** The wrapper this copy of the module put in place, and what it wraps. */
|
|
24
|
+
let installed;
|
|
25
|
+
/**
|
|
26
|
+
* Whether an `outgoing` option turns model calls off. They are read off the
|
|
27
|
+
* HTTP spans, so turning those off turns model calls off with them.
|
|
28
|
+
*/
|
|
29
|
+
export function llmCallsOff(outgoing) {
|
|
30
|
+
return (outgoing === false || outgoing?.http === false || outgoing?.llm === false);
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Wraps the global `fetch` once, inert until `activateLlmFetchObserver`.
|
|
34
|
+
*
|
|
35
|
+
* Wrapped as early as the module is created rather than when the agent
|
|
36
|
+
* starts: a client that captures `fetch` when it is constructed - the
|
|
37
|
+
* official OpenAI and Anthropic SDKs do - and is constructed before Nest
|
|
38
|
+
* instantiates the agent would otherwise keep the unwrapped one. Calls to
|
|
39
|
+
* any other host go straight to the original. An application that turns
|
|
40
|
+
* model calls off gets the original back - see `uninstallLlmFetchObserver`.
|
|
41
|
+
*/
|
|
42
|
+
export function installLlmFetchObserver() {
|
|
43
|
+
const original = globalThis.fetch;
|
|
44
|
+
if (typeof original !== "function" || original[INSTALLED]) {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
const observed = function fetch(input, init) {
|
|
48
|
+
const config = active;
|
|
49
|
+
if (!config) {
|
|
50
|
+
return original(input, init);
|
|
51
|
+
}
|
|
52
|
+
let target;
|
|
53
|
+
try {
|
|
54
|
+
target =
|
|
55
|
+
typeof input === "string"
|
|
56
|
+
? new URL(input)
|
|
57
|
+
: input instanceof URL
|
|
58
|
+
? input
|
|
59
|
+
: new URL(input.url);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return original(input, init);
|
|
63
|
+
}
|
|
64
|
+
const provider = llmProviderForHost(target.host, config.extraHosts);
|
|
65
|
+
// Outside a traced operation there is no span to tag.
|
|
66
|
+
if (!provider || !config.recorder.isRecording()) {
|
|
67
|
+
return original(input, init);
|
|
68
|
+
}
|
|
69
|
+
return observeCall(original, input, init, {
|
|
70
|
+
provider,
|
|
71
|
+
requestModel: modelFromRequestBody(init?.body) ?? modelFromUrlPath(target.pathname),
|
|
72
|
+
});
|
|
73
|
+
};
|
|
74
|
+
Object.defineProperty(observed, INSTALLED, { value: true });
|
|
75
|
+
globalThis.fetch = observed;
|
|
76
|
+
installed = { wrapper: observed, original };
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Puts the original `fetch` back, for an application that turned model calls
|
|
80
|
+
* off: with them off, nothing of this should sit in its calls' path.
|
|
81
|
+
*
|
|
82
|
+
* Only while the wrapper is still the global one. Something that wrapped
|
|
83
|
+
* `fetch` again on top of it would be unwrapped too, so in that case the
|
|
84
|
+
* wrapper stays where it is, inert - a straight pass-through.
|
|
85
|
+
*/
|
|
86
|
+
export function uninstallLlmFetchObserver() {
|
|
87
|
+
active = undefined;
|
|
88
|
+
if (installed && globalThis.fetch === installed.wrapper) {
|
|
89
|
+
globalThis.fetch = installed.original;
|
|
90
|
+
installed = undefined;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** Starts reading model calls; the returned function stops it again. */
|
|
94
|
+
export function activateLlmFetchObserver(recorder, options = {}) {
|
|
95
|
+
installLlmFetchObserver();
|
|
96
|
+
const config = {
|
|
97
|
+
recorder,
|
|
98
|
+
extraHosts: new Set((options.hosts ?? []).map((host) => host.toLowerCase())),
|
|
99
|
+
};
|
|
100
|
+
active = config;
|
|
101
|
+
return () => {
|
|
102
|
+
if (active === config) {
|
|
103
|
+
active = undefined;
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
async function observeCall(original, input, init, call) {
|
|
108
|
+
const startedAt = performance.now();
|
|
109
|
+
const holder = {};
|
|
110
|
+
const tag = (usage, stream, firstEventAt) => {
|
|
111
|
+
try {
|
|
112
|
+
holder.span?.tag?.(spanTags(call, mergeUsage({ model: call.requestModel }, usage), {
|
|
113
|
+
stream,
|
|
114
|
+
timeToFirstToken: firstEventAt === undefined
|
|
115
|
+
? undefined
|
|
116
|
+
: round(firstEventAt - startedAt),
|
|
117
|
+
}));
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
/* a lost tag must never cost the caller its response */
|
|
121
|
+
}
|
|
122
|
+
finally {
|
|
123
|
+
holder.release?.();
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
let response;
|
|
127
|
+
try {
|
|
128
|
+
response = await llmFetchContext.run(holder, () => original(input, init));
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
tag({}, false);
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
135
|
+
const stream = contentType.includes("text/event-stream");
|
|
136
|
+
const reader = stream
|
|
137
|
+
? new SseUsageReader()
|
|
138
|
+
: contentType.includes("json")
|
|
139
|
+
? new JsonUsageReader()
|
|
140
|
+
: undefined;
|
|
141
|
+
// No span was opened for it (an outer entry point covers the call), or
|
|
142
|
+
// there is nothing to read: the response goes back untouched.
|
|
143
|
+
if (!holder.span || !reader || !response.body) {
|
|
144
|
+
tag({}, stream);
|
|
145
|
+
return response;
|
|
146
|
+
}
|
|
147
|
+
let tagged = false;
|
|
148
|
+
const finish = () => {
|
|
149
|
+
if (tagged) {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
tagged = true;
|
|
153
|
+
let usage = {};
|
|
154
|
+
try {
|
|
155
|
+
usage = reader.finish();
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
/* unreadable: tag the call without its usage */
|
|
159
|
+
}
|
|
160
|
+
tag(usage, stream, reader instanceof SseUsageReader ? reader.firstEventAt : undefined);
|
|
161
|
+
};
|
|
162
|
+
// Read only as the caller reads, and cancelled when the caller cancels: a
|
|
163
|
+
// tee would keep pulling a stream the caller abandoned, and the model would
|
|
164
|
+
// go on generating - and billing - a completion nobody reads.
|
|
165
|
+
const source = response.body.getReader();
|
|
166
|
+
const body = new ReadableStream({
|
|
167
|
+
async pull(controller) {
|
|
168
|
+
let chunk;
|
|
169
|
+
try {
|
|
170
|
+
chunk = await source.read();
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
finish();
|
|
174
|
+
controller.error(error);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (chunk.done) {
|
|
178
|
+
finish();
|
|
179
|
+
controller.close();
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
try {
|
|
183
|
+
reader.push(chunk.value);
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
/* the bytes still reach the caller */
|
|
187
|
+
}
|
|
188
|
+
controller.enqueue(chunk.value);
|
|
189
|
+
},
|
|
190
|
+
cancel(reason) {
|
|
191
|
+
finish();
|
|
192
|
+
return source.cancel(reason);
|
|
193
|
+
},
|
|
194
|
+
}, { highWaterMark: 0 });
|
|
195
|
+
return rewrap(response, body);
|
|
196
|
+
}
|
|
197
|
+
/** The same response, reading through `body`. */
|
|
198
|
+
function rewrap(response, body) {
|
|
199
|
+
const wrapped = new Response(body, {
|
|
200
|
+
status: response.status,
|
|
201
|
+
statusText: response.statusText,
|
|
202
|
+
headers: response.headers,
|
|
203
|
+
});
|
|
204
|
+
// Read-only getters on a constructed response; the original's values are
|
|
205
|
+
// what the caller would have seen.
|
|
206
|
+
Object.defineProperties(wrapped, {
|
|
207
|
+
url: { value: response.url },
|
|
208
|
+
redirected: { value: response.redirected },
|
|
209
|
+
type: { value: response.type },
|
|
210
|
+
});
|
|
211
|
+
return wrapped;
|
|
212
|
+
}
|
|
213
|
+
/** The call, as tags on its outbound span - what the waterfall shows. */
|
|
214
|
+
function spanTags(call, usage, extra) {
|
|
215
|
+
return {
|
|
216
|
+
"llm.provider": call.provider,
|
|
217
|
+
// A path-borne Bedrock model id can run long; tags are not the place.
|
|
218
|
+
...(usage.model ? { "llm.model": usage.model.slice(0, 128) } : {}),
|
|
219
|
+
...(usage.inputTokens !== undefined
|
|
220
|
+
? { "llm.input_tokens": usage.inputTokens }
|
|
221
|
+
: {}),
|
|
222
|
+
...(usage.outputTokens !== undefined
|
|
223
|
+
? { "llm.output_tokens": usage.outputTokens }
|
|
224
|
+
: {}),
|
|
225
|
+
...(usage.cachedInputTokens !== undefined
|
|
226
|
+
? { "llm.cached_input_tokens": usage.cachedInputTokens }
|
|
227
|
+
: {}),
|
|
228
|
+
...(extra.stream ? { "llm.stream": true } : {}),
|
|
229
|
+
...(extra.timeToFirstToken !== undefined
|
|
230
|
+
? { "llm.time_to_first_token_ms": extra.timeToFirstToken }
|
|
231
|
+
: {}),
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
function round(value) {
|
|
235
|
+
return Math.round(value * 100) / 100;
|
|
236
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model providers the agent recognises by host, and how to read which model a
|
|
3
|
+
* call asked for before its response says.
|
|
4
|
+
*
|
|
5
|
+
* Recognised by host rather than by SDK: the official clients, the Vercel AI
|
|
6
|
+
* SDK, LangChain and a hand-written `fetch` all end in the same request to the
|
|
7
|
+
* same host, so a host list covers every client without knowing any of them.
|
|
8
|
+
*/
|
|
9
|
+
/** The provider a call to `host` goes to, or undefined when it is not one. */
|
|
10
|
+
export declare function llmProviderForHost(host: string, extraHosts?: ReadonlySet<string>): string | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* The model a JSON request body names, read from its first 64 KB.
|
|
13
|
+
*
|
|
14
|
+
* A pattern rather than `JSON.parse`: the body is the application's prompt,
|
|
15
|
+
* often far larger than the one field wanted, and every client puts `model`
|
|
16
|
+
* near the top. Bodies that are streams or forms are not read at all - reading
|
|
17
|
+
* them would consume what the request is about to send.
|
|
18
|
+
*/
|
|
19
|
+
export declare function modelFromRequestBody(body: unknown): string | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* The model a URL names, for the providers that put it in the path rather
|
|
22
|
+
* than the body: Gemini and Vertex (`.../models/gemini-2.5-flash:generateContent`)
|
|
23
|
+
* and Bedrock (`/model/anthropic.claude-sonnet-4-v1:0/converse`).
|
|
24
|
+
*/
|
|
25
|
+
export declare function modelFromUrlPath(pathname: string): string | undefined;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model providers the agent recognises by host, and how to read which model a
|
|
3
|
+
* call asked for before its response says.
|
|
4
|
+
*
|
|
5
|
+
* Recognised by host rather than by SDK: the official clients, the Vercel AI
|
|
6
|
+
* SDK, LangChain and a hand-written `fetch` all end in the same request to the
|
|
7
|
+
* same host, so a host list covers every client without knowing any of them.
|
|
8
|
+
*/
|
|
9
|
+
/** Exact hosts, each with the provider name the dashboard groups by. */
|
|
10
|
+
const EXACT_HOSTS = {
|
|
11
|
+
"api.openai.com": "openai",
|
|
12
|
+
"api.anthropic.com": "anthropic",
|
|
13
|
+
"generativelanguage.googleapis.com": "google",
|
|
14
|
+
"api.mistral.ai": "mistral",
|
|
15
|
+
"api.groq.com": "groq",
|
|
16
|
+
"openrouter.ai": "openrouter",
|
|
17
|
+
"api.together.xyz": "together",
|
|
18
|
+
"api.deepseek.com": "deepseek",
|
|
19
|
+
"api.x.ai": "xai",
|
|
20
|
+
"api.cohere.ai": "cohere",
|
|
21
|
+
"api.cohere.com": "cohere",
|
|
22
|
+
"api.perplexity.ai": "perplexity",
|
|
23
|
+
};
|
|
24
|
+
/** Hosts that carry a tenant or a region in a subdomain. */
|
|
25
|
+
const HOST_PATTERNS = [
|
|
26
|
+
[/^[a-z0-9-]+\.openai\.azure\.com$/, "azure-openai"],
|
|
27
|
+
[/^[a-z0-9-]+\.services\.ai\.azure\.com$/, "azure-openai"],
|
|
28
|
+
[/^[a-z0-9-]+-aiplatform\.googleapis\.com$/, "vertex"],
|
|
29
|
+
[/^bedrock-runtime\.[a-z0-9-]+\.amazonaws\.com$/, "bedrock"],
|
|
30
|
+
];
|
|
31
|
+
/** The provider a call to `host` goes to, or undefined when it is not one. */
|
|
32
|
+
export function llmProviderForHost(host, extraHosts = new Set()) {
|
|
33
|
+
const normalized = host.toLowerCase();
|
|
34
|
+
const hostname = normalized.replace(/:\d+$/, "");
|
|
35
|
+
const exact = EXACT_HOSTS[hostname];
|
|
36
|
+
if (exact) {
|
|
37
|
+
return exact;
|
|
38
|
+
}
|
|
39
|
+
for (const [pattern, provider] of HOST_PATTERNS) {
|
|
40
|
+
if (pattern.test(hostname)) {
|
|
41
|
+
return provider;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
if (extraHosts.has(normalized) || extraHosts.has(hostname)) {
|
|
45
|
+
return "custom";
|
|
46
|
+
}
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
/** Most of a request body read for its `model` field. Prompts can be megabytes. */
|
|
50
|
+
const MODEL_SCAN_BYTES = 64 * 1024;
|
|
51
|
+
const MODEL_FIELD = /"model"\s*:\s*"([^"\\]{1,128})"/;
|
|
52
|
+
/**
|
|
53
|
+
* The model a JSON request body names, read from its first 64 KB.
|
|
54
|
+
*
|
|
55
|
+
* A pattern rather than `JSON.parse`: the body is the application's prompt,
|
|
56
|
+
* often far larger than the one field wanted, and every client puts `model`
|
|
57
|
+
* near the top. Bodies that are streams or forms are not read at all - reading
|
|
58
|
+
* them would consume what the request is about to send.
|
|
59
|
+
*/
|
|
60
|
+
export function modelFromRequestBody(body) {
|
|
61
|
+
let text;
|
|
62
|
+
if (typeof body === "string") {
|
|
63
|
+
text = body.slice(0, MODEL_SCAN_BYTES);
|
|
64
|
+
}
|
|
65
|
+
else if (body instanceof Uint8Array) {
|
|
66
|
+
text = new TextDecoder().decode(body.subarray(0, MODEL_SCAN_BYTES));
|
|
67
|
+
}
|
|
68
|
+
else if (body instanceof ArrayBuffer) {
|
|
69
|
+
text = new TextDecoder().decode(new Uint8Array(body, 0, Math.min(body.byteLength, MODEL_SCAN_BYTES)));
|
|
70
|
+
}
|
|
71
|
+
return text ? MODEL_FIELD.exec(text)?.[1] : undefined;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The model a URL names, for the providers that put it in the path rather
|
|
75
|
+
* than the body: Gemini and Vertex (`.../models/gemini-2.5-flash:generateContent`)
|
|
76
|
+
* and Bedrock (`/model/anthropic.claude-sonnet-4-v1:0/converse`).
|
|
77
|
+
*/
|
|
78
|
+
export function modelFromUrlPath(pathname) {
|
|
79
|
+
const google = /\/models\/([^/:]+):/.exec(pathname);
|
|
80
|
+
if (google) {
|
|
81
|
+
return safeDecode(google[1]);
|
|
82
|
+
}
|
|
83
|
+
const bedrock = /\/model\/([^/]+)\/(?:invoke|converse)/.exec(pathname);
|
|
84
|
+
if (bedrock) {
|
|
85
|
+
return safeDecode(bedrock[1]);
|
|
86
|
+
}
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
function safeDecode(value) {
|
|
90
|
+
try {
|
|
91
|
+
return decodeURIComponent(value);
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading token usage out of a model provider's response - a JSON body, or
|
|
3
|
+
* the events of a server-sent stream - without ever keeping its text.
|
|
4
|
+
*/
|
|
5
|
+
/** What one call consumed, as far as the response said. */
|
|
6
|
+
export interface LlmUsage {
|
|
7
|
+
/** The model that answered - more precise than the one asked for. */
|
|
8
|
+
model?: string;
|
|
9
|
+
/** Every input token, cached ones included. */
|
|
10
|
+
inputTokens?: number;
|
|
11
|
+
outputTokens?: number;
|
|
12
|
+
/** The part of `inputTokens` served from the provider's prompt cache. */
|
|
13
|
+
cachedInputTokens?: number;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* One usage object, in whichever provider's spelling, as input, output and
|
|
17
|
+
* cached input.
|
|
18
|
+
*
|
|
19
|
+
* Input means every input token. OpenAI already counts cached tokens inside
|
|
20
|
+
* `prompt_tokens`; Anthropic reports cache reads and writes beside
|
|
21
|
+
* `input_tokens`, so they are added in - otherwise its cached calls would
|
|
22
|
+
* look nearly free of input.
|
|
23
|
+
*/
|
|
24
|
+
export declare function normalizeUsage(usage: unknown): LlmUsage;
|
|
25
|
+
/** Later readings win, field by field - a stream reports in pieces. */
|
|
26
|
+
export declare function mergeUsage(into: LlmUsage, next: LlmUsage): LlmUsage;
|
|
27
|
+
/**
|
|
28
|
+
* The usage in one parsed JSON document: a whole response body, or one event
|
|
29
|
+
* of a stream.
|
|
30
|
+
*/
|
|
31
|
+
export declare function usageFromDocument(document: unknown): LlmUsage;
|
|
32
|
+
/**
|
|
33
|
+
* Reads a JSON response as it passes through, keeping at most 2 MB.
|
|
34
|
+
*
|
|
35
|
+
* A larger body - a long completion, a batch of embeddings - is not kept: its
|
|
36
|
+
* first and last 32 KB are, and the usage is matched out of those. Every
|
|
37
|
+
* provider writes `usage` after the content and `model` before it.
|
|
38
|
+
*/
|
|
39
|
+
export declare class JsonUsageReader {
|
|
40
|
+
private readonly chunks;
|
|
41
|
+
private size;
|
|
42
|
+
private head;
|
|
43
|
+
private tail;
|
|
44
|
+
push(chunk: Uint8Array): void;
|
|
45
|
+
finish(): LlmUsage;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Reads a server-sent event stream as it passes through, one line at a time.
|
|
49
|
+
*
|
|
50
|
+
* Only `data:` lines that can carry usage or a model are parsed - the first
|
|
51
|
+
* event, and any that mention `usage` - so a long stream of text deltas costs
|
|
52
|
+
* a substring search per line rather than a parse.
|
|
53
|
+
*/
|
|
54
|
+
export declare class SseUsageReader {
|
|
55
|
+
private readonly now;
|
|
56
|
+
private readonly decoder;
|
|
57
|
+
private pending;
|
|
58
|
+
private skipping;
|
|
59
|
+
private usage;
|
|
60
|
+
private sawEvent;
|
|
61
|
+
/** When the first content event arrived, for time to first token. */
|
|
62
|
+
firstEventAt: number | undefined;
|
|
63
|
+
constructor(now?: () => number);
|
|
64
|
+
push(chunk: Uint8Array): void;
|
|
65
|
+
finish(): LlmUsage;
|
|
66
|
+
private line;
|
|
67
|
+
}
|