@eum-agent/llm-protocol-openai 1.0.1 → 1.2.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/dist/index.js +2621 -677
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,558 +1,2566 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import
|
|
3
|
-
//#region src/
|
|
4
|
-
|
|
5
|
-
const
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
//#region src/connection-fetch.ts
|
|
4
|
+
function withConnectionHeaders(fetch, headers) {
|
|
5
|
+
const configured = Object.entries(headers ?? {});
|
|
6
|
+
if (configured.length === 0) return fetch;
|
|
7
|
+
return (input, init) => {
|
|
8
|
+
const merged = new Headers(input instanceof Request ? input.headers : void 0);
|
|
9
|
+
for (const [name, value] of new Headers(init?.headers)) merged.set(name, value);
|
|
10
|
+
for (const [name, value] of configured) merged.set(name, value);
|
|
11
|
+
return fetch(input, {
|
|
12
|
+
...init,
|
|
13
|
+
headers: merged
|
|
14
|
+
});
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
//#region src/protocol/probe.ts
|
|
19
|
+
async function readBody$1(response, maxBytes) {
|
|
20
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new Error("invalid response budget");
|
|
21
|
+
const declared = response.headers.get("content-length");
|
|
22
|
+
if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
|
|
23
|
+
await response.body?.cancel();
|
|
24
|
+
throw new Error("read-limit: provider response exceeds its member budget");
|
|
25
|
+
}
|
|
26
|
+
if (!response.body) return {
|
|
27
|
+
text: "",
|
|
28
|
+
bytes: 0
|
|
29
|
+
};
|
|
30
|
+
const reader = response.body.getReader();
|
|
31
|
+
const decoder = new TextDecoder();
|
|
32
|
+
let bytes = 0, text = "";
|
|
33
|
+
try {
|
|
34
|
+
for (;;) {
|
|
35
|
+
const next = await reader.read();
|
|
36
|
+
if (next.done) break;
|
|
37
|
+
bytes += next.value.byteLength;
|
|
38
|
+
if (bytes > maxBytes) {
|
|
39
|
+
await reader.cancel();
|
|
40
|
+
throw new Error("read-limit: provider response exceeds its member budget");
|
|
41
|
+
}
|
|
42
|
+
text += decoder.decode(next.value, { stream: true });
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
text: text + decoder.decode(),
|
|
46
|
+
bytes
|
|
47
|
+
};
|
|
48
|
+
} finally {
|
|
49
|
+
reader.releaseLock();
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
function baseUrlOf(probe) {
|
|
53
|
+
const configured = probe.config.baseUrl;
|
|
54
|
+
return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
|
|
55
|
+
}
|
|
56
|
+
async function refuse(response, maxBytes = 8388608) {
|
|
57
|
+
const body = (await readBody$1(response, maxBytes)).text;
|
|
58
|
+
throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
|
|
59
|
+
}
|
|
60
|
+
function headers(probe) {
|
|
61
|
+
return {
|
|
62
|
+
...probe.options.allowUnauthenticated === true && !probe.secrets.apiKey ? {} : { authorization: `Bearer ${probe.secrets.apiKey ?? ""}` },
|
|
63
|
+
"content-type": "application/json"
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
function record$1(value) {
|
|
67
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
68
|
+
}
|
|
69
|
+
function count(value) {
|
|
70
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
|
|
71
|
+
}
|
|
72
|
+
function strings(value, allowEmpty = false) {
|
|
73
|
+
return Array.isArray(value) && value.every((one) => typeof one === "string") && (allowEmpty || value.length > 0) ? value : void 0;
|
|
74
|
+
}
|
|
75
|
+
const EFFORT_SHAPES = [
|
|
76
|
+
{
|
|
77
|
+
at: (row) => record$1(row.effort),
|
|
78
|
+
levels: "supported_levels",
|
|
79
|
+
fallback: "default_level"
|
|
12
80
|
},
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
81
|
+
{
|
|
82
|
+
at: (row) => record$1(row.reasoning_efforts),
|
|
83
|
+
levels: "valid_efforts",
|
|
84
|
+
fallback: "default_effort"
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
at: (row) => record$1(record$1(row.reasoning)?.effort),
|
|
88
|
+
levels: "valid",
|
|
89
|
+
fallback: "default"
|
|
90
|
+
}
|
|
91
|
+
];
|
|
92
|
+
function effortsOf(row) {
|
|
93
|
+
for (const shape of EFFORT_SHAPES) {
|
|
94
|
+
const object = shape.at(row);
|
|
95
|
+
const efforts = strings(object?.[shape.levels]);
|
|
96
|
+
if (efforts === void 0) continue;
|
|
97
|
+
const fallback = object?.[shape.fallback];
|
|
98
|
+
return typeof fallback === "string" && efforts.includes(fallback) ? {
|
|
99
|
+
efforts,
|
|
100
|
+
defaultEffort: fallback
|
|
101
|
+
} : { efforts };
|
|
102
|
+
}
|
|
103
|
+
return {};
|
|
104
|
+
}
|
|
105
|
+
function offerOf(row, id) {
|
|
106
|
+
const limit = record$1(row.limit);
|
|
107
|
+
const modalities = record$1(row.modalities);
|
|
108
|
+
const contextWindow = count(row.context_window) ?? count(row.context_length) ?? count(limit?.context);
|
|
109
|
+
const maxOutput = count(row.max_output_tokens) ?? count(row.max_output_length);
|
|
110
|
+
const features = strings(row.supported_features, true);
|
|
111
|
+
const sampling = strings(row.supported_sampling_parameters, true);
|
|
112
|
+
const reasoning = typeof row.supports_reasoning === "boolean" ? row.supports_reasoning : features?.includes("reasoning");
|
|
113
|
+
const { efforts, defaultEffort } = effortsOf(row);
|
|
114
|
+
const flagged = typeof row.supports_image_in === "boolean" || typeof row.supports_video_in === "boolean" ? [
|
|
115
|
+
"text",
|
|
116
|
+
...row.supports_image_in === true ? ["image"] : [],
|
|
117
|
+
...row.supports_video_in === true ? ["video"] : []
|
|
118
|
+
] : void 0;
|
|
119
|
+
const input = strings(row.input_modalities) ?? flagged ?? strings(modalities?.input);
|
|
120
|
+
const output = strings(row.output_modalities) ?? strings(modalities?.output);
|
|
121
|
+
return {
|
|
122
|
+
model: id,
|
|
123
|
+
...typeof row.name === "string" && row.name !== "" ? { name: row.name } : {},
|
|
124
|
+
...contextWindow === void 0 ? {} : { contextWindow },
|
|
125
|
+
...maxOutput === void 0 ? {} : { maxOutput },
|
|
126
|
+
...reasoning === void 0 ? {} : { reasoning },
|
|
127
|
+
...features === void 0 ? {} : { toolCall: features.includes("tools") },
|
|
128
|
+
...sampling === void 0 ? {} : { temperature: sampling.includes("temperature") },
|
|
129
|
+
...input === void 0 ? {} : { input },
|
|
130
|
+
...output === void 0 ? {} : { output },
|
|
131
|
+
...efforts === void 0 ? {} : { efforts },
|
|
132
|
+
...defaultEffort === void 0 ? {} : { defaultEffort }
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
const probeOpenAI = {
|
|
136
|
+
async listModels(probe, fetcher = globalThis.fetch) {
|
|
137
|
+
const response = await fetcher(`${baseUrlOf(probe)}/models`, {
|
|
138
|
+
method: "GET",
|
|
139
|
+
headers: headers(probe),
|
|
140
|
+
signal: probe.signal
|
|
141
|
+
});
|
|
142
|
+
if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
|
|
143
|
+
return (JSON.parse((await readBody$1(response, probe.maxResponseBytes ?? 8388608)).text).data ?? []).flatMap((row) => typeof row.id === "string" ? [offerOf(row, row.id)] : []);
|
|
144
|
+
},
|
|
145
|
+
async testConnection(probe, fetcher = globalThis.fetch, protocol = "chat-completions") {
|
|
146
|
+
if (probe.model !== void 0) {
|
|
147
|
+
probe.signal.throwIfAborted();
|
|
148
|
+
const attempt = probe.accountingDispatch?.attempt(0);
|
|
149
|
+
let succeeded = false;
|
|
150
|
+
let submitted = false;
|
|
151
|
+
try {
|
|
152
|
+
const response = await fetcher(`${baseUrlOf(probe)}/${protocol === "responses" ? "responses" : "chat/completions"}`, {
|
|
153
|
+
method: "POST",
|
|
154
|
+
headers: headers(probe),
|
|
155
|
+
body: JSON.stringify(protocol === "responses" ? {
|
|
156
|
+
model: probe.model,
|
|
157
|
+
input: [{
|
|
158
|
+
role: "user",
|
|
159
|
+
content: "ping"
|
|
160
|
+
}],
|
|
161
|
+
max_output_tokens: 16,
|
|
162
|
+
store: false
|
|
163
|
+
} : {
|
|
164
|
+
model: probe.model,
|
|
165
|
+
max_tokens: 1,
|
|
166
|
+
messages: [{
|
|
167
|
+
role: "user",
|
|
168
|
+
content: "ping"
|
|
169
|
+
}]
|
|
170
|
+
}),
|
|
171
|
+
signal: probe.signal
|
|
172
|
+
});
|
|
173
|
+
submitted = true;
|
|
174
|
+
const received = await readBody$1(response, probe.maxResponseBytes ?? 8388608);
|
|
175
|
+
if (attempt && received.text) try {
|
|
176
|
+
const usage = record$1(record$1(JSON.parse(received.text))?.usage);
|
|
177
|
+
if (usage) {
|
|
178
|
+
const field = (value) => typeof value === "number" ? value : void 0;
|
|
179
|
+
const details = record$1(usage.prompt_tokens_details ?? usage.input_tokens_details);
|
|
180
|
+
attempt.report({
|
|
181
|
+
sequence: 1,
|
|
182
|
+
inputTokens: field(usage.prompt_tokens ?? usage.input_tokens),
|
|
183
|
+
outputTokens: field(usage.completion_tokens ?? usage.output_tokens),
|
|
184
|
+
totalTokens: field(usage.total_tokens),
|
|
185
|
+
cacheReadTokens: field(details?.cached_tokens ?? usage.prompt_cache_hit_tokens)
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
} catch {}
|
|
189
|
+
if (!response.ok) throw Object.assign(new Error(received.text || response.statusText), { status: response.status });
|
|
190
|
+
succeeded = true;
|
|
191
|
+
return;
|
|
192
|
+
} finally {
|
|
193
|
+
attempt?.end({
|
|
194
|
+
outcome: succeeded ? "success" : probe.signal.aborted ? "cancelled" : "failed",
|
|
195
|
+
submission: submitted ? "submitted" : "unknown"
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
await probeOpenAI.listModels(probe, fetcher);
|
|
17
200
|
}
|
|
18
201
|
};
|
|
19
202
|
//#endregion
|
|
20
|
-
//#region src/
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
/** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
|
|
27
|
-
* every other status is not. */
|
|
28
|
-
function isRetryableStatus(status) {
|
|
29
|
-
return status === 408 || status === 409 || status === 429 || status !== void 0 && status >= 500;
|
|
203
|
+
//#region src/decisions/body.ts
|
|
204
|
+
var ResponseBodyLimitError = class extends Error {};
|
|
205
|
+
async function cancelBody(response) {
|
|
206
|
+
try {
|
|
207
|
+
await response.body?.cancel();
|
|
208
|
+
} catch {}
|
|
30
209
|
}
|
|
31
|
-
function
|
|
32
|
-
if (!(
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
210
|
+
async function readBody(response, maxBytes, signal) {
|
|
211
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) {
|
|
212
|
+
await cancelBody(response);
|
|
213
|
+
throw new ResponseBodyLimitError("Invalid response byte budget.");
|
|
214
|
+
}
|
|
215
|
+
const declared = response.headers.get("content-length");
|
|
216
|
+
if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
|
|
217
|
+
await cancelBody(response);
|
|
218
|
+
throw new ResponseBodyLimitError("Response exceeds its byte budget.");
|
|
219
|
+
}
|
|
220
|
+
if (!response.body) {
|
|
221
|
+
signal.throwIfAborted();
|
|
222
|
+
return "";
|
|
223
|
+
}
|
|
224
|
+
const reader = response.body.getReader();
|
|
225
|
+
const decoder = new TextDecoder();
|
|
226
|
+
let bytes = 0;
|
|
227
|
+
let text = "";
|
|
228
|
+
let cancellation;
|
|
229
|
+
const abort = () => {
|
|
230
|
+
cancellation ??= reader.cancel().catch(() => {});
|
|
231
|
+
};
|
|
232
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
233
|
+
try {
|
|
234
|
+
if (signal.aborted) abort();
|
|
235
|
+
for (;;) {
|
|
236
|
+
signal.throwIfAborted();
|
|
237
|
+
const next = await reader.read();
|
|
238
|
+
signal.throwIfAborted();
|
|
239
|
+
if (next.done) return text + decoder.decode();
|
|
240
|
+
bytes += next.value.byteLength;
|
|
241
|
+
if (bytes > maxBytes) throw new ResponseBodyLimitError("Response exceeds its byte budget.");
|
|
242
|
+
text += decoder.decode(next.value, { stream: true });
|
|
243
|
+
}
|
|
244
|
+
} catch (error) {
|
|
245
|
+
await (cancellation ?? reader.cancel().catch(() => {}));
|
|
246
|
+
throw error;
|
|
247
|
+
} finally {
|
|
248
|
+
signal.removeEventListener("abort", abort);
|
|
249
|
+
reader.releaseLock();
|
|
250
|
+
}
|
|
39
251
|
}
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
retryable: false
|
|
49
|
-
});
|
|
50
|
-
const rawCode = error.code ?? error.type;
|
|
51
|
-
const providerCode = typeof rawCode === "string" && (/* @__PURE__ */ new Set([
|
|
52
|
-
"usage_not_included",
|
|
53
|
-
"usage_limit_reached",
|
|
54
|
-
"insufficient_quota",
|
|
55
|
-
"context_length_exceeded",
|
|
56
|
-
"rate_limit_exceeded",
|
|
57
|
-
"overloaded_error",
|
|
58
|
-
"api_error",
|
|
59
|
-
"rate_limit_error",
|
|
60
|
-
"cyber_policy",
|
|
61
|
-
"invalid_prompt",
|
|
62
|
-
"bio_policy",
|
|
63
|
-
"misalignment_policy_violation"
|
|
64
|
-
])).has(rawCode) ? rawCode : void 0;
|
|
65
|
-
const connection = error instanceof APIConnectionError;
|
|
66
|
-
const status = Number.isInteger(error.status) && Number(error.status) >= 100 && Number(error.status) <= 599 ? error.status : void 0;
|
|
67
|
-
return failures.create({
|
|
68
|
-
code: connection ? "stream-interrupted" : status === 413 ? "request-too-large" : status === void 0 ? "provider-error" : "http-error",
|
|
69
|
-
stage: connection ? "transport" : status === 413 ? "request" : status === void 0 ? "stream" : "transport",
|
|
70
|
-
category: connection ? "network" : status === 413 ? "request-too-large" : "provider",
|
|
71
|
-
source: connection ? "transport" : "protocol",
|
|
72
|
-
...status === void 0 ? {} : { status },
|
|
73
|
-
retryable: connection || isRetryableStatus(status),
|
|
74
|
-
...providerCode === void 0 ? {} : { providerCode }
|
|
252
|
+
//#endregion
|
|
253
|
+
//#region src/decisions/failure.ts
|
|
254
|
+
function openAIDecisionsFailure(code, message, retryable = false) {
|
|
255
|
+
const error = new Error(message);
|
|
256
|
+
error.name = "DecisionFailure";
|
|
257
|
+
Object.assign(error, {
|
|
258
|
+
code,
|
|
259
|
+
retryable
|
|
75
260
|
});
|
|
261
|
+
return error;
|
|
262
|
+
}
|
|
263
|
+
function openAIDecisionsStatusFailure(status) {
|
|
264
|
+
if (status === 401 || status === 403) return openAIDecisionsFailure("credential-unavailable", "The connection credential was rejected.");
|
|
265
|
+
if (status === 429) return openAIDecisionsFailure("quota", "The decision service rate or quota limit was reached.", true);
|
|
266
|
+
if (status === 408 || status === 504) return openAIDecisionsFailure("timeout", "The decision service did not answer in time.", true);
|
|
267
|
+
return openAIDecisionsFailure("provider", "The decision service request failed.");
|
|
76
268
|
}
|
|
77
269
|
//#endregion
|
|
78
|
-
//#region src/
|
|
79
|
-
function
|
|
80
|
-
|
|
81
|
-
|
|
270
|
+
//#region src/decisions/request.ts
|
|
271
|
+
function questionOf(name, question) {
|
|
272
|
+
if (question.type === "noul") return {
|
|
273
|
+
name,
|
|
274
|
+
type: "predicate",
|
|
275
|
+
instructions: question.criteria ? `${question.instructions}\n\nOutcome criteria:\n${JSON.stringify(question.criteria)}` : question.instructions
|
|
276
|
+
};
|
|
277
|
+
if (question.type === "choice") return {
|
|
278
|
+
name,
|
|
279
|
+
type: "choice",
|
|
280
|
+
instructions: question.instructions,
|
|
281
|
+
choices: Object.entries(question.criteria).map(([value, description]) => ({
|
|
282
|
+
value,
|
|
283
|
+
...description === null ? {} : { description }
|
|
284
|
+
}))
|
|
285
|
+
};
|
|
286
|
+
return {
|
|
287
|
+
name,
|
|
288
|
+
type: "score",
|
|
289
|
+
instructions: question.instructions,
|
|
290
|
+
levels: question.criteria.map((label) => ({ label }))
|
|
291
|
+
};
|
|
82
292
|
}
|
|
83
|
-
function
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
293
|
+
function buildOpenAIDecisionsRequest(request, model) {
|
|
294
|
+
const content = [{
|
|
295
|
+
type: "input_text",
|
|
296
|
+
text: typeof request.state === "string" ? request.state : JSON.stringify(request.state)
|
|
297
|
+
}];
|
|
298
|
+
for (const image of request.images) {
|
|
299
|
+
content.push({
|
|
300
|
+
type: "input_text",
|
|
301
|
+
text: `[image: ${image.label}]`
|
|
302
|
+
});
|
|
303
|
+
content.push({
|
|
304
|
+
type: "input_image",
|
|
305
|
+
image_url: `data:${image.mediaType};base64,${Buffer.from(image.bytes).toString("base64")}`
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
model,
|
|
310
|
+
input: [{
|
|
311
|
+
role: "user",
|
|
312
|
+
content
|
|
313
|
+
}],
|
|
314
|
+
questions: Object.entries(request.questions).map(([name, question]) => questionOf(name, question))
|
|
315
|
+
};
|
|
93
316
|
}
|
|
94
|
-
|
|
317
|
+
//#endregion
|
|
318
|
+
//#region src/decisions/response.ts
|
|
319
|
+
const INVALID = "The decision service returned an unusable answer.";
|
|
320
|
+
function invalid$1() {
|
|
321
|
+
return openAIDecisionsFailure("invalid-response", INVALID);
|
|
322
|
+
}
|
|
323
|
+
function probability(value) {
|
|
324
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) throw invalid$1();
|
|
325
|
+
return value;
|
|
326
|
+
}
|
|
327
|
+
function distribution(value, question) {
|
|
328
|
+
const keys = Object.keys(question.criteria);
|
|
329
|
+
if (!Array.isArray(value) || value.length !== keys.length) throw invalid$1();
|
|
330
|
+
const result = Object.create(null);
|
|
331
|
+
for (const entry of value) {
|
|
332
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw invalid$1();
|
|
333
|
+
const raw = entry;
|
|
334
|
+
if (question.type === "choice" ? typeof raw.value !== "string" : typeof raw.value !== "number" || !Number.isInteger(raw.value)) throw invalid$1();
|
|
335
|
+
const key = String(raw.value);
|
|
336
|
+
if (!keys.includes(key) || Object.hasOwn(result, key)) throw invalid$1();
|
|
337
|
+
if (question.type === "score" && raw.label !== question.criteria[Number(key)]) throw invalid$1();
|
|
338
|
+
result[key] = probability(raw.probability);
|
|
339
|
+
}
|
|
340
|
+
return result;
|
|
341
|
+
}
|
|
342
|
+
function answerOf(raw, question) {
|
|
343
|
+
if (raw.type !== (question.type === "noul" ? "predicate" : question.type)) throw invalid$1();
|
|
344
|
+
if (question.type === "noul") return {
|
|
345
|
+
type: "noul",
|
|
346
|
+
probability: probability(raw.probability)
|
|
347
|
+
};
|
|
348
|
+
const keys = Object.keys(question.criteria);
|
|
349
|
+
const probabilities = distribution(raw.probabilities, question);
|
|
350
|
+
const confidence = raw.confidence === void 0 ? {} : { confidence: probability(raw.confidence) };
|
|
351
|
+
if (question.type === "choice") {
|
|
352
|
+
if (typeof raw.choice !== "string" || !keys.includes(raw.choice)) throw invalid$1();
|
|
353
|
+
return {
|
|
354
|
+
type: "choice",
|
|
355
|
+
choice: raw.choice,
|
|
356
|
+
probabilities,
|
|
357
|
+
...confidence
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
const score = raw.score;
|
|
361
|
+
if (typeof score !== "number" || !Number.isFinite(score) || score < 0 || score > keys.length - 1) throw invalid$1();
|
|
362
|
+
const expected = question.criteria.reduce((total, _level, index) => total + index * probabilities[String(index)], 0);
|
|
363
|
+
if (Math.abs(expected - score) > 1e-6) throw invalid$1();
|
|
95
364
|
return {
|
|
96
|
-
type: "
|
|
97
|
-
|
|
365
|
+
type: "score",
|
|
366
|
+
score,
|
|
367
|
+
probabilities,
|
|
368
|
+
...confidence
|
|
98
369
|
};
|
|
99
370
|
}
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
if (!
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
371
|
+
function normalizeOpenAIDecisionsResponse(payload, request) {
|
|
372
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) throw invalid$1();
|
|
373
|
+
const envelope = payload;
|
|
374
|
+
const list = envelope.answers;
|
|
375
|
+
if (!Array.isArray(list)) throw invalid$1();
|
|
376
|
+
const ids = Object.keys(request.questions);
|
|
377
|
+
if (list.length !== ids.length) throw invalid$1();
|
|
378
|
+
const normalized = Object.create(null);
|
|
379
|
+
for (const item of list) {
|
|
380
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) throw invalid$1();
|
|
381
|
+
const raw = item;
|
|
382
|
+
const name = raw.name;
|
|
383
|
+
if (typeof name !== "string" || !Object.hasOwn(request.questions, name)) throw invalid$1();
|
|
384
|
+
if (Object.hasOwn(normalized, name)) throw invalid$1();
|
|
385
|
+
normalized[name] = answerOf(raw, request.questions[name]);
|
|
386
|
+
}
|
|
387
|
+
const usage = envelope.usage;
|
|
388
|
+
if (usage === void 0) return { answers: normalized };
|
|
389
|
+
if (!usage || typeof usage !== "object") throw invalid$1();
|
|
390
|
+
const inputTokens = usage.input_tokens;
|
|
391
|
+
if (inputTokens === void 0) return { answers: normalized };
|
|
392
|
+
if (typeof inputTokens !== "number" || !Number.isInteger(inputTokens) || inputTokens < 0) throw invalid$1();
|
|
393
|
+
return {
|
|
394
|
+
answers: normalized,
|
|
395
|
+
usage: { inputTokens }
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
//#endregion
|
|
399
|
+
//#region src/decisions/protocol.ts
|
|
400
|
+
const TIMEOUT_MS$1 = 6e4;
|
|
401
|
+
const RESPONSE_LIMIT$1 = 8388608;
|
|
402
|
+
const options$1 = z.strictObject({ timeoutMs: z.number().int().min(1e3).max(3e5).optional() });
|
|
403
|
+
function decisionsProtocolType(networkFetch) {
|
|
404
|
+
return {
|
|
405
|
+
type: "openai-decisions",
|
|
406
|
+
label: "OpenAI Decisions API",
|
|
407
|
+
fields: [{
|
|
408
|
+
key: "baseUrl",
|
|
409
|
+
kind: "url",
|
|
410
|
+
label: "Base URL",
|
|
411
|
+
required: true
|
|
412
|
+
}],
|
|
413
|
+
userConfigurable: true,
|
|
414
|
+
optionsSchema: options$1,
|
|
415
|
+
adapters: { decision: {
|
|
416
|
+
limits: () => ({
|
|
417
|
+
images: true,
|
|
418
|
+
maxQuestions: 32,
|
|
419
|
+
maxChoiceOptions: 20,
|
|
420
|
+
maxScoreLevels: 10
|
|
421
|
+
}),
|
|
422
|
+
async evaluate({ request, signal, call }) {
|
|
423
|
+
if (signal.aborted) throw openAIDecisionsFailure("cancelled", "The decision request was cancelled.");
|
|
424
|
+
const timeoutMs = options$1.parse(call.options).timeoutMs ?? TIMEOUT_MS$1;
|
|
425
|
+
const baseUrl = typeof call.config.baseUrl === "string" ? call.config.baseUrl : "";
|
|
426
|
+
if (!baseUrl) throw openAIDecisionsFailure("unavailable", "The connection has no address.");
|
|
427
|
+
const apiKey = call.secrets.apiKey;
|
|
428
|
+
if (!apiKey) throw openAIDecisionsFailure("credential-unavailable", "The connection credential is missing.");
|
|
429
|
+
const body = buildOpenAIDecisionsRequest(request, call.model);
|
|
430
|
+
const deadline = AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
|
|
431
|
+
const accounting = call.accountingDispatch?.attempt(0);
|
|
432
|
+
let outcome = "failed";
|
|
433
|
+
let submission = "unknown";
|
|
434
|
+
try {
|
|
435
|
+
let response;
|
|
436
|
+
try {
|
|
437
|
+
response = await withConnectionHeaders(networkFetch, call.headers)(`${baseUrl.replace(/\/+$/, "")}/decisions`, {
|
|
438
|
+
method: "POST",
|
|
439
|
+
headers: {
|
|
440
|
+
"Content-Type": "application/json",
|
|
441
|
+
Authorization: `Bearer ${apiKey}`
|
|
442
|
+
},
|
|
443
|
+
body: JSON.stringify(body),
|
|
444
|
+
signal: deadline
|
|
445
|
+
});
|
|
446
|
+
} catch {
|
|
447
|
+
if (signal.aborted) throw openAIDecisionsFailure("cancelled", "The decision request was cancelled.");
|
|
448
|
+
if (deadline.aborted) throw openAIDecisionsFailure("timeout", "The decision service timed out.", true);
|
|
449
|
+
throw openAIDecisionsFailure("network", "The decision service could not be reached.", true);
|
|
450
|
+
}
|
|
451
|
+
submission = "submitted";
|
|
452
|
+
if (!response.ok) {
|
|
453
|
+
await cancelBody(response);
|
|
454
|
+
throw openAIDecisionsStatusFailure(response.status);
|
|
455
|
+
}
|
|
456
|
+
let text;
|
|
457
|
+
try {
|
|
458
|
+
text = await readBody(response, RESPONSE_LIMIT$1, deadline);
|
|
459
|
+
} catch (error) {
|
|
460
|
+
if (error instanceof ResponseBodyLimitError) throw openAIDecisionsFailure("invalid-response", "The decision service response was too large.");
|
|
461
|
+
if (signal.aborted) throw openAIDecisionsFailure("cancelled", "The decision request was cancelled.");
|
|
462
|
+
if (deadline.aborted) throw openAIDecisionsFailure("timeout", "The decision service timed out.", true);
|
|
463
|
+
throw openAIDecisionsFailure("network", "The decision response could not be read.");
|
|
464
|
+
}
|
|
465
|
+
let payload;
|
|
466
|
+
try {
|
|
467
|
+
payload = JSON.parse(text);
|
|
468
|
+
} catch {
|
|
469
|
+
throw openAIDecisionsFailure("invalid-response", "The decision service response was not JSON.");
|
|
470
|
+
}
|
|
471
|
+
const usage = payload && typeof payload === "object" ? payload.usage : void 0;
|
|
472
|
+
if (typeof usage?.input_tokens === "number") accounting?.report({
|
|
473
|
+
sequence: 1,
|
|
474
|
+
inputTokens: usage.input_tokens
|
|
475
|
+
});
|
|
476
|
+
const result = normalizeOpenAIDecisionsResponse(payload, request);
|
|
477
|
+
outcome = "success";
|
|
478
|
+
return result;
|
|
479
|
+
} finally {
|
|
480
|
+
accounting?.end({
|
|
481
|
+
outcome: signal.aborted ? "cancelled" : outcome,
|
|
482
|
+
submission
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
} },
|
|
487
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, withConnectionHeaders(networkFetch, probe.headers)) }),
|
|
488
|
+
testConnection: (probe) => probeOpenAI.listModels(probe, withConnectionHeaders(networkFetch, probe.headers)).then(() => {})
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
//#endregion
|
|
492
|
+
//#region src/embeddings/failure.ts
|
|
493
|
+
function openAIEmbeddingsFailure(code, message, retryable = false) {
|
|
494
|
+
const error = new Error(message);
|
|
495
|
+
error.name = "EmbeddingFailure";
|
|
496
|
+
return Object.assign(error, {
|
|
497
|
+
code,
|
|
498
|
+
retryable
|
|
499
|
+
});
|
|
500
|
+
}
|
|
501
|
+
function openAIEmbeddingsStatusFailure(status) {
|
|
502
|
+
if (status === 401 || status === 403) return openAIEmbeddingsFailure("credential-unavailable", "The connection credential was rejected.");
|
|
503
|
+
if (status === 429) return openAIEmbeddingsFailure("quota", "The embedding service rate or quota limit was reached.", true);
|
|
504
|
+
if (status === 408 || status === 504) return openAIEmbeddingsFailure("timeout", "The embedding service did not answer in time.", true);
|
|
505
|
+
return openAIEmbeddingsFailure("provider", "The embedding service request failed.");
|
|
506
|
+
}
|
|
507
|
+
//#endregion
|
|
508
|
+
//#region src/embeddings/models.ts
|
|
509
|
+
const shared = {
|
|
510
|
+
inputKinds: ["text"],
|
|
511
|
+
maxInputs: 2048,
|
|
512
|
+
maxInputTokens: 8192,
|
|
513
|
+
maxBatchInputTokens: 3e5,
|
|
514
|
+
purposeAware: false,
|
|
515
|
+
normalized: true
|
|
516
|
+
};
|
|
517
|
+
const openAIEmbeddingModels = {
|
|
518
|
+
"text-embedding-3-small": {
|
|
519
|
+
...shared,
|
|
520
|
+
dimensions: {
|
|
521
|
+
default: 1536,
|
|
522
|
+
range: {
|
|
523
|
+
min: 1,
|
|
524
|
+
max: 1536
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
},
|
|
528
|
+
"text-embedding-3-large": {
|
|
529
|
+
...shared,
|
|
530
|
+
dimensions: {
|
|
531
|
+
default: 3072,
|
|
532
|
+
range: {
|
|
533
|
+
min: 1,
|
|
534
|
+
max: 3072
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
function openAIEmbeddingLimits(model) {
|
|
540
|
+
return Object.hasOwn(openAIEmbeddingModels, model) ? openAIEmbeddingModels[model] : void 0;
|
|
541
|
+
}
|
|
542
|
+
//#endregion
|
|
543
|
+
//#region src/embeddings/request.ts
|
|
544
|
+
function buildOpenAIEmbeddingsRequest(request, model, params) {
|
|
545
|
+
return {
|
|
546
|
+
model,
|
|
547
|
+
input: request.inputs.map((one) => one.text),
|
|
548
|
+
encoding_format: "float",
|
|
549
|
+
...typeof params.dimensions === "number" ? { dimensions: params.dimensions } : {}
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
//#endregion
|
|
553
|
+
//#region src/embeddings/response.ts
|
|
554
|
+
function invalid() {
|
|
555
|
+
return openAIEmbeddingsFailure("invalid-response", "The embedding service returned an unusable response.");
|
|
556
|
+
}
|
|
557
|
+
function record(value) {
|
|
558
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid();
|
|
559
|
+
return value;
|
|
560
|
+
}
|
|
561
|
+
function normalizeOpenAIEmbeddingsResponse(payload, inputCount) {
|
|
562
|
+
const envelope = record(payload);
|
|
563
|
+
const data = envelope.data;
|
|
564
|
+
if (!Array.isArray(data) || data.length !== inputCount) throw invalid();
|
|
565
|
+
const vectors = new Array(inputCount);
|
|
566
|
+
for (const item of data) {
|
|
567
|
+
const raw = record(item);
|
|
568
|
+
const index = raw.index;
|
|
569
|
+
if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index >= inputCount || vectors[index] !== void 0) throw invalid();
|
|
570
|
+
const values = raw.embedding;
|
|
571
|
+
if (!Array.isArray(values) || !values.every((one) => typeof one === "number")) throw invalid();
|
|
572
|
+
vectors[index] = Float32Array.from(values);
|
|
573
|
+
}
|
|
574
|
+
const usage = envelope.usage;
|
|
575
|
+
if (usage === void 0) return { vectors };
|
|
576
|
+
const inputTokens = record(usage).prompt_tokens;
|
|
577
|
+
if (inputTokens === void 0) return { vectors };
|
|
578
|
+
if (typeof inputTokens !== "number" || !Number.isInteger(inputTokens) || inputTokens < 0) throw invalid();
|
|
579
|
+
return {
|
|
580
|
+
vectors,
|
|
581
|
+
usage: { inputTokens }
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
//#endregion
|
|
585
|
+
//#region src/embeddings/protocol.ts
|
|
586
|
+
const TIMEOUT_MS = 6e4;
|
|
587
|
+
const RESPONSE_LIMIT = 67108864;
|
|
588
|
+
const options = z.strictObject({ timeoutMs: z.number().int().min(1e3).max(3e5).optional() });
|
|
589
|
+
function cancelled() {
|
|
590
|
+
return openAIEmbeddingsFailure("cancelled", "The embedding request was cancelled.");
|
|
591
|
+
}
|
|
592
|
+
function timedOut() {
|
|
593
|
+
return openAIEmbeddingsFailure("timeout", "The embedding service timed out.", true);
|
|
594
|
+
}
|
|
595
|
+
function embeddingsProtocolType(networkFetch) {
|
|
596
|
+
return {
|
|
597
|
+
type: "openai-embeddings",
|
|
598
|
+
label: "OpenAI Embeddings API",
|
|
599
|
+
fields: [{
|
|
600
|
+
key: "baseUrl",
|
|
601
|
+
kind: "url",
|
|
602
|
+
label: "Base URL",
|
|
603
|
+
required: true
|
|
604
|
+
}],
|
|
605
|
+
userConfigurable: true,
|
|
606
|
+
optionsSchema: options,
|
|
607
|
+
adapters: { embedding: {
|
|
608
|
+
limits({ ref }) {
|
|
609
|
+
const limits = openAIEmbeddingLimits(ref.model);
|
|
610
|
+
if (!limits) throw openAIEmbeddingsFailure("unsupported", "The embedding model is not supported.");
|
|
611
|
+
return limits;
|
|
612
|
+
},
|
|
613
|
+
async embed({ request, params, signal, call }) {
|
|
614
|
+
if (signal.aborted) throw cancelled();
|
|
615
|
+
const timeoutMs = options.parse(call.options).timeoutMs ?? TIMEOUT_MS;
|
|
616
|
+
const baseUrl = typeof call.config.baseUrl === "string" ? call.config.baseUrl : "";
|
|
617
|
+
if (!baseUrl) throw openAIEmbeddingsFailure("unavailable", "The connection has no address.");
|
|
618
|
+
const apiKey = call.secrets.apiKey;
|
|
619
|
+
if (!apiKey) throw openAIEmbeddingsFailure("credential-unavailable", "The connection credential is missing.");
|
|
620
|
+
const body = buildOpenAIEmbeddingsRequest(request, call.model, params);
|
|
621
|
+
const deadline = AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]);
|
|
622
|
+
const accounting = call.accountingDispatch?.attempt(0);
|
|
623
|
+
let outcome = "failed";
|
|
624
|
+
let submission = "unknown";
|
|
625
|
+
try {
|
|
626
|
+
let response;
|
|
627
|
+
try {
|
|
628
|
+
response = await withConnectionHeaders(networkFetch, call.headers)(`${baseUrl.replace(/\/+$/, "")}/embeddings`, {
|
|
629
|
+
method: "POST",
|
|
630
|
+
headers: {
|
|
631
|
+
"Content-Type": "application/json",
|
|
632
|
+
Authorization: `Bearer ${apiKey}`
|
|
633
|
+
},
|
|
634
|
+
body: JSON.stringify(body),
|
|
635
|
+
signal: deadline
|
|
636
|
+
});
|
|
637
|
+
} catch {
|
|
638
|
+
if (signal.aborted) throw cancelled();
|
|
639
|
+
if (deadline.aborted) throw timedOut();
|
|
640
|
+
throw openAIEmbeddingsFailure("network", "The embedding service could not be reached.", true);
|
|
641
|
+
}
|
|
642
|
+
submission = "submitted";
|
|
643
|
+
if (!response.ok) {
|
|
644
|
+
await cancelBody(response);
|
|
645
|
+
throw openAIEmbeddingsStatusFailure(response.status);
|
|
646
|
+
}
|
|
647
|
+
let text;
|
|
648
|
+
try {
|
|
649
|
+
text = await readBody(response, RESPONSE_LIMIT, deadline);
|
|
650
|
+
} catch (error) {
|
|
651
|
+
if (error instanceof ResponseBodyLimitError) throw openAIEmbeddingsFailure("invalid-response", "The embedding service response was too large.");
|
|
652
|
+
if (signal.aborted) throw cancelled();
|
|
653
|
+
if (deadline.aborted) throw timedOut();
|
|
654
|
+
throw openAIEmbeddingsFailure("network", "The embedding response could not be read.");
|
|
655
|
+
}
|
|
656
|
+
let payload;
|
|
657
|
+
try {
|
|
658
|
+
payload = JSON.parse(text);
|
|
659
|
+
} catch {
|
|
660
|
+
throw openAIEmbeddingsFailure("invalid-response", "The embedding service response was not JSON.");
|
|
661
|
+
}
|
|
662
|
+
const tokens = payload && typeof payload === "object" ? payload.usage?.prompt_tokens : void 0;
|
|
663
|
+
if (typeof tokens === "number" && Number.isInteger(tokens) && tokens >= 0) accounting?.report({
|
|
664
|
+
sequence: 1,
|
|
665
|
+
inputTokens: tokens
|
|
666
|
+
});
|
|
667
|
+
const result = normalizeOpenAIEmbeddingsResponse(payload, request.inputs.length);
|
|
668
|
+
outcome = "success";
|
|
669
|
+
return result;
|
|
670
|
+
} finally {
|
|
671
|
+
accounting?.end({
|
|
672
|
+
outcome: signal.aborted ? "cancelled" : outcome,
|
|
673
|
+
submission
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
} },
|
|
678
|
+
listModels: async (probe) => ({ offers: (await probeOpenAI.listModels(probe, withConnectionHeaders(networkFetch, probe.headers))).filter((offer) => openAIEmbeddingLimits(offer.model) !== void 0) }),
|
|
679
|
+
testConnection: (probe) => probeOpenAI.listModels(probe, withConnectionHeaders(networkFetch, probe.headers)).then(() => {})
|
|
680
|
+
};
|
|
681
|
+
}
|
|
682
|
+
//#endregion
|
|
683
|
+
//#region src/logo.ts
|
|
684
|
+
const protocolLogo = "data:image/svg+xml,%3Csvg%20fill%3D%22currentColor%22%20fill-rule%3D%22evenodd%22%20height%3D%2224%22%20style%3D%22flex%3Anone%3Bline-height%3A1%22%20viewBox%3D%220%200%2024%2024%22%20width%3D%2224%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Ctitle%3EOpenAI%3C%2Ftitle%3E%3Cpath%20d%3D%22M9.205%208.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357%201.356-.523%202.117-.523%202.854%200%204.662%202.212%204.662%204.566%200%20.167%200%20.357-.024.547l-4.71-2.759a.797.797%200%2000-.856%200l-5.97%203.473zm10.609%208.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473%201.95-1.118a.433.433%200%2001.476%200l4.543%202.617c1.309.76%202.189%202.378%202.189%203.948%200%201.808-1.07%203.473-2.76%204.163zM7.802%2012.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545%201.95-4.472%204.591-4.472%201%200%201.927.333%202.712.928L8.23%205.067c-.285.166-.428.404-.428.737v6.898zM12%2015.128l-2.795-1.57v-3.33L12%208.658l2.795%201.57v3.33L12%2015.128zm1.796%207.23c-1%200-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974%201.142c.167.095.238.238.238.428v5.233c0%202.545-1.974%204.472-4.614%204.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482%204.482%200%20014.21%206.327v5.423c0%20.333.143.571.428.738l5.947%203.449-1.95%201.118a.432.432%200%2001-.476%200zm-.262%203.9c-2.688%200-4.662-2.021-4.662-4.519%200-.19.024-.38.047-.57l4.686%202.71c.286.167.571.167.856%200l5.97-3.448v2.26c0%20.19-.07.333-.237.428l-4.543%202.616c-.619.357-1.356.523-2.117.523zm5.899%202.83a5.947%205.947%200%20005.827-4.756C22.287%2018.339%2024%2015.84%2024%2013.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498%200-3.401-2.759-5.947-5.946-5.947-.642%200-1.26.095-1.88.31A5.962%205.962%200%200010.205%200a5.947%205.947%200%2000-5.827%204.757C1.713%205.447%200%207.945%200%2010.49c0%201.666.713%203.283%201.998%204.448-.119.5-.19%201-.19%201.499%200%203.401%202.759%205.946%205.946%205.946.642%200%201.26-.095%201.88-.309a5.96%205.96%200%20004.162%201.713z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E";
|
|
685
|
+
//#endregion
|
|
686
|
+
//#region src/support.ts
|
|
687
|
+
function inputLimit(offer) {
|
|
688
|
+
return Number.isSafeInteger(offer.inputLimit) && Number(offer.inputLimit) > 0 ? offer.inputLimit : void 0;
|
|
689
|
+
}
|
|
690
|
+
function normalizeOffers(input) {
|
|
691
|
+
return Object.fromEntries(input.offers.map((offer) => [offer.model, {
|
|
692
|
+
id: offer.model,
|
|
693
|
+
...offer.name === void 0 ? {} : { name: offer.name },
|
|
694
|
+
...offer.chat === void 0 ? {} : { chat: offer.chat },
|
|
695
|
+
...offer.reasoning === void 0 && !offer.efforts?.length ? {} : { reasoning: offer.efforts?.length ? true : offer.reasoning },
|
|
696
|
+
...offer.efforts?.length ? { reasoning_options: [{
|
|
697
|
+
type: "effort",
|
|
698
|
+
values: [...offer.efforts]
|
|
699
|
+
}] } : {},
|
|
700
|
+
...offer.temperature === void 0 ? {} : { temperature: offer.temperature },
|
|
701
|
+
...offer.toolCall === void 0 ? {} : { tool_call: offer.toolCall },
|
|
702
|
+
...offer.input === void 0 ? {} : { attachment: offer.input.some((one) => one !== "text") },
|
|
703
|
+
...offer.input === void 0 && offer.output === void 0 ? {} : { modalities: {
|
|
704
|
+
...offer.input === void 0 ? {} : { input: [...offer.input] },
|
|
705
|
+
...offer.output === void 0 ? {} : { output: [...offer.output] }
|
|
706
|
+
} },
|
|
707
|
+
...!offer.contextWindow && inputLimit(offer) === void 0 && !offer.maxOutput ? {} : { limit: {
|
|
708
|
+
...offer.contextWindow && offer.contextWindow > 0 ? { context: offer.contextWindow } : {},
|
|
709
|
+
...inputLimit(offer) === void 0 ? {} : { input: inputLimit(offer) },
|
|
710
|
+
...offer.maxOutput && offer.maxOutput > 0 ? { output: offer.maxOutput } : {}
|
|
711
|
+
} },
|
|
712
|
+
...offer.releaseDate === void 0 ? {} : { release_date: offer.releaseDate }
|
|
713
|
+
}]));
|
|
714
|
+
}
|
|
715
|
+
function lazySupport(read) {
|
|
716
|
+
return new Proxy({}, { get(_target, key) {
|
|
717
|
+
if (key === "normalizeListing") return normalizeOffers;
|
|
718
|
+
const service = read();
|
|
719
|
+
if (!service) throw new Error("Chat model support is unavailable");
|
|
720
|
+
const value = Reflect.get(service, key);
|
|
721
|
+
return typeof value === "function" ? value.bind(service) : value;
|
|
722
|
+
} });
|
|
723
|
+
}
|
|
724
|
+
//#endregion
|
|
725
|
+
//#region src/images/port.ts
|
|
726
|
+
const text = (en, zh) => ({
|
|
727
|
+
"en-US": en,
|
|
728
|
+
"zh-CN": zh
|
|
729
|
+
});
|
|
730
|
+
const auto = text("Auto", "\u81ea\u52a8");
|
|
731
|
+
const qualityPresentation = { options: {
|
|
732
|
+
auto,
|
|
733
|
+
low: text("Low", "\u4f4e"),
|
|
734
|
+
medium: text("Medium", "\u4e2d"),
|
|
735
|
+
high: text("High", "\u9ad8"),
|
|
736
|
+
xhigh: text("Very high", "\u5f88\u9ad8"),
|
|
737
|
+
max: text("Maximum", "\u6700\u9ad8"),
|
|
738
|
+
standard: text("Standard", "\u6807\u51c6"),
|
|
739
|
+
hd: text("HD", "\u9ad8\u6e05")
|
|
740
|
+
} };
|
|
741
|
+
const sizePresentation = { options: { auto } };
|
|
742
|
+
const imageParamsSchema = z.strictObject({
|
|
743
|
+
size: z.enum([
|
|
744
|
+
"auto",
|
|
745
|
+
"256x256",
|
|
746
|
+
"512x512",
|
|
747
|
+
"1024x1024",
|
|
748
|
+
"1536x1024",
|
|
749
|
+
"1024x1536",
|
|
750
|
+
"1792x1024",
|
|
751
|
+
"1024x1792"
|
|
752
|
+
]).optional().meta({ presentation: sizePresentation }),
|
|
753
|
+
quality: z.enum([
|
|
754
|
+
"auto",
|
|
755
|
+
"low",
|
|
756
|
+
"medium",
|
|
757
|
+
"high",
|
|
758
|
+
"xhigh",
|
|
759
|
+
"max",
|
|
760
|
+
"standard",
|
|
761
|
+
"hd"
|
|
762
|
+
]).optional().meta({ presentation: qualityPresentation }),
|
|
763
|
+
background: z.enum([
|
|
764
|
+
"auto",
|
|
765
|
+
"transparent",
|
|
766
|
+
"opaque"
|
|
767
|
+
]).optional().meta({ presentation: { options: {
|
|
768
|
+
auto,
|
|
769
|
+
transparent: text("Transparent", "\u900f\u660e"),
|
|
770
|
+
opaque: text("Opaque", "\u4e0d\u900f\u660e")
|
|
771
|
+
} } }),
|
|
772
|
+
outputFormat: z.enum([
|
|
773
|
+
"png",
|
|
774
|
+
"jpeg",
|
|
775
|
+
"webp"
|
|
776
|
+
]).optional(),
|
|
777
|
+
n: z.number().int().min(1).max(8).optional()
|
|
778
|
+
});
|
|
779
|
+
function imageParamsFor(model) {
|
|
780
|
+
if (!isGptImage(model)) return imageParamsSchema;
|
|
781
|
+
return imageParamsSchema.extend({
|
|
782
|
+
size: z.enum([
|
|
783
|
+
"auto",
|
|
784
|
+
"1024x1024",
|
|
785
|
+
"1536x1024",
|
|
786
|
+
"1024x1536"
|
|
787
|
+
]).optional().meta({ presentation: sizePresentation }),
|
|
788
|
+
quality: (model.startsWith("gpt-image-2.5-") ? z.enum([
|
|
789
|
+
"auto",
|
|
790
|
+
"low",
|
|
791
|
+
"medium",
|
|
792
|
+
"high",
|
|
793
|
+
"xhigh",
|
|
794
|
+
"max"
|
|
795
|
+
]) : z.enum([
|
|
796
|
+
"auto",
|
|
797
|
+
"low",
|
|
798
|
+
"medium",
|
|
799
|
+
"high"
|
|
800
|
+
])).optional().meta({ presentation: qualityPresentation })
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
function isGptImage(model) {
|
|
804
|
+
return model.startsWith("gpt-image") || model === "chatgpt-image-latest";
|
|
805
|
+
}
|
|
806
|
+
function fail(code, resultState, message) {
|
|
807
|
+
throw Object.assign(new Error(message), {
|
|
808
|
+
name: "GenerationFailure",
|
|
809
|
+
code,
|
|
810
|
+
resultState
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
function validBase64(value) {
|
|
814
|
+
if (value.length % 4 !== 0) return false;
|
|
815
|
+
const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
|
|
816
|
+
return !/[^A-Za-z0-9+/]/.test(value.slice(0, value.length - padding));
|
|
817
|
+
}
|
|
818
|
+
async function readResponse(response, signal) {
|
|
819
|
+
const limit = 402653184;
|
|
820
|
+
const length = response.headers.get("content-length");
|
|
821
|
+
if (length !== null && /^\d+$/.test(length) && Number(length) > limit) {
|
|
822
|
+
await response.body?.cancel().catch(() => {});
|
|
823
|
+
fail("too-large", "not-delivered", "The image response exceeds its byte budget");
|
|
824
|
+
}
|
|
825
|
+
if (!response.body) fail("invalid-output", "not-delivered", "The image response is empty");
|
|
826
|
+
const reader = response.body.getReader();
|
|
827
|
+
const chunks = [];
|
|
828
|
+
let bytes = 0;
|
|
829
|
+
try {
|
|
830
|
+
for (;;) {
|
|
831
|
+
signal.throwIfAborted();
|
|
832
|
+
const next = await reader.read();
|
|
833
|
+
if (next.done) break;
|
|
834
|
+
bytes += next.value.byteLength;
|
|
835
|
+
if (bytes > limit) {
|
|
836
|
+
await reader.cancel().catch(() => {});
|
|
837
|
+
fail("too-large", "not-delivered", "The image response exceeds its byte budget");
|
|
838
|
+
}
|
|
839
|
+
chunks.push(next.value);
|
|
840
|
+
}
|
|
841
|
+
} finally {
|
|
842
|
+
reader.releaseLock();
|
|
843
|
+
}
|
|
844
|
+
try {
|
|
845
|
+
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
846
|
+
} catch {
|
|
847
|
+
fail("invalid-output", "not-delivered", "The image service returned invalid JSON");
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
function createOpenAIImagePort(call, fetcher) {
|
|
851
|
+
return { async generate(request, signal) {
|
|
852
|
+
signal.throwIfAborted();
|
|
853
|
+
if (!call.secrets.apiKey) fail("credential-unavailable", "not-submitted", "An API key is required");
|
|
854
|
+
const params = imageParamsFor(call.model).safeParse(request.params);
|
|
855
|
+
if (!params.success) fail("invalid-params", "not-submitted", "Unsupported image parameters");
|
|
856
|
+
if (!["create", "edit"].includes(request.operation) || request.outputKind !== "image") fail("unsupported", "not-submitted", "Unsupported image operation");
|
|
857
|
+
if (request.operation === "create" && request.inputs.length) fail("invalid-input", "not-submitted", "Image creation does not accept references");
|
|
858
|
+
if (request.operation === "edit" && (request.inputs.length < 1 || request.inputs.length > 16)) fail("invalid-input", "not-submitted", "Image editing needs between one and sixteen references");
|
|
859
|
+
const { outputFormat, ...settings } = params.data;
|
|
860
|
+
const payload = {
|
|
861
|
+
model: call.model,
|
|
862
|
+
prompt: request.prompt,
|
|
863
|
+
...settings,
|
|
864
|
+
...outputFormat ? { output_format: outputFormat } : {},
|
|
865
|
+
...!isGptImage(call.model) ? { response_format: "b64_json" } : {}
|
|
866
|
+
};
|
|
867
|
+
let body = JSON.stringify(payload);
|
|
868
|
+
if (request.operation === "edit") {
|
|
869
|
+
const form = new FormData();
|
|
870
|
+
for (const [key, value] of Object.entries(payload)) form.set(key, String(value));
|
|
871
|
+
let total = 0;
|
|
872
|
+
for (const [index, input] of request.inputs.entries()) {
|
|
873
|
+
if (![
|
|
874
|
+
"image/png",
|
|
875
|
+
"image/jpeg",
|
|
876
|
+
"image/webp"
|
|
877
|
+
].includes(input.mediaType)) fail("invalid-input", "not-submitted", "Unsupported image reference media type");
|
|
878
|
+
const chunks = [];
|
|
879
|
+
let size = 0;
|
|
880
|
+
for await (const chunk of input.read(signal)) {
|
|
881
|
+
signal.throwIfAborted();
|
|
882
|
+
size += chunk.byteLength;
|
|
883
|
+
total += chunk.byteLength;
|
|
884
|
+
if (size > input.size || total > 52428800) fail("too-large", "not-submitted", "Image references exceed the request budget");
|
|
885
|
+
chunks.push(chunk);
|
|
886
|
+
}
|
|
887
|
+
if (size !== input.size) fail("invalid-input", "not-submitted", "The image reference changed size");
|
|
888
|
+
form.append("image[]", new Blob([Buffer.concat(chunks)], { type: input.mediaType }), `reference-${index}.` + input.mediaType.slice(6));
|
|
889
|
+
}
|
|
890
|
+
body = form;
|
|
891
|
+
}
|
|
892
|
+
const url = new URL(`${String(call.config.baseUrl ?? "").replace(/\/+$/, "")}/images/${request.operation === "edit" ? "edits" : "generations"}`);
|
|
893
|
+
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) fail("invalid-params", "not-submitted", "Invalid image API address");
|
|
894
|
+
const accounting = call.accountingDispatch?.attempt(0);
|
|
895
|
+
let outcome = "failed";
|
|
896
|
+
let submission = "unknown";
|
|
897
|
+
try {
|
|
898
|
+
let response;
|
|
899
|
+
try {
|
|
900
|
+
response = await fetcher(url.href, {
|
|
901
|
+
method: "POST",
|
|
902
|
+
redirect: "error",
|
|
903
|
+
signal,
|
|
904
|
+
headers: {
|
|
905
|
+
authorization: `Bearer ${call.secrets.apiKey}`,
|
|
906
|
+
...typeof body === "string" ? { "content-type": "application/json" } : {}
|
|
907
|
+
},
|
|
908
|
+
body
|
|
909
|
+
});
|
|
910
|
+
} catch {
|
|
911
|
+
fail(signal.aborted ? "cancelled" : "network", "unknown", "The image submission result is unknown");
|
|
912
|
+
}
|
|
913
|
+
submission = "submitted";
|
|
914
|
+
if (!response.ok) {
|
|
915
|
+
await response.body?.cancel().catch(() => {});
|
|
916
|
+
fail(response.status === 401 ? "credential-unavailable" : response.status === 403 ? "forbidden" : response.status === 429 ? "quota" : "provider", "not-delivered", `Image generation failed with HTTP ${response.status}`);
|
|
917
|
+
}
|
|
918
|
+
try {
|
|
919
|
+
const raw = await readResponse(response, signal);
|
|
920
|
+
const envelope = z.record(z.string(), z.unknown()).safeParse(raw);
|
|
921
|
+
if (!envelope.success) fail("invalid-output", "not-delivered", "The image response is not a JSON object");
|
|
922
|
+
const usage = envelope.data.usage && typeof envelope.data.usage === "object" ? envelope.data.usage : void 0;
|
|
923
|
+
const reportedUsage = usage ? {
|
|
924
|
+
...typeof usage.input_tokens === "number" ? { inputTokens: usage.input_tokens } : {},
|
|
925
|
+
...typeof usage.output_tokens === "number" ? { outputTokens: usage.output_tokens } : {},
|
|
926
|
+
...typeof usage.total_tokens === "number" ? { totalTokens: usage.total_tokens } : {}
|
|
927
|
+
} : void 0;
|
|
928
|
+
if (reportedUsage) accounting?.report({
|
|
929
|
+
sequence: 1,
|
|
930
|
+
...reportedUsage
|
|
931
|
+
});
|
|
932
|
+
if (envelope.data.error !== void 0 && envelope.data.error !== null) fail("provider", "not-delivered", "The image service returned an error in a successful HTTP response");
|
|
933
|
+
if (!Array.isArray(envelope.data.data)) fail("invalid-output", "not-delivered", "The image response is missing its image data array");
|
|
934
|
+
if (!envelope.data.data.length) fail("invalid-output", "not-delivered", "The image response contains no images");
|
|
935
|
+
const result = z.array(z.object({
|
|
936
|
+
b64_json: z.string().optional(),
|
|
937
|
+
url: z.string().optional()
|
|
938
|
+
})).max(8).safeParse(envelope.data.data);
|
|
939
|
+
if (!result.success) fail("invalid-output", "not-delivered", "The image response contains unsupported image entries");
|
|
940
|
+
let outputBytes = 0;
|
|
941
|
+
const assets = result.data.map((item) => {
|
|
942
|
+
if (item.b64_json === void 0) {
|
|
943
|
+
if (item.url) fail("invalid-output", "not-delivered", "The image service returned a URL instead of the requested inline image bytes; URL delivery is not configured for this connection");
|
|
944
|
+
fail("invalid-output", "not-delivered", "The image response is missing its inline image bytes");
|
|
945
|
+
}
|
|
946
|
+
if (!item.b64_json.length) fail("invalid-output", "not-delivered", "The image response contains empty inline image bytes");
|
|
947
|
+
if (!validBase64(item.b64_json)) fail("invalid-output", "not-delivered", "Invalid image encoding");
|
|
948
|
+
const bytes = Buffer.from(item.b64_json, "base64");
|
|
949
|
+
outputBytes += bytes.byteLength;
|
|
950
|
+
if (outputBytes > 268435456) fail("too-large", "not-delivered", "Image outputs exceed their byte budget");
|
|
951
|
+
if (!bytes.length) fail("invalid-output", "not-delivered", "The image is empty");
|
|
952
|
+
return {
|
|
953
|
+
mediaType: outputFormat === "jpeg" ? "image/jpeg" : outputFormat === "webp" ? "image/webp" : "image/png",
|
|
954
|
+
body: (async function* () {
|
|
955
|
+
yield bytes;
|
|
956
|
+
})()
|
|
957
|
+
};
|
|
958
|
+
});
|
|
959
|
+
outcome = "success";
|
|
960
|
+
return {
|
|
961
|
+
assets,
|
|
962
|
+
...reportedUsage ? { usage: reportedUsage } : {}
|
|
963
|
+
};
|
|
964
|
+
} catch (error) {
|
|
965
|
+
if (error?.name === "GenerationFailure") throw error;
|
|
966
|
+
fail(signal.aborted ? "cancelled" : "invalid-output", "not-delivered", "The image response could not be read completely");
|
|
967
|
+
}
|
|
968
|
+
} finally {
|
|
969
|
+
accounting?.end({
|
|
970
|
+
outcome: signal.aborted ? "cancelled" : outcome,
|
|
971
|
+
submission
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
} };
|
|
975
|
+
}
|
|
976
|
+
//#endregion
|
|
977
|
+
//#region src/images/protocol.ts
|
|
978
|
+
function imagesProtocolType(support, fetcher) {
|
|
979
|
+
return {
|
|
980
|
+
type: "openai-images",
|
|
981
|
+
label: "OpenAI Images API",
|
|
982
|
+
logo: protocolLogo,
|
|
983
|
+
fields: [{
|
|
984
|
+
key: "baseUrl",
|
|
985
|
+
kind: "url",
|
|
986
|
+
label: "Base URL",
|
|
987
|
+
required: true
|
|
988
|
+
}],
|
|
989
|
+
userConfigurable: true,
|
|
990
|
+
optionsSchema: z.strictObject({}),
|
|
991
|
+
adapters: { image: {
|
|
992
|
+
models: (input) => input.configuredModels.filter((row) => row.execution?.protocolId === "openai-images" && row.execution.profile === "openai-image-v1").map((row) => ({
|
|
993
|
+
id: row.id,
|
|
994
|
+
label: row.id,
|
|
995
|
+
outputKinds: ["image"],
|
|
996
|
+
operations: [{
|
|
997
|
+
id: "create",
|
|
998
|
+
inputKinds: [],
|
|
999
|
+
minInputs: 0,
|
|
1000
|
+
maxInputs: 0,
|
|
1001
|
+
paramsSchema: imageParamsFor(row.id)
|
|
1002
|
+
}, {
|
|
1003
|
+
id: "edit",
|
|
1004
|
+
inputKinds: ["image"],
|
|
1005
|
+
minInputs: 1,
|
|
1006
|
+
maxInputs: 16,
|
|
1007
|
+
paramsSchema: imageParamsFor(row.id)
|
|
1008
|
+
}]
|
|
1009
|
+
})),
|
|
1010
|
+
createPort: (call) => createOpenAIImagePort(call, withConnectionHeaders(fetcher, call.headers))
|
|
1011
|
+
} },
|
|
1012
|
+
executionCandidates: () => [{
|
|
1013
|
+
profile: "openai-image-v1",
|
|
1014
|
+
label: "OpenAI Images generation and editing",
|
|
1015
|
+
chat: false,
|
|
1016
|
+
generation: ["image"]
|
|
1017
|
+
}],
|
|
1018
|
+
validateExecution(input) {
|
|
1019
|
+
if (input.requested.protocolId !== "openai-images" || input.requested.profile !== "openai-image-v1" || input.requested.sourceIdentity !== void 0) throw new Error("Unsupported image execution profile");
|
|
1020
|
+
return {
|
|
1021
|
+
protocolId: "openai-images",
|
|
1022
|
+
profile: "openai-image-v1"
|
|
1023
|
+
};
|
|
1024
|
+
},
|
|
1025
|
+
normalizeListing: (input) => normalizeOffers(input),
|
|
1026
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, withConnectionHeaders(fetcher, probe.headers)) }),
|
|
1027
|
+
testConnection: (probe) => probeOpenAI.listModels(probe, withConnectionHeaders(fetcher, probe.headers)).then(() => {})
|
|
1028
|
+
};
|
|
1029
|
+
}
|
|
1030
|
+
//#endregion
|
|
1031
|
+
//#region src/protocol/facts.ts
|
|
1032
|
+
const facts = {
|
|
1033
|
+
outputLimit: { support: "optional" },
|
|
1034
|
+
temperature: {
|
|
1035
|
+
min: 0,
|
|
1036
|
+
max: 2,
|
|
1037
|
+
step: .05,
|
|
1038
|
+
default: 1
|
|
1039
|
+
},
|
|
1040
|
+
thinkingSwitch: false,
|
|
1041
|
+
limits: {
|
|
1042
|
+
requestBytes: 20971520,
|
|
1043
|
+
images: 50
|
|
1044
|
+
}
|
|
1045
|
+
};
|
|
1046
|
+
//#endregion
|
|
1047
|
+
//#region src/protocol/sdk.ts
|
|
1048
|
+
let loaded;
|
|
1049
|
+
let loading;
|
|
1050
|
+
function loadOpenAISdk() {
|
|
1051
|
+
loading ??= import("openai").then((sdk) => {
|
|
1052
|
+
loaded = sdk;
|
|
1053
|
+
return sdk;
|
|
1054
|
+
}, (error) => {
|
|
1055
|
+
loading = void 0;
|
|
1056
|
+
throw error;
|
|
1057
|
+
});
|
|
1058
|
+
return loading;
|
|
1059
|
+
}
|
|
1060
|
+
function isOpenAIApiError(error) {
|
|
1061
|
+
return loaded !== void 0 && error instanceof loaded.APIError;
|
|
1062
|
+
}
|
|
1063
|
+
function isOpenAIConnectionError(error) {
|
|
1064
|
+
return loaded !== void 0 && error instanceof loaded.APIConnectionError;
|
|
1065
|
+
}
|
|
1066
|
+
//#endregion
|
|
1067
|
+
//#region src/protocol/errors.ts
|
|
1068
|
+
function isRetryableStatus(status) {
|
|
1069
|
+
return status === 408 || status === 409 || status === 429 || status !== void 0 && status >= 500;
|
|
1070
|
+
}
|
|
1071
|
+
function retryAfterMs(error) {
|
|
1072
|
+
if (!isOpenAIApiError(error)) return void 0;
|
|
1073
|
+
const header = error.headers?.get("retry-after");
|
|
1074
|
+
if (!header) return void 0;
|
|
1075
|
+
const seconds = Number(header);
|
|
1076
|
+
if (!Number.isFinite(seconds) || seconds < 0) return void 0;
|
|
1077
|
+
const milliseconds = seconds * 1e3;
|
|
1078
|
+
return Number.isFinite(milliseconds) ? milliseconds : void 0;
|
|
1079
|
+
}
|
|
1080
|
+
function exceedsContextWindow(error) {
|
|
1081
|
+
if (error.code === "context_length_exceeded") return true;
|
|
1082
|
+
const message = error.error?.message;
|
|
1083
|
+
return error.status === 400 && typeof message === "string" && /maximum context length/i.test(message);
|
|
1084
|
+
}
|
|
1085
|
+
function toModelFailure(error, failures, transportFailure) {
|
|
1086
|
+
if (failures.owns(error)) return error;
|
|
1087
|
+
if (!isOpenAIApiError(error)) return transportFailure?.(error) ?? failures.create({
|
|
1088
|
+
code: "unknown",
|
|
1089
|
+
stage: "unknown",
|
|
1090
|
+
category: "unknown",
|
|
1091
|
+
source: "unknown",
|
|
1092
|
+
retryable: false
|
|
1093
|
+
}, { cause: error });
|
|
1094
|
+
const rawCode = error.code ?? error.type;
|
|
1095
|
+
const providerCode = typeof rawCode === "string" && (/* @__PURE__ */ new Set([
|
|
1096
|
+
"usage_not_included",
|
|
1097
|
+
"usage_limit_reached",
|
|
1098
|
+
"insufficient_quota",
|
|
1099
|
+
"context_length_exceeded",
|
|
1100
|
+
"rate_limit_exceeded",
|
|
1101
|
+
"overloaded_error",
|
|
1102
|
+
"api_error",
|
|
1103
|
+
"rate_limit_error",
|
|
1104
|
+
"cyber_policy",
|
|
1105
|
+
"invalid_prompt",
|
|
1106
|
+
"bio_policy",
|
|
1107
|
+
"misalignment_policy_violation"
|
|
1108
|
+
])).has(rawCode) ? rawCode : void 0;
|
|
1109
|
+
const connection = isOpenAIConnectionError(error);
|
|
1110
|
+
const status = Number.isInteger(error.status) && Number(error.status) >= 100 && Number(error.status) <= 599 ? error.status : void 0;
|
|
1111
|
+
const details = {
|
|
1112
|
+
...status === void 0 ? {} : { status },
|
|
1113
|
+
...typeof error.requestID === "string" ? { providerRequestId: error.requestID } : {}
|
|
1114
|
+
};
|
|
1115
|
+
if (exceedsContextWindow(error)) return failures.create({
|
|
1116
|
+
code: "context-window-exceeded",
|
|
1117
|
+
stage: "request",
|
|
1118
|
+
category: "request-too-large",
|
|
1119
|
+
source: "protocol",
|
|
1120
|
+
...status === void 0 ? {} : { status },
|
|
1121
|
+
retryable: false,
|
|
1122
|
+
...providerCode === void 0 ? {} : { providerCode }
|
|
1123
|
+
}, {
|
|
1124
|
+
cause: error,
|
|
1125
|
+
details
|
|
1126
|
+
});
|
|
1127
|
+
return failures.create({
|
|
1128
|
+
code: connection ? "stream-interrupted" : status === 413 ? "request-too-large" : status === void 0 ? "provider-error" : "http-error",
|
|
1129
|
+
stage: connection ? "transport" : status === 413 ? "request" : status === void 0 ? "stream" : "transport",
|
|
1130
|
+
category: connection ? "network" : status === 413 ? "request-too-large" : "provider",
|
|
1131
|
+
source: connection ? "transport" : "protocol",
|
|
1132
|
+
...status === void 0 ? {} : { status },
|
|
1133
|
+
retryable: connection || isRetryableStatus(status),
|
|
1134
|
+
...providerCode === void 0 ? {} : { providerCode }
|
|
1135
|
+
}, {
|
|
1136
|
+
cause: error,
|
|
1137
|
+
details
|
|
1138
|
+
});
|
|
1139
|
+
}
|
|
1140
|
+
//#endregion
|
|
1141
|
+
//#region src/protocol/request.ts
|
|
1142
|
+
function textOf(parts) {
|
|
1143
|
+
const text = parts.filter((part) => part.type === "text").map((part) => part.text).join("");
|
|
1144
|
+
return text.length > 0 ? text : null;
|
|
1145
|
+
}
|
|
1146
|
+
function toolCallsOf(parts) {
|
|
1147
|
+
const calls = parts.filter((part) => part.type === "tool-use").map((part) => ({
|
|
1148
|
+
id: part.id,
|
|
1149
|
+
type: "function",
|
|
1150
|
+
function: {
|
|
1151
|
+
name: part.name,
|
|
1152
|
+
arguments: JSON.stringify(part.input ?? {})
|
|
1153
|
+
}
|
|
1154
|
+
}));
|
|
1155
|
+
return calls.length > 0 ? calls : void 0;
|
|
1156
|
+
}
|
|
1157
|
+
function imagePart(planned) {
|
|
1158
|
+
return {
|
|
1159
|
+
type: "image_url",
|
|
1160
|
+
image_url: { url: `data:${planned.mediaType};base64,${planned.data ?? ""}` }
|
|
1161
|
+
};
|
|
1162
|
+
}
|
|
1163
|
+
function userContent(message, index, plan) {
|
|
1164
|
+
if (!message.content.some((part) => part.type === "file")) return textOf(message.content) ?? "";
|
|
1165
|
+
const parts = [];
|
|
1166
|
+
let text = "";
|
|
1167
|
+
const flush = () => {
|
|
1168
|
+
if (text.length > 0) parts.push({
|
|
1169
|
+
type: "text",
|
|
1170
|
+
text
|
|
1171
|
+
});
|
|
1172
|
+
text = "";
|
|
1173
|
+
};
|
|
1174
|
+
message.content.forEach((part, partIndex) => {
|
|
1175
|
+
if (part.type === "text") text += part.text;
|
|
1176
|
+
else if (part.type === "file") {
|
|
1177
|
+
const planned = plan.at(index, partIndex);
|
|
1178
|
+
flush();
|
|
1179
|
+
parts.push({
|
|
1180
|
+
type: "text",
|
|
1181
|
+
text: planned.label
|
|
1182
|
+
});
|
|
1183
|
+
if (planned.fate === "send") parts.push(imagePart(planned));
|
|
1184
|
+
}
|
|
1185
|
+
});
|
|
1186
|
+
flush();
|
|
1187
|
+
return parts.every((part) => part.type === "text") ? parts.map((part) => part.text).join("\n") : parts;
|
|
1188
|
+
}
|
|
1189
|
+
function toChatMessages(message, index, plan, options) {
|
|
1190
|
+
const toolResults = message.content.map((part, partIndex) => ({
|
|
1191
|
+
part,
|
|
1192
|
+
partIndex
|
|
1193
|
+
})).filter((entry) => entry.part.type === "tool-result");
|
|
1194
|
+
if (message.role === "user" && toolResults.length > 0) {
|
|
1195
|
+
const images = [];
|
|
1196
|
+
const tools = toolResults.map(({ part, partIndex }) => {
|
|
1197
|
+
const lines = [part.content];
|
|
1198
|
+
(part.files ?? []).forEach((_, fileIndex) => {
|
|
1199
|
+
const planned = plan.at(index, partIndex, fileIndex);
|
|
1200
|
+
if (planned.fate !== "send") {
|
|
1201
|
+
lines.push(planned.label);
|
|
1202
|
+
return;
|
|
1203
|
+
}
|
|
1204
|
+
images.push({
|
|
1205
|
+
type: "text",
|
|
1206
|
+
text: `${part.toolUseId} ${planned.label}`
|
|
1207
|
+
}, imagePart(planned));
|
|
1208
|
+
});
|
|
1209
|
+
return {
|
|
1210
|
+
role: "tool",
|
|
1211
|
+
content: lines.filter((line) => line !== "").join("\n"),
|
|
1212
|
+
tool_call_id: part.toolUseId
|
|
1213
|
+
};
|
|
1214
|
+
});
|
|
1215
|
+
return images.length === 0 ? tools : [...tools, {
|
|
1216
|
+
role: "user",
|
|
1217
|
+
content: [{
|
|
1218
|
+
type: "text",
|
|
1219
|
+
text: "Images returned by tool calls:"
|
|
1220
|
+
}, ...images]
|
|
1221
|
+
}];
|
|
1222
|
+
}
|
|
1223
|
+
if (message.role === "assistant") {
|
|
1224
|
+
const content = textOf(message.content);
|
|
1225
|
+
const toolCalls = toolCallsOf(message.content);
|
|
1226
|
+
if (content === null && toolCalls === void 0) return [];
|
|
1227
|
+
return [{
|
|
1228
|
+
role: "assistant",
|
|
1229
|
+
content,
|
|
1230
|
+
...openaiThinkingIsSendable(message, options) ? { reasoning_content: message.content.filter((part) => part.type === "thinking").map((part) => part.text).join("") } : {},
|
|
1231
|
+
...toolCalls === void 0 ? {} : { tool_calls: toolCalls }
|
|
1232
|
+
}];
|
|
1233
|
+
}
|
|
1234
|
+
return [{
|
|
1235
|
+
role: "user",
|
|
1236
|
+
content: userContent(message, index, plan)
|
|
1237
|
+
}];
|
|
1238
|
+
}
|
|
1239
|
+
function volatileMessages(volatile) {
|
|
1240
|
+
const content = (volatile ?? []).map((note) => note.text).join("\n\n");
|
|
1241
|
+
return content.length > 0 ? [{
|
|
1242
|
+
role: "user",
|
|
1243
|
+
content
|
|
1244
|
+
}] : [];
|
|
1245
|
+
}
|
|
1246
|
+
function withNotes(message, index, plan, options) {
|
|
1247
|
+
return [...message.role === "assistant" ? volatileMessages(message.volatile) : [], ...toChatMessages(message, index, plan, options)];
|
|
1248
|
+
}
|
|
1249
|
+
function toToolParam(tool) {
|
|
1250
|
+
return {
|
|
1251
|
+
type: "function",
|
|
1252
|
+
function: {
|
|
1253
|
+
name: tool.name,
|
|
1254
|
+
description: tool.description,
|
|
1255
|
+
parameters: tool.inputSchema
|
|
1256
|
+
}
|
|
1257
|
+
};
|
|
1258
|
+
}
|
|
1259
|
+
function openaiThinkingIsSendable(message, options) {
|
|
1260
|
+
return message.role === "assistant" && (textOf(message.content) !== null || toolCallsOf(message.content) !== void 0) && options.reasoningReplay === "reasoning-content" && message.content.filter((part) => part.type === "thinking").every((part) => part.signature === void 0 && part.issuer !== void 0 && part.issuer === options.endpoint && part.originModel === options.model) && message.outputTruncation?.incompleteThinking !== true;
|
|
1261
|
+
}
|
|
1262
|
+
function toOpenAIRequest(request, options, plan = options.support.planMedia(request, options.media ?? {
|
|
1263
|
+
acceptsImages: true,
|
|
1264
|
+
limits: void 0
|
|
1265
|
+
})) {
|
|
1266
|
+
const summary = request.purpose === "summary";
|
|
1267
|
+
if (summary && (!Number.isInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0)) throw new Error("summaryMaxTokens must be a positive integer for a summary request");
|
|
1268
|
+
const tools = request.tools && request.tools.length > 0 ? request.tools.map(toToolParam) : [];
|
|
1269
|
+
const maxTokens = summary ? Math.min(request.summaryMaxTokens, Number.isInteger(options.maxTokens) && Number(options.maxTokens) > 0 ? options.maxTokens : request.summaryMaxTokens) : options.maxTokens;
|
|
1270
|
+
const systemMessage = request.system ? [{
|
|
1271
|
+
role: "system",
|
|
1272
|
+
content: request.system.join("\n\n")
|
|
1273
|
+
}] : [];
|
|
1274
|
+
return {
|
|
1275
|
+
model: options.model,
|
|
1276
|
+
stream: true,
|
|
1277
|
+
stream_options: { include_usage: true },
|
|
1278
|
+
messages: [
|
|
1279
|
+
...systemMessage,
|
|
1280
|
+
...request.messages.flatMap((message, index) => withNotes(message, index, plan, options)),
|
|
1281
|
+
...volatileMessages(request.volatile)
|
|
1282
|
+
],
|
|
1283
|
+
...tools.length === 0 ? {} : { tools },
|
|
1284
|
+
...request.toolChoice === "none" && tools.length > 0 ? { tool_choice: "none" } : {},
|
|
1285
|
+
...options.reasoningEffort === void 0 ? {} : { reasoning_effort: options.reasoningEffort },
|
|
1286
|
+
...options.thinkingField === true && options.thinking !== void 0 ? { thinking: { type: options.thinking ? "enabled" : "disabled" } } : {},
|
|
1287
|
+
...options.temperature === void 0 ? {} : { temperature: options.temperature },
|
|
1288
|
+
...maxTokens === void 0 ? {} : { [options.outputLimitField ?? "max_tokens"]: maxTokens },
|
|
1289
|
+
...options.promptCacheKey === true && request.cacheKey !== void 0 ? { prompt_cache_key: request.cacheKey } : {},
|
|
1290
|
+
...summary && request.summaryShape !== "continuation" ? {} : options.extra,
|
|
1291
|
+
...summary && maxTokens !== void 0 ? { [options.outputLimitField ?? "max_tokens"]: maxTokens } : {},
|
|
1292
|
+
...summary && request.toolChoice === "none" && tools.length > 0 ? { tool_choice: "none" } : {}
|
|
1293
|
+
};
|
|
1294
|
+
}
|
|
1295
|
+
//#endregion
|
|
1296
|
+
//#region src/protocol/stream.ts
|
|
1297
|
+
function cacheOf(usage) {
|
|
1298
|
+
const read = usage.prompt_tokens_details?.cached_tokens ?? usage.prompt_cache_hit_tokens;
|
|
1299
|
+
return Number.isSafeInteger(read) && Number(read) >= 0 ? { cacheReadTokens: read } : {};
|
|
1300
|
+
}
|
|
1301
|
+
function toFinishReason(reason, support) {
|
|
1302
|
+
switch (reason) {
|
|
1303
|
+
case "tool_calls": return "tool-calls";
|
|
1304
|
+
case "length": return "max-tokens";
|
|
1305
|
+
case "content_filter": return "refusal";
|
|
1306
|
+
case "stop": return "stop";
|
|
1307
|
+
default: throw support.failures.create({
|
|
1308
|
+
code: reason === null ? "finish-reason-missing" : "finish-reason-unsupported",
|
|
1309
|
+
stage: "response-validation",
|
|
1310
|
+
category: "protocol",
|
|
1311
|
+
source: "protocol",
|
|
1312
|
+
retryable: false
|
|
1313
|
+
}, reason === null ? void 0 : { details: { finishReason: String(reason) } });
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
function parseToolInput(argumentsJson) {
|
|
1317
|
+
if (argumentsJson.length === 0) return {};
|
|
1318
|
+
try {
|
|
1319
|
+
return JSON.parse(argumentsJson);
|
|
1320
|
+
} catch {
|
|
1321
|
+
return;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
async function* mapOpenAIStream(chunks, support, originModel, usageReporter) {
|
|
1325
|
+
const textParts = [];
|
|
1326
|
+
const thinkingParts = [];
|
|
1327
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
1328
|
+
const toolCallOrder = [];
|
|
1329
|
+
let usageSequence = 0;
|
|
1330
|
+
let inputTokensReported = false;
|
|
1331
|
+
let inputTokens = 0;
|
|
1332
|
+
let outputTokens = 0;
|
|
1333
|
+
let finishReason = "stop";
|
|
1334
|
+
let rawFinishReason = null;
|
|
1335
|
+
let cache = {};
|
|
1336
|
+
let ended = false;
|
|
1337
|
+
let refusalText;
|
|
1338
|
+
let thinkingOpen = false;
|
|
1339
|
+
for await (const chunk of chunks) {
|
|
1340
|
+
if (chunk.usage) {
|
|
1341
|
+
inputTokensReported = Number.isSafeInteger(chunk.usage.prompt_tokens) && chunk.usage.prompt_tokens >= 0;
|
|
1342
|
+
inputTokens = inputTokensReported ? chunk.usage.prompt_tokens : 0;
|
|
1343
|
+
outputTokens = Number.isSafeInteger(chunk.usage.completion_tokens) && chunk.usage.completion_tokens >= 0 ? chunk.usage.completion_tokens : 0;
|
|
1344
|
+
cache = cacheOf(chunk.usage);
|
|
1345
|
+
const cached = chunk.usage.prompt_tokens_details?.cached_tokens ?? chunk.usage.prompt_cache_hit_tokens;
|
|
1346
|
+
if (cached !== void 0 && cached !== null && (!Number.isSafeInteger(cached) || cached < 0 || cached > inputTokens)) {
|
|
1347
|
+
inputTokensReported = false;
|
|
1348
|
+
cache = {};
|
|
1349
|
+
}
|
|
1350
|
+
usageReporter?.report({
|
|
1351
|
+
sequence: ++usageSequence,
|
|
1352
|
+
...typeof chunk.usage.prompt_tokens === "number" ? { inputTokens: chunk.usage.prompt_tokens } : {},
|
|
1353
|
+
...typeof chunk.usage.completion_tokens === "number" ? { outputTokens: chunk.usage.completion_tokens } : {},
|
|
1354
|
+
...typeof chunk.usage.total_tokens === "number" ? { totalTokens: chunk.usage.total_tokens } : {},
|
|
1355
|
+
...cache
|
|
1356
|
+
});
|
|
1357
|
+
ended = true;
|
|
1358
|
+
}
|
|
1359
|
+
const choice = chunk.choices[0];
|
|
1360
|
+
if (!choice) continue;
|
|
1361
|
+
const delta = choice.delta;
|
|
1362
|
+
const reasoningContent = delta.reasoning_content || (typeof delta.reasoning === "string" ? delta.reasoning : void 0);
|
|
1363
|
+
if (reasoningContent) {
|
|
1364
|
+
thinkingOpen = true;
|
|
1365
|
+
thinkingParts.push(reasoningContent);
|
|
1366
|
+
yield {
|
|
1367
|
+
kind: "thinking-delta",
|
|
1368
|
+
text: reasoningContent
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
if (choice.delta.content) {
|
|
1372
|
+
thinkingOpen = false;
|
|
1373
|
+
textParts.push(choice.delta.content);
|
|
1374
|
+
yield {
|
|
1375
|
+
kind: "text-delta",
|
|
1376
|
+
text: choice.delta.content
|
|
1377
|
+
};
|
|
1378
|
+
}
|
|
1379
|
+
if (choice.delta.refusal) refusalText = (refusalText ?? "") + choice.delta.refusal;
|
|
1380
|
+
for (const delta of choice.delta.tool_calls ?? []) {
|
|
1381
|
+
thinkingOpen = false;
|
|
1382
|
+
let state = toolCalls.get(delta.index);
|
|
1383
|
+
if (!state) {
|
|
1384
|
+
if (!delta.id || !delta.function?.name) throw support.failures.create({
|
|
1385
|
+
code: "response-invalid",
|
|
1386
|
+
stage: "response-validation",
|
|
1387
|
+
category: "protocol",
|
|
1388
|
+
source: "protocol",
|
|
1389
|
+
retryable: false
|
|
1390
|
+
});
|
|
1391
|
+
state = {
|
|
1392
|
+
id: delta.id,
|
|
1393
|
+
name: delta.function.name,
|
|
1394
|
+
arguments: ""
|
|
1395
|
+
};
|
|
1396
|
+
toolCalls.set(delta.index, state);
|
|
1397
|
+
toolCallOrder.push(delta.index);
|
|
1398
|
+
yield {
|
|
1399
|
+
kind: "tool-call-delta",
|
|
1400
|
+
id: state.id,
|
|
1401
|
+
name: state.name,
|
|
1402
|
+
inputDelta: ""
|
|
1403
|
+
};
|
|
1404
|
+
if (delta.function.arguments) {
|
|
1405
|
+
state.arguments += delta.function.arguments;
|
|
1406
|
+
yield {
|
|
1407
|
+
kind: "tool-call-delta",
|
|
1408
|
+
id: state.id,
|
|
1409
|
+
inputDelta: delta.function.arguments
|
|
1410
|
+
};
|
|
1411
|
+
}
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
const argumentsDelta = delta.function?.arguments ?? "";
|
|
1415
|
+
if (argumentsDelta.length === 0) continue;
|
|
1416
|
+
state.arguments += argumentsDelta;
|
|
1417
|
+
yield {
|
|
1418
|
+
kind: "tool-call-delta",
|
|
1419
|
+
id: state.id,
|
|
1420
|
+
inputDelta: argumentsDelta
|
|
1421
|
+
};
|
|
1422
|
+
}
|
|
1423
|
+
if (choice.finish_reason) {
|
|
1424
|
+
rawFinishReason = choice.finish_reason;
|
|
1425
|
+
finishReason = toFinishReason(choice.finish_reason, support);
|
|
1426
|
+
ended = true;
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
if (!ended) throw support.interruptedFailure();
|
|
1430
|
+
if (rawFinishReason === null) throw support.failures.create({
|
|
1431
|
+
code: "finish-reason-missing",
|
|
1432
|
+
stage: "response-validation",
|
|
1433
|
+
category: "protocol",
|
|
1434
|
+
source: "protocol",
|
|
1435
|
+
retryable: false
|
|
1436
|
+
});
|
|
1437
|
+
const content = [];
|
|
1438
|
+
const thinkingText = thinkingParts.join("");
|
|
1439
|
+
if (thinkingText.length > 0) content.push({
|
|
1440
|
+
type: "thinking",
|
|
1441
|
+
text: thinkingText,
|
|
1442
|
+
...originModel === void 0 ? {} : { originModel }
|
|
1443
|
+
});
|
|
1444
|
+
const text = refusalText ?? textParts.join("");
|
|
1445
|
+
if (text.length > 0) content.push({
|
|
1446
|
+
type: "text",
|
|
1447
|
+
text
|
|
1448
|
+
});
|
|
1449
|
+
const incompleteToolCalls = [];
|
|
1450
|
+
const droppedToolCalls = [];
|
|
1451
|
+
for (const index of toolCallOrder) {
|
|
1452
|
+
const call = toolCalls.get(index);
|
|
1453
|
+
if (!call) continue;
|
|
1454
|
+
const input = finishReason === "max-tokens" && call.arguments.trim() === "" ? void 0 : parseToolInput(call.arguments);
|
|
1455
|
+
if (input === void 0) {
|
|
1456
|
+
if (finishReason === "max-tokens") incompleteToolCalls.push({
|
|
1457
|
+
id: call.id,
|
|
1458
|
+
name: call.name
|
|
1459
|
+
});
|
|
1460
|
+
else droppedToolCalls.push({
|
|
1461
|
+
id: call.id,
|
|
1462
|
+
name: call.name
|
|
1463
|
+
});
|
|
1464
|
+
continue;
|
|
1465
|
+
}
|
|
1466
|
+
content.push({
|
|
1467
|
+
type: "tool-use",
|
|
1468
|
+
id: call.id,
|
|
1469
|
+
name: call.name,
|
|
1470
|
+
input
|
|
1471
|
+
});
|
|
1472
|
+
}
|
|
1473
|
+
if (finishReason !== "refusal" && finishReason !== "max-tokens" && droppedToolCalls.length === 0 && !content.some((part) => part.type === "text" || part.type === "tool-use")) throw support.failures.create({
|
|
1474
|
+
code: "response-empty",
|
|
1475
|
+
stage: "response-validation",
|
|
1476
|
+
category: "protocol",
|
|
1477
|
+
source: "protocol",
|
|
1478
|
+
retryable: false,
|
|
1479
|
+
finishReason
|
|
1480
|
+
});
|
|
1481
|
+
yield {
|
|
1482
|
+
kind: "final",
|
|
1483
|
+
finishReason,
|
|
1484
|
+
...finishReason === "max-tokens" ? { outputTruncation: {
|
|
1485
|
+
incompleteToolCalls,
|
|
1486
|
+
...thinkingOpen ? { incompleteThinking: true } : {}
|
|
1487
|
+
} } : {},
|
|
1488
|
+
...droppedToolCalls.length > 0 ? { droppedToolCalls } : {},
|
|
1489
|
+
usage: {
|
|
1490
|
+
inputTokens,
|
|
1491
|
+
outputTokens,
|
|
1492
|
+
...cache,
|
|
1493
|
+
...inputTokensReported ? {} : { inputTokensReported: false }
|
|
1494
|
+
},
|
|
1495
|
+
...finishReason === "refusal" ? { refusalCategory: "content_filter" } : {},
|
|
1496
|
+
message: {
|
|
1497
|
+
role: "assistant",
|
|
1498
|
+
content
|
|
1499
|
+
}
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1502
|
+
//#endregion
|
|
1503
|
+
//#region src/protocol/port.ts
|
|
1504
|
+
function openaiOptions(plan) {
|
|
1505
|
+
return {
|
|
1506
|
+
...plan.effort === void 0 ? {} : { reasoningEffort: plan.effort },
|
|
1507
|
+
...plan.thinking === void 0 ? {} : { thinking: plan.thinking },
|
|
1508
|
+
...plan.temperature === void 0 ? {} : { temperature: plan.temperature },
|
|
1509
|
+
...plan.maxTokens === void 0 ? {} : { maxTokens: plan.maxTokens }
|
|
1510
|
+
};
|
|
1511
|
+
}
|
|
1512
|
+
function createOpenAIModelPort(options) {
|
|
1513
|
+
async function clientForAttempt(reportProgress, dispatched) {
|
|
1514
|
+
const { default: OpenAI } = await loadOpenAISdk();
|
|
1515
|
+
return options.client ?? new OpenAI({
|
|
1516
|
+
apiKey: options.allowUnauthenticated && !options.apiKey ? "not-used" : options.apiKey ?? "",
|
|
1517
|
+
...options.allowUnauthenticated && !options.apiKey ? { defaultHeaders: { Authorization: null } } : {},
|
|
1518
|
+
fetch: async (...args) => {
|
|
1519
|
+
const pending = (options.fetch ?? globalThis.fetch)(...args);
|
|
1520
|
+
dispatched();
|
|
1521
|
+
return options.support.observeResponseProgress(await pending, reportProgress);
|
|
1522
|
+
},
|
|
1523
|
+
baseURL: options.baseURL ?? "",
|
|
1524
|
+
maxRetries: 0
|
|
1525
|
+
});
|
|
1526
|
+
}
|
|
1527
|
+
function build(request) {
|
|
1528
|
+
const capacity = options.support.freezePayload(options.catalogue?.()?.limit ?? {});
|
|
1529
|
+
const outputLimit = Number.isInteger(capacity?.output) && Number(capacity?.output) > 0 ? Number(capacity?.output) : void 0;
|
|
1530
|
+
const effectiveRequest = request.purpose === "summary" && outputLimit !== void 0 ? {
|
|
1531
|
+
...request,
|
|
1532
|
+
summaryMaxTokens: Math.min(request.summaryMaxTokens ?? 0, outputLimit)
|
|
1533
|
+
} : request;
|
|
1534
|
+
const { media: mediaOf, ...rest } = options;
|
|
1535
|
+
const media = mediaOf?.(request.params ?? {});
|
|
1536
|
+
const base = media === void 0 ? rest : {
|
|
1537
|
+
...rest,
|
|
1538
|
+
media
|
|
1539
|
+
};
|
|
1540
|
+
const requestOptions = options.params === void 0 ? base : {
|
|
1541
|
+
...base,
|
|
1542
|
+
...openaiOptions(options.params(request.params ?? {})),
|
|
1543
|
+
extra: {
|
|
1544
|
+
...options.extra,
|
|
1545
|
+
...options.support.extraParams(request.params ?? {})
|
|
1546
|
+
}
|
|
1547
|
+
};
|
|
1548
|
+
const mediaPlan = options.support.planMedia(effectiveRequest, requestOptions.media ?? {
|
|
1549
|
+
acceptsImages: true,
|
|
1550
|
+
limits: void 0
|
|
1551
|
+
});
|
|
1552
|
+
const params = options.support.freezePayload(toOpenAIRequest(effectiveRequest, requestOptions, mediaPlan));
|
|
1553
|
+
const settings = options.support.freezePayload({
|
|
1554
|
+
reasoningEffort: requestOptions.reasoningEffort,
|
|
1555
|
+
temperature: requestOptions.temperature,
|
|
1556
|
+
maxTokens: params.max_tokens,
|
|
1557
|
+
extra: request.purpose === "summary" && request.summaryShape !== "continuation" ? void 0 : requestOptions.extra
|
|
1558
|
+
});
|
|
1559
|
+
const replacements = /* @__PURE__ */ new Map();
|
|
1560
|
+
let mediaIndex = 0;
|
|
1561
|
+
for (const message of params.messages) {
|
|
1562
|
+
if (!Array.isArray(message.content)) continue;
|
|
1563
|
+
for (const part of message.content) {
|
|
1564
|
+
if (part.type !== "image_url") continue;
|
|
1565
|
+
const planned = mediaPlan.sent[mediaIndex++];
|
|
1566
|
+
if (!planned || part.image_url.url !== `data:${planned.mediaType};base64,${planned.data ?? ""}`) throw new Error("prepared_media_selection_mismatch");
|
|
1567
|
+
const data = planned.data ?? "";
|
|
1568
|
+
const hash = createHash("sha256");
|
|
1569
|
+
for (let offset = 0; offset < data.length; offset += 65536) hash.update(data.slice(offset, offset + 65536), "base64");
|
|
1570
|
+
replacements.set(part.image_url, {
|
|
1571
|
+
kind: "media",
|
|
1572
|
+
value: JSON.stringify({
|
|
1573
|
+
sha256: hash.digest("hex"),
|
|
1574
|
+
byteLength: Buffer.byteLength(data, "base64"),
|
|
1575
|
+
variantId: planned.variantId,
|
|
1576
|
+
mediaType: planned.mediaType,
|
|
1577
|
+
width: planned.width,
|
|
1578
|
+
height: planned.height,
|
|
1579
|
+
detail: part.image_url.detail ?? "auto"
|
|
1580
|
+
})
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
if (mediaIndex !== mediaPlan.sent.length) throw new Error("prepared_media_selection_mismatch");
|
|
1585
|
+
return {
|
|
1586
|
+
params,
|
|
1587
|
+
capacity,
|
|
1588
|
+
mediaPlan,
|
|
1589
|
+
replacements,
|
|
1590
|
+
replaySelections: options.support.prepareReplaySelections(effectiveRequest, ({ message, part }) => {
|
|
1591
|
+
const selected = part && openaiThinkingIsSendable(message, requestOptions);
|
|
1592
|
+
return {
|
|
1593
|
+
mode: "reasoning-content",
|
|
1594
|
+
textIncluded: !!selected,
|
|
1595
|
+
...selected ? { selectedText: part.text } : { reason: "not-applicable" },
|
|
1596
|
+
group: message.id
|
|
1597
|
+
};
|
|
1598
|
+
}),
|
|
1599
|
+
request: {
|
|
1600
|
+
...request,
|
|
1601
|
+
params: options.support.freezePayload(request.params ?? {})
|
|
1602
|
+
},
|
|
1603
|
+
fingerprint: options.support.freezePayload({
|
|
1604
|
+
rendering: "openai-chat-completions-v3",
|
|
1605
|
+
endpoint: options.endpoint ?? options.baseURL,
|
|
1606
|
+
model: params.model,
|
|
1607
|
+
purpose: request.purpose,
|
|
1608
|
+
settings
|
|
1609
|
+
})
|
|
1610
|
+
};
|
|
1611
|
+
}
|
|
1612
|
+
return options.support.createPreparedPort({
|
|
1613
|
+
prepare: build,
|
|
1614
|
+
semantics(payload) {
|
|
1615
|
+
return {
|
|
1616
|
+
replaySelections: payload.replaySelections,
|
|
1617
|
+
mediaSelections: () => options.support.mediaSelections(payload.mediaPlan),
|
|
1618
|
+
toolDefinitions: payload.params.tools ?? Object.freeze([]),
|
|
1619
|
+
parameters: Object.freeze(Object.fromEntries(Object.entries(payload.params).filter(([key]) => ![
|
|
1620
|
+
"model",
|
|
1621
|
+
"messages",
|
|
1622
|
+
"tools",
|
|
1623
|
+
"stream",
|
|
1624
|
+
"stream_options",
|
|
1625
|
+
"prompt_cache_key"
|
|
1626
|
+
].includes(key)))),
|
|
1627
|
+
format: "request-semantic-v1",
|
|
1628
|
+
protocolId: "openai",
|
|
1629
|
+
adapterVersion: "1",
|
|
1630
|
+
rendererVersion: "openai-chat-completions-v3",
|
|
1631
|
+
frames: () => options.support.semanticFrames(payload.params, {
|
|
1632
|
+
omitRoot: [
|
|
1633
|
+
"stream",
|
|
1634
|
+
"stream_options",
|
|
1635
|
+
"prompt_cache_key"
|
|
1636
|
+
],
|
|
1637
|
+
replacements: payload.replacements
|
|
1638
|
+
})
|
|
1639
|
+
};
|
|
1640
|
+
},
|
|
1641
|
+
async inspect(payload, signal) {
|
|
1642
|
+
signal.throwIfAborted();
|
|
1643
|
+
const started = options.support.performance?.now();
|
|
1644
|
+
const { params, request, capacity, mediaPlan, fingerprint } = payload;
|
|
1645
|
+
const bodyMaxTokens = params.max_tokens;
|
|
1646
|
+
const bodyMaxCompletionTokens = params.max_completion_tokens;
|
|
1647
|
+
const explicitOutputLimits = [bodyMaxTokens, bodyMaxCompletionTokens].filter((value) => Number.isInteger(value) && Number(value) > 0).map(Number);
|
|
1648
|
+
const enforced = Number.isInteger(bodyMaxCompletionTokens) && Number(bodyMaxCompletionTokens) > 0;
|
|
1649
|
+
const outputReserve = enforced ? Math.max(...explicitOutputLimits) : capacity?.output ?? Math.max(0, ...explicitOutputLimits);
|
|
1650
|
+
options.support.performance?.observe({
|
|
1651
|
+
stage: "model.project",
|
|
1652
|
+
measurementPurpose: "request",
|
|
1653
|
+
durationMs: options.support.performance.now() - started,
|
|
1654
|
+
count: 1
|
|
1655
|
+
});
|
|
1656
|
+
const text = options.support.requestText("chat-completions", params);
|
|
1657
|
+
const inspection = options.support.inspect({
|
|
1658
|
+
body: params,
|
|
1659
|
+
textTokens: 0,
|
|
1660
|
+
textBytes: Buffer.byteLength(text),
|
|
1661
|
+
tokenizer: "utf8-bytes-quarter-v1",
|
|
1662
|
+
request,
|
|
1663
|
+
capacity,
|
|
1664
|
+
outputReserve,
|
|
1665
|
+
outputReserveSource: enforced ? "enforced" : "capacity",
|
|
1666
|
+
mediaTokens: mediaPlan.tokens,
|
|
1667
|
+
fingerprint
|
|
1668
|
+
});
|
|
1669
|
+
const textTokens = await options.support.measureText(text, signal);
|
|
1670
|
+
signal.throwIfAborted();
|
|
1671
|
+
return {
|
|
1672
|
+
...inspection,
|
|
1673
|
+
inputTokens: inspection.inputTokens + textTokens
|
|
1674
|
+
};
|
|
1675
|
+
},
|
|
1676
|
+
stream(payload, signal, observer, scope) {
|
|
1677
|
+
signal.throwIfAborted();
|
|
1678
|
+
const { params } = payload;
|
|
1679
|
+
return options.support.withChatAttempts({
|
|
1680
|
+
retainCleanup: scope.retainCleanup,
|
|
1681
|
+
beforeAttempt: (_signal, ordinal) => observer?.beforeAttempt?.(ordinal),
|
|
1682
|
+
accountingDispatch: options.accountingDispatch,
|
|
1683
|
+
effective: {
|
|
1684
|
+
outputLimit: params.max_completion_tokens ?? params.max_tokens,
|
|
1685
|
+
effort: params.reasoning_effort
|
|
1686
|
+
},
|
|
1687
|
+
signal,
|
|
1688
|
+
...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
|
|
1689
|
+
...options.sleep === void 0 ? {} : { sleep: options.sleep },
|
|
1690
|
+
...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
|
|
1691
|
+
async *attempt(attemptSignal, reportProgress, attempt, usageReporter) {
|
|
1692
|
+
const observe = (event) => {
|
|
1693
|
+
try {
|
|
1694
|
+
observer?.observe?.(event);
|
|
1695
|
+
} catch {}
|
|
1696
|
+
};
|
|
1697
|
+
const attemptCount = attempt + 1;
|
|
1698
|
+
let outcome = "unknown";
|
|
1699
|
+
let timeout;
|
|
1700
|
+
let firstResponseFinished = false;
|
|
1701
|
+
let dispatchObserved = false;
|
|
1702
|
+
const markDispatched = () => {
|
|
1703
|
+
if (dispatchObserved) return;
|
|
1704
|
+
dispatchObserved = true;
|
|
1705
|
+
try {
|
|
1706
|
+
observer?.dispatched({
|
|
1707
|
+
attempt,
|
|
1708
|
+
presentation: {
|
|
1709
|
+
schema: "chat.dispatch-settings.v1",
|
|
1710
|
+
data: {
|
|
1711
|
+
model: {
|
|
1712
|
+
availability: "resolved",
|
|
1713
|
+
value: params.model,
|
|
1714
|
+
origin: "protocol"
|
|
1715
|
+
},
|
|
1716
|
+
effort: params.reasoning_effort ? {
|
|
1717
|
+
availability: "resolved",
|
|
1718
|
+
value: params.reasoning_effort,
|
|
1719
|
+
origin: "protocol"
|
|
1720
|
+
} : {
|
|
1721
|
+
availability: "resolved",
|
|
1722
|
+
value: "default",
|
|
1723
|
+
origin: "protocol"
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
}
|
|
1727
|
+
});
|
|
1728
|
+
} catch {}
|
|
1729
|
+
};
|
|
1730
|
+
observe({
|
|
1731
|
+
stage: "attempt",
|
|
1732
|
+
phase: "start",
|
|
1733
|
+
attempt: attemptCount
|
|
1734
|
+
});
|
|
1735
|
+
observe({
|
|
1736
|
+
stage: "first-response",
|
|
1737
|
+
phase: "start",
|
|
1738
|
+
attempt: attemptCount
|
|
1739
|
+
});
|
|
1740
|
+
let sdkIterator;
|
|
1741
|
+
try {
|
|
1742
|
+
const client = await clientForAttempt(reportProgress, markDispatched);
|
|
1743
|
+
attemptSignal.throwIfAborted();
|
|
1744
|
+
const pending = client.chat.completions.create(params, { signal: attemptSignal });
|
|
1745
|
+
if (options.client) markDispatched();
|
|
1746
|
+
const chunks = await pending;
|
|
1747
|
+
if (options.client) reportProgress();
|
|
1748
|
+
sdkIterator = chunks[Symbol.asyncIterator]();
|
|
1749
|
+
firstResponseFinished = true;
|
|
1750
|
+
observe({
|
|
1751
|
+
stage: "first-response",
|
|
1752
|
+
phase: "end",
|
|
1753
|
+
attempt: attemptCount,
|
|
1754
|
+
outcome: "ok"
|
|
1755
|
+
});
|
|
1756
|
+
attemptSignal.throwIfAborted();
|
|
1757
|
+
const iterator = sdkIterator;
|
|
1758
|
+
const observed = (async function* () {
|
|
1759
|
+
for (;;) {
|
|
1760
|
+
const result = await iterator.next();
|
|
1761
|
+
if (result.done) return;
|
|
1762
|
+
reportProgress();
|
|
1763
|
+
yield result.value;
|
|
1764
|
+
}
|
|
1765
|
+
})();
|
|
1766
|
+
for await (const chunk of mapOpenAIStream(observed, options.support, options.model, usageReporter)) {
|
|
1767
|
+
if (chunk.kind === "final") outcome = "ok";
|
|
1768
|
+
yield chunk;
|
|
1769
|
+
}
|
|
1770
|
+
} catch (error) {
|
|
1771
|
+
const reason = attemptSignal.aborted ? options.support.failures.verified(attemptSignal.reason) : void 0;
|
|
1772
|
+
if (reason?.code === "stream-idle-timeout") {
|
|
1773
|
+
outcome = "timeout";
|
|
1774
|
+
timeout = reason;
|
|
1775
|
+
} else outcome = attemptSignal.aborted ? "cancelled" : "error";
|
|
1776
|
+
throw error;
|
|
1777
|
+
} finally {
|
|
1778
|
+
if (sdkIterator) {
|
|
1779
|
+
const iterator = sdkIterator;
|
|
1780
|
+
scope.retainCleanup(async () => {
|
|
1781
|
+
await iterator.return?.();
|
|
1782
|
+
}).catch(() => {});
|
|
1783
|
+
}
|
|
1784
|
+
const end = {
|
|
1785
|
+
phase: "end",
|
|
1786
|
+
attempt: attemptCount,
|
|
1787
|
+
outcome,
|
|
1788
|
+
...timeout ? { failure: timeout } : {}
|
|
1789
|
+
};
|
|
1790
|
+
if (!firstResponseFinished) observe({
|
|
1791
|
+
stage: "first-response",
|
|
1792
|
+
...end
|
|
1793
|
+
});
|
|
1794
|
+
observe({
|
|
1795
|
+
stage: "attempt",
|
|
1796
|
+
...end
|
|
1797
|
+
});
|
|
1798
|
+
}
|
|
1799
|
+
},
|
|
1800
|
+
classify(error) {
|
|
1801
|
+
const portError = toModelFailure(error, options.support.failures, options.support.transportFailure);
|
|
1802
|
+
return {
|
|
1803
|
+
error: portError,
|
|
1804
|
+
retryable: portError.retryable === true,
|
|
1805
|
+
retryAfterMs: retryAfterMs(error)
|
|
1806
|
+
};
|
|
1807
|
+
}
|
|
1808
|
+
});
|
|
1809
|
+
}
|
|
1810
|
+
});
|
|
1811
|
+
}
|
|
1812
|
+
//#endregion
|
|
1813
|
+
//#region src/protocol.ts
|
|
1814
|
+
const OpenAIProtocolOptions = z.strictObject({
|
|
1815
|
+
allowUnauthenticated: z.boolean().optional(),
|
|
1816
|
+
reasoningReplay: z.enum(["omit", "reasoning-content"]).optional(),
|
|
1817
|
+
thinkingField: z.boolean().optional(),
|
|
1818
|
+
outputLimitField: z.enum(["max_tokens", "max_completion_tokens"]).optional(),
|
|
1819
|
+
promptCacheKey: z.boolean().optional()
|
|
1820
|
+
});
|
|
1821
|
+
function openaiProtocolType(support, fetch) {
|
|
1822
|
+
return {
|
|
1823
|
+
type: "openai",
|
|
1824
|
+
label: "OpenAI Chat Completions API",
|
|
1825
|
+
logo: protocolLogo,
|
|
1826
|
+
fields: [{
|
|
1827
|
+
key: "baseUrl",
|
|
1828
|
+
kind: "url",
|
|
1829
|
+
label: "Base URL",
|
|
1830
|
+
required: true
|
|
1831
|
+
}],
|
|
1832
|
+
userConfigurable: true,
|
|
1833
|
+
optionsSchema: OpenAIProtocolOptions,
|
|
1834
|
+
facts,
|
|
1835
|
+
prepareParams: (input) => support.prepareParams(input, facts),
|
|
1836
|
+
adapters: { chat: {
|
|
1837
|
+
fileKinds: ["image"],
|
|
1838
|
+
supportsModel: () => true,
|
|
1839
|
+
createPort(call) {
|
|
1840
|
+
const options = OpenAIProtocolOptions.parse(call.options);
|
|
1841
|
+
return createOpenAIModelPort({
|
|
1842
|
+
accountingDispatch: call.accountingDispatch,
|
|
1843
|
+
support,
|
|
1844
|
+
fetch: withConnectionHeaders(fetch, call.headers),
|
|
1845
|
+
model: call.model,
|
|
1846
|
+
endpoint: call.providerId,
|
|
1847
|
+
apiKey: call.secrets.apiKey ?? "",
|
|
1848
|
+
baseURL: String(call.config.baseUrl ?? ""),
|
|
1849
|
+
...options,
|
|
1850
|
+
catalogue: () => support.catalogue(call.providerId, call.model),
|
|
1851
|
+
media: (stored) => support.mediaContextOf({
|
|
1852
|
+
entry: support.catalogue(call.providerId, call.model),
|
|
1853
|
+
stored,
|
|
1854
|
+
facts,
|
|
1855
|
+
endpoint: support.endpoint(call.providerId),
|
|
1856
|
+
fileKinds: ["image"]
|
|
1857
|
+
}),
|
|
1858
|
+
params: (stored) => support.resolveParams({
|
|
1859
|
+
entry: support.catalogue(call.providerId, call.model),
|
|
1860
|
+
stored,
|
|
1861
|
+
facts,
|
|
1862
|
+
model: call.model,
|
|
1863
|
+
endpoint: support.endpoint(call.providerId)
|
|
1864
|
+
})
|
|
1865
|
+
});
|
|
1866
|
+
}
|
|
1867
|
+
} },
|
|
1868
|
+
normalizeListing: (input) => normalizeOffers(input),
|
|
1869
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, withConnectionHeaders(fetch, probe.headers)) }),
|
|
1870
|
+
testConnection: (probe) => probeOpenAI.testConnection(probe, withConnectionHeaders(fetch, probe.headers))
|
|
1871
|
+
};
|
|
1872
|
+
}
|
|
1873
|
+
//#endregion
|
|
1874
|
+
//#region src/responses/semantics.ts
|
|
1875
|
+
function responsesSemanticFields(body, mediaPlan) {
|
|
1876
|
+
const fields = /* @__PURE__ */ new Map();
|
|
1877
|
+
for (const item of body.input) if (item.type === "reasoning" && typeof item.encrypted_content === "string") fields.set(item, /* @__PURE__ */ new Map([["encrypted_content", {
|
|
1878
|
+
kind: "replay",
|
|
1879
|
+
value: JSON.stringify({
|
|
1880
|
+
sha256: createHash("sha256").update(item.encrypted_content).digest("hex"),
|
|
1881
|
+
byteLength: Buffer.byteLength(item.encrypted_content),
|
|
1882
|
+
mode: "responses-encrypted",
|
|
1883
|
+
model: body.model
|
|
1884
|
+
})
|
|
1885
|
+
}]]));
|
|
1886
|
+
let mediaIndex = 0;
|
|
1887
|
+
const mediaFields = (input) => {
|
|
1888
|
+
if (Array.isArray(input)) {
|
|
1889
|
+
for (const item of input) mediaFields(item);
|
|
1890
|
+
return;
|
|
1891
|
+
}
|
|
1892
|
+
if (input === null || typeof input !== "object") return;
|
|
1893
|
+
const item = input;
|
|
1894
|
+
if (item.type === "input_image") {
|
|
1895
|
+
const planned = mediaPlan.sent[mediaIndex++];
|
|
1896
|
+
if (!planned || item.image_url !== `data:${planned.mediaType};base64,${planned.data ?? ""}`) throw new Error("prepared_media_selection_mismatch");
|
|
1897
|
+
const data = planned.data ?? "";
|
|
1898
|
+
const hash = createHash("sha256");
|
|
1899
|
+
for (let offset = 0; offset < data.length; offset += 65536) hash.update(data.slice(offset, offset + 65536), "base64");
|
|
1900
|
+
fields.set(item, /* @__PURE__ */ new Map([["image_url", {
|
|
1901
|
+
kind: "media",
|
|
1902
|
+
value: JSON.stringify({
|
|
1903
|
+
sha256: hash.digest("hex"),
|
|
1904
|
+
byteLength: Buffer.byteLength(data, "base64"),
|
|
1905
|
+
variantId: planned.variantId,
|
|
1906
|
+
mediaType: planned.mediaType,
|
|
1907
|
+
width: planned.width,
|
|
1908
|
+
height: planned.height
|
|
1909
|
+
})
|
|
1910
|
+
}]]));
|
|
1911
|
+
}
|
|
1912
|
+
for (const key of ["content", "output"]) if (Array.isArray(item[key])) mediaFields(item[key]);
|
|
1913
|
+
};
|
|
1914
|
+
mediaFields(body.input);
|
|
1915
|
+
if (mediaIndex !== mediaPlan.sent.length) throw new Error("prepared_media_selection_mismatch");
|
|
1916
|
+
return fields;
|
|
1917
|
+
}
|
|
1918
|
+
//#endregion
|
|
1919
|
+
//#region src/responses/request.ts
|
|
1920
|
+
function replayable(message, options) {
|
|
1921
|
+
if (options.reasoningReplay === "omit" || message.outputTruncation?.incompleteThinking || !message.content.some((part) => part.type === "text" && part.text !== "" || part.type === "tool-use")) return false;
|
|
1922
|
+
return message.content.filter((part) => part.type === "thinking").every((part) => (options.reasoningReplay === "reasoning-content" || part.signature !== void 0) && part.issuer === options.endpoint && part.originModel === options.model);
|
|
1923
|
+
}
|
|
1924
|
+
function responsesReplayChoice(message, part, options) {
|
|
1925
|
+
const selected = message.role === "assistant" && replayable(message, options);
|
|
1926
|
+
const plain = options.reasoningReplay === "reasoning-content";
|
|
1927
|
+
return {
|
|
1928
|
+
mode: plain ? "reasoning-content" : "encrypted",
|
|
1929
|
+
textIncluded: selected && part.text !== "",
|
|
1930
|
+
...selected ? { selectedText: plain ? part.text : part.signature } : { reason: "not-applicable" },
|
|
1931
|
+
group: message.id
|
|
1932
|
+
};
|
|
1933
|
+
}
|
|
1934
|
+
function responsesHiddenInputTokens(request, options) {
|
|
1935
|
+
return request.messages.reduce((total, message) => {
|
|
1936
|
+
if (options.reasoningReplay === "reasoning-content" || message.role !== "assistant" || !replayable(message, options)) return total;
|
|
1937
|
+
return total + Math.max(0, ...message.content.map((part) => part.type === "thinking" ? part.outputTokens ?? 0 : 0));
|
|
1938
|
+
}, 0);
|
|
1939
|
+
}
|
|
1940
|
+
function fileParts(planned) {
|
|
1941
|
+
const label = {
|
|
1942
|
+
type: "input_text",
|
|
1943
|
+
text: planned.label
|
|
1944
|
+
};
|
|
1945
|
+
if (planned.fate !== "send") return [label];
|
|
1946
|
+
return [label, {
|
|
1947
|
+
type: "input_image",
|
|
1948
|
+
image_url: `data:${planned.mediaType};base64,${planned.data ?? ""}`
|
|
1949
|
+
}];
|
|
1950
|
+
}
|
|
1951
|
+
function outputOf(part, plan, at) {
|
|
1952
|
+
const files = part.files ?? [];
|
|
1953
|
+
if (files.length === 0) return part.content;
|
|
1954
|
+
return [...part.content === "" ? [] : [{
|
|
1955
|
+
type: "input_text",
|
|
1956
|
+
text: part.content
|
|
1957
|
+
}], ...files.flatMap((_, index) => fileParts(plan.at(at.message, at.part, index)))];
|
|
1958
|
+
}
|
|
1959
|
+
function userItems(message, index, plan) {
|
|
1960
|
+
const items = [];
|
|
1961
|
+
let text = "";
|
|
1962
|
+
let content = [];
|
|
1963
|
+
const flushText = () => {
|
|
1964
|
+
if (text.length > 0) content.push({
|
|
1965
|
+
type: "input_text",
|
|
1966
|
+
text
|
|
1967
|
+
});
|
|
1968
|
+
text = "";
|
|
1969
|
+
};
|
|
1970
|
+
const flush = () => {
|
|
1971
|
+
flushText();
|
|
1972
|
+
if (content.length > 0) items.push({
|
|
1973
|
+
type: "message",
|
|
1974
|
+
role: "user",
|
|
1975
|
+
content
|
|
111
1976
|
});
|
|
112
|
-
|
|
1977
|
+
content = [];
|
|
113
1978
|
};
|
|
114
1979
|
message.content.forEach((part, partIndex) => {
|
|
115
1980
|
if (part.type === "text") text += part.text;
|
|
116
1981
|
else if (part.type === "file") {
|
|
117
|
-
|
|
1982
|
+
flushText();
|
|
1983
|
+
content.push(...fileParts(plan.at(index, partIndex)));
|
|
1984
|
+
} else if (part.type === "tool-result") {
|
|
118
1985
|
flush();
|
|
119
|
-
|
|
120
|
-
type: "
|
|
121
|
-
|
|
1986
|
+
items.push({
|
|
1987
|
+
type: "function_call_output",
|
|
1988
|
+
call_id: part.toolUseId,
|
|
1989
|
+
output: outputOf(part, plan, {
|
|
1990
|
+
message: index,
|
|
1991
|
+
part: partIndex
|
|
1992
|
+
})
|
|
122
1993
|
});
|
|
123
|
-
if (planned.fate === "send") parts.push(imagePart(planned));
|
|
124
1994
|
}
|
|
125
1995
|
});
|
|
126
1996
|
flush();
|
|
127
|
-
return
|
|
1997
|
+
return items;
|
|
128
1998
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
partIndex
|
|
142
|
-
})).filter((entry) => entry.part.type === "tool-result");
|
|
143
|
-
if (message.role === "user" && toolResults.length > 0) {
|
|
144
|
-
const images = [];
|
|
145
|
-
const tools = toolResults.map(({ part, partIndex }) => {
|
|
146
|
-
const lines = [part.content];
|
|
147
|
-
(part.files ?? []).forEach((_, fileIndex) => {
|
|
148
|
-
const planned = plan.at(index, partIndex, fileIndex);
|
|
149
|
-
if (planned.fate !== "send") {
|
|
150
|
-
lines.push(planned.label);
|
|
151
|
-
return;
|
|
152
|
-
}
|
|
153
|
-
images.push({
|
|
154
|
-
type: "text",
|
|
155
|
-
text: `${part.toolUseId} ${planned.label}`
|
|
156
|
-
}, imagePart(planned));
|
|
1999
|
+
function assistantItems(message, options) {
|
|
2000
|
+
const sendThinking = replayable(message, options);
|
|
2001
|
+
const items = [];
|
|
2002
|
+
for (const part of message.content) if (part.type === "thinking") {
|
|
2003
|
+
if (!sendThinking) continue;
|
|
2004
|
+
if (options.reasoningReplay === "reasoning-content") {
|
|
2005
|
+
items.push({
|
|
2006
|
+
type: "reasoning",
|
|
2007
|
+
content: [{
|
|
2008
|
+
type: "reasoning_text",
|
|
2009
|
+
text: part.text
|
|
2010
|
+
}]
|
|
157
2011
|
});
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
2012
|
+
continue;
|
|
2013
|
+
}
|
|
2014
|
+
items.push({
|
|
2015
|
+
type: "reasoning",
|
|
2016
|
+
summary: part.text === "" ? [] : [{
|
|
2017
|
+
type: "summary_text",
|
|
2018
|
+
text: part.text
|
|
2019
|
+
}],
|
|
2020
|
+
encrypted_content: part.signature
|
|
163
2021
|
});
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
text: "Images returned by tool calls:"
|
|
169
|
-
}, ...images]
|
|
170
|
-
}];
|
|
171
|
-
}
|
|
172
|
-
if (message.role === "assistant") {
|
|
173
|
-
const content = textOf(message.content);
|
|
174
|
-
const toolCalls = toolCallsOf(message.content);
|
|
175
|
-
if (content === null && toolCalls === void 0) return [];
|
|
176
|
-
return [{
|
|
2022
|
+
} else if (part.type === "text") {
|
|
2023
|
+
if (part.text === "") continue;
|
|
2024
|
+
items.push({
|
|
2025
|
+
type: "message",
|
|
177
2026
|
role: "assistant",
|
|
178
|
-
content
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
2027
|
+
content: [{
|
|
2028
|
+
type: "output_text",
|
|
2029
|
+
text: part.text
|
|
2030
|
+
}]
|
|
2031
|
+
});
|
|
2032
|
+
} else if (part.type === "tool-use") items.push({
|
|
2033
|
+
type: "function_call",
|
|
2034
|
+
call_id: part.id,
|
|
2035
|
+
name: part.name,
|
|
2036
|
+
arguments: JSON.stringify(part.input ?? {})
|
|
2037
|
+
});
|
|
2038
|
+
return items;
|
|
187
2039
|
}
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
* **Appended unconditionally, without looking at what the last message is.**
|
|
193
|
-
* `toChatMessages` turns a user message carrying `tool-result` parts into
|
|
194
|
-
* `role: 'tool'` messages and drops its text parts, so writing the text into
|
|
195
|
-
* the last message — the anthropic member's shape — would lose it silently on
|
|
196
|
-
* the most common path there is: the step right after a tool call, which is
|
|
197
|
-
* when a volatile contribution first reaches the model. One message of its
|
|
198
|
-
* own has no such branch, and it puts the invariant in the code rather than
|
|
199
|
-
* in a reviewer's head.
|
|
200
|
-
*
|
|
201
|
-
* Nothing is added when there is nothing to add — an absent slot, an empty
|
|
202
|
-
* one, and one whose contributions are all empty leave the request the
|
|
203
|
-
* caller would have got anyway.
|
|
204
|
-
*/
|
|
205
|
-
function volatileMessages(volatile) {
|
|
206
|
-
const content = (volatile ?? []).map((note) => note.text).join("\n\n");
|
|
207
|
-
return content.length > 0 ? [{
|
|
2040
|
+
function noteItems(notes) {
|
|
2041
|
+
const text = (notes ?? []).map((note) => note.text).join("\n\n");
|
|
2042
|
+
return text === "" ? [] : [{
|
|
2043
|
+
type: "message",
|
|
208
2044
|
role: "user",
|
|
209
|
-
content
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
function withNotes(message, index, plan, reasoningReplay) {
|
|
215
|
-
return [...message.role === "assistant" ? volatileMessages(message.volatile) : [], ...toChatMessages(message, index, plan, reasoningReplay)];
|
|
2045
|
+
content: [{
|
|
2046
|
+
type: "input_text",
|
|
2047
|
+
text
|
|
2048
|
+
}]
|
|
2049
|
+
}];
|
|
216
2050
|
}
|
|
217
|
-
function
|
|
2051
|
+
function toolOf(tool) {
|
|
218
2052
|
return {
|
|
219
2053
|
type: "function",
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
}
|
|
2054
|
+
name: tool.name,
|
|
2055
|
+
description: tool.description,
|
|
2056
|
+
parameters: tool.inputSchema,
|
|
2057
|
+
strict: false
|
|
225
2058
|
};
|
|
226
2059
|
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
const
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
2060
|
+
function toResponsesBody(request, options, plan) {
|
|
2061
|
+
const input = [];
|
|
2062
|
+
const updates = new Map(options.effortUpdates?.map((update) => [update.beforeUserMessageId, update.effort]));
|
|
2063
|
+
request.messages.forEach((message, index) => {
|
|
2064
|
+
const effort = updates.get(message.id);
|
|
2065
|
+
if (effort !== void 0) input.push({
|
|
2066
|
+
type: "configuration_update",
|
|
2067
|
+
reasoning: { effort }
|
|
2068
|
+
});
|
|
2069
|
+
if (message.role === "user") input.push(...userItems(message, index, plan));
|
|
2070
|
+
else input.push(...noteItems(message.volatile), ...assistantItems(message, options));
|
|
236
2071
|
});
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
}] : [];
|
|
2072
|
+
input.push(...noteItems(request.volatile));
|
|
2073
|
+
const instructions = (request.system ?? []).join("\n\n");
|
|
2074
|
+
const tools = (request.tools ?? []).map(toolOf);
|
|
241
2075
|
return {
|
|
242
2076
|
model: options.model,
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
...options.
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
...options.promptCacheKey === true && request.cacheKey !== void 0 ? { prompt_cache_key: request.cacheKey } : {},
|
|
257
|
-
...summary ? {} : options.extra
|
|
2077
|
+
...instructions === "" ? {} : { instructions },
|
|
2078
|
+
input,
|
|
2079
|
+
...tools.length === 0 ? {} : {
|
|
2080
|
+
tools,
|
|
2081
|
+
tool_choice: request.toolChoice === "none" ? "none" : "auto"
|
|
2082
|
+
},
|
|
2083
|
+
...options.effort === void 0 && options.reasoningSummary === false ? {} : { reasoning: {
|
|
2084
|
+
...options.effort === void 0 ? {} : { effort: options.effort },
|
|
2085
|
+
...options.reasoningSummary === false ? {} : { summary: "auto" }
|
|
2086
|
+
} },
|
|
2087
|
+
...options.encryptedReasoningInclude !== false && (options.reasoningReplay === void 0 || options.reasoningReplay === "encrypted") ? { include: ["reasoning.encrypted_content"] } : {},
|
|
2088
|
+
store: false,
|
|
2089
|
+
stream: true
|
|
258
2090
|
};
|
|
259
2091
|
}
|
|
260
2092
|
//#endregion
|
|
261
|
-
//#region src/
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
2093
|
+
//#region src/responses/codec.ts
|
|
2094
|
+
const responsesCodec = {
|
|
2095
|
+
render: toResponsesBody,
|
|
2096
|
+
replayChoice: responsesReplayChoice,
|
|
2097
|
+
semanticFields: responsesSemanticFields,
|
|
2098
|
+
hiddenInputTokens: responsesHiddenInputTokens
|
|
2099
|
+
};
|
|
2100
|
+
//#endregion
|
|
2101
|
+
//#region src/responses/options.ts
|
|
2102
|
+
const ResponsesProtocolOptions = z.strictObject({
|
|
2103
|
+
allowUnauthenticated: z.boolean().optional(),
|
|
2104
|
+
reasoningReplay: z.enum([
|
|
2105
|
+
"encrypted",
|
|
2106
|
+
"reasoning-content",
|
|
2107
|
+
"omit"
|
|
2108
|
+
]).optional(),
|
|
2109
|
+
reasoningSummary: z.boolean().optional(),
|
|
2110
|
+
thinkingOnEffort: z.enum([
|
|
2111
|
+
"minimal",
|
|
2112
|
+
"low",
|
|
2113
|
+
"medium",
|
|
2114
|
+
"high",
|
|
2115
|
+
"xhigh",
|
|
2116
|
+
"max"
|
|
2117
|
+
]).optional(),
|
|
2118
|
+
encryptedReasoningInclude: z.boolean().optional(),
|
|
2119
|
+
effortCache: z.boolean().optional(),
|
|
2120
|
+
promptCacheKey: z.boolean().optional(),
|
|
2121
|
+
toolChoiceNone: z.boolean().optional()
|
|
2122
|
+
});
|
|
2123
|
+
//#endregion
|
|
2124
|
+
//#region src/responses/stream.ts
|
|
2125
|
+
var ResponsesStreamError = class extends Error {
|
|
2126
|
+
retryable;
|
|
2127
|
+
failureCode;
|
|
2128
|
+
constructor(message, options) {
|
|
2129
|
+
super(message);
|
|
2130
|
+
this.retryable = options.retryable;
|
|
2131
|
+
this.failureCode = options.failureCode ?? "response-invalid";
|
|
279
2132
|
}
|
|
2133
|
+
};
|
|
2134
|
+
function toFailedError(failure) {
|
|
2135
|
+
return new ResponsesStreamError("Responses stream failed", {
|
|
2136
|
+
retryable: [
|
|
2137
|
+
"rate_limit_exceeded",
|
|
2138
|
+
"server_error",
|
|
2139
|
+
"overloaded_error"
|
|
2140
|
+
].includes(String(failure.code)),
|
|
2141
|
+
failureCode: failure.code === "context_length_exceeded" ? "context-window-exceeded" : failure.code === "insufficient_quota" ? "quota-exceeded" : "provider-error"
|
|
2142
|
+
});
|
|
280
2143
|
}
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
2144
|
+
const str = (value) => typeof value === "string" ? value : "";
|
|
2145
|
+
const validCount = (value) => Number.isSafeInteger(value) && Number(value) >= 0;
|
|
2146
|
+
const num = (value) => validCount(value) ? value : 0;
|
|
2147
|
+
function unparseableCall(item) {
|
|
2148
|
+
if (item.type !== "function_call") return void 0;
|
|
2149
|
+
const id = str(item.call_id);
|
|
2150
|
+
const name = str(item.name);
|
|
2151
|
+
if (id.trim() === "" || name.trim() === "") return void 0;
|
|
2152
|
+
if (item.status !== void 0 && item.status !== "completed") return void 0;
|
|
287
2153
|
try {
|
|
288
|
-
|
|
289
|
-
} catch {
|
|
2154
|
+
JSON.parse(str(item.arguments));
|
|
290
2155
|
return;
|
|
2156
|
+
} catch {
|
|
2157
|
+
return {
|
|
2158
|
+
id,
|
|
2159
|
+
name
|
|
2160
|
+
};
|
|
291
2161
|
}
|
|
292
2162
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
const
|
|
319
|
-
if (
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
kind: "thinking-delta",
|
|
327
|
-
text: reasoningContent
|
|
328
|
-
};
|
|
2163
|
+
function partsOf(item, model) {
|
|
2164
|
+
if (item.type === "reasoning") {
|
|
2165
|
+
const summary = Array.isArray(item.summary) ? item.summary : [];
|
|
2166
|
+
const plain = Array.isArray(item.content) ? item.content : [];
|
|
2167
|
+
const text = (plain.length > 0 ? plain : summary).map((one) => str(one.text)).join("\n\n");
|
|
2168
|
+
const encrypted = str(item.encrypted_content);
|
|
2169
|
+
return [{
|
|
2170
|
+
type: "thinking",
|
|
2171
|
+
text,
|
|
2172
|
+
originModel: model,
|
|
2173
|
+
...encrypted === "" ? {} : { signature: encrypted }
|
|
2174
|
+
}];
|
|
2175
|
+
}
|
|
2176
|
+
if (item.type === "message") {
|
|
2177
|
+
const text = (Array.isArray(item.content) ? item.content : []).map((one) => {
|
|
2178
|
+
const part = one;
|
|
2179
|
+
return part.type === "output_text" ? str(part.text) : part.type === "refusal" ? str(part.refusal) : "";
|
|
2180
|
+
}).join("");
|
|
2181
|
+
return text === "" ? [] : [{
|
|
2182
|
+
type: "text",
|
|
2183
|
+
text
|
|
2184
|
+
}];
|
|
2185
|
+
}
|
|
2186
|
+
if (item.type === "function_call") {
|
|
2187
|
+
const id = str(item.call_id);
|
|
2188
|
+
const name = str(item.name);
|
|
2189
|
+
if (id.trim() === "" || name.trim() === "") throw new ResponsesStreamError("invalid model function_call: missing call_id or name", { retryable: false });
|
|
2190
|
+
if (item.status !== void 0 && item.status !== "completed") throw new ResponsesStreamError("invalid model function_call: call is not complete", { retryable: false });
|
|
2191
|
+
let input;
|
|
2192
|
+
try {
|
|
2193
|
+
input = JSON.parse(str(item.arguments));
|
|
2194
|
+
} catch {
|
|
2195
|
+
throw new ResponsesStreamError("invalid model function_call: arguments are not complete JSON", { retryable: false });
|
|
329
2196
|
}
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
2197
|
+
return [{
|
|
2198
|
+
type: "tool-use",
|
|
2199
|
+
id,
|
|
2200
|
+
name,
|
|
2201
|
+
input
|
|
2202
|
+
}];
|
|
2203
|
+
}
|
|
2204
|
+
return [];
|
|
2205
|
+
}
|
|
2206
|
+
async function* mapResponsesStream(events, options) {
|
|
2207
|
+
let usageSequence = 0;
|
|
2208
|
+
let reported = {};
|
|
2209
|
+
const items = [];
|
|
2210
|
+
const callIds = /* @__PURE__ */ new Map();
|
|
2211
|
+
const pendingCalls = /* @__PURE__ */ new Map();
|
|
2212
|
+
let openThinking = "";
|
|
2213
|
+
let refused = false;
|
|
2214
|
+
let open = "";
|
|
2215
|
+
for await (const event of events) {
|
|
2216
|
+
const response = event.response;
|
|
2217
|
+
if (response?.usage && typeof response.usage === "object") {
|
|
2218
|
+
const usage = response.usage;
|
|
2219
|
+
const details = usage.input_tokens_details ?? {};
|
|
2220
|
+
reported = {
|
|
2221
|
+
...reported,
|
|
2222
|
+
...typeof usage.input_tokens === "number" ? { inputTokens: usage.input_tokens } : {},
|
|
2223
|
+
...typeof usage.output_tokens === "number" ? { outputTokens: usage.output_tokens } : {},
|
|
2224
|
+
...typeof usage.total_tokens === "number" ? { totalTokens: usage.total_tokens } : {},
|
|
2225
|
+
...typeof details.cached_tokens === "number" ? { cacheReadTokens: details.cached_tokens } : {},
|
|
2226
|
+
...typeof details.cache_write_tokens === "number" ? { cacheWriteTokens: details.cache_write_tokens } : {}
|
|
336
2227
|
};
|
|
2228
|
+
options.usageReporter?.report({
|
|
2229
|
+
sequence: ++usageSequence,
|
|
2230
|
+
...reported
|
|
2231
|
+
});
|
|
337
2232
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
if (
|
|
344
|
-
code: "response-invalid",
|
|
345
|
-
stage: "response-validation",
|
|
346
|
-
category: "protocol",
|
|
347
|
-
source: "protocol",
|
|
348
|
-
retryable: false
|
|
349
|
-
});
|
|
350
|
-
state = {
|
|
351
|
-
id: delta.id,
|
|
352
|
-
name: delta.function.name,
|
|
353
|
-
arguments: ""
|
|
354
|
-
};
|
|
355
|
-
toolCalls.set(delta.index, state);
|
|
356
|
-
toolCallOrder.push(delta.index);
|
|
2233
|
+
switch (event.type) {
|
|
2234
|
+
case "response.output_text.delta":
|
|
2235
|
+
case "response.refusal.delta": {
|
|
2236
|
+
if (event.type === "response.refusal.delta") refused = true;
|
|
2237
|
+
const text = str(event.delta);
|
|
2238
|
+
if (text === "") break;
|
|
357
2239
|
yield {
|
|
358
|
-
kind: "
|
|
359
|
-
|
|
360
|
-
name: state.name,
|
|
361
|
-
inputDelta: ""
|
|
2240
|
+
kind: "text-delta",
|
|
2241
|
+
text
|
|
362
2242
|
};
|
|
363
|
-
|
|
364
|
-
|
|
2243
|
+
open += text;
|
|
2244
|
+
break;
|
|
2245
|
+
}
|
|
2246
|
+
case "response.reasoning_text.delta":
|
|
2247
|
+
case "response.reasoning_summary_text.delta": {
|
|
2248
|
+
const text = str(event.delta);
|
|
2249
|
+
if (text !== "") {
|
|
2250
|
+
openThinking += text;
|
|
2251
|
+
yield {
|
|
2252
|
+
kind: "thinking-delta",
|
|
2253
|
+
text
|
|
2254
|
+
};
|
|
2255
|
+
}
|
|
2256
|
+
break;
|
|
2257
|
+
}
|
|
2258
|
+
case "response.output_item.added": {
|
|
2259
|
+
const item = event.item;
|
|
2260
|
+
if (item?.type === "function_call") {
|
|
2261
|
+
const callId = str(item.call_id);
|
|
2262
|
+
callIds.set(str(item.id), callId);
|
|
2263
|
+
pendingCalls.set(str(item.id), {
|
|
2264
|
+
id: callId,
|
|
2265
|
+
...str(item.name) === "" ? {} : { name: str(item.name) }
|
|
2266
|
+
});
|
|
365
2267
|
yield {
|
|
366
2268
|
kind: "tool-call-delta",
|
|
367
|
-
id:
|
|
368
|
-
|
|
2269
|
+
id: callId,
|
|
2270
|
+
name: str(item.name),
|
|
2271
|
+
inputDelta: ""
|
|
369
2272
|
};
|
|
370
2273
|
}
|
|
371
|
-
|
|
2274
|
+
break;
|
|
372
2275
|
}
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
2276
|
+
case "response.function_call_arguments.delta": {
|
|
2277
|
+
const callId = callIds.get(str(event.item_id));
|
|
2278
|
+
if (callId !== void 0) yield {
|
|
2279
|
+
kind: "tool-call-delta",
|
|
2280
|
+
id: callId,
|
|
2281
|
+
inputDelta: str(event.delta)
|
|
2282
|
+
};
|
|
2283
|
+
break;
|
|
2284
|
+
}
|
|
2285
|
+
case "response.output_item.done": {
|
|
2286
|
+
const item = event.item;
|
|
2287
|
+
if (item !== void 0) items.push(item);
|
|
2288
|
+
if (item?.type === "function_call") {
|
|
2289
|
+
pendingCalls.delete(str(item.id));
|
|
2290
|
+
for (const [key, call] of pendingCalls) if (call.id === str(item.call_id)) pendingCalls.delete(key);
|
|
2291
|
+
}
|
|
2292
|
+
if (item?.type === "reasoning") openThinking = "";
|
|
2293
|
+
if (item?.type === "message" && Array.isArray(item.content)) refused ||= item.content.some((part) => part.type === "refusal");
|
|
2294
|
+
if (item?.type === "message") open = "";
|
|
2295
|
+
break;
|
|
2296
|
+
}
|
|
2297
|
+
case "response.completed":
|
|
2298
|
+
case "response.incomplete": {
|
|
2299
|
+
const response = event.response ?? {};
|
|
2300
|
+
const terminalItems = Array.isArray(response.output) ? response.output : items;
|
|
2301
|
+
const incompleteThinking = terminalItems.some((item) => item.type === "reasoning" && item.status === "incomplete") || openThinking !== "" && !terminalItems.some((item) => item.type === "reasoning" && item.status === "completed");
|
|
2302
|
+
refused ||= terminalItems.some((item) => item.type === "message" && Array.isArray(item.content) && item.content.some((part) => part.type === "refusal"));
|
|
2303
|
+
const usage = response.usage ?? {};
|
|
2304
|
+
const details = usage.input_tokens_details ?? {};
|
|
2305
|
+
const cache = {
|
|
2306
|
+
...validCount(details.cached_tokens) && details.cached_tokens <= num(usage.input_tokens) ? { cacheReadTokens: details.cached_tokens } : {},
|
|
2307
|
+
...validCount(details.cache_write_tokens) && details.cache_write_tokens <= num(usage.input_tokens) ? { cacheWriteTokens: details.cache_write_tokens } : {}
|
|
2308
|
+
};
|
|
2309
|
+
const truncated = event.type === "response.incomplete" && response.incomplete_details?.reason === "max_output_tokens";
|
|
2310
|
+
if (event.type === "response.incomplete" && !truncated && !refused) throw new ResponsesStreamError(`incomplete model reply (${event.type})`, { retryable: false });
|
|
2311
|
+
const incompleteToolCalls = new Map([...pendingCalls.values()].map((call) => [call.id, call]));
|
|
2312
|
+
const droppedToolCalls = [];
|
|
2313
|
+
const content = terminalItems.flatMap((item) => {
|
|
2314
|
+
const unparseable = unparseableCall(item);
|
|
2315
|
+
if (unparseable && !truncated) {
|
|
2316
|
+
droppedToolCalls.push(unparseable);
|
|
2317
|
+
return [];
|
|
2318
|
+
}
|
|
2319
|
+
try {
|
|
2320
|
+
const parts = partsOf(item, options.model);
|
|
2321
|
+
if (item.type === "function_call") incompleteToolCalls.delete(str(item.call_id));
|
|
2322
|
+
return parts;
|
|
2323
|
+
} catch (error) {
|
|
2324
|
+
if (!truncated || item.type !== "function_call" || str(item.call_id) === "") throw error;
|
|
2325
|
+
incompleteToolCalls.set(str(item.call_id), {
|
|
2326
|
+
id: str(item.call_id),
|
|
2327
|
+
...str(item.name) === "" ? {} : { name: str(item.name) }
|
|
2328
|
+
});
|
|
2329
|
+
return [];
|
|
2330
|
+
}
|
|
2331
|
+
});
|
|
2332
|
+
if (truncated && open !== "" && !terminalItems.some((item) => item.type === "message")) content.push({
|
|
2333
|
+
type: "text",
|
|
2334
|
+
text: open
|
|
2335
|
+
});
|
|
2336
|
+
if (truncated && openThinking !== "" && !terminalItems.some((item) => item.type === "reasoning")) content.unshift({
|
|
2337
|
+
type: "thinking",
|
|
2338
|
+
text: openThinking
|
|
2339
|
+
});
|
|
2340
|
+
if (!truncated && !refused && droppedToolCalls.length === 0 && !content.some((part) => part.type === "text" || part.type === "tool-use")) throw new ResponsesStreamError(`incomplete model reply (${event.type})`, {
|
|
2341
|
+
retryable: false,
|
|
2342
|
+
failureCode: "response-empty"
|
|
2343
|
+
});
|
|
2344
|
+
const finishReason = refused ? "refusal" : truncated ? "max-tokens" : droppedToolCalls.length > 0 || content.some((part) => part.type === "tool-use") ? "tool-calls" : "stop";
|
|
2345
|
+
yield {
|
|
2346
|
+
kind: "final",
|
|
2347
|
+
finishReason,
|
|
2348
|
+
...droppedToolCalls.length > 0 ? { droppedToolCalls } : {},
|
|
2349
|
+
...finishReason === "max-tokens" ? { outputTruncation: {
|
|
2350
|
+
incompleteToolCalls: [...incompleteToolCalls.values()],
|
|
2351
|
+
...incompleteThinking ? { incompleteThinking: true } : {}
|
|
2352
|
+
} } : {},
|
|
2353
|
+
usage: {
|
|
2354
|
+
inputTokens: num(usage.input_tokens),
|
|
2355
|
+
...validCount(usage.input_tokens) && (details.cached_tokens == null || validCount(details.cached_tokens) && details.cached_tokens <= usage.input_tokens) && (details.cache_write_tokens == null || validCount(details.cache_write_tokens) && details.cache_write_tokens <= usage.input_tokens) ? {} : { inputTokensReported: false },
|
|
2356
|
+
outputTokens: num(usage.output_tokens),
|
|
2357
|
+
...cache
|
|
2358
|
+
},
|
|
2359
|
+
message: {
|
|
2360
|
+
role: "assistant",
|
|
2361
|
+
content
|
|
2362
|
+
}
|
|
2363
|
+
};
|
|
2364
|
+
return;
|
|
2365
|
+
}
|
|
2366
|
+
case "response.failed":
|
|
2367
|
+
case "error": throw toFailedError(event.response?.error ?? event.error ?? event);
|
|
426
2368
|
}
|
|
427
|
-
content.push({
|
|
428
|
-
type: "tool-use",
|
|
429
|
-
id: call.id,
|
|
430
|
-
name: call.name,
|
|
431
|
-
input
|
|
432
|
-
});
|
|
433
2369
|
}
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
category: "protocol",
|
|
438
|
-
source: "protocol",
|
|
439
|
-
retryable: false,
|
|
440
|
-
finishReason
|
|
2370
|
+
throw new ResponsesStreamError("model stream interrupted", {
|
|
2371
|
+
retryable: true,
|
|
2372
|
+
failureCode: "stream-interrupted"
|
|
441
2373
|
});
|
|
442
|
-
yield {
|
|
443
|
-
kind: "final",
|
|
444
|
-
finishReason,
|
|
445
|
-
...finishReason === "max-tokens" ? { outputTruncation: {
|
|
446
|
-
incompleteToolCalls,
|
|
447
|
-
...thinkingOpen ? { incompleteThinking: true } : {}
|
|
448
|
-
} } : {},
|
|
449
|
-
usage: {
|
|
450
|
-
inputTokens,
|
|
451
|
-
outputTokens,
|
|
452
|
-
...cache
|
|
453
|
-
},
|
|
454
|
-
...finishReason === "refusal" ? { refusalCategory: "content_filter" } : {},
|
|
455
|
-
message: {
|
|
456
|
-
role: "assistant",
|
|
457
|
-
content
|
|
458
|
-
}
|
|
459
|
-
};
|
|
460
2374
|
}
|
|
461
2375
|
//#endregion
|
|
462
|
-
//#region src/
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
* which `params.ts` already put in the plan. */
|
|
466
|
-
function openaiOptions(plan) {
|
|
467
|
-
return {
|
|
468
|
-
...plan.effort === void 0 ? {} : { reasoningEffort: plan.effort },
|
|
469
|
-
...plan.thinking === void 0 ? {} : { thinking: plan.thinking },
|
|
470
|
-
...plan.temperature === void 0 ? {} : { temperature: plan.temperature },
|
|
471
|
-
...plan.maxTokens === void 0 ? {} : { maxTokens: plan.maxTokens }
|
|
472
|
-
};
|
|
473
|
-
}
|
|
474
|
-
/** Creates an OpenAI-compatible port with inspection and partial-stream retry protection. */
|
|
475
|
-
function createOpenAIModelPort(options) {
|
|
476
|
-
function clientForAttempt(reportProgress) {
|
|
477
|
-
return options.client ?? new OpenAI({
|
|
478
|
-
apiKey: options.apiKey ?? "",
|
|
479
|
-
fetch: async (...args) => options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress),
|
|
480
|
-
baseURL: options.baseURL ?? "",
|
|
481
|
-
maxRetries: 0
|
|
482
|
-
});
|
|
483
|
-
}
|
|
2376
|
+
//#region src/responses/port.ts
|
|
2377
|
+
function createResponsesPort(call, support, fetch, capability) {
|
|
2378
|
+
const options = ResponsesProtocolOptions.parse(call.options);
|
|
484
2379
|
function build(request) {
|
|
485
|
-
const
|
|
486
|
-
const
|
|
487
|
-
const
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
2380
|
+
const entry = support.catalogue(call.providerId, call.model);
|
|
2381
|
+
const endpoint = support.endpoint(call.providerId);
|
|
2382
|
+
const params = support.resolveParams({
|
|
2383
|
+
facts,
|
|
2384
|
+
entry,
|
|
2385
|
+
endpoint,
|
|
2386
|
+
model: call.model,
|
|
2387
|
+
stored: request.params ?? {}
|
|
2388
|
+
});
|
|
2389
|
+
const extra = support.extraParams(request.params ?? {});
|
|
2390
|
+
for (const key of [
|
|
2391
|
+
"input",
|
|
2392
|
+
"instructions",
|
|
2393
|
+
"store",
|
|
2394
|
+
"include",
|
|
2395
|
+
"previous_response_id",
|
|
2396
|
+
"conversation"
|
|
2397
|
+
]) if (key in extra) throw new Error(`invalid-params: reserved field ${key}`);
|
|
2398
|
+
const replay = support.planEffortCache({
|
|
2399
|
+
request,
|
|
2400
|
+
inspection: false,
|
|
2401
|
+
effort: params.effort,
|
|
2402
|
+
capability: capability(request),
|
|
2403
|
+
bindingFingerprint: support.inspectionFingerprint({
|
|
2404
|
+
connectionFingerprint: call.connectionFingerprint,
|
|
2405
|
+
providerId: call.providerId,
|
|
2406
|
+
model: call.model,
|
|
2407
|
+
config: call.config,
|
|
2408
|
+
options: call.options,
|
|
2409
|
+
system: request.system,
|
|
2410
|
+
tools: request.tools,
|
|
2411
|
+
thinking: params.thinking,
|
|
2412
|
+
extra
|
|
2413
|
+
})
|
|
2414
|
+
});
|
|
2415
|
+
const media = support.mediaContextOf({
|
|
2416
|
+
entry,
|
|
2417
|
+
endpoint,
|
|
2418
|
+
facts,
|
|
2419
|
+
stored: request.params ?? {},
|
|
2420
|
+
fileKinds: ["image"]
|
|
2421
|
+
});
|
|
2422
|
+
const mediaPlan = support.planMedia(request, media);
|
|
2423
|
+
const reasons = entry?.reasoning !== false;
|
|
2424
|
+
const settings = {
|
|
2425
|
+
model: call.model,
|
|
2426
|
+
endpoint: call.providerId,
|
|
2427
|
+
effort: params.thinking === false ? "none" : replay.baseEffort ?? (params.thinking === true ? options.thinkingOnEffort : void 0),
|
|
2428
|
+
reasoningReplay: options.reasoningReplay,
|
|
2429
|
+
reasoningSummary: reasons ? options.reasoningSummary : false,
|
|
2430
|
+
encryptedReasoningInclude: reasons ? options.encryptedReasoningInclude : false,
|
|
2431
|
+
effortUpdates: replay.updates
|
|
504
2432
|
};
|
|
2433
|
+
let maxTokens = params.maxTokens;
|
|
2434
|
+
if (request.purpose === "summary") {
|
|
2435
|
+
if (!Number.isSafeInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0) throw new Error("summaryMaxTokens must be a positive integer");
|
|
2436
|
+
maxTokens = Math.min(maxTokens ?? Infinity, Number(request.summaryMaxTokens));
|
|
2437
|
+
}
|
|
2438
|
+
const toolsWithheld = options.toolChoiceNone === false && request.toolChoice === "none" && (request.tools?.length ?? 0) > 0;
|
|
2439
|
+
const continuation = request.purpose === "summary" && request.summaryShape === "continuation";
|
|
2440
|
+
const rendered = toResponsesBody(toolsWithheld ? {
|
|
2441
|
+
...request,
|
|
2442
|
+
tools: []
|
|
2443
|
+
} : request, settings, mediaPlan);
|
|
2444
|
+
const body = support.freezePayload({
|
|
2445
|
+
...rendered,
|
|
2446
|
+
...maxTokens === void 0 ? {} : { max_output_tokens: maxTokens },
|
|
2447
|
+
...params.temperature === void 0 ? {} : { temperature: params.temperature },
|
|
2448
|
+
...request.cacheKey && options.promptCacheKey !== false ? { prompt_cache_key: request.cacheKey } : {},
|
|
2449
|
+
...request.purpose === "summary" && !continuation ? {} : extra,
|
|
2450
|
+
...continuation && maxTokens !== void 0 ? { max_output_tokens: maxTokens } : {},
|
|
2451
|
+
...continuation && "tool_choice" in rendered ? { tool_choice: rendered.tool_choice } : {}
|
|
2452
|
+
});
|
|
2453
|
+
const fields = responsesSemanticFields(body, mediaPlan);
|
|
2454
|
+
const receipts = new Map(replay.replaySources?.map((source) => [source.messageId, JSON.stringify(source.contribution)]));
|
|
505
2455
|
return {
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
2456
|
+
body,
|
|
2457
|
+
replaySelections: support.prepareReplaySelections(request, ({ message, part }) => part ? responsesReplayChoice(message, part, settings) : {
|
|
2458
|
+
mode: "effort-cache",
|
|
2459
|
+
textIncluded: false,
|
|
2460
|
+
selectedText: receipts.get(message.id),
|
|
2461
|
+
reason: "not-applicable"
|
|
2462
|
+
}),
|
|
2463
|
+
replay: support.freezePayload(replay),
|
|
2464
|
+
capacity: support.freezePayload(entry?.limit ?? {}),
|
|
2465
|
+
mediaPlan,
|
|
2466
|
+
maxTokens,
|
|
2467
|
+
toolsWithheld,
|
|
2468
|
+
fields,
|
|
2469
|
+
hiddenInputTokens: responsesHiddenInputTokens(request, settings),
|
|
2470
|
+
request: {
|
|
2471
|
+
...request,
|
|
2472
|
+
params: support.freezePayload(request.params ?? {})
|
|
2473
|
+
},
|
|
2474
|
+
connection: {
|
|
2475
|
+
baseURL: String(call.config.baseUrl),
|
|
2476
|
+
apiKey: call.secrets.apiKey,
|
|
2477
|
+
model: call.model
|
|
2478
|
+
},
|
|
2479
|
+
fingerprint: support.freezePayload({
|
|
2480
|
+
protocol: "openai-responses",
|
|
2481
|
+
model: call.model,
|
|
2482
|
+
config: call.config,
|
|
2483
|
+
params: request.params,
|
|
2484
|
+
updates: replay.updates
|
|
2485
|
+
})
|
|
509
2486
|
};
|
|
510
2487
|
}
|
|
511
|
-
return {
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
2488
|
+
return support.createPreparedPort({
|
|
2489
|
+
prepare: build,
|
|
2490
|
+
semantics(payload) {
|
|
2491
|
+
return {
|
|
2492
|
+
replaySelections: payload.replaySelections,
|
|
2493
|
+
mediaSelections: () => support.mediaSelections(payload.mediaPlan),
|
|
2494
|
+
toolDefinitions: payload.body.tools ?? Object.freeze([]),
|
|
2495
|
+
parameters: Object.freeze(Object.fromEntries(Object.entries(payload.body).filter(([key]) => ![
|
|
2496
|
+
"model",
|
|
2497
|
+
"input",
|
|
2498
|
+
"instructions",
|
|
2499
|
+
"tools",
|
|
2500
|
+
"stream",
|
|
2501
|
+
"store",
|
|
2502
|
+
"prompt_cache_key"
|
|
2503
|
+
].includes(key)))),
|
|
2504
|
+
format: "request-semantic-v1",
|
|
2505
|
+
protocolId: "openai-responses",
|
|
2506
|
+
adapterVersion: "1",
|
|
2507
|
+
rendererVersion: "responses-v1",
|
|
2508
|
+
frames: () => support.semanticFrames(payload.body, {
|
|
2509
|
+
omitRoot: [
|
|
2510
|
+
"stream",
|
|
2511
|
+
"store",
|
|
2512
|
+
"prompt_cache_key"
|
|
2513
|
+
],
|
|
2514
|
+
fields: payload.fields
|
|
2515
|
+
})
|
|
2516
|
+
};
|
|
2517
|
+
},
|
|
2518
|
+
async inspect(payload, signal) {
|
|
2519
|
+
signal.throwIfAborted();
|
|
2520
|
+
const started = support.performance?.now();
|
|
2521
|
+
const { body, request, capacity, mediaPlan, maxTokens, hiddenInputTokens, fingerprint, toolsWithheld } = payload;
|
|
2522
|
+
support.performance?.observe({
|
|
2523
|
+
stage: "model.project",
|
|
2524
|
+
measurementPurpose: "request",
|
|
2525
|
+
durationMs: support.performance.now() - started,
|
|
2526
|
+
count: 1
|
|
2527
|
+
});
|
|
2528
|
+
const text = support.requestText("responses", body);
|
|
2529
|
+
const inspection = support.inspect({
|
|
2530
|
+
body,
|
|
523
2531
|
request,
|
|
2532
|
+
textTokens: 0,
|
|
2533
|
+
textBytes: Buffer.byteLength(text),
|
|
2534
|
+
tokenizer: "utf8-bytes-quarter-v1",
|
|
524
2535
|
capacity,
|
|
525
|
-
outputReserve,
|
|
526
|
-
outputReserveSource:
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
}).tokens,
|
|
531
|
-
fingerprint: {
|
|
532
|
-
rendering: "openai-chat-completions-v3",
|
|
533
|
-
endpoint: options.endpoint ?? options.baseURL,
|
|
534
|
-
model: params.model,
|
|
535
|
-
purpose: request.purpose,
|
|
536
|
-
contextWindow: request.params?.contextWindow,
|
|
537
|
-
capacity,
|
|
538
|
-
settings: {
|
|
539
|
-
reasoningEffort: requestOptions.reasoningEffort,
|
|
540
|
-
temperature: requestOptions.temperature,
|
|
541
|
-
maxTokens: bodyMaxTokens,
|
|
542
|
-
extra: request.purpose === "summary" ? void 0 : requestOptions.extra
|
|
543
|
-
}
|
|
544
|
-
}
|
|
2536
|
+
outputReserve: maxTokens ?? capacity.output ?? 0,
|
|
2537
|
+
outputReserveSource: maxTokens === void 0 ? "capacity" : "enforced",
|
|
2538
|
+
hiddenInputTokens,
|
|
2539
|
+
mediaTokens: mediaPlan.tokens,
|
|
2540
|
+
fingerprint
|
|
545
2541
|
});
|
|
2542
|
+
const textTokens = await support.measureText(text, signal);
|
|
2543
|
+
signal.throwIfAborted();
|
|
2544
|
+
return {
|
|
2545
|
+
...inspection,
|
|
2546
|
+
inputTokens: inspection.inputTokens + textTokens,
|
|
2547
|
+
...toolsWithheld ? { toolsWithheld: true } : {}
|
|
2548
|
+
};
|
|
546
2549
|
},
|
|
547
|
-
stream(
|
|
2550
|
+
stream(payload, signal, observer, scope) {
|
|
548
2551
|
signal.throwIfAborted();
|
|
549
|
-
const {
|
|
550
|
-
|
|
2552
|
+
const { body, replay, connection } = payload;
|
|
2553
|
+
const dispatchEffort = body.reasoning?.effort === "none" ? "none" : replay.effectiveEffort ?? body.reasoning?.effort;
|
|
2554
|
+
return support.withChatAttempts({
|
|
2555
|
+
retainCleanup: scope.retainCleanup,
|
|
2556
|
+
beforeAttempt: (_signal, ordinal) => observer?.beforeAttempt?.(ordinal),
|
|
2557
|
+
accountingDispatch: call.accountingDispatch,
|
|
2558
|
+
effective: {
|
|
2559
|
+
outputLimit: body.max_output_tokens,
|
|
2560
|
+
effort: body.reasoning?.effort
|
|
2561
|
+
},
|
|
551
2562
|
signal,
|
|
552
|
-
|
|
553
|
-
...options.sleep === void 0 ? {} : { sleep: options.sleep },
|
|
554
|
-
...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
|
|
555
|
-
async *attempt(attemptSignal, reportProgress, attempt) {
|
|
2563
|
+
async *attempt(attemptSignal, reportProgress, attempt, usageReporter) {
|
|
556
2564
|
const observe = (event) => {
|
|
557
2565
|
try {
|
|
558
2566
|
observer?.observe?.(event);
|
|
@@ -560,7 +2568,44 @@ function createOpenAIModelPort(options) {
|
|
|
560
2568
|
};
|
|
561
2569
|
const attemptCount = attempt + 1;
|
|
562
2570
|
let outcome = "unknown";
|
|
2571
|
+
let timeout;
|
|
2572
|
+
const abortedOutcome = () => {
|
|
2573
|
+
const reason = support.failures.verified(attemptSignal.reason);
|
|
2574
|
+
if (reason?.code !== "stream-idle-timeout") return "cancelled";
|
|
2575
|
+
timeout = reason;
|
|
2576
|
+
return "timeout";
|
|
2577
|
+
};
|
|
563
2578
|
let firstResponseFinished = false;
|
|
2579
|
+
let attemptFinished = false;
|
|
2580
|
+
let dispatchObserved = false;
|
|
2581
|
+
const markDispatched = () => {
|
|
2582
|
+
if (dispatchObserved) return;
|
|
2583
|
+
dispatchObserved = true;
|
|
2584
|
+
try {
|
|
2585
|
+
observer?.dispatched({
|
|
2586
|
+
attempt,
|
|
2587
|
+
presentation: {
|
|
2588
|
+
schema: "chat.dispatch-settings.v1",
|
|
2589
|
+
data: {
|
|
2590
|
+
model: {
|
|
2591
|
+
availability: "resolved",
|
|
2592
|
+
value: body.model,
|
|
2593
|
+
origin: "protocol"
|
|
2594
|
+
},
|
|
2595
|
+
effort: dispatchEffort ? {
|
|
2596
|
+
availability: "resolved",
|
|
2597
|
+
value: dispatchEffort,
|
|
2598
|
+
origin: "protocol"
|
|
2599
|
+
} : {
|
|
2600
|
+
availability: "resolved",
|
|
2601
|
+
value: "default",
|
|
2602
|
+
origin: "protocol"
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
});
|
|
2607
|
+
} catch {}
|
|
2608
|
+
};
|
|
564
2609
|
observe({
|
|
565
2610
|
stage: "attempt",
|
|
566
2611
|
phase: "start",
|
|
@@ -571,9 +2616,22 @@ function createOpenAIModelPort(options) {
|
|
|
571
2616
|
phase: "start",
|
|
572
2617
|
attempt: attemptCount
|
|
573
2618
|
});
|
|
2619
|
+
let abortStream;
|
|
574
2620
|
try {
|
|
2621
|
+
const { default: OpenAI } = await loadOpenAISdk();
|
|
575
2622
|
attemptSignal.throwIfAborted();
|
|
576
|
-
const
|
|
2623
|
+
const stream = await new OpenAI({
|
|
2624
|
+
apiKey: options.allowUnauthenticated && !connection.apiKey ? "not-used" : connection.apiKey ?? "",
|
|
2625
|
+
...options.allowUnauthenticated && !connection.apiKey ? { defaultHeaders: { Authorization: null } } : {},
|
|
2626
|
+
baseURL: connection.baseURL,
|
|
2627
|
+
maxRetries: 0,
|
|
2628
|
+
fetch: async (...args) => {
|
|
2629
|
+
const pending = fetch(...args);
|
|
2630
|
+
markDispatched();
|
|
2631
|
+
return support.observeResponseProgress(await pending, reportProgress);
|
|
2632
|
+
}
|
|
2633
|
+
}).responses.create(body, { signal: attemptSignal });
|
|
2634
|
+
abortStream = () => stream.controller.abort();
|
|
577
2635
|
firstResponseFinished = true;
|
|
578
2636
|
observe({
|
|
579
2637
|
stage: "first-response",
|
|
@@ -581,252 +2639,138 @@ function createOpenAIModelPort(options) {
|
|
|
581
2639
|
attempt: attemptCount,
|
|
582
2640
|
outcome: "ok"
|
|
583
2641
|
});
|
|
584
|
-
attemptSignal.throwIfAborted();
|
|
585
|
-
try {
|
|
586
|
-
observer?.dispatched({ attempt });
|
|
587
|
-
} catch {}
|
|
588
|
-
attemptSignal.throwIfAborted();
|
|
589
2642
|
const observed = (async function* () {
|
|
590
|
-
for await (const
|
|
2643
|
+
for await (const event of stream) {
|
|
591
2644
|
reportProgress();
|
|
592
|
-
yield
|
|
2645
|
+
yield event;
|
|
593
2646
|
}
|
|
594
2647
|
})();
|
|
595
|
-
for await (const chunk of
|
|
596
|
-
|
|
597
|
-
|
|
2648
|
+
for await (const chunk of mapResponsesStream(observed, {
|
|
2649
|
+
model: connection.model,
|
|
2650
|
+
usageReporter
|
|
2651
|
+
})) {
|
|
2652
|
+
attemptSignal.throwIfAborted();
|
|
2653
|
+
if (chunk.kind === "final") {
|
|
2654
|
+
outcome = "ok";
|
|
2655
|
+
attemptFinished = true;
|
|
2656
|
+
observe({
|
|
2657
|
+
stage: "attempt",
|
|
2658
|
+
phase: "end",
|
|
2659
|
+
attempt: attemptCount,
|
|
2660
|
+
outcome
|
|
2661
|
+
});
|
|
2662
|
+
}
|
|
2663
|
+
yield chunk.kind === "final" && replay.replayData !== void 0 ? {
|
|
2664
|
+
...chunk,
|
|
2665
|
+
replayData: replay.replayData
|
|
2666
|
+
} : chunk;
|
|
598
2667
|
}
|
|
599
2668
|
} catch (error) {
|
|
600
|
-
outcome = attemptSignal.aborted ?
|
|
2669
|
+
outcome = attemptSignal.aborted ? abortedOutcome() : "error";
|
|
601
2670
|
throw error;
|
|
602
2671
|
} finally {
|
|
2672
|
+
if (attemptSignal.aborted && !attemptFinished) outcome = abortedOutcome();
|
|
2673
|
+
abortStream?.();
|
|
603
2674
|
if (!firstResponseFinished) observe({
|
|
604
2675
|
stage: "first-response",
|
|
605
2676
|
phase: "end",
|
|
606
2677
|
attempt: attemptCount,
|
|
607
|
-
outcome
|
|
2678
|
+
outcome,
|
|
2679
|
+
...timeout ? { failure: timeout } : {}
|
|
608
2680
|
});
|
|
609
|
-
observe({
|
|
2681
|
+
if (!attemptFinished) observe({
|
|
610
2682
|
stage: "attempt",
|
|
611
2683
|
phase: "end",
|
|
612
2684
|
attempt: attemptCount,
|
|
613
|
-
outcome
|
|
2685
|
+
outcome,
|
|
2686
|
+
...timeout ? { failure: timeout } : {}
|
|
614
2687
|
});
|
|
615
2688
|
}
|
|
616
2689
|
},
|
|
617
2690
|
classify(error) {
|
|
618
|
-
const
|
|
2691
|
+
const failure = error instanceof ResponsesStreamError ? error.failureCode === "context-window-exceeded" ? support.failures.create({
|
|
2692
|
+
code: error.failureCode,
|
|
2693
|
+
stage: "request",
|
|
2694
|
+
source: "protocol",
|
|
2695
|
+
category: "request-too-large",
|
|
2696
|
+
retryable: false
|
|
2697
|
+
}) : support.failures.create({
|
|
2698
|
+
code: error.failureCode,
|
|
2699
|
+
stage: "stream",
|
|
2700
|
+
source: "protocol",
|
|
2701
|
+
category: error.retryable ? "network" : "protocol",
|
|
2702
|
+
retryable: error.retryable
|
|
2703
|
+
}) : toModelFailure(error, support.failures, support.transportFailure);
|
|
619
2704
|
return {
|
|
620
|
-
error:
|
|
621
|
-
retryable:
|
|
2705
|
+
error: failure,
|
|
2706
|
+
retryable: failure.retryable === true,
|
|
622
2707
|
retryAfterMs: retryAfterMs(error)
|
|
623
2708
|
};
|
|
624
2709
|
}
|
|
625
2710
|
});
|
|
626
2711
|
}
|
|
627
|
-
};
|
|
2712
|
+
});
|
|
628
2713
|
}
|
|
629
2714
|
//#endregion
|
|
630
|
-
//#region src/protocol
|
|
631
|
-
|
|
632
|
-
if (
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
await response.body?.cancel();
|
|
636
|
-
throw new Error("read-limit: provider response exceeds its member budget");
|
|
637
|
-
}
|
|
638
|
-
if (!response.body) return {
|
|
639
|
-
text: "",
|
|
640
|
-
bytes: 0
|
|
641
|
-
};
|
|
642
|
-
const reader = response.body.getReader();
|
|
643
|
-
const decoder = new TextDecoder();
|
|
644
|
-
let bytes = 0, text = "";
|
|
645
|
-
try {
|
|
646
|
-
for (;;) {
|
|
647
|
-
const next = await reader.read();
|
|
648
|
-
if (next.done) break;
|
|
649
|
-
bytes += next.value.byteLength;
|
|
650
|
-
if (bytes > maxBytes) {
|
|
651
|
-
await reader.cancel();
|
|
652
|
-
throw new Error("read-limit: provider response exceeds its member budget");
|
|
653
|
-
}
|
|
654
|
-
text += decoder.decode(next.value, { stream: true });
|
|
655
|
-
}
|
|
656
|
-
return {
|
|
657
|
-
text: text + decoder.decode(),
|
|
658
|
-
bytes
|
|
659
|
-
};
|
|
660
|
-
} finally {
|
|
661
|
-
reader.releaseLock();
|
|
662
|
-
}
|
|
663
|
-
}
|
|
664
|
-
function baseUrlOf(probe) {
|
|
665
|
-
const configured = probe.config.baseUrl;
|
|
666
|
-
return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
|
|
667
|
-
}
|
|
668
|
-
async function refuse(response, maxBytes = 8388608) {
|
|
669
|
-
const body = (await readBody(response, maxBytes)).text;
|
|
670
|
-
throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
|
|
671
|
-
}
|
|
672
|
-
function headers(probe) {
|
|
673
|
-
return {
|
|
674
|
-
authorization: `Bearer ${probe.secrets.apiKey ?? ""}`,
|
|
675
|
-
"content-type": "application/json"
|
|
2715
|
+
//#region src/responses/protocol.ts
|
|
2716
|
+
function capability(input) {
|
|
2717
|
+
if (ResponsesProtocolOptions.parse(input.options ?? {}).effortCache === false) return {
|
|
2718
|
+
status: "unsupported",
|
|
2719
|
+
reason: "configuration-updates-unavailable"
|
|
676
2720
|
};
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
}
|
|
681
|
-
function count(value) {
|
|
682
|
-
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
|
|
683
|
-
}
|
|
684
|
-
function strings(value, allowEmpty = false) {
|
|
685
|
-
return Array.isArray(value) && value.every((one) => typeof one === "string") && (allowEmpty || value.length > 0) ? value : void 0;
|
|
686
|
-
}
|
|
687
|
-
/**
|
|
688
|
-
* One listed model as an offer. The family agrees on `id` alone, so every
|
|
689
|
-
* other field is read wherever an endpoint puts it: `context_window` or
|
|
690
|
-
* `context_length`, `max_output_tokens` or `max_output_length`,
|
|
691
|
-
* `input_modalities` or the `supports_*_in` flags, `output_modalities`,
|
|
692
|
-
* `supports_reasoning` or `reasoning` in `supported_features` (which also
|
|
693
|
-
* says `tools`), `temperature` in `supported_sampling_parameters`, and an
|
|
694
|
-
* `effort` object with its levels and default. A default the levels do not
|
|
695
|
-
* list is dropped. A valid feature or sampling list, including an empty one,
|
|
696
|
-
* answers for what it leaves out. Missing or malformed lists remain unknown.
|
|
697
|
-
*/
|
|
698
|
-
function offerOf(row, id) {
|
|
699
|
-
const contextWindow = count(row.context_window) ?? count(row.context_length);
|
|
700
|
-
const maxOutput = count(row.max_output_tokens) ?? count(row.max_output_length);
|
|
701
|
-
const features = strings(row.supported_features, true);
|
|
702
|
-
const sampling = strings(row.supported_sampling_parameters, true);
|
|
703
|
-
const reasoning = typeof row.supports_reasoning === "boolean" ? row.supports_reasoning : features?.includes("reasoning");
|
|
704
|
-
const effort = record(row.effort);
|
|
705
|
-
const efforts = strings(effort?.supported_levels);
|
|
706
|
-
const defaultEffort = typeof effort?.default_level === "string" && efforts?.includes(effort.default_level) ? effort.default_level : void 0;
|
|
707
|
-
const flagged = typeof row.supports_image_in === "boolean" || typeof row.supports_video_in === "boolean" ? [
|
|
708
|
-
"text",
|
|
709
|
-
...row.supports_image_in === true ? ["image"] : [],
|
|
710
|
-
...row.supports_video_in === true ? ["video"] : []
|
|
711
|
-
] : void 0;
|
|
712
|
-
const input = strings(row.input_modalities) ?? flagged;
|
|
713
|
-
const output = strings(row.output_modalities);
|
|
714
|
-
return {
|
|
715
|
-
model: id,
|
|
716
|
-
...typeof row.name === "string" && row.name !== "" ? { name: row.name } : {},
|
|
717
|
-
...contextWindow === void 0 ? {} : { contextWindow },
|
|
718
|
-
...maxOutput === void 0 ? {} : { maxOutput },
|
|
719
|
-
...reasoning === void 0 ? {} : { reasoning },
|
|
720
|
-
...features === void 0 ? {} : { toolCall: features.includes("tools") },
|
|
721
|
-
...sampling === void 0 ? {} : { temperature: sampling.includes("temperature") },
|
|
722
|
-
...input === void 0 ? {} : { input },
|
|
723
|
-
...output === void 0 ? {} : { output },
|
|
724
|
-
...efforts === void 0 ? {} : { efforts },
|
|
725
|
-
...defaultEffort === void 0 ? {} : { defaultEffort }
|
|
2721
|
+
if (input.params.thinking === false || input.params.effort === "none") return {
|
|
2722
|
+
status: "unsupported",
|
|
2723
|
+
reason: "reasoning-required"
|
|
726
2724
|
};
|
|
2725
|
+
return { status: "supported" };
|
|
727
2726
|
}
|
|
728
|
-
|
|
729
|
-
async listModels(probe, fetcher = globalThis.fetch) {
|
|
730
|
-
const response = await fetcher(`${baseUrlOf(probe)}/models`, {
|
|
731
|
-
method: "GET",
|
|
732
|
-
headers: headers(probe),
|
|
733
|
-
signal: probe.signal
|
|
734
|
-
});
|
|
735
|
-
if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
|
|
736
|
-
return (JSON.parse((await readBody(response, probe.maxResponseBytes ?? 8388608)).text).data ?? []).flatMap((row) => typeof row.id === "string" ? [offerOf(row, row.id)] : []);
|
|
737
|
-
},
|
|
738
|
-
async testConnection(probe, fetcher = globalThis.fetch) {
|
|
739
|
-
if (probe.model !== void 0) {
|
|
740
|
-
const response = await fetcher(`${baseUrlOf(probe)}/chat/completions`, {
|
|
741
|
-
method: "POST",
|
|
742
|
-
headers: headers(probe),
|
|
743
|
-
body: JSON.stringify({
|
|
744
|
-
model: probe.model,
|
|
745
|
-
max_tokens: 1,
|
|
746
|
-
messages: [{
|
|
747
|
-
role: "user",
|
|
748
|
-
content: "ping"
|
|
749
|
-
}]
|
|
750
|
-
}),
|
|
751
|
-
signal: probe.signal
|
|
752
|
-
});
|
|
753
|
-
if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
|
|
754
|
-
return;
|
|
755
|
-
}
|
|
756
|
-
await probeOpenAI.listModels(probe, fetcher);
|
|
757
|
-
}
|
|
758
|
-
};
|
|
759
|
-
//#endregion
|
|
760
|
-
//#region src/protocol.ts
|
|
761
|
-
/** Validated supplier options; no supplier identity is interpreted by this protocol. */
|
|
762
|
-
const OpenAIProtocolOptions = z.strictObject({
|
|
763
|
-
reasoningReplay: z.enum(["omit", "reasoning-content"]).optional(),
|
|
764
|
-
thinkingField: z.boolean().optional(),
|
|
765
|
-
outputLimitField: z.enum(["max_tokens", "max_completion_tokens"]).optional(),
|
|
766
|
-
promptCacheKey: z.boolean().optional()
|
|
767
|
-
});
|
|
768
|
-
/** Registers concrete Chat Completions request mapping, streaming and probes. */
|
|
769
|
-
function openaiProtocolType(support, fetch) {
|
|
2727
|
+
function responsesProtocolType(support, fetch) {
|
|
770
2728
|
return {
|
|
771
|
-
type: "openai",
|
|
772
|
-
label: "OpenAI
|
|
2729
|
+
type: "openai-responses",
|
|
2730
|
+
label: "OpenAI Responses API",
|
|
2731
|
+
userConfigurable: true,
|
|
2732
|
+
logo: protocolLogo,
|
|
773
2733
|
fields: [{
|
|
774
2734
|
key: "baseUrl",
|
|
775
2735
|
kind: "url",
|
|
776
2736
|
label: "Base URL",
|
|
777
2737
|
required: true
|
|
778
2738
|
}],
|
|
779
|
-
|
|
780
|
-
optionsSchema: OpenAIProtocolOptions,
|
|
2739
|
+
optionsSchema: ResponsesProtocolOptions,
|
|
781
2740
|
facts,
|
|
2741
|
+
effortCacheCapability: capability,
|
|
782
2742
|
prepareParams: (input) => support.prepareParams(input, facts),
|
|
783
|
-
chat: {
|
|
2743
|
+
adapters: { chat: {
|
|
784
2744
|
fileKinds: ["image"],
|
|
785
2745
|
supportsModel: () => true,
|
|
786
|
-
createPort(call) {
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
...options,
|
|
796
|
-
catalogue: () => support.catalogue(call.providerId, call.model),
|
|
797
|
-
media: (stored) => support.mediaContextOf({
|
|
798
|
-
entry: support.catalogue(call.providerId, call.model),
|
|
799
|
-
stored,
|
|
800
|
-
facts,
|
|
801
|
-
endpoint: support.endpoint(call.providerId),
|
|
802
|
-
fileKinds: ["image"]
|
|
803
|
-
}),
|
|
804
|
-
params: (stored) => support.resolveParams({
|
|
805
|
-
entry: support.catalogue(call.providerId, call.model),
|
|
806
|
-
stored,
|
|
807
|
-
facts,
|
|
808
|
-
model: call.model,
|
|
809
|
-
endpoint: support.endpoint(call.providerId)
|
|
810
|
-
})
|
|
811
|
-
});
|
|
812
|
-
}
|
|
813
|
-
},
|
|
814
|
-
normalizeListing: (input) => support.normalizeListing(input),
|
|
815
|
-
listModels: (probe) => probeOpenAI.listModels(probe, fetch),
|
|
816
|
-
testConnection: (probe) => probeOpenAI.testConnection(probe, fetch)
|
|
2746
|
+
createPort: (call) => createResponsesPort(call, support, withConnectionHeaders(fetch, call.headers), (request) => capability({
|
|
2747
|
+
...call,
|
|
2748
|
+
params: request.params ?? {},
|
|
2749
|
+
explicitKeys: []
|
|
2750
|
+
}))
|
|
2751
|
+
} },
|
|
2752
|
+
normalizeListing: (input) => normalizeOffers(input),
|
|
2753
|
+
listModels: async (probe) => ({ offers: await probeOpenAI.listModels(probe, withConnectionHeaders(fetch, probe.headers)) }),
|
|
2754
|
+
testConnection: (probe) => probeOpenAI.testConnection(probe, withConnectionHeaders(fetch, probe.headers), "responses")
|
|
817
2755
|
};
|
|
818
2756
|
}
|
|
819
2757
|
//#endregion
|
|
820
2758
|
//#region src/index.ts
|
|
821
|
-
/** Protocol extensions contribute no tools. */
|
|
822
2759
|
const TOOL_NAMES = [];
|
|
823
2760
|
const plugin = {
|
|
824
2761
|
name: "@eum-agent/llm-protocol-openai",
|
|
825
|
-
requires: ["
|
|
2762
|
+
requires: ["network"],
|
|
2763
|
+
optionalServices: ["model-support"],
|
|
2764
|
+
provides: ["openai-responses-codec"],
|
|
826
2765
|
apply(ctx) {
|
|
827
|
-
const support = ctx.services.
|
|
2766
|
+
const support = lazySupport(() => ctx.services.find("model-support"));
|
|
828
2767
|
const network = ctx.services.get("network");
|
|
829
|
-
ctx.
|
|
2768
|
+
ctx.services.provide("openai-responses-codec", responsesCodec);
|
|
2769
|
+
ctx.modelProtocols.register(openaiProtocolType(support, network.fetch));
|
|
2770
|
+
ctx.modelProtocols.register(responsesProtocolType(support, network.fetch));
|
|
2771
|
+
ctx.modelProtocols.register(imagesProtocolType(support, network.fetch));
|
|
2772
|
+
ctx.modelProtocols.register(decisionsProtocolType(network.fetch));
|
|
2773
|
+
ctx.modelProtocols.register(embeddingsProtocolType(network.fetch));
|
|
830
2774
|
}
|
|
831
2775
|
};
|
|
832
2776
|
//#endregion
|