@c9up/polaris 0.0.0-stage → 0.1.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.
Files changed (128) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +542 -2
  3. package/dist/Polaris.d.ts +76 -0
  4. package/dist/Polaris.d.ts.map +1 -0
  5. package/dist/Polaris.js +194 -0
  6. package/dist/Polaris.js.map +1 -0
  7. package/dist/PolarisClient.d.ts +136 -0
  8. package/dist/PolarisClient.d.ts.map +1 -0
  9. package/dist/PolarisClient.js +408 -0
  10. package/dist/PolarisClient.js.map +1 -0
  11. package/dist/PolarisProvider.d.ts +35 -0
  12. package/dist/PolarisProvider.d.ts.map +1 -0
  13. package/dist/PolarisProvider.js +47 -0
  14. package/dist/PolarisProvider.js.map +1 -0
  15. package/dist/augmentations.d.ts +15 -0
  16. package/dist/augmentations.d.ts.map +1 -0
  17. package/dist/augmentations.js +9 -0
  18. package/dist/augmentations.js.map +1 -0
  19. package/dist/budget.d.ts +44 -0
  20. package/dist/budget.d.ts.map +1 -0
  21. package/dist/budget.js +67 -0
  22. package/dist/budget.js.map +1 -0
  23. package/dist/cost.d.ts +48 -0
  24. package/dist/cost.d.ts.map +1 -0
  25. package/dist/cost.js +126 -0
  26. package/dist/cost.js.map +1 -0
  27. package/dist/drivers/anthropic.d.ts +39 -0
  28. package/dist/drivers/anthropic.d.ts.map +1 -0
  29. package/dist/drivers/anthropic.js +394 -0
  30. package/dist/drivers/anthropic.js.map +1 -0
  31. package/dist/drivers/openai-compatible.d.ts +54 -0
  32. package/dist/drivers/openai-compatible.d.ts.map +1 -0
  33. package/dist/drivers/openai-compatible.js +663 -0
  34. package/dist/drivers/openai-compatible.js.map +1 -0
  35. package/dist/drivers/status.d.ts +8 -0
  36. package/dist/drivers/status.d.ts.map +1 -0
  37. package/dist/drivers/status.js +21 -0
  38. package/dist/drivers/status.js.map +1 -0
  39. package/dist/errors.d.ts +55 -0
  40. package/dist/errors.d.ts.map +1 -0
  41. package/dist/errors.js +62 -0
  42. package/dist/errors.js.map +1 -0
  43. package/dist/extract.d.ts +38 -0
  44. package/dist/extract.d.ts.map +1 -0
  45. package/dist/extract.js +144 -0
  46. package/dist/extract.js.map +1 -0
  47. package/dist/index.d.ts +19 -0
  48. package/dist/index.d.ts.map +1 -0
  49. package/dist/index.js +13 -0
  50. package/dist/index.js.map +1 -0
  51. package/dist/log.d.ts +47 -0
  52. package/dist/log.d.ts.map +1 -0
  53. package/dist/log.js +33 -0
  54. package/dist/log.js.map +1 -0
  55. package/dist/meter.d.ts +57 -0
  56. package/dist/meter.d.ts.map +1 -0
  57. package/dist/meter.js +91 -0
  58. package/dist/meter.js.map +1 -0
  59. package/dist/providers.d.ts +23 -0
  60. package/dist/providers.d.ts.map +1 -0
  61. package/dist/providers.js +21 -0
  62. package/dist/providers.js.map +1 -0
  63. package/dist/redact.d.ts +11 -0
  64. package/dist/redact.d.ts.map +1 -0
  65. package/dist/redact.js +76 -0
  66. package/dist/redact.js.map +1 -0
  67. package/dist/response.d.ts +21 -0
  68. package/dist/response.d.ts.map +1 -0
  69. package/dist/response.js +45 -0
  70. package/dist/response.js.map +1 -0
  71. package/dist/schema.d.ts +45 -0
  72. package/dist/schema.d.ts.map +1 -0
  73. package/dist/schema.js +43 -0
  74. package/dist/schema.js.map +1 -0
  75. package/dist/services/main.d.ts +23 -0
  76. package/dist/services/main.d.ts.map +1 -0
  77. package/dist/services/main.js +43 -0
  78. package/dist/services/main.js.map +1 -0
  79. package/dist/sse.d.ts +58 -0
  80. package/dist/sse.d.ts.map +1 -0
  81. package/dist/sse.js +91 -0
  82. package/dist/sse.js.map +1 -0
  83. package/dist/testing/FakeProvider.d.ts +85 -0
  84. package/dist/testing/FakeProvider.d.ts.map +1 -0
  85. package/dist/testing/FakeProvider.js +213 -0
  86. package/dist/testing/FakeProvider.js.map +1 -0
  87. package/dist/testing/index.d.ts +7 -0
  88. package/dist/testing/index.d.ts.map +1 -0
  89. package/dist/testing/index.js +7 -0
  90. package/dist/testing/index.js.map +1 -0
  91. package/dist/tools.d.ts +68 -0
  92. package/dist/tools.d.ts.map +1 -0
  93. package/dist/tools.js +107 -0
  94. package/dist/tools.js.map +1 -0
  95. package/dist/transport.d.ts +18 -0
  96. package/dist/transport.d.ts.map +1 -0
  97. package/dist/transport.js +68 -0
  98. package/dist/transport.js.map +1 -0
  99. package/dist/types.d.ts +293 -0
  100. package/dist/types.d.ts.map +1 -0
  101. package/dist/types.js +12 -0
  102. package/dist/types.js.map +1 -0
  103. package/package.json +76 -3
  104. package/src/Polaris.ts +280 -0
  105. package/src/PolarisClient.ts +591 -0
  106. package/src/PolarisProvider.ts +73 -0
  107. package/src/augmentations.ts +17 -0
  108. package/src/budget.ts +101 -0
  109. package/src/cost.ts +170 -0
  110. package/src/drivers/anthropic.ts +520 -0
  111. package/src/drivers/openai-compatible.ts +840 -0
  112. package/src/drivers/status.ts +30 -0
  113. package/src/errors.ts +161 -0
  114. package/src/extract.ts +214 -0
  115. package/src/index.ts +69 -0
  116. package/src/log.ts +84 -0
  117. package/src/meter.ts +188 -0
  118. package/src/providers.ts +25 -0
  119. package/src/redact.ts +78 -0
  120. package/src/response.ts +65 -0
  121. package/src/schema.ts +88 -0
  122. package/src/services/main.ts +49 -0
  123. package/src/sse.ts +128 -0
  124. package/src/testing/FakeProvider.ts +321 -0
  125. package/src/testing/index.ts +12 -0
  126. package/src/tools.ts +166 -0
  127. package/src/transport.ts +85 -0
  128. package/src/types.ts +328 -0
@@ -0,0 +1,663 @@
1
+ /**
2
+ * The OpenAI-compatible driver: every endpoint that speaks OpenAI's chat
3
+ * completions API (Groq, Cloudflare Workers AI, Infomaniak, a local Ollama,
4
+ * OpenAI itself), over plain `fetch`.
5
+ *
6
+ * What a given model can do varies from one service to the next, so the
7
+ * provider config declares it; polaris refuses the rest before sending.
8
+ */
9
+ import { E_POLARIS_INVALID_CONFIG, E_POLARIS_INVALID_REQUEST, E_POLARIS_INVALID_RESPONSE, E_POLARIS_PROVIDER_UNAVAILABLE, E_POLARIS_PROVIDER_UNREACHABLE, E_POLARIS_STREAM_INCOMPLETE, } from "../errors.js";
10
+ import { createResponse } from "../response.js";
11
+ import { errorForStatus } from "./status.js";
12
+ const DEFAULT_NAME = "openai-compatible";
13
+ const DEFAULT_MAX_TOKENS = 16_000;
14
+ /** Statuses worth sending again besides 5xx: timeout, conflict, rate limit, Groq's capacity. */
15
+ const RETRYABLE = new Set([408, 409, 429, 498]);
16
+ const MAX_RETRY_DELAY = 60_000;
17
+ const BASE_RETRY_DELAY = 500;
18
+ /** Inputs per embedding request: well under OpenAI's 2048, for services that take fewer. */
19
+ const DEFAULT_EMBEDDING_BATCH = 128;
20
+ /** A provider factory for an OpenAI-compatible endpoint. */
21
+ export function openaiCompatible(config) {
22
+ return () => new OpenAICompatibleDriver(config);
23
+ }
24
+ class OpenAICompatibleDriver {
25
+ provider;
26
+ features;
27
+ defaults;
28
+ embed;
29
+ #config;
30
+ #base;
31
+ constructor(config) {
32
+ const base = typeof config.baseURL === "string" ? config.baseURL : "";
33
+ if (!URL.canParse(base) || !/^https?:$/.test(new URL(base).protocol)) {
34
+ throw new E_POLARIS_INVALID_CONFIG([
35
+ "the OpenAI-compatible driver needs a `baseURL` starting with http:// or https://",
36
+ ]);
37
+ }
38
+ if (typeof config.model !== "string" || config.model.trim() === "") {
39
+ throw new E_POLARIS_INVALID_CONFIG([
40
+ "the OpenAI-compatible driver needs a `model`",
41
+ ]);
42
+ }
43
+ if (config.maxTokens !== undefined && !isCount(config.maxTokens)) {
44
+ throw new E_POLARIS_INVALID_CONFIG([
45
+ "the OpenAI-compatible driver's `maxTokens` must be a positive integer",
46
+ ]);
47
+ }
48
+ if (config.embeddingBatchSize !== undefined &&
49
+ !isCount(config.embeddingBatchSize)) {
50
+ throw new E_POLARIS_INVALID_CONFIG([
51
+ "the OpenAI-compatible driver's `embeddingBatchSize` must be a positive integer",
52
+ ]);
53
+ }
54
+ if (config.maxRetries !== undefined &&
55
+ !(Number.isInteger(config.maxRetries) && config.maxRetries >= 0)) {
56
+ throw new E_POLARIS_INVALID_CONFIG([
57
+ "the OpenAI-compatible driver's `maxRetries` must be an integer, 0 or more",
58
+ ]);
59
+ }
60
+ this.#config = config;
61
+ this.#base = base.replace(/\/+$/, "");
62
+ this.provider = config.name ?? DEFAULT_NAME;
63
+ this.features = {
64
+ tools: true,
65
+ structuredOutput: true,
66
+ images: false,
67
+ ...config.features,
68
+ };
69
+ this.defaults = {
70
+ model: config.model,
71
+ embeddingModel: config.embeddingModel,
72
+ maxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
73
+ streamMaxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
74
+ };
75
+ const embeddingModel = config.embeddingModel;
76
+ if (embeddingModel !== undefined) {
77
+ this.embed = (request, call) => this.#embed(embeddingModel, request, call);
78
+ }
79
+ }
80
+ async chat(request, call) {
81
+ const response = await this.#post("/chat/completions", this.#body(request, false), call);
82
+ const body = parseJson(await response.text(), this.provider);
83
+ return this.#toResponse(body, request);
84
+ }
85
+ async *stream(request, call) {
86
+ const response = await this.#post("/chat/completions", this.#body(request, true), call);
87
+ if (response.body === null) {
88
+ throw new E_POLARIS_STREAM_INCOMPLETE([this.provider]);
89
+ }
90
+ const state = {
91
+ id: "",
92
+ model: "",
93
+ text: "",
94
+ reasoning: "",
95
+ calls: new Map(),
96
+ finish: undefined,
97
+ usage: undefined,
98
+ done: false,
99
+ };
100
+ for await (const data of serverSentData(response.body)) {
101
+ if (data === "[DONE]") {
102
+ state.done = true;
103
+ break;
104
+ }
105
+ yield* this.#readChunk(parseJson(data, this.provider), state);
106
+ }
107
+ if (!state.done && state.finish === undefined) {
108
+ throw new E_POLARIS_STREAM_INCOMPLETE([this.provider]);
109
+ }
110
+ const calls = [...state.calls.entries()]
111
+ .sort(([a], [b]) => a - b)
112
+ .map(([, partial]) => toToolCall(partial));
113
+ for (const toolCall of calls)
114
+ yield { type: "tool_call", call: toolCall };
115
+ yield {
116
+ type: "done",
117
+ response: createResponse({
118
+ id: state.id,
119
+ provider: this.provider,
120
+ model: state.model || (request.model ?? this.#config.model),
121
+ content: assistantContent(state.reasoning, state.text, calls),
122
+ stopReason: toStopReason(state.finish, calls.length > 0),
123
+ usage: state.usage,
124
+ }),
125
+ };
126
+ }
127
+ *#readChunk(chunk, state) {
128
+ // Ollama reports an error met mid-stream in a data line, under a 200.
129
+ if (chunk.error !== undefined) {
130
+ throw new E_POLARIS_PROVIDER_UNAVAILABLE([
131
+ this.provider,
132
+ errorMessage(chunk) ?? "the stream reported an error",
133
+ ]);
134
+ }
135
+ if (typeof chunk.id === "string")
136
+ state.id = chunk.id;
137
+ if (typeof chunk.model === "string")
138
+ state.model = chunk.model;
139
+ if (isRecord(chunk.usage))
140
+ state.usage = toUsage(chunk.usage);
141
+ const choice = first(chunk.choices);
142
+ if (choice === undefined)
143
+ return;
144
+ if (typeof choice.finish_reason === "string") {
145
+ state.finish = choice.finish_reason;
146
+ }
147
+ const delta = isRecord(choice.delta) ? choice.delta : {};
148
+ const reasoning = reasoningOf(delta);
149
+ if (reasoning !== "") {
150
+ state.reasoning += reasoning;
151
+ yield { type: "reasoning", text: reasoning };
152
+ }
153
+ if (typeof delta.content === "string" && delta.content !== "") {
154
+ state.text += delta.content;
155
+ yield { type: "text", text: delta.content };
156
+ }
157
+ // A tool call arrives in fragments, joined by their `index`.
158
+ for (const fragment of list(delta.tool_calls)) {
159
+ if (!isRecord(fragment))
160
+ continue;
161
+ const index = typeof fragment.index === "number" ? fragment.index : 0;
162
+ const partial = state.calls.get(index) ?? {
163
+ id: "",
164
+ name: "",
165
+ arguments: "",
166
+ };
167
+ if (typeof fragment.id === "string")
168
+ partial.id = fragment.id;
169
+ const fn = isRecord(fragment.function) ? fragment.function : {};
170
+ if (typeof fn.name === "string")
171
+ partial.name += fn.name;
172
+ if (typeof fn.arguments === "string")
173
+ partial.arguments += fn.arguments;
174
+ state.calls.set(index, partial);
175
+ }
176
+ }
177
+ /**
178
+ * Embed `request.inputs` in batches of `embeddingBatchSize`, one after the
179
+ * other, and join the vectors back in input order.
180
+ */
181
+ async #embed(defaultModel, request, call) {
182
+ const size = this.#config.embeddingBatchSize ?? DEFAULT_EMBEDDING_BATCH;
183
+ const vectors = [];
184
+ let inputTokens = 0;
185
+ let model = request.model ?? defaultModel;
186
+ for (let start = 0; start < request.inputs.length; start += size) {
187
+ const batch = request.inputs.slice(start, start + size);
188
+ const answer = await this.#embedBatch(request.model ?? defaultModel, batch, request.dimensions, call);
189
+ if (answer.vectors.length !== batch.length) {
190
+ throw new E_POLARIS_INVALID_RESPONSE([
191
+ this.provider,
192
+ `${answer.vectors.length} vectors for a batch of ${batch.length} inputs`,
193
+ ]);
194
+ }
195
+ vectors.push(...answer.vectors);
196
+ inputTokens += answer.inputTokens;
197
+ model = answer.model;
198
+ }
199
+ // polaris then checks that every vector has this length, across batches.
200
+ return {
201
+ provider: this.provider,
202
+ model,
203
+ dimensions: vectors[0]?.length ?? 0,
204
+ vectors,
205
+ usage: { inputTokens },
206
+ };
207
+ }
208
+ async #embedBatch(model, inputs, dimensions, call) {
209
+ const response = await this.#post("/embeddings", {
210
+ model,
211
+ input: [...inputs],
212
+ encoding_format: "float",
213
+ ...(dimensions !== undefined ? { dimensions } : {}),
214
+ }, call);
215
+ const body = parseJson(await response.text(), this.provider);
216
+ const rows = list(body.data)
217
+ .filter(isRecord)
218
+ .map((row, position) => ({
219
+ index: typeof row.index === "number" ? row.index : position,
220
+ embedding: list(row.embedding),
221
+ }))
222
+ .sort((a, b) => a.index - b.index);
223
+ const vectors = rows.map((row) => {
224
+ const numbers = row.embedding.filter((value) => typeof value === "number");
225
+ if (numbers.length !== row.embedding.length) {
226
+ throw new E_POLARIS_INVALID_RESPONSE([
227
+ this.provider,
228
+ "an embedding holds something other than numbers",
229
+ ]);
230
+ }
231
+ return Float32Array.from(numbers);
232
+ });
233
+ const usage = isRecord(body.usage) ? body.usage : {};
234
+ return {
235
+ model: typeof body.model === "string" ? body.model : model,
236
+ vectors,
237
+ inputTokens: count(usage.prompt_tokens),
238
+ };
239
+ }
240
+ #body(request, streaming) {
241
+ const config = this.#config;
242
+ const tools = request.tools ?? [];
243
+ const output = request.output;
244
+ return {
245
+ ...providerOptions(request, this.provider),
246
+ model: request.model ?? config.model,
247
+ messages: toMessages(request),
248
+ [config.maxTokensField ?? "max_tokens"]: request.maxTokens ?? config.maxTokens ?? DEFAULT_MAX_TOKENS,
249
+ // Sent either way: Infomaniak streams unless told not to.
250
+ stream: streaming,
251
+ ...(streaming && config.streamUsage !== false
252
+ ? { stream_options: { include_usage: true } }
253
+ : {}),
254
+ ...(tools.length > 0
255
+ ? {
256
+ tools: tools.map((tool) => ({
257
+ type: "function",
258
+ function: {
259
+ name: tool.name,
260
+ description: tool.description,
261
+ parameters: tool.inputSchema,
262
+ },
263
+ })),
264
+ }
265
+ : {}),
266
+ ...(request.toolChoice !== undefined
267
+ ? { tool_choice: request.toolChoice }
268
+ : {}),
269
+ ...(request.stopSequences !== undefined
270
+ ? { stop: [...request.stopSequences] }
271
+ : {}),
272
+ ...(request.effort !== undefined
273
+ ? { reasoning_effort: request.effort }
274
+ : {}),
275
+ ...(output !== undefined
276
+ ? {
277
+ response_format: {
278
+ type: "json_schema",
279
+ json_schema: {
280
+ name: output.name,
281
+ schema: output.schema,
282
+ ...(output.description !== undefined
283
+ ? { description: output.description }
284
+ : {}),
285
+ },
286
+ },
287
+ }
288
+ : {}),
289
+ };
290
+ }
291
+ /**
292
+ * POST `body`, retrying what is worth retrying, and hand back the first
293
+ * successful response. Every failure past the retries is a polaris error.
294
+ */
295
+ async #post(path, body, call) {
296
+ const config = this.#config;
297
+ const apiKey = call.apiKey ?? config.apiKey;
298
+ const headers = {
299
+ ...config.headers,
300
+ "content-type": "application/json",
301
+ accept: "application/json",
302
+ ...(apiKey !== undefined ? { authorization: `Bearer ${apiKey}` } : {}),
303
+ };
304
+ const retries = config.maxRetries ?? 2;
305
+ for (let attempt = 0;; attempt++) {
306
+ let response;
307
+ try {
308
+ response = await call.fetch(`${this.#base}${path}`, {
309
+ method: "POST",
310
+ headers,
311
+ body: JSON.stringify(body),
312
+ signal: call.signal,
313
+ });
314
+ }
315
+ catch (error) {
316
+ if (call.signal.aborted || isPolarisError(error))
317
+ throw error;
318
+ if (attempt < retries) {
319
+ await sleep(backoff(attempt, undefined), call.signal);
320
+ continue;
321
+ }
322
+ throw new E_POLARIS_PROVIDER_UNREACHABLE([
323
+ this.provider,
324
+ error instanceof Error ? error.message : String(error),
325
+ ], { cause: error });
326
+ }
327
+ if (response.ok)
328
+ return response;
329
+ const retryable = RETRYABLE.has(response.status) || response.status >= 500;
330
+ if (retryable && attempt < retries) {
331
+ await response.body?.cancel().catch(() => undefined);
332
+ await sleep(backoff(attempt, response.headers), call.signal);
333
+ continue;
334
+ }
335
+ throw await this.#failure(response);
336
+ }
337
+ }
338
+ async #failure(response) {
339
+ const text = await response.text().catch(() => "");
340
+ let message;
341
+ try {
342
+ const body = JSON.parse(text);
343
+ message = isRecord(body) ? errorMessage(body) : undefined;
344
+ }
345
+ catch {
346
+ message = undefined;
347
+ }
348
+ const detail = message ?? (text.slice(0, 300) || `HTTP ${response.status}`);
349
+ const id = response.headers.get("x-request-id");
350
+ return errorForStatus(this.provider, response.status, id ? `${detail} (request ${id})` : detail);
351
+ }
352
+ #toResponse(body, request) {
353
+ const choice = first(body.choices);
354
+ const message = choice !== undefined && isRecord(choice.message)
355
+ ? choice.message
356
+ : undefined;
357
+ if (message === undefined) {
358
+ throw new E_POLARIS_INVALID_RESPONSE([
359
+ this.provider,
360
+ "the reply has no message",
361
+ ]);
362
+ }
363
+ const calls = list(message.tool_calls)
364
+ .filter(isRecord)
365
+ .map((raw) => {
366
+ const fn = isRecord(raw.function) ? raw.function : {};
367
+ return toToolCall({
368
+ id: typeof raw.id === "string" ? raw.id : "",
369
+ name: typeof fn.name === "string" ? fn.name : "",
370
+ arguments: typeof fn.arguments === "string" ? fn.arguments : "",
371
+ });
372
+ });
373
+ const text = typeof message.content === "string" ? message.content : "";
374
+ return createResponse({
375
+ id: typeof body.id === "string" ? body.id : "",
376
+ provider: this.provider,
377
+ model: typeof body.model === "string"
378
+ ? body.model
379
+ : (request.model ?? this.#config.model),
380
+ content: assistantContent(reasoningOf(message), text, calls),
381
+ stopReason: toStopReason(typeof choice?.finish_reason === "string"
382
+ ? choice.finish_reason
383
+ : undefined, calls.length > 0),
384
+ usage: isRecord(body.usage) ? toUsage(body.usage) : undefined,
385
+ });
386
+ }
387
+ }
388
+ /** Reasoning, then text, then tool calls: the order a reply is written in. */
389
+ function assistantContent(reasoning, text, calls) {
390
+ const content = [];
391
+ if (reasoning !== "")
392
+ content.push({ type: "reasoning", text: reasoning });
393
+ if (text !== "")
394
+ content.push({ type: "text", text });
395
+ content.push(...calls);
396
+ return content;
397
+ }
398
+ /** The chat messages, the system prompt first. */
399
+ function toMessages(request) {
400
+ const out = [];
401
+ if (request.system !== undefined) {
402
+ out.push({ role: "system", content: request.system });
403
+ }
404
+ for (const message of request.messages)
405
+ out.push(...toMessage(message));
406
+ return out;
407
+ }
408
+ function toMessage(message) {
409
+ if (message.role === "assistant") {
410
+ if (typeof message.content === "string") {
411
+ return [{ role: "assistant", content: message.content }];
412
+ }
413
+ // Reasoning and another provider's blocks have no place in this API's
414
+ // history: it rebuilds nothing from them.
415
+ const text = message.content
416
+ .map((part) => (part.type === "text" ? part.text : ""))
417
+ .join("");
418
+ const calls = message.content
419
+ .filter((part) => part.type === "tool_call")
420
+ .map((part) => ({
421
+ id: part.id,
422
+ type: "function",
423
+ function: {
424
+ name: part.name,
425
+ arguments: JSON.stringify(part.input ?? {}),
426
+ },
427
+ }));
428
+ if (text === "" && calls.length === 0)
429
+ return [];
430
+ return [
431
+ {
432
+ role: "assistant",
433
+ content: text === "" ? null : text,
434
+ ...(calls.length > 0 ? { tool_calls: calls } : {}),
435
+ },
436
+ ];
437
+ }
438
+ if (typeof message.content === "string") {
439
+ return [{ role: "user", content: message.content }];
440
+ }
441
+ // A tool result is a message of its own here, and must follow the
442
+ // assistant turn that asked for it: results first, then the user's parts.
443
+ const results = message.content
444
+ .filter((part) => part.type === "tool_result")
445
+ .map((part) => ({
446
+ role: "tool",
447
+ tool_call_id: part.toolCallId,
448
+ content: part.content,
449
+ }));
450
+ const rest = message.content.filter((part) => part.type !== "tool_result");
451
+ if (rest.length === 0)
452
+ return results;
453
+ const content = rest.every((part) => part.type === "text")
454
+ ? rest.map((part) => (part.type === "text" ? part.text : "")).join("\n")
455
+ : rest.map((part) => part.type === "text"
456
+ ? { type: "text", text: part.text }
457
+ : {
458
+ type: "image_url",
459
+ image_url: { url: `data:${part.mediaType};base64,${part.data}` },
460
+ });
461
+ return [...results, { role: "user", content }];
462
+ }
463
+ function toToolCall(partial) {
464
+ let input = {};
465
+ if (partial.arguments.trim() !== "") {
466
+ try {
467
+ input = JSON.parse(partial.arguments);
468
+ }
469
+ catch {
470
+ // Left as the string the model wrote: the application's validation
471
+ // refuses it, instead of polaris guessing what was meant.
472
+ input = partial.arguments;
473
+ }
474
+ }
475
+ return { type: "tool_call", id: partial.id, name: partial.name, input };
476
+ }
477
+ /** Reasoning text where each service puts it: Groq and Ollama `reasoning`, Workers AI `reasoning_content`. */
478
+ function reasoningOf(value) {
479
+ if (typeof value.reasoning === "string")
480
+ return value.reasoning;
481
+ if (typeof value.reasoning_content === "string") {
482
+ return value.reasoning_content;
483
+ }
484
+ return "";
485
+ }
486
+ function toStopReason(reason, hasToolCalls) {
487
+ // Some servers (Ollama) finish a turn that calls tools with `stop`.
488
+ if (hasToolCalls)
489
+ return "tool_use";
490
+ switch (reason) {
491
+ case "stop":
492
+ return "end";
493
+ case "length":
494
+ return "max_tokens";
495
+ case "tool_calls":
496
+ case "function_call":
497
+ return "tool_use";
498
+ case "content_filter":
499
+ return "content_filter";
500
+ default:
501
+ return "other";
502
+ }
503
+ }
504
+ function toUsage(usage) {
505
+ const details = isRecord(usage.prompt_tokens_details)
506
+ ? usage.prompt_tokens_details
507
+ : {};
508
+ // `prompt_tokens` counts the cached tokens too; polaris's input count does not.
509
+ const cached = count(details.cached_tokens);
510
+ return {
511
+ inputTokens: Math.max(0, count(usage.prompt_tokens) - cached),
512
+ outputTokens: count(usage.completion_tokens),
513
+ cacheReadTokens: cached,
514
+ cacheWriteTokens: 0,
515
+ };
516
+ }
517
+ /**
518
+ * The message of an error body: OpenAI's `{ error: { message } }`, Ollama's
519
+ * `{ error: "…" }`, Cloudflare's `{ errors: [{ message }] }`.
520
+ */
521
+ function errorMessage(body) {
522
+ if (typeof body.error === "string")
523
+ return body.error;
524
+ if (isRecord(body.error) && typeof body.error.message === "string") {
525
+ return body.error.message;
526
+ }
527
+ const firstError = first(body.errors);
528
+ if (firstError !== undefined && typeof firstError.message === "string") {
529
+ return firstError.message;
530
+ }
531
+ return undefined;
532
+ }
533
+ function providerOptions(request, provider) {
534
+ const value = request.providerOptions?.[provider];
535
+ if (value === undefined)
536
+ return {};
537
+ if (!isRecord(value)) {
538
+ throw new E_POLARIS_INVALID_REQUEST([
539
+ `providerOptions.${provider} must be an object of request fields`,
540
+ ]);
541
+ }
542
+ return { ...value };
543
+ }
544
+ function parseJson(text, provider) {
545
+ let value;
546
+ try {
547
+ value = JSON.parse(text);
548
+ }
549
+ catch {
550
+ throw new E_POLARIS_INVALID_RESPONSE([provider, "the reply is not JSON"]);
551
+ }
552
+ if (!isRecord(value)) {
553
+ throw new E_POLARIS_INVALID_RESPONSE([
554
+ provider,
555
+ "the reply is not a JSON object",
556
+ ]);
557
+ }
558
+ return value;
559
+ }
560
+ /** The `data:` payloads of a server-sent event stream, lines rejoined across chunks. */
561
+ async function* serverSentData(body) {
562
+ const reader = body.getReader();
563
+ const decoder = new TextDecoder();
564
+ let buffer = "";
565
+ let data = [];
566
+ const lines = function* (final) {
567
+ let newline = buffer.indexOf("\n");
568
+ while (newline !== -1) {
569
+ const line = buffer.slice(0, newline).replace(/\r$/, "");
570
+ buffer = buffer.slice(newline + 1);
571
+ if (line === "") {
572
+ if (data.length > 0)
573
+ yield data.join("\n");
574
+ data = [];
575
+ }
576
+ else if (line.startsWith("data:")) {
577
+ data.push(line.slice(5).replace(/^ /, ""));
578
+ }
579
+ newline = buffer.indexOf("\n");
580
+ }
581
+ if (final) {
582
+ if (buffer.startsWith("data:"))
583
+ data.push(buffer.slice(5).replace(/^ /, ""));
584
+ if (data.length > 0)
585
+ yield data.join("\n");
586
+ }
587
+ };
588
+ try {
589
+ while (true) {
590
+ const { value, done } = await reader.read();
591
+ if (done)
592
+ break;
593
+ buffer += decoder.decode(value, { stream: true });
594
+ yield* lines(false);
595
+ }
596
+ buffer += decoder.decode();
597
+ yield* lines(true);
598
+ }
599
+ finally {
600
+ await reader.cancel().catch(() => undefined);
601
+ }
602
+ }
603
+ /**
604
+ * How long to wait before attempt `attempt + 1`: what the provider asked for
605
+ * (`retry-after-ms`, then `retry-after` in seconds or as a date), at most a
606
+ * minute; otherwise an exponential backoff with jitter.
607
+ */
608
+ function backoff(attempt, headers) {
609
+ const ms = Number(headers?.get("retry-after-ms"));
610
+ if (headers?.has("retry-after-ms") && Number.isFinite(ms) && ms >= 0) {
611
+ return Math.min(ms, MAX_RETRY_DELAY);
612
+ }
613
+ const after = headers?.get("retry-after");
614
+ if (after) {
615
+ const seconds = Number(after);
616
+ const wait = Number.isFinite(seconds)
617
+ ? seconds * 1000
618
+ : Date.parse(after) - Date.now();
619
+ if (Number.isFinite(wait) && wait >= 0) {
620
+ return Math.min(wait, MAX_RETRY_DELAY);
621
+ }
622
+ }
623
+ const exponential = BASE_RETRY_DELAY * 2 ** attempt;
624
+ return Math.min(exponential * (0.75 + Math.random() * 0.5), 8_000);
625
+ }
626
+ function sleep(ms, signal) {
627
+ if (signal.aborted)
628
+ return Promise.reject(signal.reason);
629
+ return new Promise((resolve, reject) => {
630
+ const onAbort = () => {
631
+ clearTimeout(timer);
632
+ reject(signal.reason);
633
+ };
634
+ const timer = setTimeout(() => {
635
+ signal.removeEventListener("abort", onAbort);
636
+ resolve();
637
+ }, ms);
638
+ signal.addEventListener("abort", onAbort, { once: true });
639
+ });
640
+ }
641
+ function isPolarisError(error) {
642
+ const code = error instanceof Error ? Reflect.get(error, "code") : undefined;
643
+ return typeof code === "string" && code.startsWith("E_POLARIS_");
644
+ }
645
+ function isRecord(value) {
646
+ return typeof value === "object" && value !== null && !Array.isArray(value);
647
+ }
648
+ function list(value) {
649
+ return Array.isArray(value) ? value : [];
650
+ }
651
+ function first(value) {
652
+ const head = list(value)[0];
653
+ return isRecord(head) ? head : undefined;
654
+ }
655
+ function count(value) {
656
+ return typeof value === "number" && Number.isFinite(value) && value >= 0
657
+ ? value
658
+ : 0;
659
+ }
660
+ function isCount(value) {
661
+ return Number.isInteger(value) && value > 0;
662
+ }
663
+ //# sourceMappingURL=openai-compatible.js.map