@aparte/provider-openai-compat 0.16.11 → 0.17.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.d.ts.map +1 -1
- package/dist/index.js +68 -27
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,KAAK,EACR,gBAAgB,EAChB,aAAa,EACb,4BAA4B,EAM5B,iBAAiB,EAEjB,mBAAmB,EACtB,MAAM,cAAc,CAAC;AAKtB,iGAAiG;AACjG,MAAM,WAAW,2BAA2B;IACxC,6EAA6E;IAC7E,EAAE,EAAE,MAAM,CAAC;IACX,sFAAsF;IACtF,OAAO,EAAE,MAAM,CAAC;IAChB,uCAAuC;IACvC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,8DAA8D;IAC9D,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,mBAAmB;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,sBAAsB;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iCAAiC;IACjC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,6CAA6C;IAC7C,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,+EAA+E;IAC/E,MAAM,CAAC,EAAE,aAAa,EAAE,CAAC;IACzB;;;OAGG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,4DAA4D;IAC5D,YAAY,CAAC,EAAE,4BAA4B,CAAC;CAC/C;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;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E,gBAAgB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -67,30 +67,47 @@ const OLLAMA = {
|
|
|
67
67
|
const presets = { OPENAI, MISTRAL, ZAI, OPENROUTER, LMSTUDIO, OLLAMA };
|
|
68
68
|
function toOpenAIContent(content) {
|
|
69
69
|
if (typeof content === "string") return content;
|
|
70
|
-
return content.map((p) => {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
70
|
+
return content.map((p) => p.type === "text" ? { type: "text", text: p.text } : { type: "image_url", image_url: { url: p.image } });
|
|
71
|
+
}
|
|
72
|
+
const LEGACY_TOOL_ROLES = /* @__PURE__ */ new Set(["tool_call", "tool_result"]);
|
|
73
|
+
const warnedLegacyRoles = /* @__PURE__ */ new Set();
|
|
74
|
+
function warnLegacyToolRole(role) {
|
|
75
|
+
if (warnedLegacyRoles.has(role)) return;
|
|
76
|
+
warnedLegacyRoles.add(role);
|
|
77
|
+
console.warn(
|
|
78
|
+
`[@aparte/provider-openai-compat] Skipping a message with the removed role "${role}". A tool turn is now an assistant message carrying its calls — { role: 'assistant', content: <what it said>, toolCalls } — followed by one { role: 'tool', content: <result>, toolCallId, toolName } per call. This warning is removed in 0.18.`
|
|
79
|
+
);
|
|
75
80
|
}
|
|
76
81
|
function toOpenAIMessages(messages) {
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
82
|
+
const out = [];
|
|
83
|
+
for (const msg of messages) {
|
|
84
|
+
const role = msg.role;
|
|
85
|
+
if (LEGACY_TOOL_ROLES.has(role)) {
|
|
86
|
+
warnLegacyToolRole(role);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (msg.role === "tool") {
|
|
90
|
+
out.push({ role: "tool", tool_call_id: msg.toolCallId, content: contentToText(msg.content) });
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
if (msg.role === "assistant" && msg.toolCalls?.length) {
|
|
94
|
+
out.push({
|
|
80
95
|
role: "assistant",
|
|
81
|
-
|
|
82
|
-
|
|
96
|
+
// `||`, not `??`: this API takes null (or nothing) beside `tool_calls`, and
|
|
97
|
+
// an assistant that said nothing before its calls now carries '' — which
|
|
98
|
+
// some endpoints reject and the rest read as an empty reply.
|
|
99
|
+
content: contentToText(msg.content) || null,
|
|
100
|
+
tool_calls: msg.toolCalls.map((tc) => ({
|
|
83
101
|
id: tc.id,
|
|
84
102
|
type: "function",
|
|
85
103
|
function: { name: tc.name, arguments: JSON.stringify(tc.input) }
|
|
86
104
|
}))
|
|
87
|
-
};
|
|
105
|
+
});
|
|
106
|
+
continue;
|
|
88
107
|
}
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
return { role: msg.role, content: toOpenAIContent(msg.content) };
|
|
93
|
-
});
|
|
108
|
+
out.push({ role: msg.role, content: toOpenAIContent(msg.content) });
|
|
109
|
+
}
|
|
110
|
+
return out;
|
|
94
111
|
}
|
|
95
112
|
function toOpenAITools(tools) {
|
|
96
113
|
return tools.map((t) => ({
|
|
@@ -188,7 +205,8 @@ function createOpenAICompatProvider(opts) {
|
|
|
188
205
|
};
|
|
189
206
|
if (request.tools?.length) {
|
|
190
207
|
body["tools"] = toOpenAITools(request.tools);
|
|
191
|
-
|
|
208
|
+
const forced = typeof request.toolChoice === "object" ? request.toolChoice.name : void 0;
|
|
209
|
+
body["tool_choice"] = forced ? { type: "function", function: { name: forced } } : "auto";
|
|
192
210
|
}
|
|
193
211
|
return {
|
|
194
212
|
path: "/chat/completions",
|
|
@@ -210,11 +228,14 @@ function createOpenAICompatProvider(opts) {
|
|
|
210
228
|
function parseOpenAICompatStream(stream) {
|
|
211
229
|
const decoder = new TextDecoder();
|
|
212
230
|
let buffer = "";
|
|
213
|
-
|
|
231
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
232
|
+
let lastToolKey = null;
|
|
233
|
+
const toolCallAliases = /* @__PURE__ */ new Map();
|
|
234
|
+
let mintedCallIds = 0;
|
|
214
235
|
let capturedUsage;
|
|
215
236
|
let reader = null;
|
|
216
237
|
const flushToolCalls = (controller, complete) => {
|
|
217
|
-
for (const entry of
|
|
238
|
+
for (const entry of toolCalls.values()) {
|
|
218
239
|
let input = {};
|
|
219
240
|
try {
|
|
220
241
|
input = entry.args.trim() ? JSON.parse(entry.args) : {};
|
|
@@ -231,7 +252,24 @@ function parseOpenAICompatStream(stream) {
|
|
|
231
252
|
const toolCall = { id: entry.id, name: entry.name, input };
|
|
232
253
|
controller.enqueue({ type: "tool_use", ...toolCall });
|
|
233
254
|
}
|
|
234
|
-
|
|
255
|
+
toolCalls.clear();
|
|
256
|
+
toolCallAliases.clear();
|
|
257
|
+
lastToolKey = null;
|
|
258
|
+
};
|
|
259
|
+
const toolCallKey = (tc) => {
|
|
260
|
+
let indexKey;
|
|
261
|
+
if (tc.index !== void 0 && tc.index !== null) {
|
|
262
|
+
const idx = Number(tc.index);
|
|
263
|
+
if (!Number.isInteger(idx) || idx < 0) return null;
|
|
264
|
+
indexKey = `i${idx}`;
|
|
265
|
+
}
|
|
266
|
+
const idKey = tc.id ? `d${tc.id}` : void 0;
|
|
267
|
+
const known = (idKey ? toolCallAliases.get(idKey) : void 0) ?? (indexKey ? toolCallAliases.get(indexKey) : void 0);
|
|
268
|
+
const key = known ?? (!tc.function?.name && lastToolKey !== null ? lastToolKey : idKey ?? indexKey);
|
|
269
|
+
if (key === void 0) return `p${toolCalls.size}`;
|
|
270
|
+
if (idKey) toolCallAliases.set(idKey, key);
|
|
271
|
+
if (indexKey) toolCallAliases.set(indexKey, key);
|
|
272
|
+
return key;
|
|
235
273
|
};
|
|
236
274
|
return new ReadableStream({
|
|
237
275
|
async start(controller) {
|
|
@@ -274,14 +312,17 @@ function parseOpenAICompatStream(stream) {
|
|
|
274
312
|
}
|
|
275
313
|
if (delta.tool_calls) {
|
|
276
314
|
for (const tc of delta.tool_calls) {
|
|
277
|
-
const
|
|
278
|
-
if (
|
|
279
|
-
|
|
280
|
-
|
|
315
|
+
const key = toolCallKey(tc);
|
|
316
|
+
if (key === null) continue;
|
|
317
|
+
let entry = toolCalls.get(key);
|
|
318
|
+
if (!entry) {
|
|
319
|
+
entry = { id: tc.id ?? `aparte-call-${++mintedCallIds}`, name: tc.function?.name ?? "", args: "" };
|
|
320
|
+
toolCalls.set(key, entry);
|
|
281
321
|
}
|
|
282
|
-
|
|
283
|
-
if (tc.
|
|
284
|
-
if (tc.function?.
|
|
322
|
+
lastToolKey = key;
|
|
323
|
+
if (tc.id) entry.id = tc.id;
|
|
324
|
+
if (tc.function?.name) entry.name = tc.function.name;
|
|
325
|
+
if (tc.function?.arguments) entry.args += tc.function.arguments;
|
|
285
326
|
}
|
|
286
327
|
}
|
|
287
328
|
}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/presets.ts","../src/index.ts"],"sourcesContent":["/**\n * presets.ts — vendor DATA for well-known OpenAI-compatible endpoints.\n *\n * A preset is nothing but an `OpenAICompatProviderOptions` literal: base URL +\n * branding (icon/color/helpUrl) carried over from the retired per-vendor\n * packages. No code varies per vendor — that is the whole point.\n *\n * ```ts\n * aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider(presets.MISTRAL));\n * ```\n *\n * Local servers (LM Studio, Ollama) are served through their OpenAI-compat\n * `/v1` endpoints — same format, `isLocal` just relaxes the key requirement.\n */\n\nimport type { OpenAICompatProviderOptions } from './index.js';\n\nconst OPENAI: OpenAICompatProviderOptions = {\n id: 'openai',\n baseURL: 'https://api.openai.com/v1',\n name: 'OpenAI',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm0 18a8 8 0 1 1 8-8 8 8 0 0 1-8 8z\"/><path d=\"M12 6v6l4 2\"/></svg>`,\n color: '#10a37f',\n description: 'GPT-4o, GPT-4 Turbo, and the O1 reasoning models',\n helpUrl: 'https://platform.openai.com/api-keys',\n};\n\nconst MISTRAL: OpenAICompatProviderOptions = {\n id: 'mistral',\n baseURL: 'https://api.mistral.ai/v1',\n name: 'Mistral AI',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M12 2l4 22-4-8-4 8 4-22z\"/></svg>`,\n color: '#fd7e14',\n description: 'European AI: Mistral Large, Mixtral, Codestral',\n helpUrl: 'https://console.mistral.ai/api-keys/',\n};\n\nconst ZAI: OpenAICompatProviderOptions = {\n id: 'zai',\n baseURL: 'https://open.bigmodel.cn/api/paas/v4',\n name: 'Z.ai (Zhipu)',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M13 2L3 14h9l-1 8 10-12h-9l1-8z\"/></svg>`,\n color: '#6366f1',\n description: \"Access Zhipu AI's free GLM models\",\n hasFreeModels: true,\n helpUrl: 'https://open.bigmodel.cn',\n};\n\nconst OPENROUTER: OpenAICompatProviderOptions = {\n id: 'openrouter',\n baseURL: 'https://openrouter.ai/api/v1',\n name: 'OpenRouter',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\"/><path d=\"M2 12h20\"/></svg>`,\n color: '#000000',\n description: 'Access 100+ AI models through a single API',\n hasFreeModels: true,\n helpUrl: 'https://openrouter.ai/keys',\n // OpenRouter attribution headers (sent on chat + model fetch).\n extraHeaders: {\n 'HTTP-Referer': typeof window !== 'undefined' ? window.location.origin : '',\n 'X-Title': 'aparté',\n },\n};\n\nconst LMSTUDIO: OpenAICompatProviderOptions = {\n id: 'lmstudio',\n baseURL: 'http://localhost:1234/v1',\n name: 'LM Studio',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"2\"/><path d=\"M9 9h6v6H9z\"/><path d=\"M9 1h1v3h-1zM14 1h1v3h-1zM9 20h1v3h-1zM14 20h1v3h-1zM20 9h3v1h-3zM20 14h3v1h-3zM1 9h3v1H1zM1 14h3v1H1z\"/></svg>`,\n color: '#444444',\n description: 'Run LLMs locally with the LM Studio app',\n hasFreeModels: true,\n isLocal: true,\n helpUrl: 'https://lmstudio.ai/',\n};\n\n// Ollama through its OpenAI-compat endpoint (`/v1`), NOT its native `/api/chat`.\n// Same chat-completions format as everyone else; the native-protocol niceties\n// (inline base64 images, Ollama-shaped tool calls, keep_alive) don't apply —\n// see the README's Ollama section for the behavioural delta.\nconst OLLAMA: OpenAICompatProviderOptions = {\n id: 'ollama',\n baseURL: 'http://localhost:11434/v1',\n name: 'Ollama',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M12 2a10 10 0 0 1 10 10 10 10 0 0 1-10 10 10 10 0 0 1-10-10 10 10 0 0 1 10-10zM12 11l4 2-4 2-4-2 4-2zM12 6v5M12 15v3\"/></svg>`,\n color: '#57534e',\n description: 'Run LLMs locally — free and fully private',\n hasFreeModels: true,\n isLocal: true,\n helpUrl: 'https://ollama.com/',\n};\n\n/** Vendor presets for {@link createOpenAICompatProvider}. Pure data. */\nexport const presets = { OPENAI, MISTRAL, ZAI, OPENROUTER, LMSTUDIO, OLLAMA } as const;\n","/**\n * @aparte/provider-openai-compat — ONE adapter for every OpenAI-compatible\n * chat-completions endpoint.\n *\n * The OpenAI `/chat/completions` wire format is the de-facto industry standard:\n * OpenAI, Mistral, OpenRouter, Z.ai, Groq, Together, LM Studio, Ollama (`/v1`)\n * and many more all speak it. This package is the single, zero-dependency\n * format adapter for that family — vendors differ only by DATA (base URL, auth\n * header, branding), which you pass as config (or pick from `presets`).\n *\n * It replaces the per-vendor `@aparte/provider-{openai,mistral,zai,openrouter,\n * lmstudio,ollama}` packages, whose adapter bodies were byte-identical copies\n * (drift even produced real bugs: LM Studio dropped `max_tokens`, Z.ai dropped\n * `seed` — both fixed here by construction, there is only one body now).\n *\n * Model lists are CONSUMER data: pass `models` statically, or rely on the\n * generic `GET {baseURL}/models` fetcher (part of the compat standard). For\n * vendors outside this family (Anthropic, Gemini, …) use the AI-SDK bridge\n * provider instead — this package deliberately covers ONE format.\n */\n\nimport type {\n AparteAIProvider,\n AparteAIModel,\n AparteAIProviderConfigSchema,\n AparteChatRequest,\n AparteChatMessage,\n AparteTool,\n AparteToolCall,\n AparteContentPart,\n AparteStreamEvent,\n AparteUsage,\n AparteFormatAdapter,\n} from '@aparte/core';\nimport { contentToText } from '@aparte/core';\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/** Config for one OpenAI-compatible endpoint. Everything but `id`/`baseURL` is branding/data. */\nexport interface OpenAICompatProviderOptions {\n /** Provider id used across aparté (key resolution, model picker, events). */\n id: string;\n /** Endpoint base, e.g. `https://api.openai.com/v1` or `http://localhost:11434/v1`. */\n baseURL: string;\n /** Display name (defaults to `id`). */\n name?: string;\n /** Brand icon (SVG string / data URI / icon-provider key). */\n icon?: string;\n /** Brand color. */\n color?: string;\n /** Short tag line. */\n description?: string;\n /** Where the user gets a key. */\n helpUrl?: string;\n /** Whether the vendor offers free models. */\n hasFreeModels?: boolean;\n /**\n * Local server (LM Studio, Ollama…): key optional, and the generic\n * `/models` fetch runs even without a key.\n */\n isLocal?: boolean;\n /** Static model list (consumer data). Defaults to `[]` — use `fetchModels`. */\n models?: AparteAIModel[];\n /**\n * Extra headers sent on every request (chat + model fetch), e.g.\n * OpenRouter's attribution headers `HTTP-Referer` / `X-Title`.\n */\n extraHeaders?: Record<string, string>;\n /** Override the default apiKey+endpoint settings schema. */\n configSchema?: AparteAIProviderConfigSchema;\n}\n\n// ─── Message / tool shaping (the format half) ────────────────────────────────\n\n/** Content → OpenAI multipart array when images are present. */\nfunction toOpenAIContent(content: string | AparteContentPart[]): unknown {\n if (typeof content === 'string') return content;\n return content.map(p => {\n if (p.type === 'text') return { type: 'text', text: p.text };\n if (p.type === 'image') return { type: 'image_url', image_url: { url: p.image } };\n return { type: 'text', text: '' }; // AparteFilePart — no inline-file support in the compat format\n });\n}\n\n/** AparteChatMessage[] → OpenAI messages (incl. the tool_call / tool_result envelope). */\nfunction toOpenAIMessages(messages: AparteChatMessage[]): unknown[] {\n return messages.map(msg => {\n if (msg.role === 'tool_call') {\n return {\n role: 'assistant',\n content: msg.precedingText ?? null,\n tool_calls: (msg.toolCalls ?? []).map(tc => ({\n id: tc.id,\n type: 'function',\n function: { name: tc.name, arguments: JSON.stringify(tc.input) },\n })),\n };\n }\n if (msg.role === 'tool_result') {\n return { role: 'tool', tool_call_id: msg.toolCallId, content: contentToText(msg.content) };\n }\n return { role: msg.role, content: toOpenAIContent(msg.content) };\n });\n}\n\n/** AparteTool[] → OpenAI function-tool declarations. */\nfunction toOpenAITools(tools: AparteTool[]): unknown[] {\n return tools.map(t => ({\n type: 'function',\n function: { name: t.name, description: t.description, parameters: t.inputSchema },\n }));\n}\n\n/** Accept both raw keys and user-pasted `Bearer xxx` values (local servers). */\nfunction bearer(key: string): string {\n return key.startsWith('Bearer ') ? key : `Bearer ${key}`;\n}\n\nconst DEFAULT_CONFIG_SCHEMA = (opts: OpenAICompatProviderOptions): AparteAIProviderConfigSchema => ({\n fields: opts.isLocal\n ? [\n { id: 'endpoint', type: 'url', label: 'Server', defaultValue: opts.baseURL, required: true },\n { id: 'apiKey', type: 'password', label: 'API Key / Token (optional)', placeholder: 'Bearer ...', isAdvanced: true },\n ]\n : [\n { id: 'apiKey', type: 'password', label: 'API Key', placeholder: 'sk-...', required: true },\n { id: 'endpoint', type: 'url', label: 'Custom endpoint', placeholder: opts.baseURL, isAdvanced: true },\n ],\n});\n\n// ─── The factory ─────────────────────────────────────────────────────────────\n\n/**\n * What {@link createOpenAICompatProvider} hands back: a provider whose whole\n * format-adapter surface is guaranteed present.\n *\n * `AparteAIProvider` declares that surface optional — correct in general, since a\n * provider may own its I/O through `chat()` instead — and `AparteFormatAdapter` keeps\n * `authHeaders` / `parseText` optional because some vendors authenticate by query\n * string or never answer non-streaming. THIS factory always supplies all of them, so\n * saying so here is the difference between a caller writing\n * `provider.buildRequest(req)` and a caller sprinkling `!` or writing a check that\n * cannot fail. Useful to annotate with when you drive the adapter yourself (your own\n * `fetch`, your own `AbortSignal`) from a server or an Electron main process.\n */\nexport type OpenAICompatProvider =\n AparteAIProvider\n & AparteFormatAdapter\n & Required<Pick<AparteFormatAdapter, 'authHeaders' | 'parseText'>>;\n\n/**\n * Build an `AparteAIProvider` (full format-adapter surface) for one\n * OpenAI-compatible endpoint. Register it like any provider:\n *\n * ```ts\n * import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat';\n * aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider(presets.OPENROUTER));\n * // or any compat endpoint, no preset needed:\n * aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider({ id: 'groq', baseURL: 'https://api.groq.com/openai/v1' }));\n * ```\n *\n * Returns {@link OpenAICompatProvider}: the full format-adapter surface, non-optional.\n */\nexport function createOpenAICompatProvider(opts: OpenAICompatProviderOptions): OpenAICompatProvider {\n const displayName = opts.name ?? opts.id;\n\n return {\n id: opts.id,\n\n getMetadata() {\n return {\n id: opts.id,\n name: displayName,\n icon: opts.icon,\n color: opts.color,\n description: opts.description,\n helpUrl: opts.helpUrl,\n hasFreeModels: opts.hasFreeModels,\n isLocal: opts.isLocal,\n configSchema: opts.configSchema ?? DEFAULT_CONFIG_SCHEMA(opts),\n };\n },\n\n getModels(): AparteAIModel[] {\n return opts.models ?? [];\n },\n\n /**\n * Generic `GET {baseURL}/models` — part of the compat standard. Cloud\n * endpoints need a key (returns `[]` without one); local servers fetch\n * keyless. Vendor-specific niceties (pricing, name prettifying) are\n * consumer concerns: pass `models` yourself for anything fancier.\n */\n async fetchModels(config?: string | Record<string, string>): Promise<AparteAIModel[]> {\n const apiKey = typeof config === 'string' ? config : config?.['apiKey'];\n const endpoint = (typeof config === 'object' ? config?.['endpoint'] : null) || opts.baseURL;\n if (!apiKey && !opts.isLocal) return [];\n\n try {\n const headers: Record<string, string> = { ...opts.extraHeaders };\n if (apiKey) headers['Authorization'] = bearer(apiKey);\n const response = await fetch(`${endpoint}/models`, { headers });\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n const data = await response.json() as { data?: Array<{ id: string; name?: string; context_length?: number }> };\n return (data.data ?? []).map(m => ({\n id: m.id,\n name: m.name || m.id,\n contextWindow: m.context_length,\n // `function_calling` is declared because it is a property of the\n // WIRE FORMAT, which is what this provider is: `/chat/completions`\n // takes a `tools` array, and every server behind a compat endpoint\n // accepts one. `/models` returns `{id, object, owned_by}` and says\n // nothing about tools, so waiting for it to declare the capability\n // means never declaring it — and core gates tools on exactly this\n // field, so a registered tool, an approval gate and the whole\n // elicitation path were dead on this provider: the model was asked\n // to use a tool it had never been sent.\n //\n // The failure mode of over-declaring is mild and visible: a model\n // that cannot call tools simply does not call one. The failure mode\n // of under-declaring was silent and total. A server that rejects a\n // `tools` array outright surfaces as an error from its own endpoint,\n // which is the right place for that argument to happen.\n capabilities: ['streaming', 'function_calling'],\n }));\n } catch (error) {\n console.error(`[${displayName}] Failed to fetch models:`, error);\n return [];\n }\n },\n\n // ── Format-adapter surface (transport ⊥ format) ──────────────────────\n // The vendor concern only: request shape + stream parsing. Auth and\n // network are the transport's job (AparteDirectTransport / AparteBackendTransport).\n defaultEndpoint: opts.baseURL,\n\n buildRequest(request: AparteChatRequest) {\n const body: Record<string, unknown> = {\n model: request.modelId,\n messages: toOpenAIMessages(request.messages),\n temperature: request.temperature,\n max_tokens: request.maxTokens,\n stream: request.stream ?? true,\n ...((request.stream ?? true) ? { stream_options: { include_usage: true } } : {}),\n ...(request.seed !== undefined ? { seed: request.seed } : {}),\n };\n if (request.tools?.length) {\n body['tools'] = toOpenAITools(request.tools);\n body['tool_choice'] = 'auto';\n }\n return {\n path: '/chat/completions',\n body,\n ...(opts.extraHeaders ? { headers: opts.extraHeaders } : {}),\n };\n },\n\n authHeaders(key: string) {\n return { Authorization: bearer(key) };\n },\n\n parseStream(body: ReadableStream<Uint8Array>) {\n return parseOpenAICompatStream(body);\n },\n\n parseText(json: unknown): string {\n return (json as { choices?: Array<{ message?: { content?: string } }> })?.choices?.[0]?.message?.content || '';\n },\n };\n}\n\n// ─── SSE stream parser (ported from @aparte/core parseOpenAIStream) ──────────\n\n/**\n * OpenAI-compatible SSE stream parser — this package's own copy of core's\n * `parseOpenAIStream` (the parser follows the format adapter; core keeps only\n * the aparté-native NDJSON parser).\n *\n * Handles:\n * - `delta.content` → text event\n * - `delta.reasoning_content` → thinking event (Qwen3, DeepSeek R1, …)\n * - `delta.tool_calls` → accumulate → tool_use on finish_reason='tool_calls'\n * - usage-only chunk + [DONE] → done{usage}\n */\nexport function parseOpenAICompatStream(\n stream: ReadableStream<Uint8Array>,\n): ReadableStream<AparteStreamEvent> {\n const decoder = new TextDecoder();\n let buffer = '';\n\n // Tool call accumulation state (keyed by the vendor's `index`). A null-prototype\n // object: the key comes off the wire, and on a plain `{}` a chunk whose `index` is\n // `\"__proto__\"` writes into Object.prototype for the whole page.\n let toolCallsById: Record<number, { id: string; name: string; args: string }> = Object.create(null);\n let capturedUsage: AparteUsage | undefined;\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;\n\n /*\n * Emit the accumulated calls and clear the map.\n *\n * Called at EVERY graceful end of a turn, not only on `finish_reason: 'tool_calls'`:\n * the accumulation spans the whole stream, and a vendor that ends with `stop`,\n * `length` or a bare `[DONE]` after streaming tool-call deltas used to drop them —\n * the model had asked for a tool and the loop never heard. `complete` says the\n * model declared the calls finished: a parse failure there is malformed JSON (a\n * real small-model failure) and the tool still runs, on `{}`. Elsewhere it is\n * truncation, and running a tool on `{}` for a call the model never finished would\n * be worse than dropping it — so those are dropped, with a breadcrumb.\n */\n const flushToolCalls = (controller: ReadableStreamDefaultController<AparteStreamEvent>, complete: boolean): void => {\n for (const entry of Object.values(toolCallsById)) {\n let input: Record<string, unknown> = {};\n try {\n input = entry.args.trim() ? JSON.parse(entry.args) : {};\n } catch {\n if (!complete) {\n console.warn(`[openai-compat] Tool \"${entry.name}\" was cut mid-arguments (the turn ended without finish_reason 'tool_calls'); the call is dropped. Raw:`, entry.args);\n continue;\n }\n console.warn(\n `[openai-compat] Tool \"${entry.name}\" returned malformed arguments JSON; ` +\n `passing empty input. Raw:`, entry.args,\n );\n }\n const toolCall: AparteToolCall = { id: entry.id, name: entry.name, input };\n controller.enqueue({ type: 'tool_use', ...toolCall });\n }\n toolCallsById = Object.create(null);\n };\n\n return new ReadableStream<AparteStreamEvent>({\n async start(controller) {\n reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed.startsWith('data:')) continue;\n const raw = trimmed.slice(5).trim();\n if (raw === '[DONE]') {\n // A turn that streamed tool-call deltas and ended on `stop`,\n // `length` or a bare [DONE]: the calls are still the model's.\n flushToolCalls(controller, false);\n controller.enqueue({ type: 'done', usage: capturedUsage });\n return;\n }\n try {\n const json = JSON.parse(raw);\n\n // Capture usage from the usage-only chunk (choices: [])\n if (json.usage) {\n capturedUsage = {\n inputTokens: json.usage.prompt_tokens ?? 0,\n outputTokens: json.usage.completion_tokens ?? 0,\n totalTokens: json.usage.total_tokens,\n cacheReadTokens: json.usage.prompt_tokens_details?.cached_tokens,\n };\n }\n\n const choice = json.choices?.[0];\n if (!choice) continue;\n\n const delta = choice.delta;\n if (delta) {\n if (delta.reasoning_content) {\n controller.enqueue({ type: 'thinking', delta: delta.reasoning_content });\n }\n if (delta.content) {\n controller.enqueue({ type: 'text', delta: delta.content });\n }\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n // Made a number, not annotated as one: `index` is whatever\n // the vendor's JSON put there.\n const idx = Number(tc.index ?? 0);\n if (!Number.isInteger(idx) || idx < 0) continue;\n if (!toolCallsById[idx]) {\n toolCallsById[idx] = { id: tc.id ?? '', name: tc.function?.name ?? '', args: '' };\n }\n if (tc.id) toolCallsById[idx].id = tc.id;\n if (tc.function?.name) toolCallsById[idx].name = tc.function.name;\n if (tc.function?.arguments) toolCallsById[idx].args += tc.function.arguments;\n }\n }\n }\n\n // The model declared the calls complete: emit them now (and clear\n // the map, so a server that repeats the finish chunk cannot\n // re-emit them). Do NOT emit `done` or return here: under\n // `include_usage` (which buildRequest requests) the usage-only\n // chunk arrives AFTER this finish chunk, so stopping now dropped\n // usage on every tool-call turn — i.e. most turns of an agent.\n // Keep reading; the single `done` comes from `[DONE]` below, or\n // from the end-of-stream fallback if the socket just closes.\n if (choice.finish_reason === 'tool_calls') flushToolCalls(controller, true);\n } catch {\n // Every line here is a complete, newline-terminated SSE\n // line (see buffer split above), so a parse failure is an\n // unexpected/malformed server payload, not partial JSON —\n // log a breadcrumb instead of dropping it silently.\n console.warn('[openai-compat] Skipped an unparseable SSE data line:', raw);\n }\n }\n }\n // The socket closed without [DONE]: same rule, the calls are flushed first.\n flushToolCalls(controller, false);\n controller.enqueue({ type: 'done', usage: capturedUsage });\n } catch (err: unknown) {\n // AbortError surfaces here when the caller's signal fires mid-stream:\n // the consumer (agent loop) cancelled on purpose — end quietly, the\n // same way the ai-sdk provider does. Reporting it as an `error` event\n // makes a deliberate Stop indistinguishable from a network failure,\n // and the loop's error branch then replaces the streamed answer with\n // an error bubble.\n if ((err as { name?: string } | undefined)?.name !== 'AbortError') {\n controller.enqueue({ type: 'error', message: (err as Error | undefined)?.message ?? 'Stream error' });\n }\n } finally {\n reader?.releaseLock();\n reader = null;\n controller.close();\n }\n },\n // Consumer cancelled (e.g. user hit \"stop\"): cancel the underlying reader so\n // the vendor response body stops being drained to its natural end instead of\n // silently finishing the whole SSE stream in the background.\n cancel(reason) {\n const r = reader;\n reader = null;\n return r?.cancel(reason);\n },\n });\n}\n\nexport * from './presets.js';\nexport type { AparteAIProvider, AparteAIModel } from '@aparte/core';\n"],"names":[],"mappings":";AAiBA,MAAM,SAAsC;AAAA,EACxC,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,SAAS;AACb;AAEA,MAAM,UAAuC;AAAA,EACzC,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,SAAS;AACb;AAEA,MAAM,MAAmC;AAAA,EACrC,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,eAAe;AAAA,EACf,SAAS;AACb;AAEA,MAAM,aAA0C;AAAA,EAC5C,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,eAAe;AAAA,EACf,SAAS;AAAA;AAAA,EAET,cAAc;AAAA,IACV,gBAAgB,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS;AAAA,IACzE,WAAW;AAAA,EAAA;AAEnB;AAEA,MAAM,WAAwC;AAAA,EAC1C,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,eAAe;AAAA,EACf,SAAS;AAAA,EACT,SAAS;AACb;AAMA,MAAM,SAAsC;AAAA,EACxC,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,eAAe;AAAA,EACf,SAAS;AAAA,EACT,SAAS;AACb;AAGO,MAAM,UAAU,EAA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ACtC,wBAAI,GAAG,UAAU,KAAM,eAAc,GAAG,EAAE,OAAO,GAAG,SAAS;AAC7D,wBAAI,GAAG,UAAU,UAAW,eAAc,GAAG,EAAE,QAAQ,GAAG,SAAS;AAAA,kBACvE;AAAA,gBACJ;AAAA,cACJ;AAUA,kBAAI,OAAO,kBAAkB,aAAc,gBAAe,YAAY,IAAI;AAAA,YAC9E,QAAQ;AAKJ,sBAAQ,KAAK,yDAAyD,GAAG;AAAA,YAC7E;AAAA,UACJ;AAAA,QACJ;AAEA,uBAAe,YAAY,KAAK;AAChC,mBAAW,QAAQ,EAAE,MAAM,QAAQ,OAAO,eAAe;AAAA,MAC7D,SAAS,KAAc;AAOnB,YAAK,KAAuC,SAAS,cAAc;AAC/D,qBAAW,QAAQ,EAAE,MAAM,SAAS,SAAU,KAA2B,WAAW,gBAAgB;AAAA,QACxG;AAAA,MACJ,UAAA;AACI,gBAAQ,YAAA;AACR,iBAAS;AACT,mBAAW,MAAA;AAAA,MACf;AAAA,IACJ;AAAA;AAAA;AAAA;AAAA,IAIA,OAAO,QAAQ;AACX,YAAM,IAAI;AACV,eAAS;AACT,aAAO,GAAG,OAAO,MAAM;AAAA,IAC3B;AAAA,EAAA,CACH;AACL;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/presets.ts","../src/index.ts"],"sourcesContent":["/**\n * presets.ts — vendor DATA for well-known OpenAI-compatible endpoints.\n *\n * A preset is nothing but an `OpenAICompatProviderOptions` literal: base URL +\n * branding (icon/color/helpUrl) carried over from the retired per-vendor\n * packages. No code varies per vendor — that is the whole point.\n *\n * ```ts\n * aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider(presets.MISTRAL));\n * ```\n *\n * Local servers (LM Studio, Ollama) are served through their OpenAI-compat\n * `/v1` endpoints — same format, `isLocal` just relaxes the key requirement.\n */\n\nimport type { OpenAICompatProviderOptions } from './index.js';\n\nconst OPENAI: OpenAICompatProviderOptions = {\n id: 'openai',\n baseURL: 'https://api.openai.com/v1',\n name: 'OpenAI',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm0 18a8 8 0 1 1 8-8 8 8 0 0 1-8 8z\"/><path d=\"M12 6v6l4 2\"/></svg>`,\n color: '#10a37f',\n description: 'GPT-4o, GPT-4 Turbo, and the O1 reasoning models',\n helpUrl: 'https://platform.openai.com/api-keys',\n};\n\nconst MISTRAL: OpenAICompatProviderOptions = {\n id: 'mistral',\n baseURL: 'https://api.mistral.ai/v1',\n name: 'Mistral AI',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M12 2l4 22-4-8-4 8 4-22z\"/></svg>`,\n color: '#fd7e14',\n description: 'European AI: Mistral Large, Mixtral, Codestral',\n helpUrl: 'https://console.mistral.ai/api-keys/',\n};\n\nconst ZAI: OpenAICompatProviderOptions = {\n id: 'zai',\n baseURL: 'https://open.bigmodel.cn/api/paas/v4',\n name: 'Z.ai (Zhipu)',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M13 2L3 14h9l-1 8 10-12h-9l1-8z\"/></svg>`,\n color: '#6366f1',\n description: \"Access Zhipu AI's free GLM models\",\n hasFreeModels: true,\n helpUrl: 'https://open.bigmodel.cn',\n};\n\nconst OPENROUTER: OpenAICompatProviderOptions = {\n id: 'openrouter',\n baseURL: 'https://openrouter.ai/api/v1',\n name: 'OpenRouter',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\"/><path d=\"M2 12h20\"/></svg>`,\n color: '#000000',\n description: 'Access 100+ AI models through a single API',\n hasFreeModels: true,\n helpUrl: 'https://openrouter.ai/keys',\n // OpenRouter attribution headers (sent on chat + model fetch).\n extraHeaders: {\n 'HTTP-Referer': typeof window !== 'undefined' ? window.location.origin : '',\n 'X-Title': 'aparté',\n },\n};\n\nconst LMSTUDIO: OpenAICompatProviderOptions = {\n id: 'lmstudio',\n baseURL: 'http://localhost:1234/v1',\n name: 'LM Studio',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><rect x=\"4\" y=\"4\" width=\"16\" height=\"16\" rx=\"2\"/><path d=\"M9 9h6v6H9z\"/><path d=\"M9 1h1v3h-1zM14 1h1v3h-1zM9 20h1v3h-1zM14 20h1v3h-1zM20 9h3v1h-3zM20 14h3v1h-3zM1 9h3v1H1zM1 14h3v1H1z\"/></svg>`,\n color: '#444444',\n description: 'Run LLMs locally with the LM Studio app',\n hasFreeModels: true,\n isLocal: true,\n helpUrl: 'https://lmstudio.ai/',\n};\n\n// Ollama through its OpenAI-compat endpoint (`/v1`), NOT its native `/api/chat`.\n// Same chat-completions format as everyone else; the native-protocol niceties\n// (inline base64 images, Ollama-shaped tool calls, keep_alive) don't apply —\n// see the README's Ollama section for the behavioural delta.\nconst OLLAMA: OpenAICompatProviderOptions = {\n id: 'ollama',\n baseURL: 'http://localhost:11434/v1',\n name: 'Ollama',\n icon: `<svg viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"><path d=\"M12 2a10 10 0 0 1 10 10 10 10 0 0 1-10 10 10 10 0 0 1-10-10 10 10 0 0 1 10-10zM12 11l4 2-4 2-4-2 4-2zM12 6v5M12 15v3\"/></svg>`,\n color: '#57534e',\n description: 'Run LLMs locally — free and fully private',\n hasFreeModels: true,\n isLocal: true,\n helpUrl: 'https://ollama.com/',\n};\n\n/** Vendor presets for {@link createOpenAICompatProvider}. Pure data. */\nexport const presets = { OPENAI, MISTRAL, ZAI, OPENROUTER, LMSTUDIO, OLLAMA } as const;\n","/**\n * @aparte/provider-openai-compat — ONE adapter for every OpenAI-compatible\n * chat-completions endpoint.\n *\n * The OpenAI `/chat/completions` wire format is the de-facto industry standard:\n * OpenAI, Mistral, OpenRouter, Z.ai, Groq, Together, LM Studio, Ollama (`/v1`)\n * and many more all speak it. This package is the single, zero-dependency\n * format adapter for that family — vendors differ only by DATA (base URL, auth\n * header, branding), which you pass as config (or pick from `presets`).\n *\n * It replaces the per-vendor `@aparte/provider-{openai,mistral,zai,openrouter,\n * lmstudio,ollama}` packages, whose adapter bodies were byte-identical copies\n * (drift even produced real bugs: LM Studio dropped `max_tokens`, Z.ai dropped\n * `seed` — both fixed here by construction, there is only one body now).\n *\n * Model lists are CONSUMER data: pass `models` statically, or rely on the\n * generic `GET {baseURL}/models` fetcher (part of the compat standard). For\n * vendors outside this family (Anthropic, Gemini, …) use the AI-SDK bridge\n * provider instead — this package deliberately covers ONE format.\n */\n\nimport type {\n AparteAIProvider,\n AparteAIModel,\n AparteAIProviderConfigSchema,\n AparteChatRequest,\n AparteChatMessage,\n AparteTool,\n AparteToolCall,\n AparteContentPart,\n AparteStreamEvent,\n AparteUsage,\n AparteFormatAdapter,\n} from '@aparte/core';\nimport { contentToText } from '@aparte/core';\n\n// ─── Options ─────────────────────────────────────────────────────────────────\n\n/** Config for one OpenAI-compatible endpoint. Everything but `id`/`baseURL` is branding/data. */\nexport interface OpenAICompatProviderOptions {\n /** Provider id used across aparté (key resolution, model picker, events). */\n id: string;\n /** Endpoint base, e.g. `https://api.openai.com/v1` or `http://localhost:11434/v1`. */\n baseURL: string;\n /** Display name (defaults to `id`). */\n name?: string;\n /** Brand icon (SVG string / data URI / icon-provider key). */\n icon?: string;\n /** Brand color. */\n color?: string;\n /** Short tag line. */\n description?: string;\n /** Where the user gets a key. */\n helpUrl?: string;\n /** Whether the vendor offers free models. */\n hasFreeModels?: boolean;\n /**\n * Local server (LM Studio, Ollama…): key optional, and the generic\n * `/models` fetch runs even without a key.\n */\n isLocal?: boolean;\n /** Static model list (consumer data). Defaults to `[]` — use `fetchModels`. */\n models?: AparteAIModel[];\n /**\n * Extra headers sent on every request (chat + model fetch), e.g.\n * OpenRouter's attribution headers `HTTP-Referer` / `X-Title`.\n */\n extraHeaders?: Record<string, string>;\n /** Override the default apiKey+endpoint settings schema. */\n configSchema?: AparteAIProviderConfigSchema;\n}\n\n// ─── Message / tool shaping (the format half) ────────────────────────────────\n\n/** Content → OpenAI multipart array when images are present. */\nfunction toOpenAIContent(content: string | AparteContentPart[]): unknown {\n if (typeof content === 'string') return content;\n // Two arms, exhaustive: a part is text or an image. A third used to answer the\n // removed `AparteFilePart` with an empty text part — a branch nothing could reach,\n // standing in for inline-file support this format does not have.\n return content.map(p => (p.type === 'text'\n ? { type: 'text', text: p.text }\n : { type: 'image_url', image_url: { url: p.image } }));\n}\n\n/**\n * The two roles a tool turn used to wear. `AparteChatMessage` no longer allows either, so\n * the comparison is on the role as a string: a message carrying one comes from code built\n * against an older aparté, which no type here can catch. Warned once per role, then\n * skipped — passing it on would put an unknown role on the wire and 400 the whole request.\n */\nconst LEGACY_TOOL_ROLES = new Set(['tool_call', 'tool_result']);\nconst warnedLegacyRoles = new Set<string>();\nfunction warnLegacyToolRole(role: string): void {\n if (warnedLegacyRoles.has(role)) return;\n warnedLegacyRoles.add(role);\n console.warn(\n `[@aparte/provider-openai-compat] Skipping a message with the removed role \"${role}\".`\n + \" A tool turn is now an assistant message carrying its calls — { role: 'assistant',\"\n + \" content: <what it said>, toolCalls } — followed by one { role: 'tool', content:\"\n + ' <result>, toolCallId, toolName } per call. This warning is removed in 0.18.',\n );\n}\n\n// The other half of that legacy shape, and it is deliberately NOT warned: an assistant\n// message built by hand with both `toolCalls` and image parts loses the images here.\n// Chat Completions does not carry them — an assistant message's content parts are `text`\n// and `refusal`, never `image_url` — so the mapping that used to emit them was a 400\n// waiting to happen, and the loop cannot mint the shape (`stream-run.ts` builds an\n// assistant's content from a string). Images on a USER turn are carried, unchanged.\n\n/** AparteChatMessage[] → OpenAI messages (incl. an assistant turn's calls and the `tool` answers). */\nfunction toOpenAIMessages(messages: AparteChatMessage[]): unknown[] {\n const out: unknown[] = [];\n for (const msg of messages) {\n const role: string = msg.role;\n if (LEGACY_TOOL_ROLES.has(role)) {\n warnLegacyToolRole(role);\n continue;\n }\n if (msg.role === 'tool') {\n out.push({ role: 'tool', tool_call_id: msg.toolCallId, content: contentToText(msg.content) });\n continue;\n }\n if (msg.role === 'assistant' && msg.toolCalls?.length) {\n out.push({\n role: 'assistant',\n // `||`, not `??`: this API takes null (or nothing) beside `tool_calls`, and\n // an assistant that said nothing before its calls now carries '' — which\n // some endpoints reject and the rest read as an empty reply.\n content: contentToText(msg.content) || null,\n tool_calls: msg.toolCalls.map(tc => ({\n id: tc.id,\n type: 'function',\n function: { name: tc.name, arguments: JSON.stringify(tc.input) },\n })),\n });\n continue;\n }\n out.push({ role: msg.role, content: toOpenAIContent(msg.content) });\n }\n return out;\n}\n\n/** AparteTool[] → OpenAI function-tool declarations. */\nfunction toOpenAITools(tools: AparteTool[]): unknown[] {\n return tools.map(t => ({\n type: 'function',\n function: { name: t.name, description: t.description, parameters: t.inputSchema },\n }));\n}\n\n/** Accept both raw keys and user-pasted `Bearer xxx` values (local servers). */\nfunction bearer(key: string): string {\n return key.startsWith('Bearer ') ? key : `Bearer ${key}`;\n}\n\nconst DEFAULT_CONFIG_SCHEMA = (opts: OpenAICompatProviderOptions): AparteAIProviderConfigSchema => ({\n fields: opts.isLocal\n ? [\n { id: 'endpoint', type: 'url', label: 'Server', defaultValue: opts.baseURL, required: true },\n { id: 'apiKey', type: 'password', label: 'API Key / Token (optional)', placeholder: 'Bearer ...', isAdvanced: true },\n ]\n : [\n { id: 'apiKey', type: 'password', label: 'API Key', placeholder: 'sk-...', required: true },\n { id: 'endpoint', type: 'url', label: 'Custom endpoint', placeholder: opts.baseURL, isAdvanced: true },\n ],\n});\n\n// ─── The factory ─────────────────────────────────────────────────────────────\n\n/**\n * What {@link createOpenAICompatProvider} hands back: a provider whose whole\n * format-adapter surface is guaranteed present.\n *\n * `AparteAIProvider` declares that surface optional — correct in general, since a\n * provider may own its I/O through `chat()` instead — and `AparteFormatAdapter` keeps\n * `authHeaders` / `parseText` optional because some vendors authenticate by query\n * string or never answer non-streaming. THIS factory always supplies all of them, so\n * saying so here is the difference between a caller writing\n * `provider.buildRequest(req)` and a caller sprinkling `!` or writing a check that\n * cannot fail. Useful to annotate with when you drive the adapter yourself (your own\n * `fetch`, your own `AbortSignal`) from a server or an Electron main process.\n */\nexport type OpenAICompatProvider =\n AparteAIProvider\n & AparteFormatAdapter\n & Required<Pick<AparteFormatAdapter, 'authHeaders' | 'parseText'>>;\n\n/**\n * Build an `AparteAIProvider` (full format-adapter surface) for one\n * OpenAI-compatible endpoint. Register it like any provider:\n *\n * ```ts\n * import { createOpenAICompatProvider, presets } from '@aparte/provider-openai-compat';\n * aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider(presets.OPENROUTER));\n * // or any compat endpoint, no preset needed:\n * aparteGlobalConfig.registerAIProvider(createOpenAICompatProvider({ id: 'groq', baseURL: 'https://api.groq.com/openai/v1' }));\n * ```\n *\n * Returns {@link OpenAICompatProvider}: the full format-adapter surface, non-optional.\n */\nexport function createOpenAICompatProvider(opts: OpenAICompatProviderOptions): OpenAICompatProvider {\n const displayName = opts.name ?? opts.id;\n\n return {\n id: opts.id,\n\n getMetadata() {\n return {\n id: opts.id,\n name: displayName,\n icon: opts.icon,\n color: opts.color,\n description: opts.description,\n helpUrl: opts.helpUrl,\n hasFreeModels: opts.hasFreeModels,\n isLocal: opts.isLocal,\n configSchema: opts.configSchema ?? DEFAULT_CONFIG_SCHEMA(opts),\n };\n },\n\n getModels(): AparteAIModel[] {\n return opts.models ?? [];\n },\n\n /**\n * Generic `GET {baseURL}/models` — part of the compat standard. Cloud\n * endpoints need a key (returns `[]` without one); local servers fetch\n * keyless. Vendor-specific niceties (pricing, name prettifying) are\n * consumer concerns: pass `models` yourself for anything fancier.\n */\n async fetchModels(config?: string | Record<string, string>): Promise<AparteAIModel[]> {\n const apiKey = typeof config === 'string' ? config : config?.['apiKey'];\n const endpoint = (typeof config === 'object' ? config?.['endpoint'] : null) || opts.baseURL;\n if (!apiKey && !opts.isLocal) return [];\n\n try {\n const headers: Record<string, string> = { ...opts.extraHeaders };\n if (apiKey) headers['Authorization'] = bearer(apiKey);\n const response = await fetch(`${endpoint}/models`, { headers });\n if (!response.ok) throw new Error(`HTTP ${response.status}`);\n const data = await response.json() as { data?: Array<{ id: string; name?: string; context_length?: number }> };\n return (data.data ?? []).map(m => ({\n id: m.id,\n name: m.name || m.id,\n contextWindow: m.context_length,\n // `function_calling` is declared because it is a property of the\n // WIRE FORMAT, which is what this provider is: `/chat/completions`\n // takes a `tools` array, and every server behind a compat endpoint\n // accepts one. `/models` returns `{id, object, owned_by}` and says\n // nothing about tools, so waiting for it to declare the capability\n // means never declaring it — and core gates tools on exactly this\n // field, so a registered tool, an approval gate and the whole\n // elicitation path were dead on this provider: the model was asked\n // to use a tool it had never been sent.\n //\n // The failure mode of over-declaring is mild and visible: a model\n // that cannot call tools simply does not call one. The failure mode\n // of under-declaring was silent and total. A server that rejects a\n // `tools` array outright surfaces as an error from its own endpoint,\n // which is the right place for that argument to happen.\n capabilities: ['streaming', 'function_calling'],\n }));\n } catch (error) {\n console.error(`[${displayName}] Failed to fetch models:`, error);\n return [];\n }\n },\n\n // ── Format-adapter surface (transport ⊥ format) ──────────────────────\n // The vendor concern only: request shape + stream parsing. Auth and\n // network are the transport's job (AparteDirectTransport / AparteBackendTransport).\n defaultEndpoint: opts.baseURL,\n\n buildRequest(request: AparteChatRequest) {\n const body: Record<string, unknown> = {\n model: request.modelId,\n messages: toOpenAIMessages(request.messages),\n temperature: request.temperature,\n max_tokens: request.maxTokens,\n stream: request.stream ?? true,\n ...((request.stream ?? true) ? { stream_options: { include_usage: true } } : {}),\n ...(request.seed !== undefined ? { seed: request.seed } : {}),\n };\n if (request.tools?.length) {\n body['tools'] = toOpenAITools(request.tools);\n /*\n * A forced tool travels; `'auto'` is only the DEFAULT. It used to be\n * written unconditionally, so `toolChoice: { name }` — a shape the loop\n * passes straight through, since it intercepts only `{ name, input }`\n * (the synthetic call it runs itself) — was silently downgraded to\n * \"the model decides\", while the ai-sdk bridge honoured the same field.\n * `'none'` never reaches here: core strips the tools upstream.\n */\n const forced = typeof request.toolChoice === 'object' ? request.toolChoice.name : undefined;\n body['tool_choice'] = forced ? { type: 'function', function: { name: forced } } : 'auto';\n }\n return {\n path: '/chat/completions',\n body,\n ...(opts.extraHeaders ? { headers: opts.extraHeaders } : {}),\n };\n },\n\n authHeaders(key: string) {\n return { Authorization: bearer(key) };\n },\n\n parseStream(body: ReadableStream<Uint8Array>) {\n return parseOpenAICompatStream(body);\n },\n\n parseText(json: unknown): string {\n return (json as { choices?: Array<{ message?: { content?: string } }> })?.choices?.[0]?.message?.content || '';\n },\n };\n}\n\n// ─── SSE stream parser (ported from @aparte/core parseOpenAIStream) ──────────\n\n/**\n * OpenAI-compatible SSE stream parser — this package's own copy of core's\n * `parseOpenAIStream` (the parser follows the format adapter; core keeps only\n * the aparté-native NDJSON parser).\n *\n * Handles:\n * - `delta.content` → text event\n * - `delta.reasoning_content` → thinking event (Qwen3, DeepSeek R1, …)\n * - `delta.tool_calls` → accumulate → tool_use on finish_reason='tool_calls'\n * - usage-only chunk + [DONE] → done{usage}\n */\nexport function parseOpenAICompatStream(\n stream: ReadableStream<Uint8Array>,\n): ReadableStream<AparteStreamEvent> {\n const decoder = new TextDecoder();\n let buffer = '';\n\n /*\n * Tool call accumulation state, in wire order, keyed by `toolCallKey` below.\n * A Map, not an object: the key comes off the wire, and on a plain `{}` a chunk\n * whose `index` is `\"__proto__\"` writes into Object.prototype for the whole page.\n */\n const toolCalls = new Map<string, { id: string; name: string; args: string }>();\n /** The call the last delta touched — what a bare argument fragment continues. */\n let lastToolKey: string | null = null;\n /**\n * Every key a delta has addressed a call by → that call's slot in `toolCalls`.\n * One call can be addressed both ways in one turn (by `index` in a chunk, by `id`\n * in the next), so the identity is the alias, not the key of the moment.\n */\n const toolCallAliases = new Map<string, string>();\n /** Ids minted for a vendor that sends none. Per stream, i.e. per turn. */\n let mintedCallIds = 0;\n let capturedUsage: AparteUsage | undefined;\n let reader: ReadableStreamDefaultReader<Uint8Array> | null = null;\n\n /*\n * Emit the accumulated calls and clear the map.\n *\n * Called at EVERY graceful end of a turn, not only on `finish_reason: 'tool_calls'`:\n * the accumulation spans the whole stream, and a vendor that ends with `stop`,\n * `length` or a bare `[DONE]` after streaming tool-call deltas used to drop them —\n * the model had asked for a tool and the loop never heard. `complete` says the\n * model declared the calls finished: a parse failure there is malformed JSON (a\n * real small-model failure) and the tool still runs, on `{}`. Elsewhere it is\n * truncation, and running a tool on `{}` for a call the model never finished would\n * be worse than dropping it — so those are dropped, with a breadcrumb.\n */\n const flushToolCalls = (controller: ReadableStreamDefaultController<AparteStreamEvent>, complete: boolean): void => {\n for (const entry of toolCalls.values()) {\n let input: Record<string, unknown> = {};\n try {\n input = entry.args.trim() ? JSON.parse(entry.args) : {};\n } catch {\n if (!complete) {\n console.warn(`[openai-compat] Tool \"${entry.name}\" was cut mid-arguments (the turn ended without finish_reason 'tool_calls'); the call is dropped. Raw:`, entry.args);\n continue;\n }\n console.warn(\n `[openai-compat] Tool \"${entry.name}\" returned malformed arguments JSON; ` +\n `passing empty input. Raw:`, entry.args,\n );\n }\n const toolCall: AparteToolCall = { id: entry.id, name: entry.name, input };\n controller.enqueue({ type: 'tool_use', ...toolCall });\n }\n toolCalls.clear();\n toolCallAliases.clear();\n lastToolKey = null;\n };\n\n /*\n * Which accumulated call a `delta.tool_calls` entry belongs to.\n *\n * Both `index` and `id` address a call, and a vendor may use one in a chunk and\n * the other in the next — so neither can BE the identity: a delta's keys are\n * ALIASES that all resolve to the same slot. A key already resolved names the\n * call, and every key a delta carries is recorded against the slot it lands on.\n * Picking one key instead (`index` first, `id` next) split such a call in two,\n * the second half nameless, and the turn ran the tool on `{}`.\n *\n * When no key of the delta is known yet, the function NAME decides — it appears\n * only on a call's FIRST delta, so a nameless delta continues the call before it\n * and a named one opens its own. That single rule covers the vendor whose deltas\n * never carry both addresses at once (open by `id`, continue by `index`, or the\n * reverse) and the vendor that carries neither: `index` is a streaming\n * convenience, not part of the function-call payload, and keying on it alone\n * (`Number(tc.index ?? 0)`) put every call of a server that omits it on slot 0.\n *\n * `null` means \"skip this entry\": an `index` the vendor sent that is not a\n * non-negative integer is not a slot number, it is malformed (or hostile —\n * `\"__proto__\"` was the shape that made this a Map).\n */\n const toolCallKey = (tc: { index?: unknown; id?: string; function?: { name?: string } }): string | null => {\n let indexKey: string | undefined;\n if (tc.index !== undefined && tc.index !== null) {\n // Made a number, not annotated as one: `index` is whatever the vendor's JSON put there.\n const idx = Number(tc.index);\n if (!Number.isInteger(idx) || idx < 0) return null;\n indexKey = `i${idx}`;\n }\n const idKey = tc.id ? `d${tc.id}` : undefined;\n const known = (idKey ? toolCallAliases.get(idKey) : undefined) ?? (indexKey ? toolCallAliases.get(indexKey) : undefined);\n // No key of this delta is known yet. A nameless delta never OPENS a call, so it\n // continues the call before it — which is what keeps ONE call together when the\n // vendor opens it with one address and continues it with the other, neither\n // delta carrying both. A named delta still opens its own slot.\n const key = known ?? ((!tc.function?.name && lastToolKey !== null) ? lastToolKey : (idKey ?? indexKey));\n if (key === undefined) return `p${toolCalls.size}`;\n if (idKey) toolCallAliases.set(idKey, key);\n if (indexKey) toolCallAliases.set(indexKey, key);\n return key;\n };\n\n return new ReadableStream<AparteStreamEvent>({\n async start(controller) {\n reader = stream.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split('\\n');\n buffer = lines.pop() ?? '';\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed.startsWith('data:')) continue;\n const raw = trimmed.slice(5).trim();\n if (raw === '[DONE]') {\n // A turn that streamed tool-call deltas and ended on `stop`,\n // `length` or a bare [DONE]: the calls are still the model's.\n flushToolCalls(controller, false);\n controller.enqueue({ type: 'done', usage: capturedUsage });\n return;\n }\n try {\n const json = JSON.parse(raw);\n\n // Capture usage from the usage-only chunk (choices: [])\n if (json.usage) {\n capturedUsage = {\n inputTokens: json.usage.prompt_tokens ?? 0,\n outputTokens: json.usage.completion_tokens ?? 0,\n totalTokens: json.usage.total_tokens,\n cacheReadTokens: json.usage.prompt_tokens_details?.cached_tokens,\n };\n }\n\n const choice = json.choices?.[0];\n if (!choice) continue;\n\n const delta = choice.delta;\n if (delta) {\n if (delta.reasoning_content) {\n controller.enqueue({ type: 'thinking', delta: delta.reasoning_content });\n }\n if (delta.content) {\n controller.enqueue({ type: 'text', delta: delta.content });\n }\n if (delta.tool_calls) {\n for (const tc of delta.tool_calls) {\n const key = toolCallKey(tc);\n if (key === null) continue;\n let entry = toolCalls.get(key);\n if (!entry) {\n /*\n * An id is MINTED when the vendor sends none. `id: ''`\n * used to travel: the transcript keys a row on\n * `tool-${id}` and the history a result on\n * `toolCallId`, so two id-less calls in one turn shared\n * one row (the second call's result landed on the first\n * call's line) and one history slot an OpenAI-shaped\n * endpoint rejects on the next turn. A real id arriving\n * in a later chunk still wins, below. The mint is\n * namespaced because `call_1` is what an OpenAI-shaped\n * server calls its own first call: a turn mixing an\n * id-less call with a real `call_1` minted a duplicate.\n */\n entry = { id: tc.id ?? `aparte-call-${++mintedCallIds}`, name: tc.function?.name ?? '', args: '' };\n toolCalls.set(key, entry);\n }\n lastToolKey = key;\n if (tc.id) entry.id = tc.id;\n if (tc.function?.name) entry.name = tc.function.name;\n if (tc.function?.arguments) entry.args += tc.function.arguments;\n }\n }\n }\n\n // The model declared the calls complete: emit them now (and clear\n // the map, so a server that repeats the finish chunk cannot\n // re-emit them). Do NOT emit `done` or return here: under\n // `include_usage` (which buildRequest requests) the usage-only\n // chunk arrives AFTER this finish chunk, so stopping now dropped\n // usage on every tool-call turn — i.e. most turns of an agent.\n // Keep reading; the single `done` comes from `[DONE]` below, or\n // from the end-of-stream fallback if the socket just closes.\n if (choice.finish_reason === 'tool_calls') flushToolCalls(controller, true);\n } catch {\n // Every line here is a complete, newline-terminated SSE\n // line (see buffer split above), so a parse failure is an\n // unexpected/malformed server payload, not partial JSON —\n // log a breadcrumb instead of dropping it silently.\n console.warn('[openai-compat] Skipped an unparseable SSE data line:', raw);\n }\n }\n }\n // The socket closed without [DONE]: same rule, the calls are flushed first.\n flushToolCalls(controller, false);\n controller.enqueue({ type: 'done', usage: capturedUsage });\n } catch (err: unknown) {\n // AbortError surfaces here when the caller's signal fires mid-stream:\n // the consumer (agent loop) cancelled on purpose — end quietly, the\n // same way the ai-sdk provider does. Reporting it as an `error` event\n // makes a deliberate Stop indistinguishable from a network failure,\n // and the loop's error branch then replaces the streamed answer with\n // an error bubble.\n if ((err as { name?: string } | undefined)?.name !== 'AbortError') {\n controller.enqueue({ type: 'error', message: (err as Error | undefined)?.message ?? 'Stream error' });\n }\n } finally {\n reader?.releaseLock();\n reader = null;\n controller.close();\n }\n },\n // Consumer cancelled (e.g. user hit \"stop\"): cancel the underlying reader so\n // the vendor response body stops being drained to its natural end instead of\n // silently finishing the whole SSE stream in the background.\n cancel(reason) {\n const r = reader;\n reader = null;\n return r?.cancel(reason);\n },\n });\n}\n\nexport * from './presets.js';\nexport type { AparteAIProvider, AparteAIModel } from '@aparte/core';\n"],"names":[],"mappings":";AAiBA,MAAM,SAAsC;AAAA,EACxC,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,SAAS;AACb;AAEA,MAAM,UAAuC;AAAA,EACzC,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,aAAa;AAAA,EACb,SAAS;AACb;AAEA,MAAM,MAAmC;AAAA,EACrC,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,MAAM;AAAA,EACN,MAAM;AAAA,EACN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AAAA;AAAA;AAAA;AAAA,IAIA,OAAO,QAAQ;AACX,YAAM,IAAI;AACV,eAAS;AACT,aAAO,GAAG,OAAO,MAAM;AAAA,IAC3B;AAAA,EAAA,CACH;AACL;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aparte/provider-openai-compat",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.17.0",
|
|
4
4
|
"homepage": "https://apartejs.dev/providers/ai/openai-compat/",
|
|
5
5
|
"description": "One OpenAI-compatible chat-completions adapter for any /v1 endpoint — OpenAI, Mistral, OpenRouter, Z.ai, Groq, LM Studio, Ollama and friends, via presets or plain config.",
|
|
6
6
|
"type": "module",
|
|
@@ -25,13 +25,13 @@
|
|
|
25
25
|
"node": ">=18"
|
|
26
26
|
},
|
|
27
27
|
"peerDependencies": {
|
|
28
|
-
"@aparte/core": ">=0.
|
|
28
|
+
"@aparte/core": ">=0.17.0 <1.0.0"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
31
|
"@types/node": "^22.0.0",
|
|
32
32
|
"typescript": "^5.4.0",
|
|
33
33
|
"vite": "^6.0.0",
|
|
34
|
-
"@aparte/core": "0.
|
|
34
|
+
"@aparte/core": "0.17.0"
|
|
35
35
|
},
|
|
36
36
|
"keywords": [
|
|
37
37
|
"ai",
|