@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,840 @@
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
+
10
+ import {
11
+ E_POLARIS_INVALID_CONFIG,
12
+ E_POLARIS_INVALID_REQUEST,
13
+ E_POLARIS_INVALID_RESPONSE,
14
+ E_POLARIS_PROVIDER_UNAVAILABLE,
15
+ E_POLARIS_PROVIDER_UNREACHABLE,
16
+ E_POLARIS_STREAM_INCOMPLETE,
17
+ } from "../errors.js";
18
+ import { createResponse } from "../response.js";
19
+ import type {
20
+ AssistantPart,
21
+ ChatRequest,
22
+ ChatResponse,
23
+ DriverCall,
24
+ DriverDefaults,
25
+ DriverFeatures,
26
+ EmbedRequest,
27
+ EmbedResponse,
28
+ Message,
29
+ PolarisDriver,
30
+ ProviderFactory,
31
+ StopReason,
32
+ StreamEvent,
33
+ ToolCallPart,
34
+ Usage,
35
+ UserPart,
36
+ } from "../types.js";
37
+ import { errorForStatus } from "./status.js";
38
+
39
+ const DEFAULT_NAME = "openai-compatible";
40
+ const DEFAULT_MAX_TOKENS = 16_000;
41
+ /** Statuses worth sending again besides 5xx: timeout, conflict, rate limit, Groq's capacity. */
42
+ const RETRYABLE = new Set([408, 409, 429, 498]);
43
+ const MAX_RETRY_DELAY = 60_000;
44
+ const BASE_RETRY_DELAY = 500;
45
+ /** Inputs per embedding request: well under OpenAI's 2048, for services that take fewer. */
46
+ const DEFAULT_EMBEDDING_BATCH = 128;
47
+
48
+ export interface OpenAICompatibleConfig {
49
+ /** The API's base URL, up to and including `/v1`: `http://localhost:11434/v1`. */
50
+ readonly baseURL: string;
51
+ /** The chat model every request uses unless it names another. */
52
+ readonly model: string;
53
+ /** Sent as a bearer token. Leave it out for a local server that needs none. */
54
+ readonly apiKey?: string;
55
+ /**
56
+ * The provider's name in responses and in `providerOptions` (`groq`,
57
+ * `ollama`…). Default `openai-compatible`.
58
+ */
59
+ readonly name?: string;
60
+ /** The embedding model. Without it, the provider does not embed. */
61
+ readonly embeddingModel?: string;
62
+ /**
63
+ * Inputs sent per embedding request; a longer list is split into batches
64
+ * sent one after the other, its order kept. Default 128.
65
+ */
66
+ readonly embeddingBatchSize?: number;
67
+ /**
68
+ * What the model supports. Default: tools and structured output on,
69
+ * images off. Declare what your model does, and polaris refuses the rest
70
+ * before sending.
71
+ */
72
+ readonly features?: Partial<DriverFeatures>;
73
+ /** Output limit when a request sets none. Default 16 000. */
74
+ readonly maxTokens?: number;
75
+ /**
76
+ * The field the output limit is sent in. Default `max_tokens`, which Ollama
77
+ * and Workers AI read; Infomaniak reads only `max_completion_tokens`.
78
+ */
79
+ readonly maxTokensField?: "max_tokens" | "max_completion_tokens";
80
+ /**
81
+ * Ask a stream for its token usage (`stream_options.include_usage`).
82
+ * Default true; turn it off for a service that rejects the field.
83
+ */
84
+ readonly streamUsage?: boolean;
85
+ /** Retries of a rate-limited, overloaded or failed request. Default 2. */
86
+ readonly maxRetries?: number;
87
+ /** Further headers sent with every request. */
88
+ readonly headers?: Readonly<Record<string, string>>;
89
+ }
90
+
91
+ /** A provider factory for an OpenAI-compatible endpoint. */
92
+ export function openaiCompatible(
93
+ config: OpenAICompatibleConfig,
94
+ ): ProviderFactory {
95
+ return () => new OpenAICompatibleDriver(config);
96
+ }
97
+
98
+ interface PartialCall {
99
+ id: string;
100
+ name: string;
101
+ arguments: string;
102
+ }
103
+
104
+ interface StreamState {
105
+ id: string;
106
+ model: string;
107
+ text: string;
108
+ reasoning: string;
109
+ calls: Map<number, PartialCall>;
110
+ finish: string | undefined;
111
+ usage: Usage | undefined;
112
+ done: boolean;
113
+ }
114
+
115
+ class OpenAICompatibleDriver implements PolarisDriver {
116
+ readonly provider: string;
117
+ readonly features: DriverFeatures;
118
+ readonly defaults: DriverDefaults;
119
+ readonly embed?: (
120
+ request: EmbedRequest,
121
+ call: DriverCall,
122
+ ) => Promise<EmbedResponse>;
123
+ readonly #config: OpenAICompatibleConfig;
124
+ readonly #base: string;
125
+
126
+ constructor(config: OpenAICompatibleConfig) {
127
+ const base = typeof config.baseURL === "string" ? config.baseURL : "";
128
+ if (!URL.canParse(base) || !/^https?:$/.test(new URL(base).protocol)) {
129
+ throw new E_POLARIS_INVALID_CONFIG([
130
+ "the OpenAI-compatible driver needs a `baseURL` starting with http:// or https://",
131
+ ]);
132
+ }
133
+ if (typeof config.model !== "string" || config.model.trim() === "") {
134
+ throw new E_POLARIS_INVALID_CONFIG([
135
+ "the OpenAI-compatible driver needs a `model`",
136
+ ]);
137
+ }
138
+ if (config.maxTokens !== undefined && !isCount(config.maxTokens)) {
139
+ throw new E_POLARIS_INVALID_CONFIG([
140
+ "the OpenAI-compatible driver's `maxTokens` must be a positive integer",
141
+ ]);
142
+ }
143
+ if (
144
+ config.embeddingBatchSize !== undefined &&
145
+ !isCount(config.embeddingBatchSize)
146
+ ) {
147
+ throw new E_POLARIS_INVALID_CONFIG([
148
+ "the OpenAI-compatible driver's `embeddingBatchSize` must be a positive integer",
149
+ ]);
150
+ }
151
+ if (
152
+ config.maxRetries !== undefined &&
153
+ !(Number.isInteger(config.maxRetries) && config.maxRetries >= 0)
154
+ ) {
155
+ throw new E_POLARIS_INVALID_CONFIG([
156
+ "the OpenAI-compatible driver's `maxRetries` must be an integer, 0 or more",
157
+ ]);
158
+ }
159
+ this.#config = config;
160
+ this.#base = base.replace(/\/+$/, "");
161
+ this.provider = config.name ?? DEFAULT_NAME;
162
+ this.features = {
163
+ tools: true,
164
+ structuredOutput: true,
165
+ images: false,
166
+ ...config.features,
167
+ };
168
+ this.defaults = {
169
+ model: config.model,
170
+ embeddingModel: config.embeddingModel,
171
+ maxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
172
+ streamMaxTokens: config.maxTokens ?? DEFAULT_MAX_TOKENS,
173
+ };
174
+ const embeddingModel = config.embeddingModel;
175
+ if (embeddingModel !== undefined) {
176
+ this.embed = (request, call) =>
177
+ this.#embed(embeddingModel, request, call);
178
+ }
179
+ }
180
+
181
+ async chat(request: ChatRequest, call: DriverCall): Promise<ChatResponse> {
182
+ const response = await this.#post(
183
+ "/chat/completions",
184
+ this.#body(request, false),
185
+ call,
186
+ );
187
+ const body = parseJson(await response.text(), this.provider);
188
+ return this.#toResponse(body, request);
189
+ }
190
+
191
+ async *stream(
192
+ request: ChatRequest,
193
+ call: DriverCall,
194
+ ): AsyncGenerator<StreamEvent, void, undefined> {
195
+ const response = await this.#post(
196
+ "/chat/completions",
197
+ this.#body(request, true),
198
+ call,
199
+ );
200
+ if (response.body === null) {
201
+ throw new E_POLARIS_STREAM_INCOMPLETE([this.provider]);
202
+ }
203
+
204
+ const state: StreamState = {
205
+ id: "",
206
+ model: "",
207
+ text: "",
208
+ reasoning: "",
209
+ calls: new Map(),
210
+ finish: undefined,
211
+ usage: undefined,
212
+ done: false,
213
+ };
214
+ for await (const data of serverSentData(response.body)) {
215
+ if (data === "[DONE]") {
216
+ state.done = true;
217
+ break;
218
+ }
219
+ yield* this.#readChunk(parseJson(data, this.provider), state);
220
+ }
221
+ if (!state.done && state.finish === undefined) {
222
+ throw new E_POLARIS_STREAM_INCOMPLETE([this.provider]);
223
+ }
224
+
225
+ const calls = [...state.calls.entries()]
226
+ .sort(([a], [b]) => a - b)
227
+ .map(([, partial]) => toToolCall(partial));
228
+ for (const toolCall of calls) yield { type: "tool_call", call: toolCall };
229
+
230
+ yield {
231
+ type: "done",
232
+ response: createResponse({
233
+ id: state.id,
234
+ provider: this.provider,
235
+ model: state.model || (request.model ?? this.#config.model),
236
+ content: assistantContent(state.reasoning, state.text, calls),
237
+ stopReason: toStopReason(state.finish, calls.length > 0),
238
+ usage: state.usage,
239
+ }),
240
+ };
241
+ }
242
+
243
+ *#readChunk(
244
+ chunk: Record<string, unknown>,
245
+ state: StreamState,
246
+ ): Generator<StreamEvent> {
247
+ // Ollama reports an error met mid-stream in a data line, under a 200.
248
+ if (chunk.error !== undefined) {
249
+ throw new E_POLARIS_PROVIDER_UNAVAILABLE([
250
+ this.provider,
251
+ errorMessage(chunk) ?? "the stream reported an error",
252
+ ]);
253
+ }
254
+ if (typeof chunk.id === "string") state.id = chunk.id;
255
+ if (typeof chunk.model === "string") state.model = chunk.model;
256
+ if (isRecord(chunk.usage)) state.usage = toUsage(chunk.usage);
257
+
258
+ const choice = first(chunk.choices);
259
+ if (choice === undefined) return;
260
+ if (typeof choice.finish_reason === "string") {
261
+ state.finish = choice.finish_reason;
262
+ }
263
+ const delta = isRecord(choice.delta) ? choice.delta : {};
264
+ const reasoning = reasoningOf(delta);
265
+ if (reasoning !== "") {
266
+ state.reasoning += reasoning;
267
+ yield { type: "reasoning", text: reasoning };
268
+ }
269
+ if (typeof delta.content === "string" && delta.content !== "") {
270
+ state.text += delta.content;
271
+ yield { type: "text", text: delta.content };
272
+ }
273
+ // A tool call arrives in fragments, joined by their `index`.
274
+ for (const fragment of list(delta.tool_calls)) {
275
+ if (!isRecord(fragment)) continue;
276
+ const index = typeof fragment.index === "number" ? fragment.index : 0;
277
+ const partial = state.calls.get(index) ?? {
278
+ id: "",
279
+ name: "",
280
+ arguments: "",
281
+ };
282
+ if (typeof fragment.id === "string") partial.id = fragment.id;
283
+ const fn = isRecord(fragment.function) ? fragment.function : {};
284
+ if (typeof fn.name === "string") partial.name += fn.name;
285
+ if (typeof fn.arguments === "string") partial.arguments += fn.arguments;
286
+ state.calls.set(index, partial);
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Embed `request.inputs` in batches of `embeddingBatchSize`, one after the
292
+ * other, and join the vectors back in input order.
293
+ */
294
+ async #embed(
295
+ defaultModel: string,
296
+ request: EmbedRequest,
297
+ call: DriverCall,
298
+ ): Promise<EmbedResponse> {
299
+ const size = this.#config.embeddingBatchSize ?? DEFAULT_EMBEDDING_BATCH;
300
+ const vectors: Float32Array[] = [];
301
+ let inputTokens = 0;
302
+ let model = request.model ?? defaultModel;
303
+ for (let start = 0; start < request.inputs.length; start += size) {
304
+ const batch = request.inputs.slice(start, start + size);
305
+ const answer = await this.#embedBatch(
306
+ request.model ?? defaultModel,
307
+ batch,
308
+ request.dimensions,
309
+ call,
310
+ );
311
+ if (answer.vectors.length !== batch.length) {
312
+ throw new E_POLARIS_INVALID_RESPONSE([
313
+ this.provider,
314
+ `${answer.vectors.length} vectors for a batch of ${batch.length} inputs`,
315
+ ]);
316
+ }
317
+ vectors.push(...answer.vectors);
318
+ inputTokens += answer.inputTokens;
319
+ model = answer.model;
320
+ }
321
+ // polaris then checks that every vector has this length, across batches.
322
+ return {
323
+ provider: this.provider,
324
+ model,
325
+ dimensions: vectors[0]?.length ?? 0,
326
+ vectors,
327
+ usage: { inputTokens },
328
+ };
329
+ }
330
+
331
+ async #embedBatch(
332
+ model: string,
333
+ inputs: readonly string[],
334
+ dimensions: number | undefined,
335
+ call: DriverCall,
336
+ ): Promise<{ model: string; vectors: Float32Array[]; inputTokens: number }> {
337
+ const response = await this.#post(
338
+ "/embeddings",
339
+ {
340
+ model,
341
+ input: [...inputs],
342
+ encoding_format: "float",
343
+ ...(dimensions !== undefined ? { dimensions } : {}),
344
+ },
345
+ call,
346
+ );
347
+ const body = parseJson(await response.text(), this.provider);
348
+ const rows = list(body.data)
349
+ .filter(isRecord)
350
+ .map((row, position) => ({
351
+ index: typeof row.index === "number" ? row.index : position,
352
+ embedding: list(row.embedding),
353
+ }))
354
+ .sort((a, b) => a.index - b.index);
355
+ const vectors = rows.map((row) => {
356
+ const numbers = row.embedding.filter(
357
+ (value): value is number => typeof value === "number",
358
+ );
359
+ if (numbers.length !== row.embedding.length) {
360
+ throw new E_POLARIS_INVALID_RESPONSE([
361
+ this.provider,
362
+ "an embedding holds something other than numbers",
363
+ ]);
364
+ }
365
+ return Float32Array.from(numbers);
366
+ });
367
+ const usage = isRecord(body.usage) ? body.usage : {};
368
+ return {
369
+ model: typeof body.model === "string" ? body.model : model,
370
+ vectors,
371
+ inputTokens: count(usage.prompt_tokens),
372
+ };
373
+ }
374
+
375
+ #body(request: ChatRequest, streaming: boolean): Record<string, unknown> {
376
+ const config = this.#config;
377
+ const tools = request.tools ?? [];
378
+ const output = request.output;
379
+ return {
380
+ ...providerOptions(request, this.provider),
381
+ model: request.model ?? config.model,
382
+ messages: toMessages(request),
383
+ [config.maxTokensField ?? "max_tokens"]:
384
+ request.maxTokens ?? config.maxTokens ?? DEFAULT_MAX_TOKENS,
385
+ // Sent either way: Infomaniak streams unless told not to.
386
+ stream: streaming,
387
+ ...(streaming && config.streamUsage !== false
388
+ ? { stream_options: { include_usage: true } }
389
+ : {}),
390
+ ...(tools.length > 0
391
+ ? {
392
+ tools: tools.map((tool) => ({
393
+ type: "function",
394
+ function: {
395
+ name: tool.name,
396
+ description: tool.description,
397
+ parameters: tool.inputSchema,
398
+ },
399
+ })),
400
+ }
401
+ : {}),
402
+ ...(request.toolChoice !== undefined
403
+ ? { tool_choice: request.toolChoice }
404
+ : {}),
405
+ ...(request.stopSequences !== undefined
406
+ ? { stop: [...request.stopSequences] }
407
+ : {}),
408
+ ...(request.effort !== undefined
409
+ ? { reasoning_effort: request.effort }
410
+ : {}),
411
+ ...(output !== undefined
412
+ ? {
413
+ response_format: {
414
+ type: "json_schema",
415
+ json_schema: {
416
+ name: output.name,
417
+ schema: output.schema,
418
+ ...(output.description !== undefined
419
+ ? { description: output.description }
420
+ : {}),
421
+ },
422
+ },
423
+ }
424
+ : {}),
425
+ };
426
+ }
427
+
428
+ /**
429
+ * POST `body`, retrying what is worth retrying, and hand back the first
430
+ * successful response. Every failure past the retries is a polaris error.
431
+ */
432
+ async #post(
433
+ path: string,
434
+ body: Record<string, unknown>,
435
+ call: DriverCall,
436
+ ): Promise<Response> {
437
+ const config = this.#config;
438
+ const apiKey = call.apiKey ?? config.apiKey;
439
+ const headers: Record<string, string> = {
440
+ ...config.headers,
441
+ "content-type": "application/json",
442
+ accept: "application/json",
443
+ ...(apiKey !== undefined ? { authorization: `Bearer ${apiKey}` } : {}),
444
+ };
445
+ const retries = config.maxRetries ?? 2;
446
+
447
+ for (let attempt = 0; ; attempt++) {
448
+ let response: Response;
449
+ try {
450
+ response = await call.fetch(`${this.#base}${path}`, {
451
+ method: "POST",
452
+ headers,
453
+ body: JSON.stringify(body),
454
+ signal: call.signal,
455
+ });
456
+ } catch (error) {
457
+ if (call.signal.aborted || isPolarisError(error)) throw error;
458
+ if (attempt < retries) {
459
+ await sleep(backoff(attempt, undefined), call.signal);
460
+ continue;
461
+ }
462
+ throw new E_POLARIS_PROVIDER_UNREACHABLE(
463
+ [
464
+ this.provider,
465
+ error instanceof Error ? error.message : String(error),
466
+ ],
467
+ { cause: error },
468
+ );
469
+ }
470
+ if (response.ok) return response;
471
+
472
+ const retryable =
473
+ RETRYABLE.has(response.status) || response.status >= 500;
474
+ if (retryable && attempt < retries) {
475
+ await response.body?.cancel().catch(() => undefined);
476
+ await sleep(backoff(attempt, response.headers), call.signal);
477
+ continue;
478
+ }
479
+ throw await this.#failure(response);
480
+ }
481
+ }
482
+
483
+ async #failure(response: Response): Promise<Error> {
484
+ const text = await response.text().catch(() => "");
485
+ let message: string | undefined;
486
+ try {
487
+ const body: unknown = JSON.parse(text);
488
+ message = isRecord(body) ? errorMessage(body) : undefined;
489
+ } catch {
490
+ message = undefined;
491
+ }
492
+ const detail = message ?? (text.slice(0, 300) || `HTTP ${response.status}`);
493
+ const id = response.headers.get("x-request-id");
494
+ return errorForStatus(
495
+ this.provider,
496
+ response.status,
497
+ id ? `${detail} (request ${id})` : detail,
498
+ );
499
+ }
500
+
501
+ #toResponse(
502
+ body: Record<string, unknown>,
503
+ request: ChatRequest,
504
+ ): ChatResponse {
505
+ const choice = first(body.choices);
506
+ const message =
507
+ choice !== undefined && isRecord(choice.message)
508
+ ? choice.message
509
+ : undefined;
510
+ if (message === undefined) {
511
+ throw new E_POLARIS_INVALID_RESPONSE([
512
+ this.provider,
513
+ "the reply has no message",
514
+ ]);
515
+ }
516
+ const calls = list(message.tool_calls)
517
+ .filter(isRecord)
518
+ .map((raw) => {
519
+ const fn = isRecord(raw.function) ? raw.function : {};
520
+ return toToolCall({
521
+ id: typeof raw.id === "string" ? raw.id : "",
522
+ name: typeof fn.name === "string" ? fn.name : "",
523
+ arguments: typeof fn.arguments === "string" ? fn.arguments : "",
524
+ });
525
+ });
526
+ const text = typeof message.content === "string" ? message.content : "";
527
+ return createResponse({
528
+ id: typeof body.id === "string" ? body.id : "",
529
+ provider: this.provider,
530
+ model:
531
+ typeof body.model === "string"
532
+ ? body.model
533
+ : (request.model ?? this.#config.model),
534
+ content: assistantContent(reasoningOf(message), text, calls),
535
+ stopReason: toStopReason(
536
+ typeof choice?.finish_reason === "string"
537
+ ? choice.finish_reason
538
+ : undefined,
539
+ calls.length > 0,
540
+ ),
541
+ usage: isRecord(body.usage) ? toUsage(body.usage) : undefined,
542
+ });
543
+ }
544
+ }
545
+
546
+ /** Reasoning, then text, then tool calls: the order a reply is written in. */
547
+ function assistantContent(
548
+ reasoning: string,
549
+ text: string,
550
+ calls: readonly ToolCallPart[],
551
+ ): AssistantPart[] {
552
+ const content: AssistantPart[] = [];
553
+ if (reasoning !== "") content.push({ type: "reasoning", text: reasoning });
554
+ if (text !== "") content.push({ type: "text", text });
555
+ content.push(...calls);
556
+ return content;
557
+ }
558
+
559
+ /** The chat messages, the system prompt first. */
560
+ function toMessages(request: ChatRequest): Record<string, unknown>[] {
561
+ const out: Record<string, unknown>[] = [];
562
+ if (request.system !== undefined) {
563
+ out.push({ role: "system", content: request.system });
564
+ }
565
+ for (const message of request.messages) out.push(...toMessage(message));
566
+ return out;
567
+ }
568
+
569
+ function toMessage(message: Message): Record<string, unknown>[] {
570
+ if (message.role === "assistant") {
571
+ if (typeof message.content === "string") {
572
+ return [{ role: "assistant", content: message.content }];
573
+ }
574
+ // Reasoning and another provider's blocks have no place in this API's
575
+ // history: it rebuilds nothing from them.
576
+ const text = message.content
577
+ .map((part) => (part.type === "text" ? part.text : ""))
578
+ .join("");
579
+ const calls = message.content
580
+ .filter((part): part is ToolCallPart => part.type === "tool_call")
581
+ .map((part) => ({
582
+ id: part.id,
583
+ type: "function",
584
+ function: {
585
+ name: part.name,
586
+ arguments: JSON.stringify(part.input ?? {}),
587
+ },
588
+ }));
589
+ if (text === "" && calls.length === 0) return [];
590
+ return [
591
+ {
592
+ role: "assistant",
593
+ content: text === "" ? null : text,
594
+ ...(calls.length > 0 ? { tool_calls: calls } : {}),
595
+ },
596
+ ];
597
+ }
598
+
599
+ if (typeof message.content === "string") {
600
+ return [{ role: "user", content: message.content }];
601
+ }
602
+ // A tool result is a message of its own here, and must follow the
603
+ // assistant turn that asked for it: results first, then the user's parts.
604
+ const results = message.content
605
+ .filter((part) => part.type === "tool_result")
606
+ .map((part) => ({
607
+ role: "tool",
608
+ tool_call_id: part.toolCallId,
609
+ content: part.content,
610
+ }));
611
+ const rest = message.content.filter(
612
+ (part): part is Exclude<UserPart, { type: "tool_result" }> =>
613
+ part.type !== "tool_result",
614
+ );
615
+ if (rest.length === 0) return results;
616
+ const content = rest.every((part) => part.type === "text")
617
+ ? rest.map((part) => (part.type === "text" ? part.text : "")).join("\n")
618
+ : rest.map((part) =>
619
+ part.type === "text"
620
+ ? { type: "text", text: part.text }
621
+ : {
622
+ type: "image_url",
623
+ image_url: { url: `data:${part.mediaType};base64,${part.data}` },
624
+ },
625
+ );
626
+ return [...results, { role: "user", content }];
627
+ }
628
+
629
+ function toToolCall(partial: PartialCall): ToolCallPart {
630
+ let input: unknown = {};
631
+ if (partial.arguments.trim() !== "") {
632
+ try {
633
+ input = JSON.parse(partial.arguments);
634
+ } catch {
635
+ // Left as the string the model wrote: the application's validation
636
+ // refuses it, instead of polaris guessing what was meant.
637
+ input = partial.arguments;
638
+ }
639
+ }
640
+ return { type: "tool_call", id: partial.id, name: partial.name, input };
641
+ }
642
+
643
+ /** Reasoning text where each service puts it: Groq and Ollama `reasoning`, Workers AI `reasoning_content`. */
644
+ function reasoningOf(value: Record<string, unknown>): string {
645
+ if (typeof value.reasoning === "string") return value.reasoning;
646
+ if (typeof value.reasoning_content === "string") {
647
+ return value.reasoning_content;
648
+ }
649
+ return "";
650
+ }
651
+
652
+ function toStopReason(
653
+ reason: string | undefined,
654
+ hasToolCalls: boolean,
655
+ ): StopReason {
656
+ // Some servers (Ollama) finish a turn that calls tools with `stop`.
657
+ if (hasToolCalls) return "tool_use";
658
+ switch (reason) {
659
+ case "stop":
660
+ return "end";
661
+ case "length":
662
+ return "max_tokens";
663
+ case "tool_calls":
664
+ case "function_call":
665
+ return "tool_use";
666
+ case "content_filter":
667
+ return "content_filter";
668
+ default:
669
+ return "other";
670
+ }
671
+ }
672
+
673
+ function toUsage(usage: Record<string, unknown>): Usage {
674
+ const details = isRecord(usage.prompt_tokens_details)
675
+ ? usage.prompt_tokens_details
676
+ : {};
677
+ // `prompt_tokens` counts the cached tokens too; polaris's input count does not.
678
+ const cached = count(details.cached_tokens);
679
+ return {
680
+ inputTokens: Math.max(0, count(usage.prompt_tokens) - cached),
681
+ outputTokens: count(usage.completion_tokens),
682
+ cacheReadTokens: cached,
683
+ cacheWriteTokens: 0,
684
+ };
685
+ }
686
+
687
+ /**
688
+ * The message of an error body: OpenAI's `{ error: { message } }`, Ollama's
689
+ * `{ error: "…" }`, Cloudflare's `{ errors: [{ message }] }`.
690
+ */
691
+ function errorMessage(body: Record<string, unknown>): string | undefined {
692
+ if (typeof body.error === "string") return body.error;
693
+ if (isRecord(body.error) && typeof body.error.message === "string") {
694
+ return body.error.message;
695
+ }
696
+ const firstError = first(body.errors);
697
+ if (firstError !== undefined && typeof firstError.message === "string") {
698
+ return firstError.message;
699
+ }
700
+ return undefined;
701
+ }
702
+
703
+ function providerOptions(
704
+ request: ChatRequest,
705
+ provider: string,
706
+ ): Record<string, unknown> {
707
+ const value: unknown = request.providerOptions?.[provider];
708
+ if (value === undefined) return {};
709
+ if (!isRecord(value)) {
710
+ throw new E_POLARIS_INVALID_REQUEST([
711
+ `providerOptions.${provider} must be an object of request fields`,
712
+ ]);
713
+ }
714
+ return { ...value };
715
+ }
716
+
717
+ function parseJson(text: string, provider: string): Record<string, unknown> {
718
+ let value: unknown;
719
+ try {
720
+ value = JSON.parse(text);
721
+ } catch {
722
+ throw new E_POLARIS_INVALID_RESPONSE([provider, "the reply is not JSON"]);
723
+ }
724
+ if (!isRecord(value)) {
725
+ throw new E_POLARIS_INVALID_RESPONSE([
726
+ provider,
727
+ "the reply is not a JSON object",
728
+ ]);
729
+ }
730
+ return value;
731
+ }
732
+
733
+ /** The `data:` payloads of a server-sent event stream, lines rejoined across chunks. */
734
+ async function* serverSentData(
735
+ body: ReadableStream<Uint8Array>,
736
+ ): AsyncGenerator<string> {
737
+ const reader = body.getReader();
738
+ const decoder = new TextDecoder();
739
+ let buffer = "";
740
+ let data: string[] = [];
741
+ const lines = function* (final: boolean): Generator<string> {
742
+ let newline = buffer.indexOf("\n");
743
+ while (newline !== -1) {
744
+ const line = buffer.slice(0, newline).replace(/\r$/, "");
745
+ buffer = buffer.slice(newline + 1);
746
+ if (line === "") {
747
+ if (data.length > 0) yield data.join("\n");
748
+ data = [];
749
+ } else if (line.startsWith("data:")) {
750
+ data.push(line.slice(5).replace(/^ /, ""));
751
+ }
752
+ newline = buffer.indexOf("\n");
753
+ }
754
+ if (final) {
755
+ if (buffer.startsWith("data:"))
756
+ data.push(buffer.slice(5).replace(/^ /, ""));
757
+ if (data.length > 0) yield data.join("\n");
758
+ }
759
+ };
760
+ try {
761
+ while (true) {
762
+ const { value, done } = await reader.read();
763
+ if (done) break;
764
+ buffer += decoder.decode(value, { stream: true });
765
+ yield* lines(false);
766
+ }
767
+ buffer += decoder.decode();
768
+ yield* lines(true);
769
+ } finally {
770
+ await reader.cancel().catch(() => undefined);
771
+ }
772
+ }
773
+
774
+ /**
775
+ * How long to wait before attempt `attempt + 1`: what the provider asked for
776
+ * (`retry-after-ms`, then `retry-after` in seconds or as a date), at most a
777
+ * minute; otherwise an exponential backoff with jitter.
778
+ */
779
+ function backoff(attempt: number, headers: Headers | undefined): number {
780
+ const ms = Number(headers?.get("retry-after-ms"));
781
+ if (headers?.has("retry-after-ms") && Number.isFinite(ms) && ms >= 0) {
782
+ return Math.min(ms, MAX_RETRY_DELAY);
783
+ }
784
+ const after = headers?.get("retry-after");
785
+ if (after) {
786
+ const seconds = Number(after);
787
+ const wait = Number.isFinite(seconds)
788
+ ? seconds * 1000
789
+ : Date.parse(after) - Date.now();
790
+ if (Number.isFinite(wait) && wait >= 0) {
791
+ return Math.min(wait, MAX_RETRY_DELAY);
792
+ }
793
+ }
794
+ const exponential = BASE_RETRY_DELAY * 2 ** attempt;
795
+ return Math.min(exponential * (0.75 + Math.random() * 0.5), 8_000);
796
+ }
797
+
798
+ function sleep(ms: number, signal: AbortSignal): Promise<void> {
799
+ if (signal.aborted) return Promise.reject(signal.reason);
800
+ return new Promise((resolve, reject) => {
801
+ const onAbort = () => {
802
+ clearTimeout(timer);
803
+ reject(signal.reason);
804
+ };
805
+ const timer = setTimeout(() => {
806
+ signal.removeEventListener("abort", onAbort);
807
+ resolve();
808
+ }, ms);
809
+ signal.addEventListener("abort", onAbort, { once: true });
810
+ });
811
+ }
812
+
813
+ function isPolarisError(error: unknown): boolean {
814
+ const code: unknown =
815
+ error instanceof Error ? Reflect.get(error, "code") : undefined;
816
+ return typeof code === "string" && code.startsWith("E_POLARIS_");
817
+ }
818
+
819
+ function isRecord(value: unknown): value is Record<string, unknown> {
820
+ return typeof value === "object" && value !== null && !Array.isArray(value);
821
+ }
822
+
823
+ function list(value: unknown): unknown[] {
824
+ return Array.isArray(value) ? value : [];
825
+ }
826
+
827
+ function first(value: unknown): Record<string, unknown> | undefined {
828
+ const head: unknown = list(value)[0];
829
+ return isRecord(head) ? head : undefined;
830
+ }
831
+
832
+ function count(value: unknown): number {
833
+ return typeof value === "number" && Number.isFinite(value) && value >= 0
834
+ ? value
835
+ : 0;
836
+ }
837
+
838
+ function isCount(value: number): boolean {
839
+ return Number.isInteger(value) && value > 0;
840
+ }