@fabric-harness/sdk 6.3.0 → 6.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/connector-spec/voice-telephony.md +120 -104
- package/dist/agent-route.d.ts +22 -2
- package/dist/agent-route.d.ts.map +1 -1
- package/dist/agent-route.js +32 -1
- package/dist/agent-route.js.map +1 -1
- package/dist/agent-router.d.ts +46 -0
- package/dist/agent-router.d.ts.map +1 -1
- package/dist/agent-router.js +63 -2
- package/dist/agent-router.js.map +1 -1
- package/dist/agent.d.ts.map +1 -1
- package/dist/agent.js +3 -0
- package/dist/agent.js.map +1 -1
- package/dist/attachment-store.d.ts +69 -0
- package/dist/attachment-store.d.ts.map +1 -1
- package/dist/attachment-store.js +183 -14
- package/dist/attachment-store.js.map +1 -1
- package/dist/attachments.d.ts +136 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/attachments.js +332 -0
- package/dist/attachments.js.map +1 -0
- package/dist/channel.d.ts.map +1 -1
- package/dist/channel.js +26 -3
- package/dist/channel.js.map +1 -1
- package/dist/conversation-history.d.ts +186 -0
- package/dist/conversation-history.d.ts.map +1 -0
- package/dist/conversation-history.js +481 -0
- package/dist/conversation-history.js.map +1 -0
- package/dist/conversation-ui.d.ts +43 -2
- package/dist/conversation-ui.d.ts.map +1 -1
- package/dist/conversation-ui.js +44 -14
- package/dist/conversation-ui.js.map +1 -1
- package/dist/cost-budget.d.ts +50 -0
- package/dist/cost-budget.d.ts.map +1 -1
- package/dist/cost-budget.js +74 -4
- package/dist/cost-budget.js.map +1 -1
- package/dist/cost-enforcement.d.ts +32 -0
- package/dist/cost-enforcement.d.ts.map +1 -0
- package/dist/cost-enforcement.js +116 -0
- package/dist/cost-enforcement.js.map +1 -0
- package/dist/delivered-message.d.ts +20 -6
- package/dist/delivered-message.d.ts.map +1 -1
- package/dist/delivered-message.js +37 -8
- package/dist/delivered-message.js.map +1 -1
- package/dist/events.d.ts +16 -2
- package/dist/events.d.ts.map +1 -1
- package/dist/events.js.map +1 -1
- package/dist/experimental.d.ts +2 -2
- package/dist/experimental.d.ts.map +1 -1
- package/dist/experimental.js +1 -1
- package/dist/experimental.js.map +1 -1
- package/dist/governed-voice.d.ts +6 -0
- package/dist/governed-voice.d.ts.map +1 -1
- package/dist/governed-voice.js +142 -35
- package/dist/governed-voice.js.map +1 -1
- package/dist/history.d.ts +3 -2
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +57 -23
- package/dist/history.js.map +1 -1
- package/dist/index.d.ts +21 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +11 -7
- package/dist/index.js.map +1 -1
- package/dist/loop.d.ts +25 -2
- package/dist/loop.d.ts.map +1 -1
- package/dist/loop.js +409 -60
- package/dist/loop.js.map +1 -1
- package/dist/model-pricing.d.ts +77 -4
- package/dist/model-pricing.d.ts.map +1 -1
- package/dist/model-pricing.js +259 -18
- package/dist/model-pricing.js.map +1 -1
- package/dist/model.d.ts +115 -3
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +376 -57
- package/dist/model.js.map +1 -1
- package/dist/otel-observer.d.ts +3 -1
- package/dist/otel-observer.d.ts.map +1 -1
- package/dist/otel-observer.js +40 -8
- package/dist/otel-observer.js.map +1 -1
- package/dist/persistent-agent.d.ts +5 -0
- package/dist/persistent-agent.d.ts.map +1 -1
- package/dist/persistent-agent.js +9 -1
- package/dist/persistent-agent.js.map +1 -1
- package/dist/pi-document-attachments.d.ts +43 -0
- package/dist/pi-document-attachments.d.ts.map +1 -0
- package/dist/pi-document-attachments.js +155 -0
- package/dist/pi-document-attachments.js.map +1 -0
- package/dist/pi-loop-runtime.d.ts +103 -1
- package/dist/pi-loop-runtime.d.ts.map +1 -1
- package/dist/pi-loop-runtime.js +850 -109
- package/dist/pi-loop-runtime.js.map +1 -1
- package/dist/prompt-attachments.d.ts +98 -0
- package/dist/prompt-attachments.d.ts.map +1 -0
- package/dist/prompt-attachments.js +279 -0
- package/dist/prompt-attachments.js.map +1 -0
- package/dist/session.d.ts +52 -0
- package/dist/session.d.ts.map +1 -1
- package/dist/session.js +410 -33
- package/dist/session.js.map +1 -1
- package/dist/stream-chunks.d.ts +15 -1
- package/dist/stream-chunks.d.ts.map +1 -1
- package/dist/stream-chunks.js +39 -18
- package/dist/stream-chunks.js.map +1 -1
- package/dist/strict.d.ts +23 -16
- package/dist/strict.d.ts.map +1 -1
- package/dist/strict.js +12 -8
- package/dist/strict.js.map +1 -1
- package/dist/submission-context.d.ts +7 -0
- package/dist/submission-context.d.ts.map +1 -1
- package/dist/submission-context.js.map +1 -1
- package/dist/submission-runner.d.ts +5 -0
- package/dist/submission-runner.d.ts.map +1 -1
- package/dist/submission-runner.js +97 -13
- package/dist/submission-runner.js.map +1 -1
- package/dist/submission-store-contract.d.ts.map +1 -1
- package/dist/submission-store-contract.js +15 -1
- package/dist/submission-store-contract.js.map +1 -1
- package/dist/submission-store.d.ts +12 -0
- package/dist/submission-store.d.ts.map +1 -1
- package/dist/submission-store.js +13 -4
- package/dist/submission-store.js.map +1 -1
- package/dist/trace-content.d.ts +21 -0
- package/dist/trace-content.d.ts.map +1 -0
- package/dist/trace-content.js +69 -0
- package/dist/trace-content.js.map +1 -0
- package/dist/types.d.ts +26 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/usage-completeness.d.ts +39 -0
- package/dist/usage-completeness.d.ts.map +1 -0
- package/dist/usage-completeness.js +135 -0
- package/dist/usage-completeness.js.map +1 -0
- package/dist/voice-openai-realtime.d.ts +24 -2
- package/dist/voice-openai-realtime.d.ts.map +1 -1
- package/dist/voice-openai-realtime.js +266 -49
- package/dist/voice-openai-realtime.js.map +1 -1
- package/dist/voice-pipeline.d.ts +81 -3
- package/dist/voice-pipeline.d.ts.map +1 -1
- package/dist/voice-pipeline.js +429 -60
- package/dist/voice-pipeline.js.map +1 -1
- package/dist/voice-stt-cartesia.d.ts +8 -0
- package/dist/voice-stt-cartesia.d.ts.map +1 -1
- package/dist/voice-stt-cartesia.js +77 -17
- package/dist/voice-stt-cartesia.js.map +1 -1
- package/dist/voice-stt-deepgram.d.ts +10 -2
- package/dist/voice-stt-deepgram.d.ts.map +1 -1
- package/dist/voice-stt-deepgram.js +78 -18
- package/dist/voice-stt-deepgram.js.map +1 -1
- package/dist/voice-stt.d.ts +13 -3
- package/dist/voice-stt.d.ts.map +1 -1
- package/dist/voice-tts-cartesia.d.ts +8 -0
- package/dist/voice-tts-cartesia.d.ts.map +1 -1
- package/dist/voice-tts-cartesia.js +48 -105
- package/dist/voice-tts-cartesia.js.map +1 -1
- package/dist/voice-tts-elevenlabs.d.ts +10 -1
- package/dist/voice-tts-elevenlabs.d.ts.map +1 -1
- package/dist/voice-tts-elevenlabs.js +50 -113
- package/dist/voice-tts-elevenlabs.js.map +1 -1
- package/dist/voice-ws-client.js +16 -3
- package/dist/voice-ws-client.js.map +1 -1
- package/dist/voice-ws-shared.d.ts +205 -6
- package/dist/voice-ws-shared.d.ts.map +1 -1
- package/dist/voice-ws-shared.js +510 -15
- package/dist/voice-ws-shared.js.map +1 -1
- package/dist/voice.d.ts +98 -4
- package/dist/voice.d.ts.map +1 -1
- package/dist/voice.js +71 -1
- package/dist/voice.js.map +1 -1
- package/package.json +3 -3
package/dist/model.js
CHANGED
|
@@ -1,5 +1,44 @@
|
|
|
1
1
|
import { createHash, createHmac } from "node:crypto";
|
|
2
2
|
import { applyEstimatedCost } from "./model-pricing.js";
|
|
3
|
+
import { hasPriceableUsage } from "./cost-budget.js";
|
|
4
|
+
import { attachmentOmittedPlaceholder, isNativeImageMimeType, isDocumentMimeType, collectAttachmentPayloads, redactAttachmentPayloads, redactErrorAttachmentPayloads, warnAttachmentOmittedOnce, } from "./attachments.js";
|
|
5
|
+
/**
|
|
6
|
+
* Split a message's attachments into the ones an API accepts natively and a
|
|
7
|
+
* text rendering with placeholders for the rest (unsupported kind, unsupported
|
|
8
|
+
* image type, or bytes that are unavailable). Emits one console warning per
|
|
9
|
+
* `(api, kind)` the first time a placeholder replaces a supported-by-others kind.
|
|
10
|
+
*/
|
|
11
|
+
export function partitionModelAttachments(message, support) {
|
|
12
|
+
const native = [];
|
|
13
|
+
const placeholders = [];
|
|
14
|
+
for (const attachment of message.attachments ?? []) {
|
|
15
|
+
const name = attachment.filename !== undefined ? { filename: attachment.filename } : {};
|
|
16
|
+
if (attachment.data === undefined || attachment.data.length === 0) {
|
|
17
|
+
placeholders.push(attachmentOmittedPlaceholder({ kind: attachment.type, api: support.api, reason: "unavailable", ...name }));
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
const supported = attachment.type === "document"
|
|
21
|
+
? support.documents && isDocumentMimeType(attachment.mimeType)
|
|
22
|
+
: support.images && isNativeImageMimeType(attachment.mimeType);
|
|
23
|
+
if (supported) {
|
|
24
|
+
native.push({ ...attachment, data: attachment.data });
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
const kindSupported = attachment.type === "document" ? support.documents : support.images;
|
|
28
|
+
if (!kindSupported)
|
|
29
|
+
warnAttachmentOmittedOnce(support.api, attachment.type);
|
|
30
|
+
placeholders.push(attachmentOmittedPlaceholder({
|
|
31
|
+
kind: attachment.type,
|
|
32
|
+
api: support.api,
|
|
33
|
+
...(kindSupported ? { reason: "unsupported-type", mimeType: attachment.mimeType } : {}),
|
|
34
|
+
...name,
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
const text = placeholders.length
|
|
38
|
+
? [message.content, ...placeholders].filter((part) => part.length > 0).join("\n\n")
|
|
39
|
+
: message.content;
|
|
40
|
+
return { text, native };
|
|
41
|
+
}
|
|
3
42
|
export function toolsToModelSchemas(tools) {
|
|
4
43
|
return [...tools].map((tool) => ({
|
|
5
44
|
name: tool.name,
|
|
@@ -7,8 +46,10 @@ export function toolsToModelSchemas(tools) {
|
|
|
7
46
|
...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
|
|
8
47
|
}));
|
|
9
48
|
}
|
|
10
|
-
|
|
11
|
-
const
|
|
49
|
+
/** @internal Default transient model retries shared by generate and stream paths. */
|
|
50
|
+
export const MAX_TRANSIENT_MODEL_RETRIES = 3;
|
|
51
|
+
/** @internal Default base backoff shared by generate and stream paths. */
|
|
52
|
+
export const TRANSIENT_MODEL_RETRY_BASE_DELAY_MS = 2_000;
|
|
12
53
|
export async function generateWithRuntime(provider, request, options = {}) {
|
|
13
54
|
const maxAttempts = (options.retries ?? MAX_TRANSIENT_MODEL_RETRIES) + 1;
|
|
14
55
|
const baseDelayMs = options.retryDelayMs ?? TRANSIENT_MODEL_RETRY_BASE_DELAY_MS;
|
|
@@ -38,28 +79,22 @@ export async function generateWithRuntime(provider, request, options = {}) {
|
|
|
38
79
|
status: "start",
|
|
39
80
|
...(request.model !== undefined ? { model: request.model } : {}),
|
|
40
81
|
});
|
|
82
|
+
let response;
|
|
41
83
|
try {
|
|
42
|
-
|
|
84
|
+
response = await provider.generate({ ...request, signal: controller.signal });
|
|
43
85
|
if (timeout)
|
|
44
86
|
clearTimeout(timeout);
|
|
45
87
|
options.signal?.removeEventListener("abort", abortListener);
|
|
46
|
-
await options.onAttempt?.({
|
|
47
|
-
provider: provider.name,
|
|
48
|
-
attempt,
|
|
49
|
-
maxAttempts,
|
|
50
|
-
status: "success",
|
|
51
|
-
durationMs: Date.now() - startedAt,
|
|
52
|
-
...(request.model !== undefined ? { model: request.model } : {}),
|
|
53
|
-
...(response.usage !== undefined ? { usage: response.usage } : {}),
|
|
54
|
-
});
|
|
55
|
-
return response;
|
|
56
88
|
}
|
|
57
89
|
catch (error) {
|
|
58
90
|
if (timeout)
|
|
59
91
|
clearTimeout(timeout);
|
|
60
92
|
options.signal?.removeEventListener("abort", abortListener);
|
|
61
93
|
lastError = error;
|
|
62
|
-
|
|
94
|
+
// Providers can echo submitted attachment bytes in error text; strip
|
|
95
|
+
// them before the message reaches attempt journals and telemetry.
|
|
96
|
+
// Exact-match redaction covers payloads too short for the generic rules.
|
|
97
|
+
const message = redactAttachmentPayloads(error instanceof Error ? error.message : String(error), collectAttachmentPayloads(request.messages));
|
|
63
98
|
const canRetry = attempt < maxAttempts && !options.signal?.aborted && isRetryableModelError(error);
|
|
64
99
|
await options.onAttempt?.({
|
|
65
100
|
provider: provider.name,
|
|
@@ -80,12 +115,31 @@ export async function generateWithRuntime(provider, request, options = {}) {
|
|
|
80
115
|
: calculateRetryDelay(baseDelayMs, attempt);
|
|
81
116
|
await sleepWithAbort(waitMs, retryAbortController.signal);
|
|
82
117
|
}
|
|
118
|
+
if (response === undefined)
|
|
119
|
+
continue;
|
|
120
|
+
// Record success outside the provider try: a failure here is local
|
|
121
|
+
// (journal/telemetry), must not be classified as a provider error, and
|
|
122
|
+
// must never trigger another paid model call.
|
|
123
|
+
await options.onAttempt?.({
|
|
124
|
+
provider: provider.name,
|
|
125
|
+
attempt,
|
|
126
|
+
maxAttempts,
|
|
127
|
+
status: "success",
|
|
128
|
+
durationMs: Date.now() - startedAt,
|
|
129
|
+
...(request.model !== undefined ? { model: request.model } : {}),
|
|
130
|
+
...(response.usage !== undefined ? { usage: response.usage } : {}),
|
|
131
|
+
});
|
|
132
|
+
return response;
|
|
83
133
|
}
|
|
84
134
|
}
|
|
85
135
|
finally {
|
|
86
136
|
options.signal?.removeEventListener("abort", onCallerAbort);
|
|
87
137
|
}
|
|
88
|
-
|
|
138
|
+
// The rejected error reaches callers, loggers and CLIs directly, so it gets
|
|
139
|
+
// the same exact-payload redaction as the attempt events: message, stack,
|
|
140
|
+
// a ProviderHttpError body and any cause chain. Redaction is in place, so
|
|
141
|
+
// the class, status, retryAfterMs and retry classification are unchanged.
|
|
142
|
+
throw redactErrorAttachmentPayloads(lastError, collectAttachmentPayloads(request.messages));
|
|
89
143
|
}
|
|
90
144
|
/**
|
|
91
145
|
* Strip a routing prefix (`<provider-name>/`) from a model reference. `AgentInit.model` keeps
|
|
@@ -293,9 +347,15 @@ export class OpenAICompatibleModelProvider {
|
|
|
293
347
|
rateLimiter;
|
|
294
348
|
rateLimitKey;
|
|
295
349
|
fetchImpl;
|
|
350
|
+
messageOptions;
|
|
296
351
|
constructor(options) {
|
|
297
352
|
this.name = options.name ?? "openai-compatible";
|
|
298
353
|
this.baseUrl = options.baseUrl.replace(/\/$/, "");
|
|
354
|
+
this.messageOptions = {
|
|
355
|
+
api: "openai-completions",
|
|
356
|
+
images: options.imageInput ?? true,
|
|
357
|
+
documents: options.documentInput ?? isOpenAIPlatformBaseUrl(this.baseUrl),
|
|
358
|
+
};
|
|
299
359
|
this.apiKey = options.apiKey;
|
|
300
360
|
this.tokenProvider = options.tokenProvider;
|
|
301
361
|
if (options.defaultModel !== undefined)
|
|
@@ -331,7 +391,7 @@ export class OpenAICompatibleModelProvider {
|
|
|
331
391
|
},
|
|
332
392
|
body: JSON.stringify({
|
|
333
393
|
model,
|
|
334
|
-
messages: request.messages.map(toOpenAIMessage),
|
|
394
|
+
messages: request.messages.map((message) => toOpenAIMessage(message, this.messageOptions)),
|
|
335
395
|
...(request.tools !== undefined ? { tools: request.tools.map(toOpenAITool) } : {}),
|
|
336
396
|
...(shouldApplyReasoning(model, request.thinkingLevel)
|
|
337
397
|
? { reasoning_effort: openAIReasoningEffort(request.thinkingLevel) }
|
|
@@ -352,7 +412,7 @@ export class OpenAICompatibleModelProvider {
|
|
|
352
412
|
throw new Error(`${this.name}: failed to parse response as JSON: ${message}`);
|
|
353
413
|
}
|
|
354
414
|
const result = openAIChatCompletionToModelResponse(json);
|
|
355
|
-
|
|
415
|
+
priceAdapterUsage(`${this.name}/${model}`, result.usage);
|
|
356
416
|
return result;
|
|
357
417
|
}
|
|
358
418
|
async *stream(request) {
|
|
@@ -376,7 +436,7 @@ export class OpenAICompatibleModelProvider {
|
|
|
376
436
|
model,
|
|
377
437
|
stream: true,
|
|
378
438
|
stream_options: { include_usage: true },
|
|
379
|
-
messages: request.messages.map(toOpenAIMessage),
|
|
439
|
+
messages: request.messages.map((message) => toOpenAIMessage(message, this.messageOptions)),
|
|
380
440
|
...(request.tools !== undefined ? { tools: request.tools.map(toOpenAITool) } : {}),
|
|
381
441
|
...(shouldApplyReasoning(model, request.thinkingLevel)
|
|
382
442
|
? { reasoning_effort: openAIReasoningEffort(request.thinkingLevel) }
|
|
@@ -392,6 +452,7 @@ export class OpenAICompatibleModelProvider {
|
|
|
392
452
|
const thinking = [];
|
|
393
453
|
const toolCallBuffers = new Map();
|
|
394
454
|
let usage;
|
|
455
|
+
let stopReason;
|
|
395
456
|
for await (const event of decodeOpenAISSE(response.body)) {
|
|
396
457
|
if (event === "[DONE]")
|
|
397
458
|
break;
|
|
@@ -399,6 +460,8 @@ export class OpenAICompatibleModelProvider {
|
|
|
399
460
|
if (!json)
|
|
400
461
|
continue;
|
|
401
462
|
const choice = json.choices?.[0];
|
|
463
|
+
if (typeof choice?.finish_reason === "string")
|
|
464
|
+
stopReason = normalizeOpenAIFinishReason(choice.finish_reason);
|
|
402
465
|
const delta = choice?.delta;
|
|
403
466
|
const contentDelta = openAIMessageText(delta?.content) ?? "";
|
|
404
467
|
const reasoningDelta = typeof delta?.reasoning_content === "string"
|
|
@@ -456,14 +519,15 @@ export class OpenAICompatibleModelProvider {
|
|
|
456
519
|
toolCalls: [...toolCallBuffers.values()].map((buf, index) => ({
|
|
457
520
|
id: buf.id ?? `openai-stream-${index + 1}`,
|
|
458
521
|
name: buf.name ?? "",
|
|
459
|
-
input: buf.args
|
|
522
|
+
input: parseToolArguments(buf.args, stopReason),
|
|
460
523
|
})),
|
|
461
524
|
}
|
|
462
525
|
: {}),
|
|
463
526
|
...(usage ? { usage } : {}),
|
|
527
|
+
...(stopReason ? { stopReason } : {}),
|
|
464
528
|
};
|
|
465
529
|
if (done.usage)
|
|
466
|
-
|
|
530
|
+
priceAdapterUsage(`${this.name}/${model}`, done.usage);
|
|
467
531
|
yield { done };
|
|
468
532
|
}
|
|
469
533
|
}
|
|
@@ -488,14 +552,14 @@ export class AzureOpenAIModelProvider {
|
|
|
488
552
|
...(request.signal !== undefined ? { signal: request.signal } : {}),
|
|
489
553
|
headers: { "content-type": "application/json", "api-key": this.apiKey, ...this.headers },
|
|
490
554
|
body: JSON.stringify({
|
|
491
|
-
messages: request.messages.map(toOpenAIMessage),
|
|
555
|
+
messages: request.messages.map((message) => toOpenAIMessage(message, { api: "azure-openai-completions", images: true, documents: false })),
|
|
492
556
|
...(request.tools !== undefined ? { tools: request.tools.map(toOpenAITool) } : {}),
|
|
493
557
|
}),
|
|
494
558
|
});
|
|
495
559
|
if (!response.ok)
|
|
496
560
|
throw formatProviderHttpError(this.name, this.deployment, response.status, response.statusText, await response.text(), response.headers);
|
|
497
561
|
const result = openAIChatCompletionToModelResponse((await response.json()));
|
|
498
|
-
|
|
562
|
+
priceAdapterUsage(`azure-openai/${this.deployment}`, result.usage);
|
|
499
563
|
return result;
|
|
500
564
|
}
|
|
501
565
|
}
|
|
@@ -526,7 +590,7 @@ export class GeminiModelProvider {
|
|
|
526
590
|
if (!response.ok)
|
|
527
591
|
throw formatProviderHttpError(this.name, model, response.status, response.statusText, await response.text(), response.headers);
|
|
528
592
|
const result = geminiResponseToModelResponse((await response.json()));
|
|
529
|
-
|
|
593
|
+
priceAdapterUsage(`gemini/${model}`, result.usage);
|
|
530
594
|
return result;
|
|
531
595
|
}
|
|
532
596
|
}
|
|
@@ -564,7 +628,7 @@ export class VertexAIModelProvider {
|
|
|
564
628
|
if (!response.ok)
|
|
565
629
|
throw formatProviderHttpError(this.name, model, response.status, response.statusText, await response.text(), response.headers);
|
|
566
630
|
const result = geminiResponseToModelResponse((await response.json()));
|
|
567
|
-
|
|
631
|
+
priceAdapterUsage(`gemini/${model}`, result.usage);
|
|
568
632
|
return result;
|
|
569
633
|
}
|
|
570
634
|
}
|
|
@@ -615,7 +679,7 @@ export class BedrockModelProvider {
|
|
|
615
679
|
if (!response.ok)
|
|
616
680
|
throw formatProviderHttpError(this.name, model, response.status, response.statusText, await response.text(), response.headers);
|
|
617
681
|
const result = bedrockResponseToModelResponse((await response.json()));
|
|
618
|
-
|
|
682
|
+
priceAdapterUsage(`bedrock/${model}`, result.usage);
|
|
619
683
|
return result;
|
|
620
684
|
}
|
|
621
685
|
}
|
|
@@ -650,7 +714,7 @@ export class CohereModelProvider {
|
|
|
650
714
|
if (!response.ok)
|
|
651
715
|
throw formatProviderHttpError(this.name, model, response.status, response.statusText, await response.text(), response.headers);
|
|
652
716
|
const result = cohereResponseToModelResponse((await response.json()));
|
|
653
|
-
|
|
717
|
+
priceAdapterUsage(`cohere/${model}`, result.usage);
|
|
654
718
|
return result;
|
|
655
719
|
}
|
|
656
720
|
}
|
|
@@ -732,7 +796,7 @@ export class AnthropicModelProvider {
|
|
|
732
796
|
if (!response.ok)
|
|
733
797
|
throw formatProviderHttpError(this.name, model, response.status, response.statusText, await response.text(), response.headers);
|
|
734
798
|
const result = anthropicResponseToModelResponse((await response.json()));
|
|
735
|
-
|
|
799
|
+
priceAdapterUsage(`anthropic/${model}`, result.usage);
|
|
736
800
|
return result;
|
|
737
801
|
}
|
|
738
802
|
async *stream(request) {
|
|
@@ -776,6 +840,7 @@ export class AnthropicModelProvider {
|
|
|
776
840
|
const thinking = [];
|
|
777
841
|
const toolCallBuffers = new Map();
|
|
778
842
|
let usage;
|
|
843
|
+
let stopReason;
|
|
779
844
|
for await (const event of decodeAnthropicSSE(response.body)) {
|
|
780
845
|
const type = event.event ?? "";
|
|
781
846
|
const data = event.data;
|
|
@@ -822,6 +887,9 @@ export class AnthropicModelProvider {
|
|
|
822
887
|
}
|
|
823
888
|
}
|
|
824
889
|
else if (type === "message_delta") {
|
|
890
|
+
const messageDelta = data.delta;
|
|
891
|
+
if (typeof messageDelta?.stop_reason === "string")
|
|
892
|
+
stopReason = normalizeAnthropicStopReason(messageDelta.stop_reason);
|
|
825
893
|
const u = data.usage;
|
|
826
894
|
if (u) {
|
|
827
895
|
usage = usage ?? {};
|
|
@@ -833,9 +901,6 @@ export class AnthropicModelProvider {
|
|
|
833
901
|
usage.cachedInputTokens = u.cache_read_input_tokens;
|
|
834
902
|
if (typeof u.cache_creation_input_tokens === "number")
|
|
835
903
|
usage.cacheWriteTokens = u.cache_creation_input_tokens;
|
|
836
|
-
if (usage.inputTokens !== undefined || usage.outputTokens !== undefined) {
|
|
837
|
-
usage.totalTokens = (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);
|
|
838
|
-
}
|
|
839
904
|
}
|
|
840
905
|
}
|
|
841
906
|
else if (type === "message_start") {
|
|
@@ -860,14 +925,15 @@ export class AnthropicModelProvider {
|
|
|
860
925
|
toolCalls: [...toolCallBuffers.values()].map((buf, index) => ({
|
|
861
926
|
id: buf.id ?? `anthropic-stream-${index + 1}`,
|
|
862
927
|
name: buf.name ?? "",
|
|
863
|
-
input: buf.args
|
|
928
|
+
input: parseToolArguments(buf.args, stopReason),
|
|
864
929
|
})),
|
|
865
930
|
}
|
|
866
931
|
: {}),
|
|
867
|
-
...(usage ? { usage } : {}),
|
|
932
|
+
...(usage ? { usage: foldSeparateCacheReads(usage) } : {}),
|
|
933
|
+
...(stopReason ? { stopReason } : {}),
|
|
868
934
|
};
|
|
869
935
|
if (done.usage)
|
|
870
|
-
|
|
936
|
+
priceAdapterUsage(`anthropic/${model}`, done.usage);
|
|
871
937
|
yield { done };
|
|
872
938
|
}
|
|
873
939
|
}
|
|
@@ -893,12 +959,14 @@ function estimateUsage(messages) {
|
|
|
893
959
|
const chars = messages.reduce((sum, message) => sum + message.content.length, 0);
|
|
894
960
|
return { totalTokens: Math.ceil(chars / 4) };
|
|
895
961
|
}
|
|
896
|
-
|
|
962
|
+
/** @internal */
|
|
963
|
+
export function calculateRetryDelay(baseMs, attempt) {
|
|
897
964
|
const baseDelay = baseMs * 2 ** (attempt - 1);
|
|
898
965
|
const jittered = baseDelay * (0.75 + Math.random() * 0.5);
|
|
899
966
|
return Math.round(jittered);
|
|
900
967
|
}
|
|
901
|
-
|
|
968
|
+
/** @internal Shared transient-model-error classifier for generate and stream retries. */
|
|
969
|
+
export function isRetryableModelError(error) {
|
|
902
970
|
if (error instanceof ProviderHttpError)
|
|
903
971
|
return error.status === 429 || error.status >= 500;
|
|
904
972
|
if (error instanceof Error && error.name === "AbortError")
|
|
@@ -909,7 +977,8 @@ function isRetryableModelError(error) {
|
|
|
909
977
|
function delay(ms) {
|
|
910
978
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
911
979
|
}
|
|
912
|
-
|
|
980
|
+
/** @internal */
|
|
981
|
+
export function sleepWithAbort(ms, signal) {
|
|
913
982
|
if (signal.aborted)
|
|
914
983
|
return Promise.reject(createAbortError(signal.reason));
|
|
915
984
|
return new Promise((resolve, reject) => {
|
|
@@ -935,7 +1004,7 @@ function createAbortError(reason) {
|
|
|
935
1004
|
err.name = "AbortError";
|
|
936
1005
|
return err;
|
|
937
1006
|
}
|
|
938
|
-
export function toOpenAIMessage(message) {
|
|
1007
|
+
export function toOpenAIMessage(message, options) {
|
|
939
1008
|
if (message.role === "tool") {
|
|
940
1009
|
return {
|
|
941
1010
|
role: "tool",
|
|
@@ -950,8 +1019,44 @@ export function toOpenAIMessage(message) {
|
|
|
950
1019
|
tool_calls: message.toolCalls.map(toOpenAIToolCallForMessage),
|
|
951
1020
|
};
|
|
952
1021
|
}
|
|
1022
|
+
if (message.role === "user" && message.attachments?.length) {
|
|
1023
|
+
const opts = typeof options === "object" && options !== null ? options : {};
|
|
1024
|
+
const { text, native } = partitionModelAttachments(message, {
|
|
1025
|
+
api: opts.api ?? "openai-completions",
|
|
1026
|
+
images: opts.images ?? true,
|
|
1027
|
+
documents: opts.documents ?? false,
|
|
1028
|
+
});
|
|
1029
|
+
if (native.length === 0)
|
|
1030
|
+
return { role: "user", content: text };
|
|
1031
|
+
return {
|
|
1032
|
+
role: "user",
|
|
1033
|
+
content: [
|
|
1034
|
+
...(text ? [{ type: "text", text }] : []),
|
|
1035
|
+
...native.map((attachment) => attachment.type === "document"
|
|
1036
|
+
? {
|
|
1037
|
+
type: "file",
|
|
1038
|
+
file: {
|
|
1039
|
+
filename: attachment.filename ?? "document.pdf",
|
|
1040
|
+
file_data: `data:${attachment.mimeType};base64,${attachment.data}`,
|
|
1041
|
+
},
|
|
1042
|
+
}
|
|
1043
|
+
: {
|
|
1044
|
+
type: "image_url",
|
|
1045
|
+
image_url: { url: `data:${attachment.mimeType};base64,${attachment.data}` },
|
|
1046
|
+
}),
|
|
1047
|
+
],
|
|
1048
|
+
};
|
|
1049
|
+
}
|
|
953
1050
|
return { role: message.role, content: message.content };
|
|
954
1051
|
}
|
|
1052
|
+
function isOpenAIPlatformBaseUrl(baseUrl) {
|
|
1053
|
+
try {
|
|
1054
|
+
return new URL(baseUrl).hostname === "api.openai.com";
|
|
1055
|
+
}
|
|
1056
|
+
catch {
|
|
1057
|
+
return false;
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
955
1060
|
function toOpenAIToolCallForMessage(call) {
|
|
956
1061
|
return {
|
|
957
1062
|
id: call.id,
|
|
@@ -989,16 +1094,116 @@ function normalizeOpenAIParameters(schema) {
|
|
|
989
1094
|
required: Array.isArray(objectSchema.required) ? objectSchema.required : [],
|
|
990
1095
|
};
|
|
991
1096
|
}
|
|
992
|
-
function fromOpenAIToolCall(call) {
|
|
1097
|
+
function fromOpenAIToolCall(call, stopReason) {
|
|
993
1098
|
return {
|
|
994
1099
|
id: call.id,
|
|
995
1100
|
name: call.function.name,
|
|
996
|
-
input:
|
|
1101
|
+
input: parseToolArguments(call.function.arguments ?? "", stopReason),
|
|
997
1102
|
};
|
|
998
1103
|
}
|
|
1104
|
+
/**
|
|
1105
|
+
* Parse streamed or returned tool-call argument JSON. Arguments from a
|
|
1106
|
+
* `length`-truncated response may be incomplete JSON; they are never executed,
|
|
1107
|
+
* so an unparseable truncated payload degrades to `{}` instead of failing the
|
|
1108
|
+
* whole response. Complete responses keep strict parsing.
|
|
1109
|
+
*/
|
|
1110
|
+
function parseToolArguments(args, stopReason) {
|
|
1111
|
+
if (!args)
|
|
1112
|
+
return {};
|
|
1113
|
+
if (stopReason !== "length")
|
|
1114
|
+
return JSON.parse(args);
|
|
1115
|
+
try {
|
|
1116
|
+
return JSON.parse(args);
|
|
1117
|
+
}
|
|
1118
|
+
catch {
|
|
1119
|
+
return {};
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
/** Normalize an OpenAI-compatible `finish_reason`. */
|
|
1123
|
+
function normalizeOpenAIFinishReason(reason) {
|
|
1124
|
+
switch (reason) {
|
|
1125
|
+
case "stop":
|
|
1126
|
+
return "stop";
|
|
1127
|
+
case "length":
|
|
1128
|
+
return "length";
|
|
1129
|
+
case "tool_calls":
|
|
1130
|
+
case "function_call":
|
|
1131
|
+
return "tool_calls";
|
|
1132
|
+
case "content_filter":
|
|
1133
|
+
return "content_filter";
|
|
1134
|
+
default:
|
|
1135
|
+
return "other";
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
function normalizeAnthropicStopReason(reason) {
|
|
1139
|
+
switch (reason) {
|
|
1140
|
+
case "end_turn":
|
|
1141
|
+
case "stop_sequence":
|
|
1142
|
+
return "stop";
|
|
1143
|
+
case "max_tokens":
|
|
1144
|
+
case "model_context_window_exceeded":
|
|
1145
|
+
return "length";
|
|
1146
|
+
case "tool_use":
|
|
1147
|
+
return "tool_calls";
|
|
1148
|
+
case "refusal":
|
|
1149
|
+
return "content_filter";
|
|
1150
|
+
default:
|
|
1151
|
+
return "other";
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
function normalizeGeminiFinishReason(reason) {
|
|
1155
|
+
switch (reason) {
|
|
1156
|
+
case "STOP":
|
|
1157
|
+
return "stop";
|
|
1158
|
+
case "MAX_TOKENS":
|
|
1159
|
+
return "length";
|
|
1160
|
+
case "SAFETY":
|
|
1161
|
+
case "RECITATION":
|
|
1162
|
+
case "BLOCKLIST":
|
|
1163
|
+
case "PROHIBITED_CONTENT":
|
|
1164
|
+
case "SPII":
|
|
1165
|
+
case "IMAGE_SAFETY":
|
|
1166
|
+
return "content_filter";
|
|
1167
|
+
default:
|
|
1168
|
+
return "other";
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
function normalizeBedrockStopReason(reason) {
|
|
1172
|
+
switch (reason) {
|
|
1173
|
+
case "end_turn":
|
|
1174
|
+
case "stop_sequence":
|
|
1175
|
+
return "stop";
|
|
1176
|
+
case "max_tokens":
|
|
1177
|
+
case "model_context_window_exceeded":
|
|
1178
|
+
return "length";
|
|
1179
|
+
case "tool_use":
|
|
1180
|
+
return "tool_calls";
|
|
1181
|
+
case "guardrail_intervened":
|
|
1182
|
+
case "content_filtered":
|
|
1183
|
+
return "content_filter";
|
|
1184
|
+
default:
|
|
1185
|
+
return "other";
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
function normalizeCohereFinishReason(reason) {
|
|
1189
|
+
switch (reason) {
|
|
1190
|
+
case "COMPLETE":
|
|
1191
|
+
case "STOP_SEQUENCE":
|
|
1192
|
+
return "stop";
|
|
1193
|
+
case "MAX_TOKENS":
|
|
1194
|
+
return "length";
|
|
1195
|
+
case "TOOL_CALL":
|
|
1196
|
+
return "tool_calls";
|
|
1197
|
+
default:
|
|
1198
|
+
return "other";
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
999
1201
|
export function openAIChatCompletionToModelResponse(json) {
|
|
1000
1202
|
const choice = json.choices?.[0];
|
|
1001
1203
|
const message = choice?.message;
|
|
1204
|
+
const stopReason = typeof choice?.finish_reason === "string"
|
|
1205
|
+
? normalizeOpenAIFinishReason(choice.finish_reason)
|
|
1206
|
+
: undefined;
|
|
1002
1207
|
const content = openAIMessageText(message?.content);
|
|
1003
1208
|
const reasoning = typeof message?.reasoning_content === "string"
|
|
1004
1209
|
? message.reasoning_content
|
|
@@ -1006,7 +1211,10 @@ export function openAIChatCompletionToModelResponse(json) {
|
|
|
1006
1211
|
const result = {
|
|
1007
1212
|
...(content ? { message: { role: "assistant", content } } : {}),
|
|
1008
1213
|
...(reasoning ? { thinking: reasoning } : {}),
|
|
1009
|
-
...(message?.tool_calls
|
|
1214
|
+
...(message?.tool_calls
|
|
1215
|
+
? { toolCalls: message.tool_calls.map((call) => fromOpenAIToolCall(call, stopReason)) }
|
|
1216
|
+
: {}),
|
|
1217
|
+
...(stopReason ? { stopReason } : {}),
|
|
1010
1218
|
};
|
|
1011
1219
|
if (json.usage) {
|
|
1012
1220
|
const usage = {};
|
|
@@ -1068,6 +1276,7 @@ function toAnthropicMessages(messages) {
|
|
|
1068
1276
|
type: "tool_result",
|
|
1069
1277
|
tool_use_id: message.toolCallId ?? message.name ?? "tool",
|
|
1070
1278
|
content: message.content,
|
|
1279
|
+
...(message.isError ? { is_error: true } : {}),
|
|
1071
1280
|
},
|
|
1072
1281
|
],
|
|
1073
1282
|
};
|
|
@@ -1085,6 +1294,31 @@ function toAnthropicMessages(messages) {
|
|
|
1085
1294
|
],
|
|
1086
1295
|
};
|
|
1087
1296
|
}
|
|
1297
|
+
if (message.role === "user" && message.attachments?.length) {
|
|
1298
|
+
const { text, native } = partitionModelAttachments(message, {
|
|
1299
|
+
api: "anthropic-messages",
|
|
1300
|
+
images: true,
|
|
1301
|
+
documents: true,
|
|
1302
|
+
});
|
|
1303
|
+
if (native.length === 0)
|
|
1304
|
+
return { role: "user", content: text };
|
|
1305
|
+
return {
|
|
1306
|
+
role: "user",
|
|
1307
|
+
content: [
|
|
1308
|
+
...native.map((attachment) => attachment.type === "document"
|
|
1309
|
+
? {
|
|
1310
|
+
type: "document",
|
|
1311
|
+
source: { type: "base64", media_type: attachment.mimeType, data: attachment.data },
|
|
1312
|
+
...(attachment.filename ? { title: attachment.filename } : {}),
|
|
1313
|
+
}
|
|
1314
|
+
: {
|
|
1315
|
+
type: "image",
|
|
1316
|
+
source: { type: "base64", media_type: attachment.mimeType, data: attachment.data },
|
|
1317
|
+
}),
|
|
1318
|
+
...(text ? [{ type: "text", text }] : []),
|
|
1319
|
+
],
|
|
1320
|
+
};
|
|
1321
|
+
}
|
|
1088
1322
|
return {
|
|
1089
1323
|
role: message.role === "assistant" ? "assistant" : "user",
|
|
1090
1324
|
content: message.content,
|
|
@@ -1119,6 +1353,22 @@ function toGeminiRequest(request, model) {
|
|
|
1119
1353
|
functionCall: { name: call.name, args: call.input ?? {} },
|
|
1120
1354
|
})),
|
|
1121
1355
|
};
|
|
1356
|
+
if (message.role === "user" && message.attachments?.length) {
|
|
1357
|
+
const { text, native } = partitionModelAttachments(message, {
|
|
1358
|
+
api: "google-generative-ai",
|
|
1359
|
+
images: true,
|
|
1360
|
+
documents: true,
|
|
1361
|
+
});
|
|
1362
|
+
return {
|
|
1363
|
+
role: "user",
|
|
1364
|
+
parts: [
|
|
1365
|
+
...(text || native.length === 0 ? [{ text }] : []),
|
|
1366
|
+
...native.map((attachment) => ({
|
|
1367
|
+
inlineData: { mimeType: attachment.mimeType, data: attachment.data },
|
|
1368
|
+
})),
|
|
1369
|
+
],
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1122
1372
|
return {
|
|
1123
1373
|
role: message.role === "assistant" ? "model" : "user",
|
|
1124
1374
|
parts: [{ text: message.content }],
|
|
@@ -1165,14 +1415,28 @@ function geminiResponseToModelResponse(json) {
|
|
|
1165
1415
|
: {}),
|
|
1166
1416
|
...(toolCalls.length > 0 ? { toolCalls } : {}),
|
|
1167
1417
|
};
|
|
1418
|
+
const finishReason = json.candidates?.[0]?.finishReason;
|
|
1419
|
+
if (typeof finishReason === "string")
|
|
1420
|
+
result.stopReason = normalizeGeminiFinishReason(finishReason);
|
|
1168
1421
|
if (json.usageMetadata) {
|
|
1169
1422
|
const usage = {};
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
if (
|
|
1175
|
-
usage.
|
|
1423
|
+
const meta = json.usageMetadata;
|
|
1424
|
+
// Gemini bills thinking tokens as output and tool-use prompt tokens as
|
|
1425
|
+
// input; its total includes both, so leaving them out would underprice
|
|
1426
|
+
// the call and leave the total unexplained.
|
|
1427
|
+
if (meta.promptTokenCount !== undefined || meta.toolUsePromptTokenCount !== undefined)
|
|
1428
|
+
usage.inputTokens = (meta.promptTokenCount ?? 0) + (meta.toolUsePromptTokenCount ?? 0);
|
|
1429
|
+
// Output is reported only when the candidates count is: a thoughts count
|
|
1430
|
+
// alone is a fragment of the output, and recording it as the whole
|
|
1431
|
+
// output would price the missing candidate tokens at $0.
|
|
1432
|
+
if (meta.candidatesTokenCount !== undefined)
|
|
1433
|
+
usage.outputTokens = meta.candidatesTokenCount + (meta.thoughtsTokenCount ?? 0);
|
|
1434
|
+
// Cached content is a subset of the prompt count, which is the
|
|
1435
|
+
// `ModelUsage` convention already.
|
|
1436
|
+
if (meta.cachedContentTokenCount !== undefined)
|
|
1437
|
+
usage.cachedInputTokens = meta.cachedContentTokenCount;
|
|
1438
|
+
if (meta.totalTokenCount !== undefined)
|
|
1439
|
+
usage.totalTokens = meta.totalTokenCount;
|
|
1176
1440
|
result.usage = usage;
|
|
1177
1441
|
}
|
|
1178
1442
|
return result;
|
|
@@ -1205,7 +1469,7 @@ function toBedrockRequest(request) {
|
|
|
1205
1469
|
};
|
|
1206
1470
|
return {
|
|
1207
1471
|
role: message.role === "assistant" ? "assistant" : "user",
|
|
1208
|
-
content: [{ text: message
|
|
1472
|
+
content: [{ text: textWithAttachmentPlaceholders(message, "bedrock-converse") }],
|
|
1209
1473
|
};
|
|
1210
1474
|
});
|
|
1211
1475
|
return {
|
|
@@ -1242,15 +1506,24 @@ function bedrockResponseToModelResponse(json) {
|
|
|
1242
1506
|
...(texts.length ? { message: { role: "assistant", content: texts.join("\n") } } : {}),
|
|
1243
1507
|
...(toolCalls.length ? { toolCalls } : {}),
|
|
1244
1508
|
};
|
|
1509
|
+
if (typeof json.stopReason === "string")
|
|
1510
|
+
result.stopReason = normalizeBedrockStopReason(json.stopReason);
|
|
1245
1511
|
if (json.usage) {
|
|
1246
1512
|
const usage = {};
|
|
1247
1513
|
if (json.usage.inputTokens !== undefined)
|
|
1248
1514
|
usage.inputTokens = json.usage.inputTokens;
|
|
1249
1515
|
if (json.usage.outputTokens !== undefined)
|
|
1250
1516
|
usage.outputTokens = json.usage.outputTokens;
|
|
1517
|
+
// Bedrock's total includes prompt-cache reads and writes, reported
|
|
1518
|
+
// outside inputTokens (as Anthropic does); reads are folded into
|
|
1519
|
+
// `inputTokens` below, writes stay separate.
|
|
1520
|
+
if (json.usage.cacheReadInputTokens !== undefined)
|
|
1521
|
+
usage.cachedInputTokens = json.usage.cacheReadInputTokens;
|
|
1522
|
+
if (json.usage.cacheWriteInputTokens !== undefined)
|
|
1523
|
+
usage.cacheWriteTokens = json.usage.cacheWriteInputTokens;
|
|
1251
1524
|
if (json.usage.totalTokens !== undefined)
|
|
1252
1525
|
usage.totalTokens = json.usage.totalTokens;
|
|
1253
|
-
result.usage = usage;
|
|
1526
|
+
result.usage = foldSeparateCacheReads(usage);
|
|
1254
1527
|
}
|
|
1255
1528
|
return result;
|
|
1256
1529
|
}
|
|
@@ -1262,7 +1535,13 @@ function toCohereMessage(message) {
|
|
|
1262
1535
|
: message.role === "tool"
|
|
1263
1536
|
? "tool"
|
|
1264
1537
|
: "user";
|
|
1265
|
-
return { role, content: message
|
|
1538
|
+
return { role, content: textWithAttachmentPlaceholders(message, "cohere-chat") };
|
|
1539
|
+
}
|
|
1540
|
+
/** Text-only adapters: attachments become placeholders appended to the text. */
|
|
1541
|
+
function textWithAttachmentPlaceholders(message, api) {
|
|
1542
|
+
if (!message.attachments?.length)
|
|
1543
|
+
return message.content;
|
|
1544
|
+
return partitionModelAttachments(message, { api, images: false, documents: false }).text;
|
|
1266
1545
|
}
|
|
1267
1546
|
function cohereResponseToModelResponse(json) {
|
|
1268
1547
|
const content = json.message?.content
|
|
@@ -1270,6 +1549,8 @@ function cohereResponseToModelResponse(json) {
|
|
|
1270
1549
|
.filter((text) => typeof text === "string")
|
|
1271
1550
|
.join("\n") ?? "";
|
|
1272
1551
|
const result = content ? { message: { role: "assistant", content } } : {};
|
|
1552
|
+
if (typeof json.finish_reason === "string")
|
|
1553
|
+
result.stopReason = normalizeCohereFinishReason(json.finish_reason);
|
|
1273
1554
|
const billed = json.usage?.billed_units;
|
|
1274
1555
|
if (billed) {
|
|
1275
1556
|
const usage = {};
|
|
@@ -1277,8 +1558,10 @@ function cohereResponseToModelResponse(json) {
|
|
|
1277
1558
|
usage.inputTokens = billed.input_tokens;
|
|
1278
1559
|
if (billed.output_tokens !== undefined)
|
|
1279
1560
|
usage.outputTokens = billed.output_tokens;
|
|
1280
|
-
|
|
1281
|
-
|
|
1561
|
+
// No provider total: synthesize one only from complete counts, so a
|
|
1562
|
+
// missing output count is not mistaken for proof of zero output.
|
|
1563
|
+
if (usage.inputTokens !== undefined && usage.outputTokens !== undefined)
|
|
1564
|
+
usage.totalTokens = usage.inputTokens + usage.outputTokens;
|
|
1282
1565
|
result.usage = usage;
|
|
1283
1566
|
}
|
|
1284
1567
|
return result;
|
|
@@ -1303,6 +1586,8 @@ function anthropicResponseToModelResponse(json) {
|
|
|
1303
1586
|
...(thinkingChunks.length > 0 ? { thinking: thinkingChunks.join("\n") } : {}),
|
|
1304
1587
|
...(toolCalls.length > 0 ? { toolCalls } : {}),
|
|
1305
1588
|
};
|
|
1589
|
+
if (typeof json.stop_reason === "string")
|
|
1590
|
+
result.stopReason = normalizeAnthropicStopReason(json.stop_reason);
|
|
1306
1591
|
if (json.usage) {
|
|
1307
1592
|
const usage = {};
|
|
1308
1593
|
if (json.usage.input_tokens !== undefined)
|
|
@@ -1313,9 +1598,7 @@ function anthropicResponseToModelResponse(json) {
|
|
|
1313
1598
|
usage.cachedInputTokens = json.usage.cache_read_input_tokens;
|
|
1314
1599
|
if (json.usage.cache_creation_input_tokens !== undefined)
|
|
1315
1600
|
usage.cacheWriteTokens = json.usage.cache_creation_input_tokens;
|
|
1316
|
-
|
|
1317
|
-
usage.totalTokens = (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);
|
|
1318
|
-
result.usage = usage;
|
|
1601
|
+
result.usage = foldSeparateCacheReads(usage);
|
|
1319
1602
|
}
|
|
1320
1603
|
return result;
|
|
1321
1604
|
}
|
|
@@ -1412,6 +1695,38 @@ async function* decodeOpenAISSE(stream) {
|
|
|
1412
1695
|
reader.releaseLock();
|
|
1413
1696
|
}
|
|
1414
1697
|
}
|
|
1698
|
+
/**
|
|
1699
|
+
* Normalize usage from a provider that reports prompt-cache reads outside its
|
|
1700
|
+
* input count (Anthropic, Bedrock) to the {@link ModelUsage} convention:
|
|
1701
|
+
* `inputTokens` includes `cachedInputTokens`, and `cacheWriteTokens` stays
|
|
1702
|
+
* separate. An absent input count stays absent. When the provider sent no
|
|
1703
|
+
* total, one is synthesized only from complete counts (input with cache reads,
|
|
1704
|
+
* cache writes and output), so a missing output count stays visibly missing.
|
|
1705
|
+
*/
|
|
1706
|
+
function foldSeparateCacheReads(usage) {
|
|
1707
|
+
if (usage.inputTokens !== undefined && usage.cachedInputTokens !== undefined)
|
|
1708
|
+
usage.inputTokens += usage.cachedInputTokens;
|
|
1709
|
+
if (usage.totalTokens === undefined &&
|
|
1710
|
+
usage.inputTokens !== undefined &&
|
|
1711
|
+
usage.outputTokens !== undefined)
|
|
1712
|
+
usage.totalTokens = usage.inputTokens + (usage.cacheWriteTokens ?? 0) + usage.outputTokens;
|
|
1713
|
+
return usage;
|
|
1714
|
+
}
|
|
1715
|
+
/**
|
|
1716
|
+
* Price an adapter's usage from the static table, but only when the usage is
|
|
1717
|
+
* complete and consistent ({@link hasPriceableUsage}). A cost synthesized from
|
|
1718
|
+
* partial counts (a total the input and output counts do not explain, or a
|
|
1719
|
+
* dropped input count) would be recorded as a known, too-low cost; leaving it
|
|
1720
|
+
* unpriced lets the cost budget's unknown-cost policy classify the call.
|
|
1721
|
+
* Provider-reported `costUsd` is kept as-is.
|
|
1722
|
+
*/
|
|
1723
|
+
function priceAdapterUsage(modelRef, usage) {
|
|
1724
|
+
if (!usage || usage.costUsd !== undefined)
|
|
1725
|
+
return;
|
|
1726
|
+
if (!hasPriceableUsage(usage))
|
|
1727
|
+
return;
|
|
1728
|
+
applyEstimatedCost(modelRef, usage);
|
|
1729
|
+
}
|
|
1415
1730
|
/**
|
|
1416
1731
|
* Decode an Anthropic-style SSE stream — Anthropic emits `event: <type>`
|
|
1417
1732
|
* followed by `data: {...}` for each event. Yields `{ event, data }` pairs.
|
|
@@ -1460,19 +1775,23 @@ export class ProviderHttpError extends Error {
|
|
|
1460
1775
|
provider;
|
|
1461
1776
|
status;
|
|
1462
1777
|
statusText;
|
|
1463
|
-
body;
|
|
1464
1778
|
/**
|
|
1465
1779
|
* Wait duration extracted from a `Retry-After` response header on 429
|
|
1466
1780
|
* responses. When set, the resilience wrapper waits exactly this long
|
|
1467
1781
|
* instead of using exponential backoff.
|
|
1468
1782
|
*/
|
|
1469
1783
|
retryAfterMs;
|
|
1784
|
+
/** Response body, with echoed attachment payloads redacted. */
|
|
1785
|
+
body;
|
|
1470
1786
|
constructor(message, provider, status, statusText, body, retryAfterMs) {
|
|
1471
|
-
|
|
1787
|
+
// A 4xx body often quotes the rejected request, including image and PDF
|
|
1788
|
+
// data URLs. Neither the message nor the body may carry those bytes into
|
|
1789
|
+
// logs, session entries, or events.
|
|
1790
|
+
super(redactAttachmentPayloads(message));
|
|
1472
1791
|
this.provider = provider;
|
|
1473
1792
|
this.status = status;
|
|
1474
1793
|
this.statusText = statusText;
|
|
1475
|
-
this.body = body;
|
|
1794
|
+
this.body = redactAttachmentPayloads(body);
|
|
1476
1795
|
this.name = "ProviderHttpError";
|
|
1477
1796
|
if (retryAfterMs !== undefined && Number.isFinite(retryAfterMs) && retryAfterMs > 0) {
|
|
1478
1797
|
this.retryAfterMs = retryAfterMs;
|