@eum-agent/llm-protocol-openai 0.0.0-stage → 1.0.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 +703 -0
- package/package.json +42 -3
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,703 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { countTokens } from "gpt-tokenizer/encoding/o200k_base";
|
|
3
|
+
import OpenAI, { APIConnectionError, APIError } from "openai";
|
|
4
|
+
//#region src/protocol/facts.ts
|
|
5
|
+
/** Parameter ranges and request limits for this provider wire. */
|
|
6
|
+
const facts = {
|
|
7
|
+
maxTokensRequired: false,
|
|
8
|
+
maxTokensFallback: 8192,
|
|
9
|
+
temperature: {
|
|
10
|
+
min: 0,
|
|
11
|
+
max: 2,
|
|
12
|
+
step: .05,
|
|
13
|
+
default: 1
|
|
14
|
+
},
|
|
15
|
+
thinkingSwitch: false,
|
|
16
|
+
limits: {
|
|
17
|
+
requestBytes: 20971520,
|
|
18
|
+
images: 50
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
//#endregion
|
|
22
|
+
//#region src/protocol/errors.ts
|
|
23
|
+
/**
|
|
24
|
+
* Maps the OpenAI SDK's `APIError` into the host's port error shape:
|
|
25
|
+
* `.headers` is never read into, or attached to, what this module hands
|
|
26
|
+
* back. The error body travels as `providerText`, for the runtime's guard to
|
|
27
|
+
* redact against the endpoint's credentials and show.
|
|
28
|
+
*/
|
|
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
|
+
/** Timeouts, conflicts, rate limits and 5xx are worth a second attempt;
|
|
51
|
+
* every other status is not. */
|
|
52
|
+
function isRetryableStatus(status) {
|
|
53
|
+
return status === 408 || status === 409 || status === 429 || status !== void 0 && status >= 500;
|
|
54
|
+
}
|
|
55
|
+
function retryAfterMs(error) {
|
|
56
|
+
if (!(error instanceof APIError)) return void 0;
|
|
57
|
+
const header = error.headers?.get("retry-after");
|
|
58
|
+
if (!header) return void 0;
|
|
59
|
+
const seconds = Number(header);
|
|
60
|
+
if (!Number.isFinite(seconds)) return void 0;
|
|
61
|
+
return seconds * 1e3;
|
|
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 });
|
|
75
|
+
}
|
|
76
|
+
/** The parsed error body when the SDK parsed one, else the SDK's message,
|
|
77
|
+
* which carries the raw body text. Never the headers. */
|
|
78
|
+
function providerTextOf(error) {
|
|
79
|
+
const text = error.error === void 0 ? error.message : JSON.stringify(error.error);
|
|
80
|
+
return text === void 0 || text.trim() === "" ? void 0 : text;
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
83
|
+
//#region src/protocol/request.ts
|
|
84
|
+
function textOf(parts) {
|
|
85
|
+
const text = parts.filter((part) => part.type === "text").map((part) => part.text).join("");
|
|
86
|
+
return text.length > 0 ? text : null;
|
|
87
|
+
}
|
|
88
|
+
function toolCallsOf(parts) {
|
|
89
|
+
const calls = parts.filter((part) => part.type === "tool-use").map((part) => ({
|
|
90
|
+
id: part.id,
|
|
91
|
+
type: "function",
|
|
92
|
+
function: {
|
|
93
|
+
name: part.name,
|
|
94
|
+
arguments: JSON.stringify(part.input ?? {})
|
|
95
|
+
}
|
|
96
|
+
}));
|
|
97
|
+
return calls.length > 0 ? calls : void 0;
|
|
98
|
+
}
|
|
99
|
+
function imagePart(planned) {
|
|
100
|
+
return {
|
|
101
|
+
type: "image_url",
|
|
102
|
+
image_url: { url: `data:${planned.mediaType};base64,${planned.data ?? ""}` }
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/** A user message's parts in order: text, and each file as its label and
|
|
106
|
+
* image, or as the line standing in for it. A message whose parts are all
|
|
107
|
+
* text stays the one string it always was. */
|
|
108
|
+
function userContent(message, index, plan) {
|
|
109
|
+
if (!message.content.some((part) => part.type === "file")) return textOf(message.content) ?? "";
|
|
110
|
+
const parts = [];
|
|
111
|
+
let text = "";
|
|
112
|
+
const flush = () => {
|
|
113
|
+
if (text.length > 0) parts.push({
|
|
114
|
+
type: "text",
|
|
115
|
+
text
|
|
116
|
+
});
|
|
117
|
+
text = "";
|
|
118
|
+
};
|
|
119
|
+
message.content.forEach((part, partIndex) => {
|
|
120
|
+
if (part.type === "text") text += part.text;
|
|
121
|
+
else if (part.type === "file") {
|
|
122
|
+
const planned = plan.at(index, partIndex);
|
|
123
|
+
flush();
|
|
124
|
+
parts.push({
|
|
125
|
+
type: "text",
|
|
126
|
+
text: planned.label
|
|
127
|
+
});
|
|
128
|
+
if (planned.fate === "send") parts.push(imagePart(planned));
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
flush();
|
|
132
|
+
return parts.every((part) => part.type === "text") ? parts.map((part) => part.text).join("\n") : parts;
|
|
133
|
+
}
|
|
134
|
+
/** One kernel message becomes zero or more wire messages: a `user`
|
|
135
|
+
* message's `tool-result` parts each become their own `role: 'tool'`
|
|
136
|
+
* message; everything else becomes exactly one message.
|
|
137
|
+
*
|
|
138
|
+
* A `role: 'tool'` message holds text alone, so the images a batch of
|
|
139
|
+
* results handed back follow it in one user message, each after the id of
|
|
140
|
+
* the call it came from; an image standing in as a line of text stays in
|
|
141
|
+
* its call's own tool message. */
|
|
142
|
+
function toChatMessages(message, index, plan) {
|
|
143
|
+
const toolResults = message.content.map((part, partIndex) => ({
|
|
144
|
+
part,
|
|
145
|
+
partIndex
|
|
146
|
+
})).filter((entry) => entry.part.type === "tool-result");
|
|
147
|
+
if (message.role === "user" && toolResults.length > 0) {
|
|
148
|
+
const images = [];
|
|
149
|
+
const tools = toolResults.map(({ part, partIndex }) => {
|
|
150
|
+
const lines = [part.content];
|
|
151
|
+
(part.files ?? []).forEach((_, fileIndex) => {
|
|
152
|
+
const planned = plan.at(index, partIndex, fileIndex);
|
|
153
|
+
if (planned.fate !== "send") {
|
|
154
|
+
lines.push(planned.label);
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
images.push({
|
|
158
|
+
type: "text",
|
|
159
|
+
text: `${part.toolUseId} ${planned.label}`
|
|
160
|
+
}, imagePart(planned));
|
|
161
|
+
});
|
|
162
|
+
return {
|
|
163
|
+
role: "tool",
|
|
164
|
+
content: lines.filter((line) => line !== "").join("\n"),
|
|
165
|
+
tool_call_id: part.toolUseId
|
|
166
|
+
};
|
|
167
|
+
});
|
|
168
|
+
return images.length === 0 ? tools : [...tools, {
|
|
169
|
+
role: "user",
|
|
170
|
+
content: [{
|
|
171
|
+
type: "text",
|
|
172
|
+
text: "Images returned by tool calls:"
|
|
173
|
+
}, ...images]
|
|
174
|
+
}];
|
|
175
|
+
}
|
|
176
|
+
if (message.role === "assistant") return [{
|
|
177
|
+
role: "assistant",
|
|
178
|
+
content: textOf(message.content),
|
|
179
|
+
...toolCallsOf(message.content) ? { tool_calls: toolCallsOf(message.content) } : {}
|
|
180
|
+
}];
|
|
181
|
+
return [{
|
|
182
|
+
role: "user",
|
|
183
|
+
content: userContent(message, index, plan)
|
|
184
|
+
}];
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* The volatile slot's contributions, as one standalone message to put after
|
|
188
|
+
* everything `toChatMessages` produced.
|
|
189
|
+
*
|
|
190
|
+
* **Appended unconditionally, without looking at what the last message is.**
|
|
191
|
+
* `toChatMessages` turns a user message carrying `tool-result` parts into
|
|
192
|
+
* `role: 'tool'` messages and drops its text parts, so writing the text into
|
|
193
|
+
* the last message — the anthropic member's shape — would lose it silently on
|
|
194
|
+
* the most common path there is: the step right after a tool call, which is
|
|
195
|
+
* when a volatile contribution first reaches the model. One message of its
|
|
196
|
+
* own has no such branch, and it puts the invariant in the code rather than
|
|
197
|
+
* in a reviewer's head.
|
|
198
|
+
*
|
|
199
|
+
* Nothing is added when there is nothing to add — an absent slot, an empty
|
|
200
|
+
* one, and one whose contributions are all empty leave the request the
|
|
201
|
+
* caller would have got anyway.
|
|
202
|
+
*/
|
|
203
|
+
function volatileMessages(volatile) {
|
|
204
|
+
const content = (volatile ?? []).map((note) => note.text).join("\n\n");
|
|
205
|
+
return content.length > 0 ? [{
|
|
206
|
+
role: "user",
|
|
207
|
+
content
|
|
208
|
+
}] : [];
|
|
209
|
+
}
|
|
210
|
+
/** A reply's recorded notes go just before it — where the request that
|
|
211
|
+
* 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
|
+
}
|
|
215
|
+
function toToolParam(tool) {
|
|
216
|
+
return {
|
|
217
|
+
type: "function",
|
|
218
|
+
function: {
|
|
219
|
+
name: tool.name,
|
|
220
|
+
description: tool.description,
|
|
221
|
+
parameters: tool.inputSchema
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function toOpenAIRequest(request, options) {
|
|
226
|
+
const summary = request.purpose === "summary";
|
|
227
|
+
if (summary && (!Number.isInteger(request.summaryMaxTokens) || Number(request.summaryMaxTokens) <= 0)) throw new Error("summaryMaxTokens must be a positive integer for a summary request");
|
|
228
|
+
const tools = request.tools && request.tools.length > 0 ? request.tools.map(toToolParam) : [];
|
|
229
|
+
const maxTokens = summary ? Math.min(request.summaryMaxTokens, Number.isInteger(options.maxTokens) && Number(options.maxTokens) > 0 ? options.maxTokens : request.summaryMaxTokens) : options.maxTokens;
|
|
230
|
+
const plan = options.support.planMedia(request, options.media ?? {
|
|
231
|
+
acceptsImages: true,
|
|
232
|
+
limits: void 0
|
|
233
|
+
});
|
|
234
|
+
const systemMessage = request.system ? [{
|
|
235
|
+
role: "system",
|
|
236
|
+
content: request.system.join("\n\n")
|
|
237
|
+
}] : [];
|
|
238
|
+
return {
|
|
239
|
+
model: options.model,
|
|
240
|
+
stream: true,
|
|
241
|
+
stream_options: { include_usage: true },
|
|
242
|
+
messages: [
|
|
243
|
+
...systemMessage,
|
|
244
|
+
...request.messages.flatMap((message, index) => withNotes(message, index, plan)),
|
|
245
|
+
...volatileMessages(request.volatile)
|
|
246
|
+
],
|
|
247
|
+
...tools.length === 0 ? {} : { tools },
|
|
248
|
+
...request.toolChoice === "none" && tools.length > 0 ? { tool_choice: "none" } : {},
|
|
249
|
+
...options.reasoningEffort === void 0 ? {} : { reasoning_effort: options.reasoningEffort },
|
|
250
|
+
...options.thinkingField === true && options.thinking !== void 0 ? { thinking: { type: options.thinking ? "enabled" : "disabled" } } : {},
|
|
251
|
+
...options.temperature === void 0 ? {} : { temperature: options.temperature },
|
|
252
|
+
...maxTokens === void 0 ? {} : { [options.outputLimitField ?? "max_tokens"]: maxTokens },
|
|
253
|
+
...options.promptCacheKey === true && request.cacheKey !== void 0 ? { prompt_cache_key: request.cacheKey } : {},
|
|
254
|
+
...summary ? {} : options.extra
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
//#endregion
|
|
258
|
+
//#region src/protocol/stream.ts
|
|
259
|
+
function cacheOf(usage) {
|
|
260
|
+
const read = usage.prompt_tokens_details?.cached_tokens ?? usage.prompt_cache_hit_tokens;
|
|
261
|
+
return typeof read === "number" && read >= 0 ? { cacheReadTokens: read } : {};
|
|
262
|
+
}
|
|
263
|
+
function toFinishReason(reason) {
|
|
264
|
+
switch (reason) {
|
|
265
|
+
case "tool_calls": return "tool-calls";
|
|
266
|
+
case "length": return "max-tokens";
|
|
267
|
+
case "content_filter": return "refusal";
|
|
268
|
+
default: return "stop";
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/** The accumulated arguments as JSON, or `undefined` when they will not
|
|
272
|
+
* parse — which is what a tool call the endpoint cut off at its output cap
|
|
273
|
+
* looks like. `JSON.parse` never produces `undefined` itself, so it is free
|
|
274
|
+
* to stand for "no usable input here". */
|
|
275
|
+
function parseToolInput(argumentsJson) {
|
|
276
|
+
if (argumentsJson.length === 0) return {};
|
|
277
|
+
try {
|
|
278
|
+
return JSON.parse(argumentsJson);
|
|
279
|
+
} catch {
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* What a reply that was nothing but a cut-off tool call says instead.
|
|
285
|
+
*
|
|
286
|
+
* The call is dropped, and with nothing else in the reply that would leave an
|
|
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.
|
|
292
|
+
*/
|
|
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
|
+
async function* mapOpenAIStream(chunks, support) {
|
|
295
|
+
const textParts = [];
|
|
296
|
+
const thinkingParts = [];
|
|
297
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
298
|
+
const toolCallOrder = [];
|
|
299
|
+
let inputTokens = 0;
|
|
300
|
+
let outputTokens = 0;
|
|
301
|
+
let finishReason = "stop";
|
|
302
|
+
let cache = {};
|
|
303
|
+
let ended = false;
|
|
304
|
+
let refusalText;
|
|
305
|
+
for await (const chunk of chunks) {
|
|
306
|
+
if (chunk.usage) {
|
|
307
|
+
inputTokens = chunk.usage.prompt_tokens;
|
|
308
|
+
outputTokens = chunk.usage.completion_tokens;
|
|
309
|
+
cache = cacheOf(chunk.usage);
|
|
310
|
+
ended = true;
|
|
311
|
+
}
|
|
312
|
+
const choice = chunk.choices[0];
|
|
313
|
+
if (!choice) continue;
|
|
314
|
+
const delta = choice.delta;
|
|
315
|
+
const reasoningContent = delta.reasoning_content || (typeof delta.reasoning === "string" ? delta.reasoning : void 0);
|
|
316
|
+
if (reasoningContent) {
|
|
317
|
+
thinkingParts.push(reasoningContent);
|
|
318
|
+
yield {
|
|
319
|
+
kind: "thinking-delta",
|
|
320
|
+
text: reasoningContent
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
if (choice.delta.content) {
|
|
324
|
+
textParts.push(choice.delta.content);
|
|
325
|
+
yield {
|
|
326
|
+
kind: "text-delta",
|
|
327
|
+
text: choice.delta.content
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
if (choice.delta.refusal) refusalText = (refusalText ?? "") + choice.delta.refusal;
|
|
331
|
+
for (const delta of choice.delta.tool_calls ?? []) {
|
|
332
|
+
let state = toolCalls.get(delta.index);
|
|
333
|
+
if (!state) {
|
|
334
|
+
if (!delta.id || !delta.function?.name) throw new Error(`mapOpenAIStream: tool_calls delta at index ${delta.index} arrived before its id/name`);
|
|
335
|
+
state = {
|
|
336
|
+
id: delta.id,
|
|
337
|
+
name: delta.function.name,
|
|
338
|
+
arguments: ""
|
|
339
|
+
};
|
|
340
|
+
toolCalls.set(delta.index, state);
|
|
341
|
+
toolCallOrder.push(delta.index);
|
|
342
|
+
yield {
|
|
343
|
+
kind: "tool-call-delta",
|
|
344
|
+
id: state.id,
|
|
345
|
+
name: state.name,
|
|
346
|
+
inputDelta: ""
|
|
347
|
+
};
|
|
348
|
+
if (delta.function.arguments) {
|
|
349
|
+
state.arguments += delta.function.arguments;
|
|
350
|
+
yield {
|
|
351
|
+
kind: "tool-call-delta",
|
|
352
|
+
id: state.id,
|
|
353
|
+
inputDelta: delta.function.arguments
|
|
354
|
+
};
|
|
355
|
+
}
|
|
356
|
+
continue;
|
|
357
|
+
}
|
|
358
|
+
const argumentsDelta = delta.function?.arguments ?? "";
|
|
359
|
+
if (argumentsDelta.length === 0) continue;
|
|
360
|
+
state.arguments += argumentsDelta;
|
|
361
|
+
yield {
|
|
362
|
+
kind: "tool-call-delta",
|
|
363
|
+
id: state.id,
|
|
364
|
+
inputDelta: argumentsDelta
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
if (choice.finish_reason) {
|
|
368
|
+
finishReason = toFinishReason(choice.finish_reason);
|
|
369
|
+
ended = true;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (!ended) throw support.interruptedFailure();
|
|
373
|
+
const content = [];
|
|
374
|
+
const thinkingText = thinkingParts.join("");
|
|
375
|
+
if (thinkingText.length > 0) content.push({
|
|
376
|
+
type: "thinking",
|
|
377
|
+
text: thinkingText
|
|
378
|
+
});
|
|
379
|
+
const text = refusalText ?? textParts.join("");
|
|
380
|
+
if (text.length > 0) content.push({
|
|
381
|
+
type: "text",
|
|
382
|
+
text
|
|
383
|
+
});
|
|
384
|
+
let cutOff = false;
|
|
385
|
+
for (const index of toolCallOrder) {
|
|
386
|
+
const call = toolCalls.get(index);
|
|
387
|
+
if (!call) continue;
|
|
388
|
+
const input = parseToolInput(call.arguments);
|
|
389
|
+
if (input === void 0) {
|
|
390
|
+
cutOff = true;
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
content.push({
|
|
394
|
+
type: "tool-use",
|
|
395
|
+
id: call.id,
|
|
396
|
+
name: call.name,
|
|
397
|
+
input
|
|
398
|
+
});
|
|
399
|
+
}
|
|
400
|
+
if (content.length === 0 && cutOff) content.push({
|
|
401
|
+
type: "text",
|
|
402
|
+
text: CUT_OFF_NOTICE
|
|
403
|
+
});
|
|
404
|
+
yield {
|
|
405
|
+
kind: "final",
|
|
406
|
+
finishReason,
|
|
407
|
+
usage: {
|
|
408
|
+
inputTokens,
|
|
409
|
+
outputTokens,
|
|
410
|
+
...cache
|
|
411
|
+
},
|
|
412
|
+
...finishReason === "refusal" ? { refusalCategory: "content_filter" } : {},
|
|
413
|
+
message: {
|
|
414
|
+
role: "assistant",
|
|
415
|
+
content
|
|
416
|
+
}
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
//#endregion
|
|
420
|
+
//#region src/protocol/port.ts
|
|
421
|
+
/** The neutral plan in this family's spelling: on and off go out as the
|
|
422
|
+
* endpoint's `thinking` field where it has one, else as `effort: 'none'`,
|
|
423
|
+
* which `params.ts` already put in the plan. */
|
|
424
|
+
function openaiOptions(plan) {
|
|
425
|
+
return {
|
|
426
|
+
...plan.effort === void 0 ? {} : { reasoningEffort: plan.effort },
|
|
427
|
+
...plan.thinking === void 0 ? {} : { thinking: plan.thinking },
|
|
428
|
+
...plan.temperature === void 0 ? {} : { temperature: plan.temperature },
|
|
429
|
+
...plan.maxTokens === void 0 ? {} : { maxTokens: plan.maxTokens }
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
/** Creates an OpenAI-compatible port with inspection and partial-stream retry protection. */
|
|
433
|
+
function createOpenAIModelPort(options) {
|
|
434
|
+
function clientForAttempt(reportProgress) {
|
|
435
|
+
return options.client ?? new OpenAI({
|
|
436
|
+
apiKey: options.apiKey ?? "",
|
|
437
|
+
fetch: async (...args) => options.support.observeResponseProgress(await (options.fetch ?? globalThis.fetch)(...args), reportProgress),
|
|
438
|
+
baseURL: options.baseURL ?? "",
|
|
439
|
+
maxRetries: 0
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
function build(request) {
|
|
443
|
+
const capacity = options.catalogue?.()?.limit;
|
|
444
|
+
const outputLimit = Number.isInteger(capacity?.output) && Number(capacity?.output) > 0 ? Number(capacity?.output) : void 0;
|
|
445
|
+
const effectiveRequest = request.purpose === "summary" && outputLimit !== void 0 ? {
|
|
446
|
+
...request,
|
|
447
|
+
summaryMaxTokens: Math.min(request.summaryMaxTokens ?? 0, outputLimit)
|
|
448
|
+
} : request;
|
|
449
|
+
const { media: mediaOf, ...rest } = options;
|
|
450
|
+
const media = mediaOf?.(request.params ?? {});
|
|
451
|
+
const base = media === void 0 ? rest : {
|
|
452
|
+
...rest,
|
|
453
|
+
media
|
|
454
|
+
};
|
|
455
|
+
const requestOptions = options.params === void 0 ? base : {
|
|
456
|
+
...base,
|
|
457
|
+
...openaiOptions(options.params(request.params ?? {})),
|
|
458
|
+
extra: {
|
|
459
|
+
...options.extra,
|
|
460
|
+
...options.support.extraParams(request.params ?? {})
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
return {
|
|
464
|
+
params: toOpenAIRequest(effectiveRequest, requestOptions),
|
|
465
|
+
requestOptions,
|
|
466
|
+
capacity
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
return {
|
|
470
|
+
inspect(request) {
|
|
471
|
+
const { params, requestOptions, capacity } = build(request);
|
|
472
|
+
const bodyMaxTokens = params.max_tokens;
|
|
473
|
+
const bodyMaxCompletionTokens = params.max_completion_tokens;
|
|
474
|
+
const explicitOutputLimits = [bodyMaxTokens, bodyMaxCompletionTokens].filter((value) => Number.isInteger(value) && Number(value) > 0).map(Number);
|
|
475
|
+
const enforced = Number.isInteger(bodyMaxCompletionTokens) && Number(bodyMaxCompletionTokens) > 0;
|
|
476
|
+
const outputReserve = enforced ? Math.max(...explicitOutputLimits) : capacity?.output ?? Math.max(0, ...explicitOutputLimits);
|
|
477
|
+
return options.support.inspect({
|
|
478
|
+
body: params,
|
|
479
|
+
textTokens: countTokens(JSON.stringify(params), { disallowedSpecial: /* @__PURE__ */ new Set() }),
|
|
480
|
+
tokenizer: "o200k_base-json-v1",
|
|
481
|
+
request,
|
|
482
|
+
capacity,
|
|
483
|
+
outputReserve,
|
|
484
|
+
outputReserveSource: enforced ? "enforced" : "capacity",
|
|
485
|
+
mediaTokens: options.support.planMedia(request, requestOptions.media ?? {
|
|
486
|
+
acceptsImages: true,
|
|
487
|
+
limits: void 0
|
|
488
|
+
}).tokens,
|
|
489
|
+
fingerprint: {
|
|
490
|
+
rendering: "openai-chat-completions-v3",
|
|
491
|
+
endpoint: options.endpoint ?? options.baseURL,
|
|
492
|
+
model: params.model,
|
|
493
|
+
purpose: request.purpose,
|
|
494
|
+
contextWindow: request.params?.contextWindow,
|
|
495
|
+
capacity,
|
|
496
|
+
settings: {
|
|
497
|
+
reasoningEffort: requestOptions.reasoningEffort,
|
|
498
|
+
temperature: requestOptions.temperature,
|
|
499
|
+
maxTokens: bodyMaxTokens,
|
|
500
|
+
extra: request.purpose === "summary" ? void 0 : requestOptions.extra
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
});
|
|
504
|
+
},
|
|
505
|
+
stream(request, signal) {
|
|
506
|
+
const { params } = build(request);
|
|
507
|
+
return options.support.withChatAttempts({
|
|
508
|
+
signal,
|
|
509
|
+
...options.maxRetries === void 0 ? {} : { maxRetries: options.maxRetries },
|
|
510
|
+
...options.sleep === void 0 ? {} : { sleep: options.sleep },
|
|
511
|
+
...options.idleMs === void 0 ? {} : { idleMs: options.idleMs },
|
|
512
|
+
async *attempt(attemptSignal, reportProgress) {
|
|
513
|
+
const chunks = await clientForAttempt(reportProgress).chat.completions.create(params, { signal: attemptSignal });
|
|
514
|
+
yield* mapOpenAIStream((async function* () {
|
|
515
|
+
for await (const chunk of chunks) {
|
|
516
|
+
reportProgress();
|
|
517
|
+
yield chunk;
|
|
518
|
+
}
|
|
519
|
+
})(), options.support);
|
|
520
|
+
},
|
|
521
|
+
classify(error) {
|
|
522
|
+
const portError = toPortError(error);
|
|
523
|
+
return {
|
|
524
|
+
error: portError,
|
|
525
|
+
retryable: portError.retryable,
|
|
526
|
+
retryAfterMs: retryAfterMs(error)
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
//#endregion
|
|
534
|
+
//#region src/protocol/probe.ts
|
|
535
|
+
function baseUrlOf(probe) {
|
|
536
|
+
const configured = probe.config.baseUrl;
|
|
537
|
+
return (typeof configured === "string" ? configured : "").replace(/\/+$/, "");
|
|
538
|
+
}
|
|
539
|
+
async function refuse(response) {
|
|
540
|
+
const body = await response.text().catch(() => "");
|
|
541
|
+
throw Object.assign(new Error(body === "" ? response.statusText : body), { status: response.status });
|
|
542
|
+
}
|
|
543
|
+
function headers(probe) {
|
|
544
|
+
return {
|
|
545
|
+
authorization: `Bearer ${probe.secrets.apiKey ?? ""}`,
|
|
546
|
+
"content-type": "application/json"
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
function record(value) {
|
|
550
|
+
return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
|
|
551
|
+
}
|
|
552
|
+
function count(value) {
|
|
553
|
+
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
|
|
554
|
+
}
|
|
555
|
+
function strings(value, allowEmpty = false) {
|
|
556
|
+
return Array.isArray(value) && value.every((one) => typeof one === "string") && (allowEmpty || value.length > 0) ? value : void 0;
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* One listed model as an offer. The family agrees on `id` alone, so every
|
|
560
|
+
* other field is read wherever an endpoint puts it: `context_window` or
|
|
561
|
+
* `context_length`, `max_output_tokens` or `max_output_length`,
|
|
562
|
+
* `input_modalities` or the `supports_*_in` flags, `output_modalities`,
|
|
563
|
+
* `supports_reasoning` or `reasoning` in `supported_features` (which also
|
|
564
|
+
* says `tools`), `temperature` in `supported_sampling_parameters`, and an
|
|
565
|
+
* `effort` object with its levels and default. A default the levels do not
|
|
566
|
+
* list is dropped. A valid feature or sampling list, including an empty one,
|
|
567
|
+
* answers for what it leaves out. Missing or malformed lists remain unknown.
|
|
568
|
+
*/
|
|
569
|
+
function offerOf(row, id) {
|
|
570
|
+
const contextWindow = count(row.context_window) ?? count(row.context_length);
|
|
571
|
+
const maxOutput = count(row.max_output_tokens) ?? count(row.max_output_length);
|
|
572
|
+
const features = strings(row.supported_features, true);
|
|
573
|
+
const sampling = strings(row.supported_sampling_parameters, true);
|
|
574
|
+
const reasoning = typeof row.supports_reasoning === "boolean" ? row.supports_reasoning : features?.includes("reasoning");
|
|
575
|
+
const effort = record(row.effort);
|
|
576
|
+
const efforts = strings(effort?.supported_levels);
|
|
577
|
+
const defaultEffort = typeof effort?.default_level === "string" && efforts?.includes(effort.default_level) ? effort.default_level : void 0;
|
|
578
|
+
const flagged = typeof row.supports_image_in === "boolean" || typeof row.supports_video_in === "boolean" ? [
|
|
579
|
+
"text",
|
|
580
|
+
...row.supports_image_in === true ? ["image"] : [],
|
|
581
|
+
...row.supports_video_in === true ? ["video"] : []
|
|
582
|
+
] : void 0;
|
|
583
|
+
const input = strings(row.input_modalities) ?? flagged;
|
|
584
|
+
const output = strings(row.output_modalities);
|
|
585
|
+
return {
|
|
586
|
+
model: id,
|
|
587
|
+
...typeof row.name === "string" && row.name !== "" ? { name: row.name } : {},
|
|
588
|
+
...contextWindow === void 0 ? {} : { contextWindow },
|
|
589
|
+
...maxOutput === void 0 ? {} : { maxOutput },
|
|
590
|
+
...reasoning === void 0 ? {} : { reasoning },
|
|
591
|
+
...features === void 0 ? {} : { toolCall: features.includes("tools") },
|
|
592
|
+
...sampling === void 0 ? {} : { temperature: sampling.includes("temperature") },
|
|
593
|
+
...input === void 0 ? {} : { input },
|
|
594
|
+
...output === void 0 ? {} : { output },
|
|
595
|
+
...efforts === void 0 ? {} : { efforts },
|
|
596
|
+
...defaultEffort === void 0 ? {} : { defaultEffort }
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
const probeOpenAI = {
|
|
600
|
+
async listModels(probe, fetcher = globalThis.fetch) {
|
|
601
|
+
const response = await fetcher(`${baseUrlOf(probe)}/models`, {
|
|
602
|
+
method: "GET",
|
|
603
|
+
headers: headers(probe),
|
|
604
|
+
signal: probe.signal
|
|
605
|
+
});
|
|
606
|
+
if (!response.ok) await refuse(response);
|
|
607
|
+
return ((await response.json()).data ?? []).flatMap((row) => typeof row.id === "string" ? [offerOf(row, row.id)] : []);
|
|
608
|
+
},
|
|
609
|
+
async testConnection(probe, fetcher = globalThis.fetch) {
|
|
610
|
+
if (probe.model !== void 0) {
|
|
611
|
+
const response = await fetcher(`${baseUrlOf(probe)}/chat/completions`, {
|
|
612
|
+
method: "POST",
|
|
613
|
+
headers: headers(probe),
|
|
614
|
+
body: JSON.stringify({
|
|
615
|
+
model: probe.model,
|
|
616
|
+
max_tokens: 1,
|
|
617
|
+
messages: [{
|
|
618
|
+
role: "user",
|
|
619
|
+
content: "ping"
|
|
620
|
+
}]
|
|
621
|
+
}),
|
|
622
|
+
signal: probe.signal
|
|
623
|
+
});
|
|
624
|
+
if (!response.ok) await refuse(response);
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
await probeOpenAI.listModels(probe, fetcher);
|
|
628
|
+
}
|
|
629
|
+
};
|
|
630
|
+
//#endregion
|
|
631
|
+
//#region src/protocol.ts
|
|
632
|
+
/** Validated supplier options; no supplier identity is interpreted by this protocol. */
|
|
633
|
+
const OpenAIProtocolOptions = z.strictObject({
|
|
634
|
+
thinkingField: z.boolean().optional(),
|
|
635
|
+
outputLimitField: z.enum(["max_tokens", "max_completion_tokens"]).optional(),
|
|
636
|
+
promptCacheKey: z.boolean().optional()
|
|
637
|
+
});
|
|
638
|
+
/** Registers concrete Chat Completions request mapping, streaming and probes. */
|
|
639
|
+
function openaiProtocolType(support, fetch) {
|
|
640
|
+
return {
|
|
641
|
+
type: "openai",
|
|
642
|
+
label: "OpenAI Chat Completions",
|
|
643
|
+
fields: [{
|
|
644
|
+
key: "baseUrl",
|
|
645
|
+
kind: "url",
|
|
646
|
+
label: "Base URL",
|
|
647
|
+
required: true
|
|
648
|
+
}],
|
|
649
|
+
userConfigurable: true,
|
|
650
|
+
optionsSchema: OpenAIProtocolOptions,
|
|
651
|
+
facts,
|
|
652
|
+
prepareParams: (input) => support.prepareParams(input, facts),
|
|
653
|
+
chat: {
|
|
654
|
+
fileKinds: ["image"],
|
|
655
|
+
supportsModel: () => true,
|
|
656
|
+
createPort(call) {
|
|
657
|
+
const options = OpenAIProtocolOptions.parse(call.options);
|
|
658
|
+
return createOpenAIModelPort({
|
|
659
|
+
support,
|
|
660
|
+
fetch,
|
|
661
|
+
model: call.model,
|
|
662
|
+
endpoint: call.providerId,
|
|
663
|
+
apiKey: call.secrets.apiKey ?? "",
|
|
664
|
+
baseURL: String(call.config.baseUrl ?? ""),
|
|
665
|
+
...options,
|
|
666
|
+
catalogue: () => support.catalogue(call.providerId, call.model),
|
|
667
|
+
media: (stored) => support.mediaContextOf({
|
|
668
|
+
entry: support.catalogue(call.providerId, call.model),
|
|
669
|
+
stored,
|
|
670
|
+
facts,
|
|
671
|
+
endpoint: support.endpoint(call.providerId),
|
|
672
|
+
fileKinds: ["image"]
|
|
673
|
+
}),
|
|
674
|
+
params: (stored) => support.resolveParams({
|
|
675
|
+
entry: support.catalogue(call.providerId, call.model),
|
|
676
|
+
stored,
|
|
677
|
+
facts,
|
|
678
|
+
model: call.model,
|
|
679
|
+
endpoint: support.endpoint(call.providerId)
|
|
680
|
+
})
|
|
681
|
+
});
|
|
682
|
+
}
|
|
683
|
+
},
|
|
684
|
+
normalizeListing: (input) => support.normalizeListing(input),
|
|
685
|
+
listModels: (probe) => probeOpenAI.listModels(probe, fetch),
|
|
686
|
+
testConnection: (probe) => probeOpenAI.testConnection(probe, fetch)
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
//#endregion
|
|
690
|
+
//#region src/index.ts
|
|
691
|
+
/** Protocol extensions contribute no tools. */
|
|
692
|
+
const TOOL_NAMES = [];
|
|
693
|
+
const plugin = {
|
|
694
|
+
name: "@eum-agent/llm-protocol-openai",
|
|
695
|
+
requires: ["model-support", "network"],
|
|
696
|
+
apply(ctx) {
|
|
697
|
+
const support = ctx.services.get("model-support");
|
|
698
|
+
const network = ctx.services.get("network");
|
|
699
|
+
ctx.models.registerProtocol(openaiProtocolType(support, network.fetch));
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
//#endregion
|
|
703
|
+
export { TOOL_NAMES, plugin as default };
|
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@eum-agent/llm-protocol-openai",
|
|
3
|
-
"
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
"displayName": {
|
|
4
|
+
"en-US": "OpenAI Model Protocol",
|
|
5
|
+
"zh-CN": "模型协议 · OpenAI"
|
|
6
|
+
},
|
|
7
|
+
"version": "1.0.0",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"description": "Public OpenAI model communication protocol",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"@eum-agent/plugin": "1.0.0"
|
|
21
|
+
},
|
|
22
|
+
"dependencies": {
|
|
23
|
+
"zod": "^4.4.3",
|
|
24
|
+
"openai": "^7.8.0",
|
|
25
|
+
"gpt-tokenizer": "4.0.0"
|
|
26
|
+
},
|
|
27
|
+
"yaoguang": {
|
|
28
|
+
"kind": "extension",
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"@eum-agent/llm-management": "1.0.0"
|
|
31
|
+
},
|
|
32
|
+
"foundationDependencies": {
|
|
33
|
+
"@eum-agent/infra-local": "1.0.0"
|
|
34
|
+
},
|
|
35
|
+
"description": {
|
|
36
|
+
"en-US": "Public OpenAI model communication protocol",
|
|
37
|
+
"zh-CN": "OpenAI 公共模型协议"
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "tsdown",
|
|
42
|
+
"test": "vitest run",
|
|
43
|
+
"typecheck": "tsc --noEmit"
|
|
44
|
+
}
|
|
6
45
|
}
|
package/README.md
DELETED