@absolutejs/ai 0.0.5 → 0.0.7
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/ai/index.js +305 -20
- package/dist/ai/index.js.map +12 -10
- package/dist/ai/providers/anthropic.js +66 -5
- package/dist/ai/providers/anthropic.js.map +5 -4
- package/dist/ai/providers/gemini.js +88 -6
- package/dist/ai/providers/gemini.js.map +5 -4
- package/dist/ai/providers/ollama.js +68 -3
- package/dist/ai/providers/ollama.js.map +5 -4
- package/dist/ai/providers/openai.js +101 -5
- package/dist/ai/providers/openai.js.map +5 -4
- package/dist/ai/providers/openaiCompatible.js +106 -6
- package/dist/ai/providers/openaiCompatible.js.map +6 -5
- package/dist/ai/providers/openaiResponses.js +88 -4
- package/dist/ai/providers/openaiResponses.js.map +5 -4
- package/dist/src/ai/index.d.ts +2 -0
- package/dist/src/ai/providers/instrumentation.d.ts +2 -0
- package/dist/src/ai/providers/oauth2TokenSource.d.ts +29 -0
- package/dist/src/ai/providers/openai.d.ts +2 -1
- package/dist/src/ai/providers/openaiCompatible.d.ts +2 -1
- package/dist/src/ai/providers/openaiResponses.d.ts +2 -27
- package/dist/types/ai.d.ts +60 -5
- package/package.json +1 -1
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/ai/providers/ollama.ts"],
|
|
3
|
+
"sources": ["../src/ai/providers/instrumentation.ts", "../src/ai/providers/ollama.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import type {\n AIChunk,\n
|
|
5
|
+
"import type {\n AIChunk,\n AIProviderConfig,\n AIProviderStreamParams,\n AIUsage,\n} from \"../../../types/ai\";\n\nexport const instrumentAIProvider = (\n provider: AIProviderConfig,\n providerName?: string,\n): AIProviderConfig => ({\n stream: (params: AIProviderStreamParams) => {\n if (!params.onUsage && !params.onSpan) {\n return provider.stream(params);\n }\n return tapStream(provider.stream(params), params, providerName);\n },\n});\n\nasync function* tapStream(\n source: AsyncIterable<AIChunk>,\n params: AIProviderStreamParams,\n providerName?: string,\n): AsyncIterable<AIChunk> {\n const startedAt = Date.now();\n let lastUsage: AIUsage | undefined;\n try {\n for await (const chunk of source) {\n if (chunk.type === \"done\" && chunk.usage) {\n lastUsage = chunk.usage;\n }\n yield chunk;\n }\n } finally {\n if (lastUsage && params.onUsage) {\n try {\n params.onUsage({\n ...lastUsage,\n model: params.model,\n provider: providerName,\n });\n } catch {\n // operator-supplied callback errors must not affect stream consumers\n }\n }\n if (params.onSpan) {\n try {\n params.onSpan({\n durationMs: Date.now() - startedAt,\n model: params.model,\n provider: providerName,\n usage: lastUsage,\n });\n } catch {\n // same\n }\n }\n }\n}\n",
|
|
6
|
+
"import type {\n AIChunk,\n AIDoneChunk,\n AIProviderConfig,\n AIProviderStreamParams,\n AIProviderToolDefinition,\n} from \"../../../types/ai\";\nimport { instrumentAIProvider } from \"./instrumentation\";\n\ntype OllamaConfig = {\n baseUrl?: string;\n};\n\ntype OllamaMessage = {\n content: string;\n role: \"assistant\" | \"system\" | \"tool\" | \"user\";\n tool_calls?: Array<{\n function: { arguments: Record<string, unknown>; name: string };\n }>;\n};\n\nconst DEFAULT_BASE_URL = \"http://localhost:11434\";\nconst ZERO_TOKENS = 0;\n\nconst DONE_CHUNK: AIChunk = { type: \"done\" };\n\nconst mapToolDefinitions = (tools: AIProviderToolDefinition[]) =>\n tools.map((tool) => ({\n function: {\n description: tool.description,\n name: tool.name,\n parameters: tool.input_schema,\n },\n type: \"function\",\n }));\n\nconst convertMessage = (msg: AIProviderStreamParams[\"messages\"][number]) => {\n if (typeof msg.content === \"string\") {\n return [{ content: msg.content, role: msg.role }];\n }\n\n const results: OllamaMessage[] = [];\n const toolUseBlocks = msg.content.filter(\n (block) => block.type === \"tool_use\",\n );\n const toolResultBlocks = msg.content.filter(\n (block) => block.type === \"tool_result\",\n );\n\n if (toolUseBlocks.length > 0) {\n results.push({\n content: \"\",\n role: \"assistant\",\n tool_calls: toolUseBlocks.map((block) => ({\n function: {\n arguments:\n typeof block.input === \"object\" && block.input !== null\n ? { ...block.input }\n : {},\n name: block.name,\n },\n })),\n });\n }\n\n for (const block of toolResultBlocks) {\n results.push({\n content: typeof block.content === \"string\" ? block.content : \"\",\n role: \"tool\",\n });\n }\n\n return results;\n};\n\nconst buildRequestBody = (params: AIProviderStreamParams) => {\n const messages: OllamaMessage[] = params.messages.flatMap(convertMessage);\n\n if (params.systemPrompt) {\n messages.unshift({ content: params.systemPrompt, role: \"system\" });\n }\n\n const body: Record<string, unknown> = {\n messages,\n model: params.model,\n stream: true,\n };\n\n if (params.tools && params.tools.length > 0) {\n body.tools = mapToolDefinitions(params.tools);\n }\n\n const options: Record<string, unknown> = {};\n if (typeof params.temperature === \"number\") options.temperature = params.temperature;\n if (typeof params.topP === \"number\") options.top_p = params.topP;\n if (typeof params.maxTokens === \"number\") options.num_predict = params.maxTokens;\n if (params.stopSequences && params.stopSequences.length > 0) options.stop = params.stopSequences;\n if (typeof params.seed === \"number\") options.seed = params.seed;\n if (typeof params.frequencyPenalty === \"number\") options.frequency_penalty = params.frequencyPenalty;\n if (typeof params.presencePenalty === \"number\") options.presence_penalty = params.presencePenalty;\n if (Object.keys(options).length > 0) {\n body.options = options;\n }\n\n if (params.responseFormat?.type === \"json_object\") {\n body.format = \"json\";\n } else if (params.responseFormat?.type === \"json_schema\") {\n body.format = params.responseFormat.schema;\n }\n\n return body;\n};\n\nconst isRecord = (val: unknown): val is Record<string, unknown> =>\n val !== null && typeof val === \"object\" && !Array.isArray(val);\n\nconst tryParseJSON = (text: string) => {\n try {\n const result: unknown = JSON.parse(text);\n if (isRecord(result)) {\n return result;\n }\n\n return null;\n } catch {\n return null;\n }\n};\n\nconst buildDoneChunk = (parsed: Record<string, unknown>): AIDoneChunk => {\n const promptEvalCount =\n typeof parsed.prompt_eval_count === \"number\"\n ? parsed.prompt_eval_count\n : undefined;\n const evalCount =\n typeof parsed.eval_count === \"number\" ? parsed.eval_count : undefined;\n const totalDuration =\n typeof parsed.total_duration === \"number\"\n ? parsed.total_duration\n : undefined;\n\n const hasTokenCounts =\n promptEvalCount !== undefined || evalCount !== undefined;\n if (hasTokenCounts) {\n return {\n type: \"done\",\n usage: {\n inputTokens: promptEvalCount ?? ZERO_TOKENS,\n outputTokens: evalCount ?? ZERO_TOKENS,\n },\n };\n }\n\n if (totalDuration !== undefined) {\n return {\n type: \"done\",\n usage: { inputTokens: ZERO_TOKENS, outputTokens: ZERO_TOKENS },\n };\n }\n\n return { type: \"done\" };\n};\n\nconst buildTextChunk = (content: string): AIChunk => ({\n content,\n type: \"text\",\n});\n\nconst extractToolCalls = (message: Record<string, unknown>) => {\n const toolCalls = message.tool_calls;\n\n if (!Array.isArray(toolCalls) || toolCalls.length === 0) {\n return [];\n }\n\n return toolCalls\n .filter(isRecord)\n .filter((call) => isRecord(call.function))\n .map((call) => {\n const func = call.function;\n\n if (!isRecord(func)) {\n return {\n id: crypto.randomUUID(),\n input: {},\n name: \"\",\n type: \"tool_use\" as const,\n };\n }\n\n return {\n id: crypto.randomUUID(),\n input: func.arguments ?? {},\n name: typeof func.name === \"string\" ? func.name : \"\",\n type: \"tool_use\" as const,\n };\n });\n};\n\nconst extractChunks = (parsed: Record<string, unknown>) => {\n const { message } = parsed;\n\n if (!isRecord(message)) {\n return [];\n }\n\n const toolChunks = extractToolCalls(message);\n\n if (toolChunks.length > 0) {\n return toolChunks;\n }\n\n const { content } = message;\n\n if (typeof content !== \"string\" || !content) {\n return [];\n }\n\n return [buildTextChunk(content)];\n};\n\nconst processLine = (line: string) => {\n const trimmed = line.trim();\n\n if (!trimmed) {\n return [];\n }\n\n const parsed = tryParseJSON(trimmed);\n\n if (!parsed) {\n return [];\n }\n\n if (parsed.done === true) {\n return [buildDoneChunk(parsed)];\n }\n\n return extractChunks(parsed);\n};\n\nconst processBufferedLines = (lines: string[]) => lines.flatMap(processLine);\n\nconst readStreamChunks = async (\n reader: ReadableStreamDefaultReader<Uint8Array>,\n decoder: TextDecoder,\n buffer: string,\n signal?: AbortSignal,\n) => {\n const emptyChunks: AIChunk[] = [];\n\n if (signal?.aborted) {\n return {\n allChunks: emptyChunks,\n currentBuffer: buffer,\n finished: true,\n };\n }\n\n const result = await reader.read();\n const { done, value } = result;\n\n if (done) {\n return {\n allChunks: emptyChunks,\n currentBuffer: buffer,\n finished: true,\n };\n }\n\n const currentBuffer = buffer + decoder.decode(value, { stream: true });\n const lines = currentBuffer.split(\"\\n\");\n const remainder = lines.pop() ?? \"\";\n const allChunks = processBufferedLines(lines);\n const finished = allChunks.some((c) => c.type === \"done\");\n\n return { allChunks, currentBuffer: remainder, finished };\n};\n\nconst parseNDJSONStream = async function* (\n body: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n) {\n const reader = body.getReader();\n\n try {\n yield* parseNDJSONStreamInner(reader, signal);\n } finally {\n reader.releaseLock();\n }\n};\n\nconst parseNDJSONStreamInner = async function* (\n reader: ReadableStreamDefaultReader<Uint8Array>,\n signal?: AbortSignal,\n) {\n const decoder = new TextDecoder();\n let buffer = \"\";\n let done = false;\n\n while (!done) {\n // eslint-disable-next-line no-await-in-loop\n const result = await readStreamChunks(reader, decoder, buffer, signal);\n buffer = result.currentBuffer;\n done = result.finished;\n\n yield* result.allChunks;\n }\n\n yield DONE_CHUNK;\n};\n\nconst fetchAndStream = async function* (\n baseUrl: string,\n params: AIProviderStreamParams,\n) {\n const requestBody = buildRequestBody(params);\n\n const response = await fetch(`${baseUrl}/api/chat`, {\n body: JSON.stringify(requestBody),\n headers: { \"Content-Type\": \"application/json\" },\n method: \"POST\",\n signal: params.signal,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Ollama API error ${response.status}: ${errorText}`);\n }\n\n if (!response.body) {\n throw new Error(\"Ollama API returned no response body\");\n }\n\n yield* parseNDJSONStream(response.body, params.signal);\n};\n\nexport const ollama = (config: OllamaConfig = {}): AIProviderConfig => {\n const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;\n\n return instrumentAIProvider(\n {\n stream: (params: AIProviderStreamParams) =>\n fetchAndStream(baseUrl, params),\n },\n \"ollama\",\n );\n};\n"
|
|
6
7
|
],
|
|
7
|
-
"mappings": ";;
|
|
8
|
-
"debugId": "
|
|
8
|
+
"mappings": ";;AAOO,IAAM,uBAAuB,CAClC,UACA,kBACsB;AAAA,EACtB,QAAQ,CAAC,WAAmC;AAAA,IAC1C,IAAI,CAAC,OAAO,WAAW,CAAC,OAAO,QAAQ;AAAA,MACrC,OAAO,SAAS,OAAO,MAAM;AAAA,IAC/B;AAAA,IACA,OAAO,UAAU,SAAS,OAAO,MAAM,GAAG,QAAQ,YAAY;AAAA;AAElE;AAEA,gBAAgB,SAAS,CACvB,QACA,QACA,cACwB;AAAA,EACxB,MAAM,YAAY,KAAK,IAAI;AAAA,EAC3B,IAAI;AAAA,EACJ,IAAI;AAAA,IACF,iBAAiB,SAAS,QAAQ;AAAA,MAChC,IAAI,MAAM,SAAS,UAAU,MAAM,OAAO;AAAA,QACxC,YAAY,MAAM;AAAA,MACpB;AAAA,MACA,MAAM;AAAA,IACR;AAAA,YACA;AAAA,IACA,IAAI,aAAa,OAAO,SAAS;AAAA,MAC/B,IAAI;AAAA,QACF,OAAO,QAAQ;AAAA,aACV;AAAA,UACH,OAAO,OAAO;AAAA,UACd,UAAU;AAAA,QACZ,CAAC;AAAA,QACD,MAAM;AAAA,IAGV;AAAA,IACA,IAAI,OAAO,QAAQ;AAAA,MACjB,IAAI;AAAA,QACF,OAAO,OAAO;AAAA,UACZ,YAAY,KAAK,IAAI,IAAI;AAAA,UACzB,OAAO,OAAO;AAAA,UACd,UAAU;AAAA,UACV,OAAO;AAAA,QACT,CAAC;AAAA,QACD,MAAM;AAAA,IAGV;AAAA;AAAA;;;ACnCJ,IAAM,mBAAmB;AACzB,IAAM,cAAc;AAEpB,IAAM,aAAsB,EAAE,MAAM,OAAO;AAE3C,IAAM,qBAAqB,CAAC,UAC1B,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QAAQ,OAAO;AAAA,EACjB,CAAC;AAAA,EAED,IAAI,CAAC,SAAS,IAAI;AAAA,IAChB,MAAM,YAAY,MAAM,SAAS,KAAK;AAAA,IACtC,MAAM,IAAI,MAAM,oBAAoB,SAAS,WAAW,WAAW;AAAA,EACrE;AAAA,EAEA,IAAI,CAAC,SAAS,MAAM;AAAA,IAClB,MAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AAAA,EAEA,OAAO,kBAAkB,SAAS,MAAM,OAAO,MAAM;AAAA;AAGhD,IAAM,SAAS,CAAC,SAAuB,CAAC,MAAwB;AAAA,EACrE,MAAM,UAAU,OAAO,WAAW;AAAA,EAElC,OAAO,qBACL;AAAA,IACE,QAAQ,CAAC,WACP,eAAe,SAAS,MAAM;AAAA,EAClC,GACA,QACF;AAAA;",
|
|
9
|
+
"debugId": "B1BA0AA1295D475464756E2164756E21",
|
|
9
10
|
"names": []
|
|
10
11
|
}
|
|
@@ -1,5 +1,48 @@
|
|
|
1
1
|
// @bun
|
|
2
|
+
// src/ai/providers/instrumentation.ts
|
|
3
|
+
var instrumentAIProvider = (provider, providerName) => ({
|
|
4
|
+
stream: (params) => {
|
|
5
|
+
if (!params.onUsage && !params.onSpan) {
|
|
6
|
+
return provider.stream(params);
|
|
7
|
+
}
|
|
8
|
+
return tapStream(provider.stream(params), params, providerName);
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
async function* tapStream(source, params, providerName) {
|
|
12
|
+
const startedAt = Date.now();
|
|
13
|
+
let lastUsage;
|
|
14
|
+
try {
|
|
15
|
+
for await (const chunk of source) {
|
|
16
|
+
if (chunk.type === "done" && chunk.usage) {
|
|
17
|
+
lastUsage = chunk.usage;
|
|
18
|
+
}
|
|
19
|
+
yield chunk;
|
|
20
|
+
}
|
|
21
|
+
} finally {
|
|
22
|
+
if (lastUsage && params.onUsage) {
|
|
23
|
+
try {
|
|
24
|
+
params.onUsage({
|
|
25
|
+
...lastUsage,
|
|
26
|
+
model: params.model,
|
|
27
|
+
provider: providerName
|
|
28
|
+
});
|
|
29
|
+
} catch {}
|
|
30
|
+
}
|
|
31
|
+
if (params.onSpan) {
|
|
32
|
+
try {
|
|
33
|
+
params.onSpan({
|
|
34
|
+
durationMs: Date.now() - startedAt,
|
|
35
|
+
model: params.model,
|
|
36
|
+
provider: providerName,
|
|
37
|
+
usage: lastUsage
|
|
38
|
+
});
|
|
39
|
+
} catch {}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
2
44
|
// src/ai/providers/openai.ts
|
|
45
|
+
var h2IfHttps = (url) => url.startsWith("https://") ? { protocol: "http2" } : {};
|
|
3
46
|
var DEFAULT_BASE_URL = "https://api.openai.com";
|
|
4
47
|
var SSE_DATA_PREFIX_LENGTH = 6;
|
|
5
48
|
var DONE_SENTINEL = "[DONE]";
|
|
@@ -112,6 +155,45 @@ var buildRequestBody = (params) => {
|
|
|
112
155
|
};
|
|
113
156
|
if (params.tools && params.tools.length > 0) {
|
|
114
157
|
body.tools = mapToolDefinitions(params.tools);
|
|
158
|
+
if (params.toolChoice === "auto" || params.toolChoice === "none" || params.toolChoice === "required") {
|
|
159
|
+
body.tool_choice = params.toolChoice;
|
|
160
|
+
} else if (params.toolChoice && typeof params.toolChoice === "object") {
|
|
161
|
+
body.tool_choice = {
|
|
162
|
+
function: { name: params.toolChoice.name },
|
|
163
|
+
type: "function"
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
if (typeof params.parallelToolCalls === "boolean") {
|
|
167
|
+
body.parallel_tool_calls = params.parallelToolCalls;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (typeof params.temperature === "number")
|
|
171
|
+
body.temperature = params.temperature;
|
|
172
|
+
if (typeof params.topP === "number")
|
|
173
|
+
body.top_p = params.topP;
|
|
174
|
+
if (typeof params.maxTokens === "number")
|
|
175
|
+
body.max_tokens = params.maxTokens;
|
|
176
|
+
if (params.stopSequences && params.stopSequences.length > 0)
|
|
177
|
+
body.stop = params.stopSequences;
|
|
178
|
+
if (typeof params.seed === "number")
|
|
179
|
+
body.seed = params.seed;
|
|
180
|
+
if (typeof params.frequencyPenalty === "number")
|
|
181
|
+
body.frequency_penalty = params.frequencyPenalty;
|
|
182
|
+
if (typeof params.presencePenalty === "number")
|
|
183
|
+
body.presence_penalty = params.presencePenalty;
|
|
184
|
+
if (params.responseFormat) {
|
|
185
|
+
if (params.responseFormat.type === "text" || params.responseFormat.type === "json_object") {
|
|
186
|
+
body.response_format = { type: params.responseFormat.type };
|
|
187
|
+
} else if (params.responseFormat.type === "json_schema") {
|
|
188
|
+
body.response_format = {
|
|
189
|
+
json_schema: {
|
|
190
|
+
name: params.responseFormat.name,
|
|
191
|
+
schema: params.responseFormat.schema,
|
|
192
|
+
strict: params.responseFormat.strict ?? true
|
|
193
|
+
},
|
|
194
|
+
type: "json_schema"
|
|
195
|
+
};
|
|
196
|
+
}
|
|
115
197
|
}
|
|
116
198
|
return body;
|
|
117
199
|
};
|
|
@@ -287,7 +369,9 @@ var parseSSEStream = async function* (body, signal) {
|
|
|
287
369
|
}
|
|
288
370
|
};
|
|
289
371
|
var fetchOpenAIStream = async function* (baseUrl, apiKey, body, signal) {
|
|
290
|
-
const
|
|
372
|
+
const target = `${baseUrl}/v1/chat/completions`;
|
|
373
|
+
const response = await fetch(target, {
|
|
374
|
+
...h2IfHttps(target),
|
|
291
375
|
body: JSON.stringify(body),
|
|
292
376
|
headers: {
|
|
293
377
|
Authorization: `Bearer ${apiKey}`,
|
|
@@ -307,16 +391,28 @@ var fetchOpenAIStream = async function* (baseUrl, apiKey, body, signal) {
|
|
|
307
391
|
};
|
|
308
392
|
var openai = (config) => {
|
|
309
393
|
const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
|
|
310
|
-
|
|
394
|
+
if (!config.apiKey && !config.tokenSource) {
|
|
395
|
+
throw new Error("openai() requires either apiKey or tokenSource");
|
|
396
|
+
}
|
|
397
|
+
const resolveKey = async () => {
|
|
398
|
+
if (config.tokenSource) {
|
|
399
|
+
return await Promise.resolve(config.tokenSource());
|
|
400
|
+
}
|
|
401
|
+
return config.apiKey;
|
|
402
|
+
};
|
|
403
|
+
return instrumentAIProvider({
|
|
311
404
|
stream: (params) => {
|
|
312
405
|
const body = buildRequestBody(params);
|
|
313
|
-
return
|
|
406
|
+
return async function* () {
|
|
407
|
+
const apiKey = await resolveKey();
|
|
408
|
+
yield* fetchOpenAIStream(baseUrl, apiKey, body, params.signal);
|
|
409
|
+
}();
|
|
314
410
|
}
|
|
315
|
-
};
|
|
411
|
+
}, "openai");
|
|
316
412
|
};
|
|
317
413
|
export {
|
|
318
414
|
openai
|
|
319
415
|
};
|
|
320
416
|
|
|
321
|
-
//# debugId=
|
|
417
|
+
//# debugId=355EFC91257F586E64756E2164756E21
|
|
322
418
|
//# sourceMappingURL=openai.js.map
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/ai/providers/openai.ts"],
|
|
3
|
+
"sources": ["../src/ai/providers/instrumentation.ts", "../src/ai/providers/openai.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import type {\n AIProviderConfig,\n AIProviderContentBlock,\n AIProviderMessage,\n AIProviderStreamParams,\n AIProviderToolDefinition,\n AIUsage,\n} from \"../../../types/ai\";\n\ntype OpenAIConfig = {\n apiKey: string;\n baseUrl?: string;\n};\n\ntype OpenAIMessage = {\n content: string | Array<Record<string, unknown>> | null;\n role: \"user\" | \"assistant\" | \"system\" | \"tool\";\n tool_call_id?: string;\n tool_calls?: Array<{\n function: { arguments: string; name: string };\n id: string;\n type: \"function\";\n }>;\n};\n\ntype PendingToolCall = {\n arguments: string;\n id: string;\n name: string;\n};\n\ntype UsageRef = {\n current: AIUsage | undefined;\n};\n\ntype StreamState = {\n buffer: string;\n pendingToolCalls: Map<number, PendingToolCall>;\n usageRef: UsageRef;\n};\n\nconst DEFAULT_BASE_URL = \"https://api.openai.com\";\nconst SSE_DATA_PREFIX_LENGTH = 6;\nconst DONE_SENTINEL = \"[DONE]\";\nconst NOT_FOUND = -1;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isRecordArray = (\n value: unknown,\n): value is Array<Record<string, unknown>> =>\n Array.isArray(value) && value.length > 0 && isRecord(value[0]);\n\nconst hasArrayContent = (\n msg: AIProviderMessage,\n): msg is AIProviderMessage & { content: AIProviderContentBlock[] } =>\n typeof msg.content !== \"string\" && Array.isArray(msg.content);\n\nconst buildToolMessages = (blocks: AIProviderContentBlock[]) => {\n const toolUseBlocks = blocks.filter((block) => block.type === \"tool_use\");\n const toolResultBlocks = blocks.filter(\n (block) => block.type === \"tool_result\",\n );\n const messages: OpenAIMessage[] = [];\n\n if (toolUseBlocks.length > 0) {\n messages.push({\n content: null,\n role: \"assistant\",\n tool_calls: toolUseBlocks.map((block) => ({\n function: {\n arguments:\n typeof block.input === \"string\"\n ? block.input\n : JSON.stringify(block.input),\n name: block.name,\n },\n id: block.id,\n type: \"function\" as const,\n })),\n });\n }\n\n for (const result of toolResultBlocks) {\n messages.push({\n content: typeof result.content === \"string\" ? result.content : \"\",\n role: \"tool\",\n tool_call_id: result.tool_use_id,\n });\n }\n\n return messages;\n};\n\nconst processMessageAtIndex = (\n result: OpenAIMessage[],\n msg: AIProviderMessage,\n idx: number,\n) => {\n if (!hasArrayContent(msg)) {\n return;\n }\n\n const hasToolBlocks = msg.content.some(\n (block) => block.type === \"tool_use\" || block.type === \"tool_result\",\n );\n\n if (!hasToolBlocks) {\n return;\n }\n\n const toolMessages = buildToolMessages(msg.content);\n result.splice(idx, 1, ...toolMessages);\n};\n\nconst convertSingleMessage = (\n result: OpenAIMessage[],\n msg: AIProviderMessage | undefined,\n idx: number,\n) => {\n if (!msg) {\n return;\n }\n\n processMessageAtIndex(result, msg, idx);\n};\n\nconst convertToolResultMessages = (\n messages: OpenAIMessage[],\n params: AIProviderStreamParams,\n) => {\n const result = [...messages];\n\n for (let idx = 0; idx < params.messages.length; idx++) {\n convertSingleMessage(result, params.messages[idx], idx);\n }\n\n return result;\n};\n\nconst mapToolDefinitions = (tools: AIProviderToolDefinition[]) =>\n tools.map((tool) => ({\n function: {\n description: tool.description,\n name: tool.name,\n parameters: tool.input_schema,\n },\n type: \"function\",\n }));\n\nconst mapContentBlockToOpenAI = (block: AIProviderContentBlock) => {\n if (block.type === \"image\") {\n return {\n image_url: {\n url: `data:${block.source.media_type};base64,${block.source.data}`,\n },\n type: \"image_url\",\n };\n }\n\n if (block.type === \"document\") {\n return {\n file: {\n file_data: `data:${block.source.media_type};base64,${block.source.data}`,\n filename: block.name ?? \"document.pdf\",\n },\n type: \"file\",\n };\n }\n\n if (block.type === \"text\") {\n return { text: block.content, type: \"text\" };\n }\n\n return null;\n};\n\nconst mapOpenAIContent = (msg: AIProviderStreamParams[\"messages\"][number]) => {\n if (typeof msg.content === \"string\") {\n return msg.content;\n }\n\n const hasMedia = msg.content.some(\n (block) => block.type === \"image\" || block.type === \"document\",\n );\n\n if (!hasMedia) {\n return null;\n }\n\n return msg.content\n .map(mapContentBlockToOpenAI)\n .filter((mapped) => mapped !== null);\n};\n\nconst buildRequestBody = (params: AIProviderStreamParams) => {\n const messages = convertToolResultMessages(\n params.messages.map((msg) => ({\n content: mapOpenAIContent(msg),\n role: msg.role,\n })),\n params,\n );\n\n const body: Record<string, unknown> = {\n messages,\n model: params.model,\n stream: true,\n stream_options: { include_usage: true },\n };\n\n if (params.tools && params.tools.length > 0) {\n body.tools = mapToolDefinitions(params.tools);\n }\n\n return body;\n};\n\nconst parseToolInput = (rawArguments: string) => {\n try {\n return JSON.parse(rawArguments);\n } catch {\n return rawArguments;\n }\n};\n\nconst flushPendingToolCalls = function* (\n pendingToolCalls: Map<number, PendingToolCall>,\n) {\n for (const [, tool] of pendingToolCalls) {\n const input = parseToolInput(tool.arguments);\n yield {\n id: tool.id,\n input,\n name: tool.name,\n type: \"tool_use\" as const,\n };\n }\n\n pendingToolCalls.clear();\n};\n\nconst extractUsage = (parsedUsage: Record<string, number>) => ({\n inputTokens: parsedUsage.prompt_tokens ?? 0,\n outputTokens: parsedUsage.completion_tokens ?? 0,\n});\n\nconst resolveToolCallIndex = (toolCall: Record<string, unknown>) => {\n const raw = typeof toolCall.index === \"number\" ? toolCall.index : NOT_FOUND;\n\n return raw < 0 ? undefined : raw;\n};\n\nconst initPendingToolCall = (\n toolCall: Record<string, unknown>,\n func: Record<string, unknown> | null,\n index: number,\n pendingToolCalls: Map<number, PendingToolCall>,\n) => {\n if (pendingToolCalls.has(index)) {\n return;\n }\n\n const toolId = typeof toolCall.id === \"string\" ? toolCall.id : \"\";\n const toolName = func && typeof func.name === \"string\" ? func.name : \"\";\n\n pendingToolCalls.set(index, {\n arguments: \"\",\n id: toolId,\n name: toolName,\n });\n};\n\nconst updatePendingToolCall = (\n toolCall: Record<string, unknown>,\n func: Record<string, unknown> | null,\n pending: PendingToolCall,\n) => {\n if (typeof toolCall.id === \"string\") {\n pending.id = toolCall.id;\n }\n\n if (func && typeof func.name === \"string\") {\n pending.name = func.name;\n }\n\n if (func && typeof func.arguments === \"string\") {\n pending.arguments += func.arguments;\n }\n};\n\nconst processToolCallDelta = (\n toolCall: Record<string, unknown>,\n pendingToolCalls: Map<number, PendingToolCall>,\n) => {\n const index = resolveToolCallIndex(toolCall);\n if (index === undefined) {\n return;\n }\n\n const func = isRecord(toolCall.function) ? toolCall.function : null;\n initPendingToolCall(toolCall, func, index, pendingToolCalls);\n\n const pending = pendingToolCalls.get(index);\n if (!pending) {\n return;\n }\n\n updatePendingToolCall(toolCall, func, pending);\n};\n\nconst processToolCallDeltas = (\n toolCalls: Array<Record<string, unknown>>,\n pendingToolCalls: Map<number, PendingToolCall>,\n) => {\n for (const toolCall of toolCalls) {\n processToolCallDelta(toolCall, pendingToolCalls);\n }\n};\n\nconst processDelta = function* (\n delta: Record<string, unknown>,\n pendingToolCalls: Map<number, PendingToolCall>,\n) {\n if (typeof delta.content === \"string\") {\n yield { content: delta.content, type: \"text\" as const };\n }\n\n if (isRecordArray(delta.tool_calls)) {\n processToolCallDeltas(delta.tool_calls, pendingToolCalls);\n }\n};\n\nconst processChoice = function* (\n choice: Record<string, unknown>,\n pendingToolCalls: Map<number, PendingToolCall>,\n) {\n const delta = isRecord(choice.delta) ? choice.delta : null;\n if (delta) {\n yield* processDelta(delta, pendingToolCalls);\n }\n\n if (choice.finish_reason === \"tool_calls\") {\n yield* flushPendingToolCalls(pendingToolCalls);\n }\n};\n\nconst narrowUsageRecord = (parsed: Record<string, unknown>) => {\n if (!isRecord(parsed.usage)) {\n return undefined;\n }\n\n const { usage } = parsed;\n const promptTokens =\n typeof usage.prompt_tokens === \"number\" ? usage.prompt_tokens : 0;\n const completionTokens =\n typeof usage.completion_tokens === \"number\" ? usage.completion_tokens : 0;\n\n return extractUsage({\n completion_tokens: completionTokens,\n prompt_tokens: promptTokens,\n });\n};\n\nconst processSSELine = function* (\n line: string,\n pendingToolCalls: Map<number, PendingToolCall>,\n currentUsage: AIUsage | undefined,\n) {\n const trimmed = line.trim();\n if (!trimmed || !trimmed.startsWith(\"data: \")) {\n return;\n }\n\n const data = trimmed.slice(SSE_DATA_PREFIX_LENGTH);\n if (data === DONE_SENTINEL) {\n yield* flushPendingToolCalls(pendingToolCalls);\n yield { type: \"done\" as const, usage: currentUsage };\n\n return;\n }\n\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(data);\n } catch {\n return;\n }\n\n const usageUpdate = narrowUsageRecord(parsed);\n if (usageUpdate) {\n yield { type: \"usage_update\" as const, usage: usageUpdate };\n }\n\n const { choices } = parsed;\n if (!isRecordArray(choices)) {\n return;\n }\n\n const [firstChoice] = choices;\n if (!firstChoice) {\n return;\n }\n\n yield* processChoice(firstChoice, pendingToolCalls);\n};\n\nconst isUsageUpdate = (chunk: {\n type: string;\n usage?: AIUsage;\n}): chunk is { type: \"usage_update\"; usage: AIUsage } =>\n chunk.type === \"usage_update\";\n\nconst collectYieldableChunks = (\n line: string,\n pendingToolCalls: Map<number, PendingToolCall>,\n usageRef: UsageRef,\n) => {\n const allChunks = Array.from(\n processSSELine(line, pendingToolCalls, usageRef.current),\n );\n const usageChunks = allChunks.filter(isUsageUpdate);\n const lastUsage = usageChunks.at(NOT_FOUND);\n\n if (lastUsage) {\n usageRef.current = lastUsage.usage;\n }\n\n return allChunks.filter((chunk) => !isUsageUpdate(chunk));\n};\n\nconst processSSELines = function* (\n lines: string[],\n pendingToolCalls: Map<number, PendingToolCall>,\n usageRef: UsageRef,\n) {\n for (const line of lines) {\n yield* collectYieldableChunks(line, pendingToolCalls, usageRef);\n }\n};\n\nconst processStreamValue = (\n value: Uint8Array,\n decoder: TextDecoder,\n state: StreamState,\n) => {\n state.buffer += decoder.decode(value, { stream: true });\n const lines = state.buffer.split(\"\\n\");\n state.buffer = lines.pop() ?? \"\";\n\n return lines;\n};\n\nconst drainReader = async function* (\n reader: ReadableStreamDefaultReader<Uint8Array>,\n decoder: TextDecoder,\n state: StreamState,\n signal?: AbortSignal,\n) {\n /* eslint-disable no-await-in-loop */\n for (\n let result = await reader.read();\n !result.done && !signal?.aborted;\n result = await reader.read()\n ) {\n /* eslint-enable no-await-in-loop */\n const lines = processStreamValue(result.value, decoder, state);\n yield* processSSELines(lines, state.pendingToolCalls, state.usageRef);\n }\n};\n\nconst parseSSEStream = async function* (\n body: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n const state: StreamState = {\n buffer: \"\",\n pendingToolCalls: new Map<number, PendingToolCall>(),\n usageRef: { current: undefined },\n };\n\n try {\n yield* drainReader(reader, decoder, state, signal);\n yield { type: \"done\" as const, usage: state.usageRef.current };\n } finally {\n reader.releaseLock();\n }\n};\n\nconst fetchOpenAIStream = async function* (\n baseUrl: string,\n apiKey: string,\n body: Record<string, unknown>,\n signal?: AbortSignal,\n) {\n const response = await fetch(`${baseUrl}/v1/chat/completions`, {\n body: JSON.stringify(body),\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n method: \"POST\",\n signal,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`OpenAI API error ${response.status}: ${errorText}`);\n }\n\n if (!response.body) {\n throw new Error(\"OpenAI API returned no response body\");\n }\n\n yield* parseSSEStream(response.body, signal);\n};\n\nexport const openai = (config: OpenAIConfig): AIProviderConfig => {\n const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;\n\n return {\n stream: (params: AIProviderStreamParams) => {\n const body = buildRequestBody(params);\n\n return fetchOpenAIStream(baseUrl, config.apiKey, body, params.signal);\n },\n };\n};\n"
|
|
5
|
+
"import type {\n AIChunk,\n AIProviderConfig,\n AIProviderStreamParams,\n AIUsage,\n} from \"../../../types/ai\";\n\nexport const instrumentAIProvider = (\n provider: AIProviderConfig,\n providerName?: string,\n): AIProviderConfig => ({\n stream: (params: AIProviderStreamParams) => {\n if (!params.onUsage && !params.onSpan) {\n return provider.stream(params);\n }\n return tapStream(provider.stream(params), params, providerName);\n },\n});\n\nasync function* tapStream(\n source: AsyncIterable<AIChunk>,\n params: AIProviderStreamParams,\n providerName?: string,\n): AsyncIterable<AIChunk> {\n const startedAt = Date.now();\n let lastUsage: AIUsage | undefined;\n try {\n for await (const chunk of source) {\n if (chunk.type === \"done\" && chunk.usage) {\n lastUsage = chunk.usage;\n }\n yield chunk;\n }\n } finally {\n if (lastUsage && params.onUsage) {\n try {\n params.onUsage({\n ...lastUsage,\n model: params.model,\n provider: providerName,\n });\n } catch {\n // operator-supplied callback errors must not affect stream consumers\n }\n }\n if (params.onSpan) {\n try {\n params.onSpan({\n durationMs: Date.now() - startedAt,\n model: params.model,\n provider: providerName,\n usage: lastUsage,\n });\n } catch {\n // same\n }\n }\n }\n}\n",
|
|
6
|
+
"import type {\n AIProviderConfig,\n AIProviderContentBlock,\n AIProviderMessage,\n AIProviderStreamParams,\n AIProviderToolDefinition,\n AIUsage,\n} from \"../../../types/ai\";\n\n// Opportunistic HTTP/2 multiplexing for outbound HTTPS (Bun 1.3.14+).\n// The `protocol` option lands in @types/bun 1.3.14; widen locally for now.\nimport { instrumentAIProvider } from \"./instrumentation\";\n// Hard-skip on non-HTTPS — Bun's h2 client throws HTTP2Unsupported on h2c.\ntype H2Init = RequestInit & { protocol?: \"http2\" };\nconst h2IfHttps = (url: string): H2Init =>\n url.startsWith(\"https://\") ? { protocol: \"http2\" } : {};\n\ntype OpenAIConfig = {\n apiKey?: string;\n baseUrl?: string;\n tokenSource?: () => Promise<string> | string;\n};\n\ntype OpenAIMessage = {\n content: string | Array<Record<string, unknown>> | null;\n role: \"user\" | \"assistant\" | \"system\" | \"tool\";\n tool_call_id?: string;\n tool_calls?: Array<{\n function: { arguments: string; name: string };\n id: string;\n type: \"function\";\n }>;\n};\n\ntype PendingToolCall = {\n arguments: string;\n id: string;\n name: string;\n};\n\ntype UsageRef = {\n current: AIUsage | undefined;\n};\n\ntype StreamState = {\n buffer: string;\n pendingToolCalls: Map<number, PendingToolCall>;\n usageRef: UsageRef;\n};\n\nconst DEFAULT_BASE_URL = \"https://api.openai.com\";\nconst SSE_DATA_PREFIX_LENGTH = 6;\nconst DONE_SENTINEL = \"[DONE]\";\nconst NOT_FOUND = -1;\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null;\n\nconst isRecordArray = (\n value: unknown,\n): value is Array<Record<string, unknown>> =>\n Array.isArray(value) && value.length > 0 && isRecord(value[0]);\n\nconst hasArrayContent = (\n msg: AIProviderMessage,\n): msg is AIProviderMessage & { content: AIProviderContentBlock[] } =>\n typeof msg.content !== \"string\" && Array.isArray(msg.content);\n\nconst buildToolMessages = (blocks: AIProviderContentBlock[]) => {\n const toolUseBlocks = blocks.filter((block) => block.type === \"tool_use\");\n const toolResultBlocks = blocks.filter(\n (block) => block.type === \"tool_result\",\n );\n const messages: OpenAIMessage[] = [];\n\n if (toolUseBlocks.length > 0) {\n messages.push({\n content: null,\n role: \"assistant\",\n tool_calls: toolUseBlocks.map((block) => ({\n function: {\n arguments:\n typeof block.input === \"string\"\n ? block.input\n : JSON.stringify(block.input),\n name: block.name,\n },\n id: block.id,\n type: \"function\" as const,\n })),\n });\n }\n\n for (const result of toolResultBlocks) {\n messages.push({\n content: typeof result.content === \"string\" ? result.content : \"\",\n role: \"tool\",\n tool_call_id: result.tool_use_id,\n });\n }\n\n return messages;\n};\n\nconst processMessageAtIndex = (\n result: OpenAIMessage[],\n msg: AIProviderMessage,\n idx: number,\n) => {\n if (!hasArrayContent(msg)) {\n return;\n }\n\n const hasToolBlocks = msg.content.some(\n (block) => block.type === \"tool_use\" || block.type === \"tool_result\",\n );\n\n if (!hasToolBlocks) {\n return;\n }\n\n const toolMessages = buildToolMessages(msg.content);\n result.splice(idx, 1, ...toolMessages);\n};\n\nconst convertSingleMessage = (\n result: OpenAIMessage[],\n msg: AIProviderMessage | undefined,\n idx: number,\n) => {\n if (!msg) {\n return;\n }\n\n processMessageAtIndex(result, msg, idx);\n};\n\nconst convertToolResultMessages = (\n messages: OpenAIMessage[],\n params: AIProviderStreamParams,\n) => {\n const result = [...messages];\n\n for (let idx = 0; idx < params.messages.length; idx++) {\n convertSingleMessage(result, params.messages[idx], idx);\n }\n\n return result;\n};\n\nconst mapToolDefinitions = (tools: AIProviderToolDefinition[]) =>\n tools.map((tool) => ({\n function: {\n description: tool.description,\n name: tool.name,\n parameters: tool.input_schema,\n },\n type: \"function\",\n }));\n\nconst mapContentBlockToOpenAI = (block: AIProviderContentBlock) => {\n if (block.type === \"image\") {\n return {\n image_url: {\n url: `data:${block.source.media_type};base64,${block.source.data}`,\n },\n type: \"image_url\",\n };\n }\n\n if (block.type === \"document\") {\n return {\n file: {\n file_data: `data:${block.source.media_type};base64,${block.source.data}`,\n filename: block.name ?? \"document.pdf\",\n },\n type: \"file\",\n };\n }\n\n if (block.type === \"text\") {\n return { text: block.content, type: \"text\" };\n }\n\n return null;\n};\n\nconst mapOpenAIContent = (msg: AIProviderStreamParams[\"messages\"][number]) => {\n if (typeof msg.content === \"string\") {\n return msg.content;\n }\n\n const hasMedia = msg.content.some(\n (block) => block.type === \"image\" || block.type === \"document\",\n );\n\n if (!hasMedia) {\n return null;\n }\n\n return msg.content\n .map(mapContentBlockToOpenAI)\n .filter((mapped) => mapped !== null);\n};\n\nconst buildRequestBody = (params: AIProviderStreamParams) => {\n const messages = convertToolResultMessages(\n params.messages.map((msg) => ({\n content: mapOpenAIContent(msg),\n role: msg.role,\n })),\n params,\n );\n\n const body: Record<string, unknown> = {\n messages,\n model: params.model,\n stream: true,\n stream_options: { include_usage: true },\n };\n\n if (params.tools && params.tools.length > 0) {\n body.tools = mapToolDefinitions(params.tools);\n if (params.toolChoice === \"auto\" || params.toolChoice === \"none\" || params.toolChoice === \"required\") {\n body.tool_choice = params.toolChoice;\n } else if (params.toolChoice && typeof params.toolChoice === \"object\") {\n body.tool_choice = {\n function: { name: params.toolChoice.name },\n type: \"function\",\n };\n }\n if (typeof params.parallelToolCalls === \"boolean\") {\n body.parallel_tool_calls = params.parallelToolCalls;\n }\n }\n\n if (typeof params.temperature === \"number\") body.temperature = params.temperature;\n if (typeof params.topP === \"number\") body.top_p = params.topP;\n if (typeof params.maxTokens === \"number\") body.max_tokens = params.maxTokens;\n if (params.stopSequences && params.stopSequences.length > 0) body.stop = params.stopSequences;\n if (typeof params.seed === \"number\") body.seed = params.seed;\n if (typeof params.frequencyPenalty === \"number\") body.frequency_penalty = params.frequencyPenalty;\n if (typeof params.presencePenalty === \"number\") body.presence_penalty = params.presencePenalty;\n\n if (params.responseFormat) {\n if (params.responseFormat.type === \"text\" || params.responseFormat.type === \"json_object\") {\n body.response_format = { type: params.responseFormat.type };\n } else if (params.responseFormat.type === \"json_schema\") {\n body.response_format = {\n json_schema: {\n name: params.responseFormat.name,\n schema: params.responseFormat.schema,\n strict: params.responseFormat.strict ?? true,\n },\n type: \"json_schema\",\n };\n }\n }\n\n return body;\n};\n\nconst parseToolInput = (rawArguments: string) => {\n try {\n return JSON.parse(rawArguments);\n } catch {\n return rawArguments;\n }\n};\n\nconst flushPendingToolCalls = function* (\n pendingToolCalls: Map<number, PendingToolCall>,\n) {\n for (const [, tool] of pendingToolCalls) {\n const input = parseToolInput(tool.arguments);\n yield {\n id: tool.id,\n input,\n name: tool.name,\n type: \"tool_use\" as const,\n };\n }\n\n pendingToolCalls.clear();\n};\n\nconst extractUsage = (parsedUsage: Record<string, number>) => ({\n inputTokens: parsedUsage.prompt_tokens ?? 0,\n outputTokens: parsedUsage.completion_tokens ?? 0,\n});\n\nconst resolveToolCallIndex = (toolCall: Record<string, unknown>) => {\n const raw = typeof toolCall.index === \"number\" ? toolCall.index : NOT_FOUND;\n\n return raw < 0 ? undefined : raw;\n};\n\nconst initPendingToolCall = (\n toolCall: Record<string, unknown>,\n func: Record<string, unknown> | null,\n index: number,\n pendingToolCalls: Map<number, PendingToolCall>,\n) => {\n if (pendingToolCalls.has(index)) {\n return;\n }\n\n const toolId = typeof toolCall.id === \"string\" ? toolCall.id : \"\";\n const toolName = func && typeof func.name === \"string\" ? func.name : \"\";\n\n pendingToolCalls.set(index, {\n arguments: \"\",\n id: toolId,\n name: toolName,\n });\n};\n\nconst updatePendingToolCall = (\n toolCall: Record<string, unknown>,\n func: Record<string, unknown> | null,\n pending: PendingToolCall,\n) => {\n if (typeof toolCall.id === \"string\") {\n pending.id = toolCall.id;\n }\n\n if (func && typeof func.name === \"string\") {\n pending.name = func.name;\n }\n\n if (func && typeof func.arguments === \"string\") {\n pending.arguments += func.arguments;\n }\n};\n\nconst processToolCallDelta = (\n toolCall: Record<string, unknown>,\n pendingToolCalls: Map<number, PendingToolCall>,\n) => {\n const index = resolveToolCallIndex(toolCall);\n if (index === undefined) {\n return;\n }\n\n const func = isRecord(toolCall.function) ? toolCall.function : null;\n initPendingToolCall(toolCall, func, index, pendingToolCalls);\n\n const pending = pendingToolCalls.get(index);\n if (!pending) {\n return;\n }\n\n updatePendingToolCall(toolCall, func, pending);\n};\n\nconst processToolCallDeltas = (\n toolCalls: Array<Record<string, unknown>>,\n pendingToolCalls: Map<number, PendingToolCall>,\n) => {\n for (const toolCall of toolCalls) {\n processToolCallDelta(toolCall, pendingToolCalls);\n }\n};\n\nconst processDelta = function* (\n delta: Record<string, unknown>,\n pendingToolCalls: Map<number, PendingToolCall>,\n) {\n if (typeof delta.content === \"string\") {\n yield { content: delta.content, type: \"text\" as const };\n }\n\n if (isRecordArray(delta.tool_calls)) {\n processToolCallDeltas(delta.tool_calls, pendingToolCalls);\n }\n};\n\nconst processChoice = function* (\n choice: Record<string, unknown>,\n pendingToolCalls: Map<number, PendingToolCall>,\n) {\n const delta = isRecord(choice.delta) ? choice.delta : null;\n if (delta) {\n yield* processDelta(delta, pendingToolCalls);\n }\n\n if (choice.finish_reason === \"tool_calls\") {\n yield* flushPendingToolCalls(pendingToolCalls);\n }\n};\n\nconst narrowUsageRecord = (parsed: Record<string, unknown>) => {\n if (!isRecord(parsed.usage)) {\n return undefined;\n }\n\n const { usage } = parsed;\n const promptTokens =\n typeof usage.prompt_tokens === \"number\" ? usage.prompt_tokens : 0;\n const completionTokens =\n typeof usage.completion_tokens === \"number\" ? usage.completion_tokens : 0;\n\n return extractUsage({\n completion_tokens: completionTokens,\n prompt_tokens: promptTokens,\n });\n};\n\nconst processSSELine = function* (\n line: string,\n pendingToolCalls: Map<number, PendingToolCall>,\n currentUsage: AIUsage | undefined,\n) {\n const trimmed = line.trim();\n if (!trimmed || !trimmed.startsWith(\"data: \")) {\n return;\n }\n\n const data = trimmed.slice(SSE_DATA_PREFIX_LENGTH);\n if (data === DONE_SENTINEL) {\n yield* flushPendingToolCalls(pendingToolCalls);\n yield { type: \"done\" as const, usage: currentUsage };\n\n return;\n }\n\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(data);\n } catch {\n return;\n }\n\n const usageUpdate = narrowUsageRecord(parsed);\n if (usageUpdate) {\n yield { type: \"usage_update\" as const, usage: usageUpdate };\n }\n\n const { choices } = parsed;\n if (!isRecordArray(choices)) {\n return;\n }\n\n const [firstChoice] = choices;\n if (!firstChoice) {\n return;\n }\n\n yield* processChoice(firstChoice, pendingToolCalls);\n};\n\nconst isUsageUpdate = (chunk: {\n type: string;\n usage?: AIUsage;\n}): chunk is { type: \"usage_update\"; usage: AIUsage } =>\n chunk.type === \"usage_update\";\n\nconst collectYieldableChunks = (\n line: string,\n pendingToolCalls: Map<number, PendingToolCall>,\n usageRef: UsageRef,\n) => {\n const allChunks = Array.from(\n processSSELine(line, pendingToolCalls, usageRef.current),\n );\n const usageChunks = allChunks.filter(isUsageUpdate);\n const lastUsage = usageChunks.at(NOT_FOUND);\n\n if (lastUsage) {\n usageRef.current = lastUsage.usage;\n }\n\n return allChunks.filter((chunk) => !isUsageUpdate(chunk));\n};\n\nconst processSSELines = function* (\n lines: string[],\n pendingToolCalls: Map<number, PendingToolCall>,\n usageRef: UsageRef,\n) {\n for (const line of lines) {\n yield* collectYieldableChunks(line, pendingToolCalls, usageRef);\n }\n};\n\nconst processStreamValue = (\n value: Uint8Array,\n decoder: TextDecoder,\n state: StreamState,\n) => {\n state.buffer += decoder.decode(value, { stream: true });\n const lines = state.buffer.split(\"\\n\");\n state.buffer = lines.pop() ?? \"\";\n\n return lines;\n};\n\nconst drainReader = async function* (\n reader: ReadableStreamDefaultReader<Uint8Array>,\n decoder: TextDecoder,\n state: StreamState,\n signal?: AbortSignal,\n) {\n /* eslint-disable no-await-in-loop */\n for (\n let result = await reader.read();\n !result.done && !signal?.aborted;\n result = await reader.read()\n ) {\n /* eslint-enable no-await-in-loop */\n const lines = processStreamValue(result.value, decoder, state);\n yield* processSSELines(lines, state.pendingToolCalls, state.usageRef);\n }\n};\n\nconst parseSSEStream = async function* (\n body: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n) {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n const state: StreamState = {\n buffer: \"\",\n pendingToolCalls: new Map<number, PendingToolCall>(),\n usageRef: { current: undefined },\n };\n\n try {\n yield* drainReader(reader, decoder, state, signal);\n yield { type: \"done\" as const, usage: state.usageRef.current };\n } finally {\n reader.releaseLock();\n }\n};\n\nconst fetchOpenAIStream = async function* (\n baseUrl: string,\n apiKey: string,\n body: Record<string, unknown>,\n signal?: AbortSignal,\n) {\n const target = `${baseUrl}/v1/chat/completions`;\n const response = await fetch(target, {\n ...h2IfHttps(target),\n body: JSON.stringify(body),\n headers: {\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n method: \"POST\",\n signal,\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`OpenAI API error ${response.status}: ${errorText}`);\n }\n\n if (!response.body) {\n throw new Error(\"OpenAI API returned no response body\");\n }\n\n yield* parseSSEStream(response.body, signal);\n};\n\nexport const openai = (config: OpenAIConfig): AIProviderConfig => {\n const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;\n if (!config.apiKey && !config.tokenSource) {\n throw new Error(\"openai() requires either apiKey or tokenSource\");\n }\n const resolveKey = async () => {\n if (config.tokenSource) {\n return await Promise.resolve(config.tokenSource());\n }\n return config.apiKey!;\n };\n\n return instrumentAIProvider(\n {\n stream: (params: AIProviderStreamParams) => {\n const body = buildRequestBody(params);\n return (async function* () {\n const apiKey = await resolveKey();\n yield* fetchOpenAIStream(baseUrl, apiKey, body, params.signal);\n })();\n },\n },\n \"openai\",\n );\n};\n"
|
|
6
7
|
],
|
|
7
|
-
"mappings": ";;AAyCA,IAAM,mBAAmB;AACzB,IAAM,yBAAyB;AAC/B,IAAM,gBAAgB;AACtB,IAAM,YAAY;AAElB,IAAM,WAAW,CAAC,UAChB,OAAO,UAAU,YAAY,UAAU;AAEzC,IAAM,gBAAgB,CACpB,UAEA,MAAM,QAAQ,KAAK,KAAK,MAAM,SAAS,KAAK,SAAS,MAAM,EAAE;AAE/D,IAAM,kBAAkB,CACtB,QAEA,OAAO,IAAI,YAAY,YAAY,MAAM,QA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ClB;AAAA,IACA,QAAQ;AAAA,IACR;AAAA,EACF,CAAC;AAAA,EAED,IAAI,CAAC,SAAS,IAAI;AAAA,IAChB,MAAM,YAAY,MAAM,SAAS,KAAK;AAAA,IACtC,MAAM,IAAI,MAAM,oBAAoB,SAAS,WAAW,WAAW;AAAA,EACrE;AAAA,EAEA,IAAI,CAAC,SAAS,MAAM;AAAA,IAClB,MAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AAAA,EAEA,OAAO,eAAe,SAAS,MAAM,MAAM;AAAA;AAGtC,IAAM,SAAS,CAAC,WAA2C;AAAA,EAChE,MAAM,UAAU,OAAO,WAAW;AAAA,EAClC,IAAI,CAAC,OAAO,UAAU,CAAC,OAAO,aAAa;AAAA,IACzC,MAAM,IAAI,MAAM,gDAAgD;AAAA,EAClE;AAAA,EACA,MAAM,aAAa,YAAY;AAAA,IAC7B,IAAI,OAAO,aAAa;AAAA,MACtB,OAAO,MAAM,QAAQ,QAAQ,OAAO,YAAY,CAAC;AAAA,IACnD;AAAA,IACA,OAAO,OAAO;AAAA;AAAA,EAGhB,OAAO,qBACL;AAAA,IACE,QAAQ,CAAC,WAAmC;AAAA,MAC1C,MAAM,OAAO,iBAAiB,MAAM;AAAA,MACpC,OAAQ,gBAAgB,GAAG;AAAA,QACzB,MAAM,SAAS,MAAM,WAAW;AAAA,QAChC,OAAO,kBAAkB,SAAS,QAAQ,MAAM,OAAO,MAAM;AAAA,QAC5D;AAAA;AAAA,EAEP,GACA,QACF;AAAA;",
|
|
9
|
+
"debugId": "355EFC91257F586E64756E2164756E21",
|
|
9
10
|
"names": []
|
|
10
11
|
}
|
|
@@ -1,5 +1,48 @@
|
|
|
1
1
|
// @bun
|
|
2
|
+
// src/ai/providers/instrumentation.ts
|
|
3
|
+
var instrumentAIProvider = (provider, providerName) => ({
|
|
4
|
+
stream: (params) => {
|
|
5
|
+
if (!params.onUsage && !params.onSpan) {
|
|
6
|
+
return provider.stream(params);
|
|
7
|
+
}
|
|
8
|
+
return tapStream(provider.stream(params), params, providerName);
|
|
9
|
+
}
|
|
10
|
+
});
|
|
11
|
+
async function* tapStream(source, params, providerName) {
|
|
12
|
+
const startedAt = Date.now();
|
|
13
|
+
let lastUsage;
|
|
14
|
+
try {
|
|
15
|
+
for await (const chunk of source) {
|
|
16
|
+
if (chunk.type === "done" && chunk.usage) {
|
|
17
|
+
lastUsage = chunk.usage;
|
|
18
|
+
}
|
|
19
|
+
yield chunk;
|
|
20
|
+
}
|
|
21
|
+
} finally {
|
|
22
|
+
if (lastUsage && params.onUsage) {
|
|
23
|
+
try {
|
|
24
|
+
params.onUsage({
|
|
25
|
+
...lastUsage,
|
|
26
|
+
model: params.model,
|
|
27
|
+
provider: providerName
|
|
28
|
+
});
|
|
29
|
+
} catch {}
|
|
30
|
+
}
|
|
31
|
+
if (params.onSpan) {
|
|
32
|
+
try {
|
|
33
|
+
params.onSpan({
|
|
34
|
+
durationMs: Date.now() - startedAt,
|
|
35
|
+
model: params.model,
|
|
36
|
+
provider: providerName,
|
|
37
|
+
usage: lastUsage
|
|
38
|
+
});
|
|
39
|
+
} catch {}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
2
44
|
// src/ai/providers/openai.ts
|
|
45
|
+
var h2IfHttps = (url) => url.startsWith("https://") ? { protocol: "http2" } : {};
|
|
3
46
|
var DEFAULT_BASE_URL = "https://api.openai.com";
|
|
4
47
|
var SSE_DATA_PREFIX_LENGTH = 6;
|
|
5
48
|
var DONE_SENTINEL = "[DONE]";
|
|
@@ -112,6 +155,45 @@ var buildRequestBody = (params) => {
|
|
|
112
155
|
};
|
|
113
156
|
if (params.tools && params.tools.length > 0) {
|
|
114
157
|
body.tools = mapToolDefinitions(params.tools);
|
|
158
|
+
if (params.toolChoice === "auto" || params.toolChoice === "none" || params.toolChoice === "required") {
|
|
159
|
+
body.tool_choice = params.toolChoice;
|
|
160
|
+
} else if (params.toolChoice && typeof params.toolChoice === "object") {
|
|
161
|
+
body.tool_choice = {
|
|
162
|
+
function: { name: params.toolChoice.name },
|
|
163
|
+
type: "function"
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
if (typeof params.parallelToolCalls === "boolean") {
|
|
167
|
+
body.parallel_tool_calls = params.parallelToolCalls;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (typeof params.temperature === "number")
|
|
171
|
+
body.temperature = params.temperature;
|
|
172
|
+
if (typeof params.topP === "number")
|
|
173
|
+
body.top_p = params.topP;
|
|
174
|
+
if (typeof params.maxTokens === "number")
|
|
175
|
+
body.max_tokens = params.maxTokens;
|
|
176
|
+
if (params.stopSequences && params.stopSequences.length > 0)
|
|
177
|
+
body.stop = params.stopSequences;
|
|
178
|
+
if (typeof params.seed === "number")
|
|
179
|
+
body.seed = params.seed;
|
|
180
|
+
if (typeof params.frequencyPenalty === "number")
|
|
181
|
+
body.frequency_penalty = params.frequencyPenalty;
|
|
182
|
+
if (typeof params.presencePenalty === "number")
|
|
183
|
+
body.presence_penalty = params.presencePenalty;
|
|
184
|
+
if (params.responseFormat) {
|
|
185
|
+
if (params.responseFormat.type === "text" || params.responseFormat.type === "json_object") {
|
|
186
|
+
body.response_format = { type: params.responseFormat.type };
|
|
187
|
+
} else if (params.responseFormat.type === "json_schema") {
|
|
188
|
+
body.response_format = {
|
|
189
|
+
json_schema: {
|
|
190
|
+
name: params.responseFormat.name,
|
|
191
|
+
schema: params.responseFormat.schema,
|
|
192
|
+
strict: params.responseFormat.strict ?? true
|
|
193
|
+
},
|
|
194
|
+
type: "json_schema"
|
|
195
|
+
};
|
|
196
|
+
}
|
|
115
197
|
}
|
|
116
198
|
return body;
|
|
117
199
|
};
|
|
@@ -287,7 +369,9 @@ var parseSSEStream = async function* (body, signal) {
|
|
|
287
369
|
}
|
|
288
370
|
};
|
|
289
371
|
var fetchOpenAIStream = async function* (baseUrl, apiKey, body, signal) {
|
|
290
|
-
const
|
|
372
|
+
const target = `${baseUrl}/v1/chat/completions`;
|
|
373
|
+
const response = await fetch(target, {
|
|
374
|
+
...h2IfHttps(target),
|
|
291
375
|
body: JSON.stringify(body),
|
|
292
376
|
headers: {
|
|
293
377
|
Authorization: `Bearer ${apiKey}`,
|
|
@@ -307,12 +391,24 @@ var fetchOpenAIStream = async function* (baseUrl, apiKey, body, signal) {
|
|
|
307
391
|
};
|
|
308
392
|
var openai = (config) => {
|
|
309
393
|
const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
|
|
310
|
-
|
|
394
|
+
if (!config.apiKey && !config.tokenSource) {
|
|
395
|
+
throw new Error("openai() requires either apiKey or tokenSource");
|
|
396
|
+
}
|
|
397
|
+
const resolveKey = async () => {
|
|
398
|
+
if (config.tokenSource) {
|
|
399
|
+
return await Promise.resolve(config.tokenSource());
|
|
400
|
+
}
|
|
401
|
+
return config.apiKey;
|
|
402
|
+
};
|
|
403
|
+
return instrumentAIProvider({
|
|
311
404
|
stream: (params) => {
|
|
312
405
|
const body = buildRequestBody(params);
|
|
313
|
-
return
|
|
406
|
+
return async function* () {
|
|
407
|
+
const apiKey = await resolveKey();
|
|
408
|
+
yield* fetchOpenAIStream(baseUrl, apiKey, body, params.signal);
|
|
409
|
+
}();
|
|
314
410
|
}
|
|
315
|
-
};
|
|
411
|
+
}, "openai");
|
|
316
412
|
};
|
|
317
413
|
|
|
318
414
|
// src/ai/providers/openaiCompatible.ts
|
|
@@ -340,7 +436,11 @@ var moonshot = (config) => openaiCompatible({
|
|
|
340
436
|
apiKey: config.apiKey,
|
|
341
437
|
baseUrl: "https://api.moonshot.ai"
|
|
342
438
|
});
|
|
343
|
-
var openaiCompatible = (config) => openai({
|
|
439
|
+
var openaiCompatible = (config) => openai({
|
|
440
|
+
apiKey: config.apiKey,
|
|
441
|
+
baseUrl: config.baseUrl,
|
|
442
|
+
tokenSource: config.tokenSource
|
|
443
|
+
});
|
|
344
444
|
var xai = (config) => openaiCompatible({
|
|
345
445
|
apiKey: config.apiKey,
|
|
346
446
|
baseUrl: "https://api.x.ai"
|
|
@@ -356,5 +456,5 @@ export {
|
|
|
356
456
|
alibaba
|
|
357
457
|
};
|
|
358
458
|
|
|
359
|
-
//# debugId=
|
|
459
|
+
//# debugId=40C77C2E503A6C6D64756E2164756E21
|
|
360
460
|
//# sourceMappingURL=openaiCompatible.js.map
|