@eum-agent/llm-protocol-openai 1.0.0 → 1.0.1
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 +223 -93
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import { countTokens } from "gpt-tokenizer/encoding/o200k_base";
|
|
3
2
|
import OpenAI, { APIConnectionError, APIError } from "openai";
|
|
4
3
|
//#region src/protocol/facts.ts
|
|
5
4
|
/** Parameter ranges and request limits for this provider wire. */
|
|
6
5
|
const facts = {
|
|
7
|
-
|
|
8
|
-
maxTokensFallback: 8192,
|
|
6
|
+
outputLimit: { support: "optional" },
|
|
9
7
|
temperature: {
|
|
10
8
|
min: 0,
|
|
11
9
|
max: 2,
|
|
@@ -21,32 +19,10 @@ const facts = {
|
|
|
21
19
|
//#endregion
|
|
22
20
|
//#region src/protocol/errors.ts
|
|
23
21
|
/**
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* redact against the endpoint's credentials and show.
|
|
22
|
+
* SDK exceptions have two consumers: explicit probes retain provider text for
|
|
23
|
+
* their credential-redaction boundary, while Agent calls accept only fixed
|
|
24
|
+
* templates and allowlisted facts through the host factory.
|
|
28
25
|
*/
|
|
29
|
-
/** Thrown by `stream()` once retries are exhausted (or the failure was
|
|
30
|
-
* never retryable) — mirrors the anthropic member's `ModelCallError`; the
|
|
31
|
-
* two packages share no code, only the shape of the port error they both
|
|
32
|
-
* produce. */
|
|
33
|
-
var ModelCallError = class extends Error {
|
|
34
|
-
status;
|
|
35
|
-
retryable;
|
|
36
|
-
/** The endpoint's own error body, unredacted. The runtime's guard removes
|
|
37
|
-
* every credential of the endpoint from it before it reaches a reason. */
|
|
38
|
-
providerText;
|
|
39
|
-
/** What the status alone says the refusal is (`failureKindOf`). */
|
|
40
|
-
kind;
|
|
41
|
-
constructor(message, options) {
|
|
42
|
-
super(message);
|
|
43
|
-
this.name = "ModelCallError";
|
|
44
|
-
this.status = options.status;
|
|
45
|
-
this.retryable = options.retryable;
|
|
46
|
-
this.providerText = options.providerText;
|
|
47
|
-
this.kind = options.status === 413 ? "request-too-large" : void 0;
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
26
|
/** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
|
|
51
27
|
* every other status is not. */
|
|
52
28
|
function isRetryableStatus(status) {
|
|
@@ -57,27 +33,46 @@ function retryAfterMs(error) {
|
|
|
57
33
|
const header = error.headers?.get("retry-after");
|
|
58
34
|
if (!header) return void 0;
|
|
59
35
|
const seconds = Number(header);
|
|
60
|
-
if (!Number.isFinite(seconds)) return void 0;
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
function toPortError(error) {
|
|
64
|
-
if (error instanceof APIError) {
|
|
65
|
-
const status = error.status;
|
|
66
|
-
const retryable = error instanceof APIConnectionError || isRetryableStatus(status);
|
|
67
|
-
const type = error.type;
|
|
68
|
-
return new ModelCallError(`OpenAI-compatible API error (status ${status ?? "unknown"}${type ? `, type ${type}` : ""})`, {
|
|
69
|
-
status,
|
|
70
|
-
retryable,
|
|
71
|
-
providerText: providerTextOf(error)
|
|
72
|
-
});
|
|
73
|
-
}
|
|
74
|
-
return new ModelCallError(`OpenAI-compatible call failed: ${error instanceof Error ? error.message : String(error)}`, { retryable: false });
|
|
36
|
+
if (!Number.isFinite(seconds) || seconds < 0) return void 0;
|
|
37
|
+
const milliseconds = seconds * 1e3;
|
|
38
|
+
return Number.isFinite(milliseconds) ? milliseconds : void 0;
|
|
75
39
|
}
|
|
76
|
-
/**
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
40
|
+
/** Maps verified SDK classes and factory identities to bounded Agent failure candidates. */
|
|
41
|
+
function toModelFailure(error, failures) {
|
|
42
|
+
if (failures.owns(error)) return error;
|
|
43
|
+
if (!(error instanceof APIError)) return failures.create({
|
|
44
|
+
code: "unknown",
|
|
45
|
+
stage: "unknown",
|
|
46
|
+
category: "unknown",
|
|
47
|
+
source: "unknown",
|
|
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 }
|
|
75
|
+
});
|
|
81
76
|
}
|
|
82
77
|
//#endregion
|
|
83
78
|
//#region src/protocol/request.ts
|
|
@@ -133,13 +128,14 @@ function userContent(message, index, plan) {
|
|
|
133
128
|
}
|
|
134
129
|
/** One kernel message becomes zero or more wire messages: a `user`
|
|
135
130
|
* message's `tool-result` parts each become their own `role: 'tool'`
|
|
136
|
-
* message
|
|
131
|
+
* message. Assistant replies without text or tool calls are omitted after
|
|
132
|
+
* reasoning is stripped; the endpoint requires at least one of those fields.
|
|
137
133
|
*
|
|
138
134
|
* A `role: 'tool'` message holds text alone, so the images a batch of
|
|
139
135
|
* results handed back follow it in one user message, each after the id of
|
|
140
136
|
* the call it came from; an image standing in as a line of text stays in
|
|
141
137
|
* its call's own tool message. */
|
|
142
|
-
function toChatMessages(message, index, plan) {
|
|
138
|
+
function toChatMessages(message, index, plan, reasoningReplay) {
|
|
143
139
|
const toolResults = message.content.map((part, partIndex) => ({
|
|
144
140
|
part,
|
|
145
141
|
partIndex
|
|
@@ -173,11 +169,17 @@ function toChatMessages(message, index, plan) {
|
|
|
173
169
|
}, ...images]
|
|
174
170
|
}];
|
|
175
171
|
}
|
|
176
|
-
if (message.role === "assistant")
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
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 [{
|
|
177
|
+
role: "assistant",
|
|
178
|
+
content,
|
|
179
|
+
...reasoningReplay === "reasoning-content" && message.outputTruncation?.incompleteThinking !== true ? { reasoning_content: message.content.filter((part) => part.type === "thinking").map((part) => part.text).join("") } : {},
|
|
180
|
+
...toolCalls === void 0 ? {} : { tool_calls: toolCalls }
|
|
181
|
+
}];
|
|
182
|
+
}
|
|
181
183
|
return [{
|
|
182
184
|
role: "user",
|
|
183
185
|
content: userContent(message, index, plan)
|
|
@@ -209,8 +211,8 @@ function volatileMessages(volatile) {
|
|
|
209
211
|
}
|
|
210
212
|
/** A reply's recorded notes go just before it — where the request that
|
|
211
213
|
* produced it carried them — so every request extends the previous one. */
|
|
212
|
-
function withNotes(message, index, plan) {
|
|
213
|
-
return [...message.role === "assistant" ? volatileMessages(message.volatile) : [], ...toChatMessages(message, index, plan)];
|
|
214
|
+
function withNotes(message, index, plan, reasoningReplay) {
|
|
215
|
+
return [...message.role === "assistant" ? volatileMessages(message.volatile) : [], ...toChatMessages(message, index, plan, reasoningReplay)];
|
|
214
216
|
}
|
|
215
217
|
function toToolParam(tool) {
|
|
216
218
|
return {
|
|
@@ -222,6 +224,7 @@ function toToolParam(tool) {
|
|
|
222
224
|
}
|
|
223
225
|
};
|
|
224
226
|
}
|
|
227
|
+
/** Renders provider history without empty assistant messages; rejects invalid summary budgets. */
|
|
225
228
|
function toOpenAIRequest(request, options) {
|
|
226
229
|
const summary = request.purpose === "summary";
|
|
227
230
|
if (summary && (!Number.isInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0)) throw new Error("summaryMaxTokens must be a positive integer for a summary request");
|
|
@@ -241,7 +244,7 @@ function toOpenAIRequest(request, options) {
|
|
|
241
244
|
stream_options: { include_usage: true },
|
|
242
245
|
messages: [
|
|
243
246
|
...systemMessage,
|
|
244
|
-
...request.messages.flatMap((message, index) => withNotes(message, index, plan)),
|
|
247
|
+
...request.messages.flatMap((message, index) => withNotes(message, index, plan, options.reasoningReplay)),
|
|
245
248
|
...volatileMessages(request.volatile)
|
|
246
249
|
],
|
|
247
250
|
...tools.length === 0 ? {} : { tools },
|
|
@@ -260,12 +263,19 @@ function cacheOf(usage) {
|
|
|
260
263
|
const read = usage.prompt_tokens_details?.cached_tokens ?? usage.prompt_cache_hit_tokens;
|
|
261
264
|
return typeof read === "number" && read >= 0 ? { cacheReadTokens: read } : {};
|
|
262
265
|
}
|
|
263
|
-
function toFinishReason(reason) {
|
|
266
|
+
function toFinishReason(reason, support) {
|
|
264
267
|
switch (reason) {
|
|
265
268
|
case "tool_calls": return "tool-calls";
|
|
266
269
|
case "length": return "max-tokens";
|
|
267
270
|
case "content_filter": return "refusal";
|
|
268
|
-
|
|
271
|
+
case "stop": return "stop";
|
|
272
|
+
default: throw support.failures.create({
|
|
273
|
+
code: reason === null ? "finish-reason-missing" : "finish-reason-unsupported",
|
|
274
|
+
stage: "response-validation",
|
|
275
|
+
category: "protocol",
|
|
276
|
+
source: "protocol",
|
|
277
|
+
retryable: false
|
|
278
|
+
});
|
|
269
279
|
}
|
|
270
280
|
}
|
|
271
281
|
/** The accumulated arguments as JSON, or `undefined` when they will not
|
|
@@ -281,16 +291,10 @@ function parseToolInput(argumentsJson) {
|
|
|
281
291
|
}
|
|
282
292
|
}
|
|
283
293
|
/**
|
|
284
|
-
*
|
|
285
|
-
*
|
|
286
|
-
*
|
|
287
|
-
* assistant message with no content — which reads as a model that had nothing
|
|
288
|
-
* to say and ends the turn as an ordinary completion. This sentence is the
|
|
289
|
-
* adapter's own, not the endpoint's, and it goes where both the person and the
|
|
290
|
-
* next turn read it. The `anthropic` member carries the same one for the same
|
|
291
|
-
* reason.
|
|
294
|
+
* Streams provider deltas and one validated final reply. Missing terminal reasons,
|
|
295
|
+
* unknown reasons and replies without text or usable tool calls fail without retry.
|
|
296
|
+
* A stream with neither usage nor a terminal reason retains interruption semantics.
|
|
292
297
|
*/
|
|
293
|
-
const CUT_OFF_NOTICE = "[The reply was cut off while a tool call was still being written; none of it could be used.]";
|
|
294
298
|
async function* mapOpenAIStream(chunks, support) {
|
|
295
299
|
const textParts = [];
|
|
296
300
|
const thinkingParts = [];
|
|
@@ -299,9 +303,11 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
299
303
|
let inputTokens = 0;
|
|
300
304
|
let outputTokens = 0;
|
|
301
305
|
let finishReason = "stop";
|
|
306
|
+
let rawFinishReason = null;
|
|
302
307
|
let cache = {};
|
|
303
308
|
let ended = false;
|
|
304
309
|
let refusalText;
|
|
310
|
+
let thinkingOpen = false;
|
|
305
311
|
for await (const chunk of chunks) {
|
|
306
312
|
if (chunk.usage) {
|
|
307
313
|
inputTokens = chunk.usage.prompt_tokens;
|
|
@@ -314,6 +320,7 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
314
320
|
const delta = choice.delta;
|
|
315
321
|
const reasoningContent = delta.reasoning_content || (typeof delta.reasoning === "string" ? delta.reasoning : void 0);
|
|
316
322
|
if (reasoningContent) {
|
|
323
|
+
thinkingOpen = true;
|
|
317
324
|
thinkingParts.push(reasoningContent);
|
|
318
325
|
yield {
|
|
319
326
|
kind: "thinking-delta",
|
|
@@ -321,6 +328,7 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
321
328
|
};
|
|
322
329
|
}
|
|
323
330
|
if (choice.delta.content) {
|
|
331
|
+
thinkingOpen = false;
|
|
324
332
|
textParts.push(choice.delta.content);
|
|
325
333
|
yield {
|
|
326
334
|
kind: "text-delta",
|
|
@@ -329,9 +337,16 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
329
337
|
}
|
|
330
338
|
if (choice.delta.refusal) refusalText = (refusalText ?? "") + choice.delta.refusal;
|
|
331
339
|
for (const delta of choice.delta.tool_calls ?? []) {
|
|
340
|
+
thinkingOpen = false;
|
|
332
341
|
let state = toolCalls.get(delta.index);
|
|
333
342
|
if (!state) {
|
|
334
|
-
if (!delta.id || !delta.function?.name) throw
|
|
343
|
+
if (!delta.id || !delta.function?.name) throw support.failures.create({
|
|
344
|
+
code: "response-invalid",
|
|
345
|
+
stage: "response-validation",
|
|
346
|
+
category: "protocol",
|
|
347
|
+
source: "protocol",
|
|
348
|
+
retryable: false
|
|
349
|
+
});
|
|
335
350
|
state = {
|
|
336
351
|
id: delta.id,
|
|
337
352
|
name: delta.function.name,
|
|
@@ -365,11 +380,19 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
365
380
|
};
|
|
366
381
|
}
|
|
367
382
|
if (choice.finish_reason) {
|
|
368
|
-
|
|
383
|
+
rawFinishReason = choice.finish_reason;
|
|
384
|
+
finishReason = toFinishReason(choice.finish_reason, support);
|
|
369
385
|
ended = true;
|
|
370
386
|
}
|
|
371
387
|
}
|
|
372
388
|
if (!ended) throw support.interruptedFailure();
|
|
389
|
+
if (rawFinishReason === null) throw support.failures.create({
|
|
390
|
+
code: "finish-reason-missing",
|
|
391
|
+
stage: "response-validation",
|
|
392
|
+
category: "protocol",
|
|
393
|
+
source: "protocol",
|
|
394
|
+
retryable: false
|
|
395
|
+
});
|
|
373
396
|
const content = [];
|
|
374
397
|
const thinkingText = thinkingParts.join("");
|
|
375
398
|
if (thinkingText.length > 0) content.push({
|
|
@@ -381,13 +404,24 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
381
404
|
type: "text",
|
|
382
405
|
text
|
|
383
406
|
});
|
|
384
|
-
|
|
407
|
+
const incompleteToolCalls = [];
|
|
385
408
|
for (const index of toolCallOrder) {
|
|
386
409
|
const call = toolCalls.get(index);
|
|
387
410
|
if (!call) continue;
|
|
388
|
-
const input = parseToolInput(call.arguments);
|
|
411
|
+
const input = finishReason === "max-tokens" && call.arguments.trim() === "" ? void 0 : parseToolInput(call.arguments);
|
|
389
412
|
if (input === void 0) {
|
|
390
|
-
|
|
413
|
+
if (finishReason !== "max-tokens") throw support.failures.create({
|
|
414
|
+
code: "response-invalid",
|
|
415
|
+
stage: "response-validation",
|
|
416
|
+
category: "protocol",
|
|
417
|
+
source: "protocol",
|
|
418
|
+
retryable: false,
|
|
419
|
+
finishReason
|
|
420
|
+
});
|
|
421
|
+
incompleteToolCalls.push({
|
|
422
|
+
id: call.id,
|
|
423
|
+
name: call.name
|
|
424
|
+
});
|
|
391
425
|
continue;
|
|
392
426
|
}
|
|
393
427
|
content.push({
|
|
@@ -397,13 +431,21 @@ async function* mapOpenAIStream(chunks, support) {
|
|
|
397
431
|
input
|
|
398
432
|
});
|
|
399
433
|
}
|
|
400
|
-
if (content.
|
|
401
|
-
|
|
402
|
-
|
|
434
|
+
if (finishReason !== "refusal" && finishReason !== "max-tokens" && !content.some((part) => part.type === "text" || part.type === "tool-use")) throw support.failures.create({
|
|
435
|
+
code: "response-empty",
|
|
436
|
+
stage: "response-validation",
|
|
437
|
+
category: "protocol",
|
|
438
|
+
source: "protocol",
|
|
439
|
+
retryable: false,
|
|
440
|
+
finishReason
|
|
403
441
|
});
|
|
404
442
|
yield {
|
|
405
443
|
kind: "final",
|
|
406
444
|
finishReason,
|
|
445
|
+
...finishReason === "max-tokens" ? { outputTruncation: {
|
|
446
|
+
incompleteToolCalls,
|
|
447
|
+
...thinkingOpen ? { incompleteThinking: true } : {}
|
|
448
|
+
} } : {},
|
|
407
449
|
usage: {
|
|
408
450
|
inputTokens,
|
|
409
451
|
outputTokens,
|
|
@@ -476,8 +518,8 @@ function createOpenAIModelPort(options) {
|
|
|
476
518
|
const outputReserve = enforced ? Math.max(...explicitOutputLimits) : capacity?.output ?? Math.max(0, ...explicitOutputLimits);
|
|
477
519
|
return options.support.inspect({
|
|
478
520
|
body: params,
|
|
479
|
-
textTokens:
|
|
480
|
-
tokenizer: "o200k_base-
|
|
521
|
+
textTokens: options.support.measureText(options.support.requestText("chat-completions", params)),
|
|
522
|
+
tokenizer: "o200k_base-protocol-text-v2",
|
|
481
523
|
request,
|
|
482
524
|
capacity,
|
|
483
525
|
outputReserve,
|
|
@@ -502,27 +544,81 @@ function createOpenAIModelPort(options) {
|
|
|
502
544
|
}
|
|
503
545
|
});
|
|
504
546
|
},
|
|
505
|
-
stream(request, signal) {
|
|
547
|
+
stream(request, signal, observer) {
|
|
548
|
+
signal.throwIfAborted();
|
|
506
549
|
const { params } = build(request);
|
|
507
550
|
return options.support.withChatAttempts({
|
|
508
551
|
signal,
|
|
509
552
|
...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
|
|
510
553
|
...options.sleep === void 0 ? {} : { sleep: options.sleep },
|
|
511
554
|
...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
|
|
512
|
-
async *attempt(attemptSignal, reportProgress) {
|
|
513
|
-
const
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
555
|
+
async *attempt(attemptSignal, reportProgress, attempt) {
|
|
556
|
+
const observe = (event) => {
|
|
557
|
+
try {
|
|
558
|
+
observer?.observe?.(event);
|
|
559
|
+
} catch {}
|
|
560
|
+
};
|
|
561
|
+
const attemptCount = attempt + 1;
|
|
562
|
+
let outcome = "unknown";
|
|
563
|
+
let firstResponseFinished = false;
|
|
564
|
+
observe({
|
|
565
|
+
stage: "attempt",
|
|
566
|
+
phase: "start",
|
|
567
|
+
attempt: attemptCount
|
|
568
|
+
});
|
|
569
|
+
observe({
|
|
570
|
+
stage: "first-response",
|
|
571
|
+
phase: "start",
|
|
572
|
+
attempt: attemptCount
|
|
573
|
+
});
|
|
574
|
+
try {
|
|
575
|
+
attemptSignal.throwIfAborted();
|
|
576
|
+
const chunks = await clientForAttempt(reportProgress).chat.completions.create(params, { signal: attemptSignal });
|
|
577
|
+
firstResponseFinished = true;
|
|
578
|
+
observe({
|
|
579
|
+
stage: "first-response",
|
|
580
|
+
phase: "end",
|
|
581
|
+
attempt: attemptCount,
|
|
582
|
+
outcome: "ok"
|
|
583
|
+
});
|
|
584
|
+
attemptSignal.throwIfAborted();
|
|
585
|
+
try {
|
|
586
|
+
observer?.dispatched({ attempt });
|
|
587
|
+
} catch {}
|
|
588
|
+
attemptSignal.throwIfAborted();
|
|
589
|
+
const observed = (async function* () {
|
|
590
|
+
for await (const chunk of chunks) {
|
|
591
|
+
reportProgress();
|
|
592
|
+
yield chunk;
|
|
593
|
+
}
|
|
594
|
+
})();
|
|
595
|
+
for await (const chunk of mapOpenAIStream(observed, options.support)) {
|
|
596
|
+
if (chunk.kind === "final") outcome = "ok";
|
|
517
597
|
yield chunk;
|
|
518
598
|
}
|
|
519
|
-
}
|
|
599
|
+
} catch (error) {
|
|
600
|
+
outcome = attemptSignal.aborted ? "cancelled" : "error";
|
|
601
|
+
throw error;
|
|
602
|
+
} finally {
|
|
603
|
+
if (!firstResponseFinished) observe({
|
|
604
|
+
stage: "first-response",
|
|
605
|
+
phase: "end",
|
|
606
|
+
attempt: attemptCount,
|
|
607
|
+
outcome
|
|
608
|
+
});
|
|
609
|
+
observe({
|
|
610
|
+
stage: "attempt",
|
|
611
|
+
phase: "end",
|
|
612
|
+
attempt: attemptCount,
|
|
613
|
+
outcome
|
|
614
|
+
});
|
|
615
|
+
}
|
|
520
616
|
},
|
|
521
617
|
classify(error) {
|
|
522
|
-
const portError =
|
|
618
|
+
const portError = toModelFailure(error, options.support.failures);
|
|
523
619
|
return {
|
|
524
620
|
error: portError,
|
|
525
|
-
retryable: portError.retryable,
|
|
621
|
+
retryable: portError.retryable === true,
|
|
526
622
|
retryAfterMs: retryAfterMs(error)
|
|
527
623
|
};
|
|
528
624
|
}
|
|
@@ -532,12 +628,45 @@ function createOpenAIModelPort(options) {
|
|
|
532
628
|
}
|
|
533
629
|
//#endregion
|
|
534
630
|
//#region src/protocol/probe.ts
|
|
631
|
+
async function readBody(response, maxBytes) {
|
|
632
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1) throw new Error("invalid response budget");
|
|
633
|
+
const declared = response.headers.get("content-length");
|
|
634
|
+
if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
|
|
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
|
+
}
|
|
535
664
|
function baseUrlOf(probe) {
|
|
536
665
|
const configured = probe.config.baseUrl;
|
|
537
666
|
return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
|
|
538
667
|
}
|
|
539
|
-
async function refuse(response) {
|
|
540
|
-
const body = await response.text
|
|
668
|
+
async function refuse(response, maxBytes = 8388608) {
|
|
669
|
+
const body = (await readBody(response, maxBytes)).text;
|
|
541
670
|
throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
|
|
542
671
|
}
|
|
543
672
|
function headers(probe) {
|
|
@@ -603,8 +732,8 @@ const probeOpenAI = {
|
|
|
603
732
|
headers: headers(probe),
|
|
604
733
|
signal: probe.signal
|
|
605
734
|
});
|
|
606
|
-
if (!response.ok) await refuse(response);
|
|
607
|
-
return ((await response.
|
|
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)] : []);
|
|
608
737
|
},
|
|
609
738
|
async testConnection(probe, fetcher = globalThis.fetch) {
|
|
610
739
|
if (probe.model !== void 0) {
|
|
@@ -621,7 +750,7 @@ const probeOpenAI = {
|
|
|
621
750
|
}),
|
|
622
751
|
signal: probe.signal
|
|
623
752
|
});
|
|
624
|
-
if (!response.ok) await refuse(response);
|
|
753
|
+
if (!response.ok) await refuse(response, probe.maxResponseBytes ?? 8388608);
|
|
625
754
|
return;
|
|
626
755
|
}
|
|
627
756
|
await probeOpenAI.listModels(probe, fetcher);
|
|
@@ -631,6 +760,7 @@ const probeOpenAI = {
|
|
|
631
760
|
//#region src/protocol.ts
|
|
632
761
|
/** Validated supplier options; no supplier identity is interpreted by this protocol. */
|
|
633
762
|
const OpenAIProtocolOptions = z.strictObject({
|
|
763
|
+
reasoningReplay: z.enum(["omit", "reasoning-content"]).optional(),
|
|
634
764
|
thinkingField: z.boolean().optional(),
|
|
635
765
|
outputLimitField: z.enum(["max_tokens", "max_completion_tokens"]).optional(),
|
|
636
766
|
promptCacheKey: z.boolean().optional()
|
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"en-US": "OpenAI Model Protocol",
|
|
5
5
|
"zh-CN": "模型协议 · OpenAI"
|
|
6
6
|
},
|
|
7
|
-
"version": "1.0.
|
|
7
|
+
"version": "1.0.1",
|
|
8
8
|
"type": "module",
|
|
9
9
|
"description": "Public OpenAI model communication protocol",
|
|
10
10
|
"license": "MIT",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
"dist"
|
|
18
18
|
],
|
|
19
19
|
"devDependencies": {
|
|
20
|
-
"@eum-agent/plugin": "1.0.
|
|
20
|
+
"@eum-agent/plugin": "1.0.1"
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
23
|
"zod": "^4.4.3",
|
|
@@ -27,10 +27,10 @@
|
|
|
27
27
|
"yaoguang": {
|
|
28
28
|
"kind": "extension",
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@eum-agent/llm-management": "1.0.
|
|
30
|
+
"@eum-agent/llm-management": "1.0.1"
|
|
31
31
|
},
|
|
32
32
|
"foundationDependencies": {
|
|
33
|
-
"@eum-agent/infra-local": "1.0.
|
|
33
|
+
"@eum-agent/infra-local": "1.0.1"
|
|
34
34
|
},
|
|
35
35
|
"description": {
|
|
36
36
|
"en-US": "Public OpenAI model communication protocol",
|