@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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 C9up
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,543 @@
1
- # Temporary Holding Version
1
+ # @c9up/polaris
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ One API for language models, whatever the provider. Your application sends a
4
+ request and reads a reply the same way, whether it talks to Claude, to an
5
+ OpenAI-compatible endpoint or to a model running on your own server.
6
+ Switching provider is a config change.
7
+
8
+ It ships two providers: Claude, and every service that speaks OpenAI's chat
9
+ completions API (Groq, Cloudflare Workers AI, Infomaniak, a local Ollama
10
+ server, OpenAI itself).
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @c9up/polaris
16
+ ```
17
+
18
+ Register the provider in `reamrc.ts`:
19
+
20
+ ```ts
21
+ providers: [() => import('@c9up/polaris/provider')]
22
+ ```
23
+
24
+ ## Configure
25
+
26
+ `config/polaris.ts` declares the providers by name and picks a default:
27
+
28
+ ```ts
29
+ import { defineConfig, type InferProviders, providers } from '@c9up/polaris'
30
+
31
+ const polarisConfig = defineConfig({
32
+ default: 'claude',
33
+ providers: {
34
+ claude: providers.anthropic({
35
+ model: 'claude-opus-5-5',
36
+ apiKey: env.get('ANTHROPIC_API_KEY'),
37
+ }),
38
+ },
39
+ // Optional bounds, applied to every call:
40
+ timeout: 600_000, // ms, per call, streams included
41
+ maxResponseBytes: 32 * 1024 * 1024,
42
+ })
43
+
44
+ export default polarisConfig
45
+
46
+ declare module '@c9up/polaris/types' {
47
+ interface ProvidersList extends InferProviders<typeof polarisConfig> {}
48
+ }
49
+ ```
50
+
51
+ The `declare module` block makes `polaris.use('claude')` type-checked: a name
52
+ that is not in `providers` does not compile.
53
+
54
+ ## Send a request
55
+
56
+ ```ts
57
+ import polaris from '@c9up/polaris/services/main'
58
+
59
+ const reply = await polaris.use('claude').chat({
60
+ system: 'Answer in one sentence.',
61
+ messages: [{ role: 'user', content: 'What is a cross-border commuter?' }],
62
+ })
63
+
64
+ reply.text // the reply's text
65
+ reply.toolCalls // the tools the model asks to run
66
+ reply.stopReason // 'end', 'max_tokens', 'tool_use', 'refusal'…
67
+ reply.usage // input, output and cache tokens
68
+ ```
69
+
70
+ `polaris.chat()` without `use()` goes to the default provider.
71
+
72
+ ### Stream a reply
73
+
74
+ ```ts
75
+ for await (const event of polaris.stream({ messages })) {
76
+ if (event.type === 'text') process.stdout.write(event.text)
77
+ if (event.type === 'done') console.log(event.response.usage)
78
+ }
79
+ ```
80
+
81
+ The stream ends with one `done` event holding the whole response. Leaving the
82
+ loop early cancels the request to the provider.
83
+
84
+ ### Stream a reply to the browser
85
+
86
+ In a ream route, answer with an SSE stream and hand it to `streamTo()`:
87
+
88
+ ```ts
89
+ router.post('/chat', async ({ auth, request, response }) => {
90
+ // The question comes from the browser; the history comes from your
91
+ // database. Never take assistant turns or tool results from the client.
92
+ const { question } = await request.validateUsing(chatValidator)
93
+ const messages = [...(await conversations.history(auth.user)), { role: 'user', content: question }]
94
+
95
+ const sse = await response.sse()
96
+ void polaris.use('claude').streamTo(sse, { messages }).then((outcome) => {
97
+ if (outcome.status === 'failed') logger.error(outcome.error)
98
+ })
99
+ })
100
+ ```
101
+
102
+ Do not `await` it: ream starts sending the response once the handler has
103
+ returned, so an awaited stream would reach the browser all at once, at the end.
104
+ `streamTo()` never rejects; how it ended is in its result (`done`,
105
+ `client_left` or `failed`).
106
+
107
+ The browser receives named events: `text` and `reasoning` (`{ text }`),
108
+ `tool_call` (`{ id, name, input }`), then `done` (`{ id, provider, model, text,
109
+ stopReason, usage }`), after which the stream ends. `{ prefix: 'polaris.' }`
110
+ names them `polaris.text` and so on. When the browser leaves, the request to
111
+ the provider is cancelled, and you stop paying for a reply nobody reads. A
112
+ failure sends `error` with the polaris code only (`{ code: 'E_POLARIS_RATE_LIMITED' }`,
113
+ or `null` for another error): a message can carry details the page must not see.
114
+
115
+ The stream of the request is what carries the reply, rather than a relay
116
+ channel: it belongs to the one client waiting, and its close tells for sure
117
+ that the client left, even with several instances. To show the same reply to
118
+ other people as well (a consultant following the conversation), broadcast the
119
+ events on a relay channel next to it.
120
+
121
+ ### Embeddings
122
+
123
+ ```ts
124
+ const { vectors, model, dimensions } = await polaris.use('local').embed({ inputs: passages })
125
+ ```
126
+
127
+ One `Float32Array` per input, in input order, every one of `dimensions`
128
+ numbers. `model` is the model that answered: keep it with the vectors, so an
129
+ index can refuse vectors from another model, which would not compare.
130
+
131
+ A long list is split into batches of `embeddingBatchSize` inputs (128 by
132
+ default), sent one after the other, their order kept; polaris checks that
133
+ every batch answered with vectors of one size. `dimensions` in the request
134
+ asks a model that can shorten its vectors for that length.
135
+
136
+ Claude has no embedding model: `polaris.use('claude').features.embeddings` is
137
+ `false`, and `embed()` raises `E_POLARIS_UNSUPPORTED`.
138
+ Use an OpenAI-compatible provider with an `embeddingModel`, such as a local
139
+ Ollama (`bge-m3`, `nomic-embed-text`: the texts never leave the server),
140
+ Infomaniak in Switzerland (`bge_multilingual_gemma2`), Cloudflare Workers AI
141
+ (`@cf/baai/bge-m3`) or OpenAI (`text-embedding-3-small`).
142
+
143
+ ## Tools
144
+
145
+ A tool is a function the model may ask your application to run. Declare it
146
+ with a schema for its input, and let `run()` handle the back and forth:
147
+
148
+ ```ts
149
+ import rune from '@c9up/rune'
150
+ import { defineTool, ToolError } from '@c9up/polaris'
151
+
152
+ const cantonRule = defineTool({
153
+ name: 'canton_rule',
154
+ description: 'Look up a tax rule for a Swiss canton',
155
+ schema: rune.create({ canton: rune.string().minLength(2) }),
156
+ async run({ canton }) {
157
+ const rule = await rules.find(canton)
158
+ if (!rule) throw new ToolError(`No canton named '${canton}'.`)
159
+ return rule
160
+ },
161
+ })
162
+
163
+ const { response, messages, steps, usage } = await polaris.run(
164
+ { messages: [{ role: 'user', content: 'How is a cross-border commuter taxed in Geneva?' }], tools: [cantonRule] },
165
+ { maxSteps: 5, onToolError: (error, call) => logger.warn({ error, tool: call.name }) },
166
+ )
167
+ ```
168
+
169
+ `run()` sends the request, runs the tools the model calls, sends their results
170
+ back, and goes on until the model answers without calling a tool:
171
+
172
+ - The handler's input is typed from the schema, and checked by it first. Input
173
+ that fails the schema goes back to the model as an error it can correct; the
174
+ handler does not run.
175
+ - The calls of one turn run at the same time, and their results go back in one
176
+ message.
177
+ - A `ToolError`'s message is shown to the model. Any other error reaches it as
178
+ "The tool failed.": its message and stack stay on your server.
179
+ `onToolError` receives the real error.
180
+ - After `maxSteps` requests (8 by default) with the model still calling tools,
181
+ `run()` raises `E_POLARIS_TOO_MANY_STEPS`.
182
+ - A reply cut at the output limit, or refused, is returned without running its
183
+ tool calls, which may be incomplete.
184
+
185
+ The schema is any object that implements Standard Schema v1 and Standard JSON
186
+ Schema v1, as rune's schemas do. polaris itself depends on no validation
187
+ library. A returned string goes to the model as it is; anything else is sent as
188
+ JSON.
189
+
190
+ ## Structured output
191
+
192
+ `extract()` asks for one JSON value that matches a schema, and returns it typed
193
+ and validated:
194
+
195
+ ```ts
196
+ const profile = rune.create({
197
+ canton: rune.string().minLength(2),
198
+ borderCommuter: rune.boolean(),
199
+ })
200
+
201
+ const { value, attempts, usage } = await polaris.extract({
202
+ messages: conversation,
203
+ schema: profile,
204
+ name: 'profile',
205
+ description: "The person's situation, as far as the conversation tells",
206
+ })
207
+
208
+ value.canton // string, checked by the schema
209
+ ```
210
+
211
+ - The provider's own structured-output mode is used when it has one. Without
212
+ it, polaris gives the model a tool to call with the answer.
213
+ - The answer is always checked against the schema itself, constraints the
214
+ provider does not enforce included (`minLength`, `minimum`…).
215
+ - An answer that fails the schema, or is not JSON, goes back to the model with
216
+ the schema's issues, once by default (`{ retries: 2 }` to allow more). After
217
+ that, `extract()` raises `E_POLARIS_INVALID_OUTPUT`; its `cause.issues` lists
218
+ what was wrong.
219
+ - A refused answer, or one cut at the output limit, raises at once: asking
220
+ again the same way would not help.
221
+
222
+ ## Claude
223
+
224
+ `providers.anthropic()` talks to Claude through the official SDK. Install it
225
+ next to polaris; it is loaded the first time the provider is used:
226
+
227
+ ```sh
228
+ pnpm add @anthropic-ai/sdk
229
+ ```
230
+
231
+ | Option | What it does |
232
+ |---|---|
233
+ | `model` | The model every request uses, unless the request names another. Required. |
234
+ | `apiKey` | The API key. Without it, the SDK reads `ANTHROPIC_API_KEY`. |
235
+ | `baseURL` | Another endpoint that speaks the Anthropic API. |
236
+ | `maxTokens` | The output limit when a request sets none. Default 16 000, or 64 000 for a stream. |
237
+ | `maxRetries` | How many times a rate-limited, overloaded or failed request is retried, following the API's `retry-after`. Default 2. All retries stay within the call's deadline. |
238
+ | `fallbacks` | When the model declines a request, run it again on a fallback model: `'default'` lets the API choose, or name the models. Recommended on the current Opus, Sonnet and Fable models. |
239
+ | `betas` | Extra `anthropic-beta` flags sent with every request. |
240
+
241
+ Fields polaris does not model go through `providerOptions.anthropic`, as they
242
+ are written in the API:
243
+
244
+ ```ts
245
+ await polaris.chat({
246
+ messages,
247
+ providerOptions: { anthropic: { thinking: { type: 'adaptive', display: 'summarized' } } },
248
+ })
249
+ ```
250
+
251
+ A structured output's schema is rewritten into what Claude accepts (every
252
+ object closed with `additionalProperties: false`, unsupported constraints moved
253
+ into the description), with the SDK's own rewrite; polaris then checks the
254
+ answer against your full schema.
255
+
256
+ Claude's reasoning comes back as `reasoning` parts. Every part of a reply keeps
257
+ the block Claude sent (`origin`), so a reply passed back in the next request
258
+ reaches Claude exactly as Claude wrote it: Claude rejects a history whose
259
+ reasoning was altered. Blocks with no neutral equivalent, such as the result
260
+ of a server-side tool, come back as `provider` parts for the same reason.
261
+
262
+ ## OpenAI-compatible services
263
+
264
+ `providers.openaiCompatible()` talks to a service that speaks OpenAI's chat
265
+ completions API. It needs no SDK.
266
+
267
+ ```ts
268
+ providers: {
269
+ // A local Ollama server: no key, data never leaves the machine.
270
+ local: providers.openaiCompatible({
271
+ name: 'ollama',
272
+ baseURL: 'http://localhost:11434/v1',
273
+ model: 'qwen3',
274
+ embeddingModel: 'bge-m3',
275
+ }),
276
+ groq: providers.openaiCompatible({
277
+ name: 'groq',
278
+ baseURL: 'https://api.groq.com/openai/v1',
279
+ apiKey: env.get('GROQ_API_KEY'),
280
+ model: 'openai/gpt-oss-20b',
281
+ }),
282
+ workers: providers.openaiCompatible({
283
+ name: 'workers-ai',
284
+ baseURL: `https://api.cloudflare.com/client/v4/accounts/${env.get('CF_ACCOUNT_ID')}/ai/v1`,
285
+ apiKey: env.get('CF_API_TOKEN'),
286
+ model: '@cf/qwen/qwen3-30b-a3b-fp8',
287
+ }),
288
+ // Hosted in Switzerland: "data centers in Switzerland", requests neither
289
+ // stored nor used for training (infomaniak.com/en/hosting/llm-api).
290
+ swiss: providers.openaiCompatible({
291
+ name: 'infomaniak',
292
+ baseURL: `https://api.infomaniak.com/2/ai/${env.get('INFOMANIAK_PRODUCT_ID')}/openai/v1`,
293
+ apiKey: env.get('INFOMANIAK_TOKEN'),
294
+ model: 'Qwen/Qwen3-VL-235B-A22B-Instruct',
295
+ maxTokensField: 'max_completion_tokens',
296
+ }),
297
+ }
298
+ ```
299
+
300
+ | Option | What it does |
301
+ |---|---|
302
+ | `baseURL` | The API's base URL, up to and including `/v1`. Required. |
303
+ | `model` | The chat model every request uses, unless the request names another. Required. |
304
+ | `apiKey` | Sent as a bearer token. Leave it out for a server that needs none. |
305
+ | `name` | The provider's name in responses and in `providerOptions`. Default `openai-compatible`. |
306
+ | `embeddingModel` | The embedding model. Without it, the provider does not embed. |
307
+ | `embeddingBatchSize` | Inputs per embedding request; a longer list is sent in batches, in order. Default 128. |
308
+ | `features` | What the model supports: `{ tools, structuredOutput, images }`. Default: tools and structured output on, images off. |
309
+ | `maxTokens` | The output limit when a request sets none. Default 16 000. |
310
+ | `maxTokensField` | `max_tokens` (default: Ollama, Workers AI) or `max_completion_tokens` (Infomaniak). |
311
+ | `streamUsage` | Ask a stream for its token usage. Default true; turn it off for a service that rejects the field. |
312
+ | `maxRetries` | How many times a rate-limited, overloaded or failed request is retried, following `retry-after`. Default 2. |
313
+ | `headers` | Further headers sent with every request. |
314
+
315
+ What a model can do depends on the model, not on the API: declare it in
316
+ `features`, and polaris refuses a request asking for more before sending it.
317
+ Reasoning comes back as `reasoning` parts, wherever the service puts it
318
+ (`reasoning` for Groq and Ollama, `reasoning_content` for Workers AI). A tool
319
+ call whose arguments are not valid JSON keeps the string the model wrote, so
320
+ your validation refuses it.
321
+
322
+ Notes on the services, from their documentation:
323
+
324
+ - **Ollama** ignores `toolChoice`, and reports an error met mid-stream inside
325
+ the stream; polaris raises it as `E_POLARIS_PROVIDER_UNAVAILABLE`.
326
+ - **Groq** offers strict structured output on a few models only, and none while
327
+ streaming or with tools.
328
+ - **Infomaniak** streams unless told not to (polaris always says), reads only
329
+ `max_completion_tokens`, and rejects the older `json_object` format (polaris
330
+ only sends `json_schema`).
331
+ - **Workers AI** documents structured output for a few models only, and none
332
+ while streaming.
333
+
334
+ ## Cost, budgets and the exchange log
335
+
336
+ Declare your prices, and every response carries its cost, computed exactly
337
+ with `@c9up/atom` (decimal strings, never floating point):
338
+
339
+ ```ts
340
+ defineConfig({
341
+ providers: { claude: providers.anthropic({ model: 'claude-opus-5-5' }) },
342
+ pricing: {
343
+ currency: 'USD',
344
+ // Per million tokens, by the model id the provider answers with.
345
+ models: { 'claude-opus-5-5': { input: '4', output: '20', cacheRead: '0.2' } },
346
+ },
347
+ })
348
+
349
+ const reply = await polaris.chat(request)
350
+ reply.cost // for example { amount: '0.0114', currency: 'USD' }
351
+ reply.usage // { inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }
352
+ ```
353
+
354
+ The three input counts never overlap: `inputTokens` are the tokens billed at
355
+ the full input price, neither read from nor written to a cache. Cache prices
356
+ default to the input price. `run()` and `extract()` add up the cost of their
357
+ requests.
358
+
359
+ ### Budgets
360
+
361
+ A budget limits what a scope (a user, a tenant) may spend:
362
+
363
+ ```ts
364
+ defineConfig({
365
+ // ...
366
+ budget: {
367
+ limit: (scope) => (scope.startsWith('user:') ? '5' : undefined),
368
+ store: redisBudgetStore, // `add(scope, amount)` must be atomic
369
+ },
370
+ })
371
+
372
+ await polaris.chat(request, { scope: `user:${user.id}` })
373
+ await polaris.chat(request, { maxCost: '0.50' }) // a ceiling for this one request
374
+ ```
375
+
376
+ Before a request is sent, its most expensive outcome is estimated: its input
377
+ from its length (erring high) and its output at the full `maxTokens`. That
378
+ estimate is reserved on the scope; if the total would pass the limit, the
379
+ reservation is taken back and the request refused with
380
+ `E_POLARIS_BUDGET_EXCEEDED`, before anything is sent. Once the reply is in,
381
+ the reservation is replaced by the real cost. Reserving rather than reading
382
+ the spend is what keeps requests sent at the same moment from passing the
383
+ limit together. A failed request gives its reservation back; a stream the
384
+ client left after it started keeps it, as the provider may bill it.
385
+
386
+ The default store is in memory: one process, lost on restart. A scope with no
387
+ limit is neither refused nor counted. A budget needs a price for the model
388
+ asked for, or the request is refused with `E_POLARIS_UNKNOWN_PRICE`: a budget
389
+ cannot be kept for a model whose cost is unknown.
390
+
391
+ ### Exchange log
392
+
393
+ ```ts
394
+ defineConfig({
395
+ // ...
396
+ log: { handler: (entry) => logger.info(entry, 'llm exchange') },
397
+ })
398
+ ```
399
+
400
+ Every exchange reaches `handler`: provider, model, operation, status (`ok`,
401
+ `error`, `cancelled`), the polaris error code, stop reason, usage, cost,
402
+ duration and scope. It holds no message content: conversations carry personal
403
+ data. `content: true` adds the request and the response; `redact(entry)` runs
404
+ before every entry is handed over, to take out what must not be kept. A
405
+ per-call key never appears in an entry, and a handler that throws does not
406
+ fail the call.
407
+
408
+ ## A key per call
409
+
410
+ When each account brings its own provider key, pass it with the call:
411
+
412
+ ```ts
413
+ await polaris.use('claude').chat(request, { apiKey: account.llmKey })
414
+ ```
415
+
416
+ It replaces the configured key for that call only. If the provider's error
417
+ mentions the key, polaris replaces the error with `E_POLARIS_PROVIDER_FAILED`,
418
+ whose message has the key taken out and which keeps no reference to the
419
+ original error.
420
+
421
+ ## Limits and cancellation
422
+
423
+ Every call runs under a deadline (`timeout`, overridable per call) and reads at
424
+ most `maxResponseBytes` from the provider. Pass `signal` to cancel a call:
425
+
426
+ ```ts
427
+ await polaris.chat(request, { signal: AbortSignal.timeout(5_000) })
428
+ ```
429
+
430
+ A call that runs out of time raises `E_POLARIS_TIMEOUT`. A call cancelled by
431
+ your signal rejects with your signal's reason.
432
+
433
+ ## Checked before sending
434
+
435
+ polaris checks a request against what the provider supports before anything
436
+ leaves the server. Asking a provider for something it cannot do raises
437
+ `E_POLARIS_UNSUPPORTED` the same way on every provider: tools, structured
438
+ output, images, streaming or embeddings.
439
+
440
+ ## Testing
441
+
442
+ `polaris.fake()` makes every provider answer from a script until `restore()`:
443
+ no network, no key.
444
+
445
+ ```ts
446
+ const fake = polaris.fake()
447
+ fake
448
+ .reply('Bonjour') // a text reply
449
+ .callTool('canton_rule', { canton: 'GE' }) // a turn that calls a tool
450
+ .replyJson({ canton: 'VD', borderCommuter: true }) // a structured answer
451
+ .reply({ text: 'Hello', chunks: ['Hel', 'lo'], usage: { inputTokens: 900, outputTokens: 40 } })
452
+ .fail(new errors.E_POLARIS_RATE_LIMITED(['fake', 'slow down']))
453
+
454
+ await assistant.answer(question)
455
+
456
+ fake.assertSent((request) => request.system?.includes('newcomer'))
457
+ fake.assertSentCount(2)
458
+ fake.calls // every call: operation, provider, request, per-call key
459
+ polaris.restore()
460
+ ```
461
+
462
+ Each request takes the next scripted reply, in order; a request the script
463
+ did not plan for raises `E_POLARIS_FAKE_NO_REPLY`. `replyJson()` answers as
464
+ structured output, or through the answer's tool when the fake is told it has
465
+ no structured output (`polaris.fake({ features: { structuredOutput: false } })`).
466
+ Streams send the reply's chunks, then `done`. Embeddings return the same
467
+ vector for the same text (`fake.embedWith(fn)` to choose them).
468
+
469
+ The fake reports usage (10 input and 10 output tokens unless the reply says
470
+ otherwise), so prices, budgets and the exchange log run as they would against
471
+ a provider. It answers with the model `fake-model` unless the request names
472
+ one: give it a price to test cost code.
473
+
474
+ `FakeProvider` is also exported from `@c9up/polaris/testing`, to declare it as
475
+ a provider of its own: `providers: { main: () => fake.driver('main') }`.
476
+
477
+ ## Write a driver
478
+
479
+ A driver is an object with a provider name, the features it supports and a
480
+ `chat()` method. `stream()` and `embed()` are optional.
481
+
482
+ ```ts
483
+ import { createResponse, type PolarisDriver } from '@c9up/polaris'
484
+
485
+ export function myDriver(options: { apiKey: string }): PolarisDriver {
486
+ return {
487
+ provider: 'my-provider',
488
+ features: { tools: false, structuredOutput: false, images: false },
489
+ async chat(request, call) {
490
+ const response = await call.fetch('https://llm.example/v1/chat', {
491
+ method: 'POST',
492
+ signal: call.signal,
493
+ headers: { authorization: `Bearer ${call.apiKey ?? options.apiKey}` },
494
+ body: JSON.stringify({ messages: request.messages }),
495
+ })
496
+ const body = await response.json()
497
+ return createResponse({
498
+ id: body.id,
499
+ provider: 'my-provider',
500
+ model: body.model,
501
+ content: [{ type: 'text', text: body.text }],
502
+ stopReason: 'end',
503
+ usage: { inputTokens: body.input_tokens, outputTokens: body.output_tokens },
504
+ })
505
+ },
506
+ }
507
+ }
508
+ ```
509
+
510
+ Send every HTTP request through `call.fetch` with `call.signal`: that is how
511
+ the deadline, the size limit and cancellation reach the network.
512
+
513
+ ## Errors
514
+
515
+ | Code | When |
516
+ |---|---|
517
+ | `E_POLARIS_MISSING_CONFIG` | The application has no `polaris` config. |
518
+ | `E_POLARIS_INVALID_CONFIG` | A config value or a call option is out of range. |
519
+ | `E_POLARIS_NO_DEFAULT_PROVIDER` | `use()` without a name, and no `default`. |
520
+ | `E_POLARIS_UNKNOWN_PROVIDER` | `use(name)` names an undeclared provider. |
521
+ | `E_POLARIS_INVALID_REQUEST` | No messages, a bad token limit, two tools with one name… |
522
+ | `E_POLARIS_UNSUPPORTED` | The provider cannot serve what the request asks for. |
523
+ | `E_POLARIS_TIMEOUT` | The call ran past its deadline. |
524
+ | `E_POLARIS_RESPONSE_TOO_LARGE` | The provider sent more than `maxResponseBytes`. |
525
+ | `E_POLARIS_STREAM_INCOMPLETE` | A stream ended without its final response. |
526
+ | `E_POLARIS_BUDGET_EXCEEDED` | A request would pass its `maxCost` or its scope's budget. Nothing was sent. HTTP status 429. |
527
+ | `E_POLARIS_UNKNOWN_PRICE` | A budget applies, but `pricing` has no price for the model. Nothing was sent. |
528
+ | `E_POLARIS_INVALID_OUTPUT` | `extract()` got no answer matching the schema, after its retries; or the answer was refused or cut. |
529
+ | `E_POLARIS_TOO_MANY_STEPS` | `run()` reached `maxSteps` with the model still calling tools. |
530
+ | `E_POLARIS_INVALID_RESPONSE` | A driver broke the contract (wrong number of vectors…). |
531
+ | `E_POLARIS_AUTHENTICATION` | The provider refused the key (401, 403). HTTP status 502. |
532
+ | `E_POLARIS_RATE_LIMITED` | The provider is rate limiting, after the retries. HTTP status 503. |
533
+ | `E_POLARIS_PROVIDER_UNAVAILABLE` | The provider is overloaded or failing, after the retries. HTTP status 503. |
534
+ | `E_POLARIS_PROVIDER_REJECTED` | The provider rejected the request itself (400, 404…). HTTP status 502. |
535
+ | `E_POLARIS_PROVIDER_UNREACHABLE` | The provider could not be reached. HTTP status 502. |
536
+ | `E_POLARIS_PROVIDER_FAILED` | A provider error mentioned the call's key; the key is removed. |
537
+ | `E_POLARIS_FAKE_NO_REPLY` | The test fake was asked for a reply it was not given. |
538
+ | `E_POLARIS_ASSERTION_FAILED` | An assertion of the test fake does not hold. |
539
+ | `E_POLARIS_NOT_BOOTED` | `services/main` was used before the provider booted. |
540
+
541
+ ## License
542
+
543
+ MIT
@@ -0,0 +1,76 @@
1
+ import type { ExtractRequest, ExtractResult } from "./extract.js";
2
+ import { type CallOptions, type ExtractOptions, PolarisClient, type RunOptions, type RunRequest, type RunResult, type StreamToOptions } from "./PolarisClient.js";
3
+ import type { SchemaOutput, StandardSchema } from "./schema.js";
4
+ import type { SseSink, StreamToResult } from "./sse.js";
5
+ import { type FakeOptions, FakeProvider } from "./testing/FakeProvider.js";
6
+ import type { ChatRequest, ChatResponse, EmbedRequest, EmbedResponse, PolarisConfig, ProviderFactory, ProvidersList, StreamEvent } from "./types.js";
7
+ /**
8
+ * Declare the providers an application talks to.
9
+ *
10
+ * const polarisConfig = defineConfig({
11
+ * default: 'claude',
12
+ * providers: {
13
+ * claude: providers.anthropic({ apiKey: env.get('ANTHROPIC_API_KEY'), model: 'claude-opus-5-5' }),
14
+ * },
15
+ * })
16
+ * export default polarisConfig
17
+ *
18
+ * declare module '@c9up/polaris/types' {
19
+ * interface ProvidersList extends InferProviders<typeof polarisConfig> {}
20
+ * }
21
+ *
22
+ * The shape is @adonisjs/mail's (`default`, named entries built by helpers,
23
+ * a list interface the application augments). Adonis has no LLM package.
24
+ *
25
+ * NAMED DEVIATION: it returns the config itself, where @adonisjs/mail wraps it
26
+ * in a `ConfigProvider` resolved at boot. A provider factory needs nothing
27
+ * from the application, and the other packages of this cohort (rover, nova)
28
+ * return plain config the same way.
29
+ */
30
+ export declare function defineConfig<KnownProviders extends Record<string, ProviderFactory>>(config: PolarisConfig<KnownProviders>): PolarisConfig<KnownProviders>;
31
+ /**
32
+ * The providers the application declared in {@link ProvidersList}, as an
33
+ * object type `Polaris` can take. A mapped type, because an interface carries
34
+ * no index signature and is never assignable to a `Record`.
35
+ */
36
+ export type DeclaredProviders = {
37
+ [K in keyof ProvidersList & string]: Extract<ProvidersList[K], ProviderFactory>;
38
+ };
39
+ /** The manager `@c9up/polaris/services/main` and the container hand out. */
40
+ export type PolarisService = Polaris<DeclaredProviders>;
41
+ /**
42
+ * The provider manager: builds each declared provider the first time it is
43
+ * used and keeps it for the life of the process.
44
+ */
45
+ export declare class Polaris<KnownProviders extends Record<string, ProviderFactory>> {
46
+ #private;
47
+ constructor(config: PolarisConfig<KnownProviders>);
48
+ /**
49
+ * The provider declared under `name`, or the `default` one. Built on first
50
+ * use, then the same instance every time.
51
+ */
52
+ use<K extends keyof KnownProviders & string>(name?: K): PolarisClient;
53
+ /**
54
+ * Answer every request from a script instead of the providers, until
55
+ * `restore()`: for tests. Prices, budgets and the log apply as usual.
56
+ *
57
+ * const fake = polaris.fake()
58
+ * fake.reply('Bonjour')
59
+ */
60
+ fake(options?: FakeOptions): FakeProvider;
61
+ /** Back to the real providers after `fake()`. */
62
+ restore(): void;
63
+ /** `use().chat()`: the default provider. */
64
+ chat(request: ChatRequest, options?: CallOptions): Promise<ChatResponse>;
65
+ /** `use().stream()`: the default provider. */
66
+ stream(request: ChatRequest, options?: CallOptions): AsyncGenerator<StreamEvent, void, undefined>;
67
+ /** `use().run()`: the default provider. */
68
+ run(request: RunRequest, options?: RunOptions): Promise<RunResult>;
69
+ /** `use().streamTo()`: the default provider. */
70
+ streamTo(sink: SseSink, request: ChatRequest, options?: StreamToOptions): Promise<StreamToResult>;
71
+ /** `use().extract()`: the default provider. */
72
+ extract<S extends StandardSchema>(request: ExtractRequest<S>, options?: ExtractOptions): Promise<ExtractResult<SchemaOutput<S>>>;
73
+ /** `use().embed()`: the default provider. */
74
+ embed(request: EmbedRequest, options?: CallOptions): Promise<EmbedResponse>;
75
+ }
76
+ //# sourceMappingURL=Polaris.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Polaris.d.ts","sourceRoot":"","sources":["../src/Polaris.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClE,OAAO,EACN,KAAK,WAAW,EAEhB,KAAK,cAAc,EAGnB,aAAa,EACb,KAAK,UAAU,EACf,KAAK,UAAU,EACf,KAAK,SAAS,EACd,KAAK,eAAe,EACpB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAChE,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AACxD,OAAO,EAAE,KAAK,WAAW,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC3E,OAAO,KAAK,EACX,WAAW,EACX,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,aAAa,EAEb,eAAe,EACf,aAAa,EACb,WAAW,EACX,MAAM,YAAY,CAAC;AAKpB;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,YAAY,CAC3B,cAAc,SAAS,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC,EACrD,MAAM,EAAE,aAAa,CAAC,cAAc,CAAC,GAAG,aAAa,CAAC,cAAc,CAAC,CAEtE;AAED;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GAAG;KAC9B,CAAC,IAAI,MAAM,aAAa,GAAG,MAAM,GAAG,OAAO,CAC3C,aAAa,CAAC,CAAC,CAAC,EAChB,eAAe,CACf;CACD,CAAC;AAEF,4EAA4E;AAC5E,MAAM,MAAM,cAAc,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;AAExD;;;GAGG;AACH,qBAAa,OAAO,CAAC,cAAc,SAAS,MAAM,CAAC,MAAM,EAAE,eAAe,CAAC;;gBAY9D,MAAM,EAAE,aAAa,CAAC,cAAc,CAAC;IAqEjD;;;OAGG;IACH,GAAG,CAAC,CAAC,SAAS,MAAM,cAAc,GAAG,MAAM,EAAE,IAAI,CAAC,EAAE,CAAC,GAAG,aAAa;IAwCrE;;;;;;OAMG;IACH,IAAI,CAAC,OAAO,CAAC,EAAE,WAAW,GAAG,YAAY;IAMzC,iDAAiD;IACjD,OAAO,IAAI,IAAI;IAIf,4CAA4C;IAC5C,IAAI,CAAC,OAAO,EAAE,WAAW,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC;IAIxE,8CAA8C;IAC9C,MAAM,CACL,OAAO,EAAE,WAAW,EACpB,OAAO,CAAC,EAAE,WAAW,GACnB,cAAc,CAAC,WAAW,EAAE,IAAI,EAAE,SAAS,CAAC;IAI/C,2CAA2C;IAC3C,GAAG,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC;IAIlE,gDAAgD;IAChD,QAAQ,CACP,IAAI,EAAE,OAAO,EACb,OAAO,EAAE,WAAW,EACpB,OAAO,CAAC,EAAE,eAAe,GACvB,OAAO,CAAC,cAAc,CAAC;IAI1B,+CAA+C;IAC/C,OAAO,CAAC,CAAC,SAAS,cAAc,EAC/B,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,EAC1B,OAAO,CAAC,EAAE,cAAc,GACtB,OAAO,CAAC,aAAa,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC;IAI1C,6CAA6C;IAC7C,KAAK,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,aAAa,CAAC;CAG3E"}