@senselab-ai/amfs 0.3.2 → 0.4.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.
- package/dist/adapters/http.d.ts +185 -6
- package/dist/adapters/http.js +315 -12
- package/dist/index.d.ts +10 -4
- package/dist/index.js +6 -3
- package/dist/instrument/anthropic.d.ts +15 -0
- package/dist/instrument/anthropic.js +53 -0
- package/dist/instrument/common.d.ts +47 -0
- package/dist/instrument/common.js +179 -0
- package/dist/instrument/index.d.ts +3 -0
- package/dist/instrument/index.js +2 -0
- package/dist/instrument/openai.d.ts +28 -0
- package/dist/instrument/openai.js +88 -0
- package/dist/memory.d.ts +263 -0
- package/dist/memory.js +468 -32
- package/dist/models.d.ts +14 -0
- package/dist/models.js +15 -0
- package/dist/replay.d.ts +228 -0
- package/dist/replay.js +514 -0
- package/dist/session.d.ts +69 -0
- package/dist/session.js +139 -0
- package/package.json +10 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,17 +1,23 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @senselab-ai/amfs — Agent Memory File System TypeScript SDK
|
|
3
3
|
*/
|
|
4
|
-
export { AgentMemory, MemoryScope } from "./memory.js";
|
|
4
|
+
export { AgentMemory, MemoryScope, API_KEY_ENV, BRANCH_ENV, HTTP_URL_ENV, MEMORY_BRANCH_ATTRIBUTE, } from "./memory.js";
|
|
5
5
|
export type { AgentMemoryOptions, SearchOptions, MemoryStats } from "./memory.js";
|
|
6
6
|
export type { AmfsAdapter, WatchHandle } from "./adapter.js";
|
|
7
7
|
export { createWatchHandle } from "./adapter.js";
|
|
8
8
|
export { InMemoryAdapter } from "./adapters/filesystem.js";
|
|
9
|
-
export { HttpAdapter } from "./adapters/http.js";
|
|
10
|
-
export type { HttpAdapterOptions, DecisionTrace, DecisionTraceSummary } from "./adapters/http.js";
|
|
9
|
+
export { AGENT_ID_HEADER, HttpAdapter, SESSION_HEADER, toDecisionTrace, toDecisionTracePage, } from "./adapters/http.js";
|
|
10
|
+
export type { HttpAdapterOptions, DecisionTrace, DecisionTraceSummary, DecisionTracePage, ListTracesOptions, ToolCall, SessionMetadata, } from "./adapters/http.js";
|
|
11
|
+
export { validateSessionAttributes, SESSION_ATTRIBUTES_MAX_KEYS, SDK_STAMPED_ATTRIBUTES, SESSION_ATTRIBUTE_KEY_MAX_LEN, SESSION_ATTRIBUTE_VALUE_MAX_LEN, } from "./session.js";
|
|
12
|
+
export type { AttributeValue, SessionAttributes, RecordLlmCallInput, LlmCallRecord, } from "./session.js";
|
|
13
|
+
export { instrumentOpenAI, instrumentAnthropic } from "./instrument/index.js";
|
|
14
|
+
export type { LlmCallSink } from "./instrument/index.js";
|
|
11
15
|
export { CausalTagger, CoWEngine } from "./engine.js";
|
|
12
16
|
export { ReadTracker } from "./tracker.js";
|
|
13
17
|
export type { ExternalContext } from "./tracker.js";
|
|
14
18
|
export { OutcomeBackPropagator } from "./outcome.js";
|
|
19
|
+
export { ReplayReceiver, ReplayError, SignatureError, PayloadError, parseReplayRequest, signReplayBody, verifyReplaySignature, replayAttributes, replayOutcomeRef, createFetchHandler, commitAttributes, serveReplay, CASE_ID_ATTRIBUTE, EVENT_PING, EVENT_REPLAY_REQUESTED, SIGNATURE_HEADER, EVENT_HEADER, DELIVERY_HEADER, } from "./replay.js";
|
|
20
|
+
export type { ReplayRequest, ReplayResult, ReplayAnswer, ReplayMemory, ReplayReceiverOptions, ReplayResponse, HeaderBag, } from "./replay.js";
|
|
15
21
|
export { defaultConfig } from "./config.js";
|
|
16
|
-
export { OutcomeType, OUTCOME_MULTIPLIERS, } from "./models.js";
|
|
22
|
+
export { MemoryType, OutcomeType, OUTCOME_MULTIPLIERS, } from "./models.js";
|
|
17
23
|
export type { MemoryEntry, OutcomeRecord, Provenance, ArtifactRef, AMFSConfig, LayerConfig, RecallConfig, ScopeInfo, ScoredEntry, } from "./models.js";
|
package/dist/index.js
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @senselab-ai/amfs — Agent Memory File System TypeScript SDK
|
|
3
3
|
*/
|
|
4
|
-
export { AgentMemory, MemoryScope } from "./memory.js";
|
|
4
|
+
export { AgentMemory, MemoryScope, API_KEY_ENV, BRANCH_ENV, HTTP_URL_ENV, MEMORY_BRANCH_ATTRIBUTE, } from "./memory.js";
|
|
5
5
|
export { createWatchHandle } from "./adapter.js";
|
|
6
6
|
export { InMemoryAdapter } from "./adapters/filesystem.js";
|
|
7
|
-
export { HttpAdapter } from "./adapters/http.js";
|
|
7
|
+
export { AGENT_ID_HEADER, HttpAdapter, SESSION_HEADER, toDecisionTrace, toDecisionTracePage, } from "./adapters/http.js";
|
|
8
|
+
export { validateSessionAttributes, SESSION_ATTRIBUTES_MAX_KEYS, SDK_STAMPED_ATTRIBUTES, SESSION_ATTRIBUTE_KEY_MAX_LEN, SESSION_ATTRIBUTE_VALUE_MAX_LEN, } from "./session.js";
|
|
9
|
+
export { instrumentOpenAI, instrumentAnthropic } from "./instrument/index.js";
|
|
8
10
|
export { CausalTagger, CoWEngine } from "./engine.js";
|
|
9
11
|
export { ReadTracker } from "./tracker.js";
|
|
10
12
|
export { OutcomeBackPropagator } from "./outcome.js";
|
|
13
|
+
export { ReplayReceiver, ReplayError, SignatureError, PayloadError, parseReplayRequest, signReplayBody, verifyReplaySignature, replayAttributes, replayOutcomeRef, createFetchHandler, commitAttributes, serveReplay, CASE_ID_ATTRIBUTE, EVENT_PING, EVENT_REPLAY_REQUESTED, SIGNATURE_HEADER, EVENT_HEADER, DELIVERY_HEADER, } from "./replay.js";
|
|
11
14
|
export { defaultConfig } from "./config.js";
|
|
12
|
-
export { OutcomeType, OUTCOME_MULTIPLIERS, } from "./models.js";
|
|
15
|
+
export { MemoryType, OutcomeType, OUTCOME_MULTIPLIERS, } from "./models.js";
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `instrumentAnthropic(client, memory)` — every `messages.create` on the
|
|
3
|
+
* `@anthropic-ai/sdk` client is recorded with `memory.recordLlmCall`.
|
|
4
|
+
*
|
|
5
|
+
* Streaming calls (`stream: true`) are recorded when the stream ends: input
|
|
6
|
+
* tokens come from `message_start`, output tokens from the final
|
|
7
|
+
* `message_delta`. The `messages.stream()` helper is not patched; iterate
|
|
8
|
+
* `create({ stream: true })` or call `memory.recordLlmCall` by hand.
|
|
9
|
+
* `@anthropic-ai/sdk` is an optional peer and is not imported here.
|
|
10
|
+
*/
|
|
11
|
+
import type { Extractor, LlmCallSink } from "./common.js";
|
|
12
|
+
export declare const extractMessage: Extractor;
|
|
13
|
+
export declare const extractMessageEvent: Extractor;
|
|
14
|
+
/** Instrument an Anthropic client in place and return it. Idempotent. */
|
|
15
|
+
export declare function instrumentAnthropic<C>(client: C, memory: LlmCallSink): C;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `instrumentAnthropic(client, memory)` — every `messages.create` on the
|
|
3
|
+
* `@anthropic-ai/sdk` client is recorded with `memory.recordLlmCall`.
|
|
4
|
+
*
|
|
5
|
+
* Streaming calls (`stream: true`) are recorded when the stream ends: input
|
|
6
|
+
* tokens come from `message_start`, output tokens from the final
|
|
7
|
+
* `message_delta`. The `messages.stream()` helper is not patched; iterate
|
|
8
|
+
* `create({ stream: true })` or call `memory.recordLlmCall` by hand.
|
|
9
|
+
* `@anthropic-ai/sdk` is an optional peer and is not imported here.
|
|
10
|
+
*/
|
|
11
|
+
import { asInt, get, isInstrumented, markInstrumented, patchMethod, resolve } from "./common.js";
|
|
12
|
+
const PROVIDER = "anthropic";
|
|
13
|
+
function readUsage(u, usage, outputOnly = false) {
|
|
14
|
+
if (!u)
|
|
15
|
+
return;
|
|
16
|
+
if (!outputOnly) {
|
|
17
|
+
const inTok = asInt(get(u, "input_tokens"));
|
|
18
|
+
if (inTok !== undefined)
|
|
19
|
+
usage.inputTokens = inTok;
|
|
20
|
+
}
|
|
21
|
+
const outTok = asInt(get(u, "output_tokens"));
|
|
22
|
+
if (outTok !== undefined)
|
|
23
|
+
usage.outputTokens = outTok;
|
|
24
|
+
}
|
|
25
|
+
export const extractMessage = (message, usage) => {
|
|
26
|
+
const model = get(message, "model");
|
|
27
|
+
if (typeof model === "string" && model)
|
|
28
|
+
usage.model = model;
|
|
29
|
+
readUsage(get(message, "usage"), usage);
|
|
30
|
+
};
|
|
31
|
+
export const extractMessageEvent = (event, usage) => {
|
|
32
|
+
const type = String(get(event, "type") ?? "");
|
|
33
|
+
if (type === "message_start")
|
|
34
|
+
extractMessage(get(event, "message"), usage);
|
|
35
|
+
else if (type === "message_delta")
|
|
36
|
+
readUsage(get(event, "usage"), usage, true);
|
|
37
|
+
};
|
|
38
|
+
/** Instrument an Anthropic client in place and return it. Idempotent. */
|
|
39
|
+
export function instrumentAnthropic(client, memory) {
|
|
40
|
+
if (isInstrumented(client))
|
|
41
|
+
return client;
|
|
42
|
+
const messages = resolve(client, ["messages"]);
|
|
43
|
+
if (messages) {
|
|
44
|
+
patchMethod(messages, "create", {
|
|
45
|
+
provider: PROVIDER,
|
|
46
|
+
sink: memory,
|
|
47
|
+
extract: extractMessage,
|
|
48
|
+
onChunk: extractMessageEvent,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
markInstrumented(client);
|
|
52
|
+
return client;
|
|
53
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared machinery for the provider instrumentations.
|
|
3
|
+
*
|
|
4
|
+
* Each `instrument*` function replaces a client method on the *instance* with a
|
|
5
|
+
* wrapper that times the call, reads token usage off the response (or, for a
|
|
6
|
+
* stream, accumulates it while the caller iterates and records when the stream
|
|
7
|
+
* ends) and hands the result to `memory.recordLlmCall`. The wrapped call is
|
|
8
|
+
* never altered: an instrumentation failure is logged and swallowed, an error
|
|
9
|
+
* from the provider is recorded as a failed call and re-thrown unchanged.
|
|
10
|
+
*
|
|
11
|
+
* Responses are read by duck typing, so neither `openai` nor `@anthropic-ai/sdk`
|
|
12
|
+
* is imported — they are optional peers — and tests drive the wrappers with
|
|
13
|
+
* plain objects.
|
|
14
|
+
*/
|
|
15
|
+
import type { RecordLlmCallInput } from "../session.js";
|
|
16
|
+
/** The one method of `AgentMemory` the instrumentations need. */
|
|
17
|
+
export interface LlmCallSink {
|
|
18
|
+
recordLlmCall(call: RecordLlmCallInput, startedAt?: Date): unknown;
|
|
19
|
+
}
|
|
20
|
+
export interface Usage {
|
|
21
|
+
model?: string;
|
|
22
|
+
inputTokens?: number;
|
|
23
|
+
outputTokens?: number;
|
|
24
|
+
}
|
|
25
|
+
export type Extractor = (response: unknown, usage: Usage) => void;
|
|
26
|
+
export declare function isInstrumented(target: unknown): boolean;
|
|
27
|
+
export declare function markInstrumented(target: unknown): void;
|
|
28
|
+
export declare function get(obj: unknown, key: string): unknown;
|
|
29
|
+
export declare function asInt(value: unknown): number | undefined;
|
|
30
|
+
export declare function resolve(target: unknown, path: string[]): unknown;
|
|
31
|
+
export interface PatchOptions {
|
|
32
|
+
provider: string;
|
|
33
|
+
sink: LlmCallSink;
|
|
34
|
+
/** Reads usage from a complete response. */
|
|
35
|
+
extract: Extractor;
|
|
36
|
+
/** Reads usage from one stream chunk, accumulating into the usage. */
|
|
37
|
+
onChunk: Extractor;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Replace `owner[method]` with an instrumented wrapper. Returns whether anything
|
|
41
|
+
* was patched (`false` when the method is missing or already wrapped).
|
|
42
|
+
*
|
|
43
|
+
* The provider SDKs return a promise-like (`APIPromise`) from `create`; the
|
|
44
|
+
* wrapper awaits it, so callers always get a plain `Promise`. `stream: true`
|
|
45
|
+
* calls resolve to an async iterable, which is proxied.
|
|
46
|
+
*/
|
|
47
|
+
export declare function patchMethod(owner: unknown, method: string, options: PatchOptions): boolean;
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared machinery for the provider instrumentations.
|
|
3
|
+
*
|
|
4
|
+
* Each `instrument*` function replaces a client method on the *instance* with a
|
|
5
|
+
* wrapper that times the call, reads token usage off the response (or, for a
|
|
6
|
+
* stream, accumulates it while the caller iterates and records when the stream
|
|
7
|
+
* ends) and hands the result to `memory.recordLlmCall`. The wrapped call is
|
|
8
|
+
* never altered: an instrumentation failure is logged and swallowed, an error
|
|
9
|
+
* from the provider is recorded as a failed call and re-thrown unchanged.
|
|
10
|
+
*
|
|
11
|
+
* Responses are read by duck typing, so neither `openai` nor `@anthropic-ai/sdk`
|
|
12
|
+
* is imported — they are optional peers — and tests drive the wrappers with
|
|
13
|
+
* plain objects.
|
|
14
|
+
*/
|
|
15
|
+
const FLAG = "__amfsInstrumented";
|
|
16
|
+
export function isInstrumented(target) {
|
|
17
|
+
return Boolean(target?.[FLAG]);
|
|
18
|
+
}
|
|
19
|
+
export function markInstrumented(target) {
|
|
20
|
+
try {
|
|
21
|
+
Object.defineProperty(target, FLAG, { value: true, enumerable: false, configurable: true });
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
// frozen or proxy — nothing to do
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export function get(obj, key) {
|
|
28
|
+
if (obj === null || obj === undefined)
|
|
29
|
+
return undefined;
|
|
30
|
+
return obj[key];
|
|
31
|
+
}
|
|
32
|
+
export function asInt(value) {
|
|
33
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
34
|
+
return undefined;
|
|
35
|
+
return Math.trunc(value);
|
|
36
|
+
}
|
|
37
|
+
export function resolve(target, path) {
|
|
38
|
+
let obj = target;
|
|
39
|
+
for (const hop of path) {
|
|
40
|
+
obj = get(obj, hop);
|
|
41
|
+
if (obj === null || obj === undefined)
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
return obj;
|
|
45
|
+
}
|
|
46
|
+
function isAsyncIterable(value) {
|
|
47
|
+
return (value !== null &&
|
|
48
|
+
typeof value === "object" &&
|
|
49
|
+
typeof value[Symbol.asyncIterator] === "function");
|
|
50
|
+
}
|
|
51
|
+
function warn(message, err) {
|
|
52
|
+
try {
|
|
53
|
+
console.warn(`[amfs] ${message}`, err);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
// no console — stay silent
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
class Call {
|
|
60
|
+
sink;
|
|
61
|
+
provider;
|
|
62
|
+
requestedModel;
|
|
63
|
+
startedAt = new Date();
|
|
64
|
+
t0 = performance.now();
|
|
65
|
+
done = false;
|
|
66
|
+
constructor(sink, provider, requestedModel) {
|
|
67
|
+
this.sink = sink;
|
|
68
|
+
this.provider = provider;
|
|
69
|
+
this.requestedModel = requestedModel;
|
|
70
|
+
}
|
|
71
|
+
record(usage, error) {
|
|
72
|
+
if (this.done)
|
|
73
|
+
return;
|
|
74
|
+
this.done = true;
|
|
75
|
+
const latencyMs = performance.now() - this.t0;
|
|
76
|
+
try {
|
|
77
|
+
const model = usage.model || this.requestedModel || "";
|
|
78
|
+
if (!model)
|
|
79
|
+
return; // nothing to attribute the call to
|
|
80
|
+
this.sink.recordLlmCall({
|
|
81
|
+
model,
|
|
82
|
+
provider: this.provider,
|
|
83
|
+
inputTokens: usage.inputTokens ?? 0,
|
|
84
|
+
outputTokens: usage.outputTokens ?? 0,
|
|
85
|
+
latencyMs,
|
|
86
|
+
...(error !== undefined ? { error: String(error) } : {}),
|
|
87
|
+
}, this.startedAt);
|
|
88
|
+
}
|
|
89
|
+
catch (err) {
|
|
90
|
+
warn(`${this.provider} instrumentation: could not record call`, err);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Wrap an async iterable so its chunks are observed and the call is recorded
|
|
96
|
+
* once the stream is exhausted, breaks, or is returned early. Every other
|
|
97
|
+
* property (e.g. `controller`, `finalMessage()`) is forwarded to the original.
|
|
98
|
+
*/
|
|
99
|
+
function proxyStream(inner, call, onChunk) {
|
|
100
|
+
const usage = {};
|
|
101
|
+
const iterate = async function* () {
|
|
102
|
+
try {
|
|
103
|
+
for await (const chunk of inner) {
|
|
104
|
+
try {
|
|
105
|
+
onChunk(chunk, usage);
|
|
106
|
+
}
|
|
107
|
+
catch (err) {
|
|
108
|
+
warn("stream chunk extraction failed", err);
|
|
109
|
+
}
|
|
110
|
+
yield chunk;
|
|
111
|
+
}
|
|
112
|
+
call.record(usage);
|
|
113
|
+
}
|
|
114
|
+
catch (err) {
|
|
115
|
+
call.record(usage, err);
|
|
116
|
+
throw err;
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
call.record(usage); // early `return()` / `break` lands here
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
return new Proxy(inner, {
|
|
123
|
+
get(target, prop, receiver) {
|
|
124
|
+
if (prop === Symbol.asyncIterator)
|
|
125
|
+
return () => iterate();
|
|
126
|
+
const value = Reflect.get(target, prop, receiver);
|
|
127
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Replace `owner[method]` with an instrumented wrapper. Returns whether anything
|
|
133
|
+
* was patched (`false` when the method is missing or already wrapped).
|
|
134
|
+
*
|
|
135
|
+
* The provider SDKs return a promise-like (`APIPromise`) from `create`; the
|
|
136
|
+
* wrapper awaits it, so callers always get a plain `Promise`. `stream: true`
|
|
137
|
+
* calls resolve to an async iterable, which is proxied.
|
|
138
|
+
*/
|
|
139
|
+
export function patchMethod(owner, method, options) {
|
|
140
|
+
if (owner === null || typeof owner !== "object")
|
|
141
|
+
return false;
|
|
142
|
+
const holder = owner;
|
|
143
|
+
const original = holder[method];
|
|
144
|
+
if (typeof original !== "function" || isInstrumented(original))
|
|
145
|
+
return false;
|
|
146
|
+
const wrapper = async function (...args) {
|
|
147
|
+
const params = (args[0] ?? {});
|
|
148
|
+
const call = new Call(options.sink, options.provider, typeof params.model === "string" ? params.model : undefined);
|
|
149
|
+
let result;
|
|
150
|
+
try {
|
|
151
|
+
result = await original.apply(this ?? owner, args);
|
|
152
|
+
}
|
|
153
|
+
catch (err) {
|
|
154
|
+
call.record({}, err);
|
|
155
|
+
throw err;
|
|
156
|
+
}
|
|
157
|
+
try {
|
|
158
|
+
if (params.stream === true && isAsyncIterable(result)) {
|
|
159
|
+
return proxyStream(result, call, options.onChunk);
|
|
160
|
+
}
|
|
161
|
+
const usage = {};
|
|
162
|
+
options.extract(result, usage);
|
|
163
|
+
call.record(usage);
|
|
164
|
+
}
|
|
165
|
+
catch (err) {
|
|
166
|
+
warn(`${options.provider} instrumentation failed; call unaffected`, err);
|
|
167
|
+
}
|
|
168
|
+
return result;
|
|
169
|
+
};
|
|
170
|
+
markInstrumented(wrapper);
|
|
171
|
+
try {
|
|
172
|
+
holder[method] = wrapper;
|
|
173
|
+
}
|
|
174
|
+
catch (err) {
|
|
175
|
+
warn(`${options.provider} instrumentation: cannot patch ${method}`, err);
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `instrumentOpenAI(client, memory)` — every `chat.completions.create` and
|
|
3
|
+
* `responses.create` on the `openai` package's client is recorded with
|
|
4
|
+
* `memory.recordLlmCall` (model, tokens, latency, provider).
|
|
5
|
+
*
|
|
6
|
+
* Streaming calls (`stream: true`) are recorded when the stream ends; the Chat
|
|
7
|
+
* Completions API only sends token counts on the final chunk when the request
|
|
8
|
+
* has `stream_options: { include_usage: true }` — without it the call is still
|
|
9
|
+
* recorded, with a model and latency but zero tokens. `openai` is an optional
|
|
10
|
+
* peer and is not imported here.
|
|
11
|
+
*/
|
|
12
|
+
import type { Extractor, LlmCallSink } from "./common.js";
|
|
13
|
+
export declare const extractChatCompletion: Extractor;
|
|
14
|
+
export declare const extractResponse: Extractor;
|
|
15
|
+
/** Responses API stream: the terminal event carries the whole response. */
|
|
16
|
+
export declare const extractResponseEvent: Extractor;
|
|
17
|
+
/**
|
|
18
|
+
* Instrument an OpenAI (or AzureOpenAI) client in place and return it. Every
|
|
19
|
+
* call made through it is recorded on `memory` until the next
|
|
20
|
+
* `commitOutcomeAsync`, which ships the calls with the outcome. Idempotent.
|
|
21
|
+
*
|
|
22
|
+
* ```ts
|
|
23
|
+
* const openai = instrumentOpenAI(new OpenAI(), memory);
|
|
24
|
+
* const r = await openai.chat.completions.create({ model: "gpt-4o-mini", messages });
|
|
25
|
+
* await memory.commitOutcomeAsync("deploy-42", OutcomeType.SUCCESS);
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
export declare function instrumentOpenAI<C>(client: C, memory: LlmCallSink): C;
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `instrumentOpenAI(client, memory)` — every `chat.completions.create` and
|
|
3
|
+
* `responses.create` on the `openai` package's client is recorded with
|
|
4
|
+
* `memory.recordLlmCall` (model, tokens, latency, provider).
|
|
5
|
+
*
|
|
6
|
+
* Streaming calls (`stream: true`) are recorded when the stream ends; the Chat
|
|
7
|
+
* Completions API only sends token counts on the final chunk when the request
|
|
8
|
+
* has `stream_options: { include_usage: true }` — without it the call is still
|
|
9
|
+
* recorded, with a model and latency but zero tokens. `openai` is an optional
|
|
10
|
+
* peer and is not imported here.
|
|
11
|
+
*/
|
|
12
|
+
import { asInt, get, isInstrumented, markInstrumented, patchMethod, resolve } from "./common.js";
|
|
13
|
+
const PROVIDER = "openai";
|
|
14
|
+
export const extractChatCompletion = (response, usage) => {
|
|
15
|
+
const model = get(response, "model");
|
|
16
|
+
if (typeof model === "string" && model)
|
|
17
|
+
usage.model = model;
|
|
18
|
+
const u = get(response, "usage");
|
|
19
|
+
if (u) {
|
|
20
|
+
const inTok = asInt(get(u, "prompt_tokens"));
|
|
21
|
+
const outTok = asInt(get(u, "completion_tokens"));
|
|
22
|
+
if (inTok !== undefined)
|
|
23
|
+
usage.inputTokens = inTok;
|
|
24
|
+
if (outTok !== undefined)
|
|
25
|
+
usage.outputTokens = outTok;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
export const extractResponse = (response, usage) => {
|
|
29
|
+
const model = get(response, "model");
|
|
30
|
+
if (typeof model === "string" && model)
|
|
31
|
+
usage.model = model;
|
|
32
|
+
const u = get(response, "usage");
|
|
33
|
+
if (u) {
|
|
34
|
+
const inTok = asInt(get(u, "input_tokens"));
|
|
35
|
+
const outTok = asInt(get(u, "output_tokens"));
|
|
36
|
+
if (inTok !== undefined)
|
|
37
|
+
usage.inputTokens = inTok;
|
|
38
|
+
if (outTok !== undefined)
|
|
39
|
+
usage.outputTokens = outTok;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
/** Responses API stream: the terminal event carries the whole response. */
|
|
43
|
+
export const extractResponseEvent = (event, usage) => {
|
|
44
|
+
const type = String(get(event, "type") ?? "");
|
|
45
|
+
if (type === "response.completed" || type === "response.incomplete" || type === "response.failed") {
|
|
46
|
+
extractResponse(get(event, "response"), usage);
|
|
47
|
+
}
|
|
48
|
+
else if (type === "response.created") {
|
|
49
|
+
const model = get(get(event, "response"), "model");
|
|
50
|
+
if (typeof model === "string" && model)
|
|
51
|
+
usage.model = model;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Instrument an OpenAI (or AzureOpenAI) client in place and return it. Every
|
|
56
|
+
* call made through it is recorded on `memory` until the next
|
|
57
|
+
* `commitOutcomeAsync`, which ships the calls with the outcome. Idempotent.
|
|
58
|
+
*
|
|
59
|
+
* ```ts
|
|
60
|
+
* const openai = instrumentOpenAI(new OpenAI(), memory);
|
|
61
|
+
* const r = await openai.chat.completions.create({ model: "gpt-4o-mini", messages });
|
|
62
|
+
* await memory.commitOutcomeAsync("deploy-42", OutcomeType.SUCCESS);
|
|
63
|
+
* ```
|
|
64
|
+
*/
|
|
65
|
+
export function instrumentOpenAI(client, memory) {
|
|
66
|
+
if (isInstrumented(client))
|
|
67
|
+
return client;
|
|
68
|
+
const completions = resolve(client, ["chat", "completions"]);
|
|
69
|
+
if (completions) {
|
|
70
|
+
patchMethod(completions, "create", {
|
|
71
|
+
provider: PROVIDER,
|
|
72
|
+
sink: memory,
|
|
73
|
+
extract: extractChatCompletion,
|
|
74
|
+
onChunk: extractChatCompletion,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
const responses = resolve(client, ["responses"]);
|
|
78
|
+
if (responses) {
|
|
79
|
+
patchMethod(responses, "create", {
|
|
80
|
+
provider: PROVIDER,
|
|
81
|
+
sink: memory,
|
|
82
|
+
extract: extractResponse,
|
|
83
|
+
onChunk: extractResponseEvent,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
markInstrumented(client);
|
|
87
|
+
return client;
|
|
88
|
+
}
|