@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.
- package/LICENSE +21 -0
- package/README.md +542 -2
- package/dist/Polaris.d.ts +76 -0
- package/dist/Polaris.d.ts.map +1 -0
- package/dist/Polaris.js +194 -0
- package/dist/Polaris.js.map +1 -0
- package/dist/PolarisClient.d.ts +136 -0
- package/dist/PolarisClient.d.ts.map +1 -0
- package/dist/PolarisClient.js +408 -0
- package/dist/PolarisClient.js.map +1 -0
- package/dist/PolarisProvider.d.ts +35 -0
- package/dist/PolarisProvider.d.ts.map +1 -0
- package/dist/PolarisProvider.js +47 -0
- package/dist/PolarisProvider.js.map +1 -0
- package/dist/augmentations.d.ts +15 -0
- package/dist/augmentations.d.ts.map +1 -0
- package/dist/augmentations.js +9 -0
- package/dist/augmentations.js.map +1 -0
- package/dist/budget.d.ts +44 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +67 -0
- package/dist/budget.js.map +1 -0
- package/dist/cost.d.ts +48 -0
- package/dist/cost.d.ts.map +1 -0
- package/dist/cost.js +126 -0
- package/dist/cost.js.map +1 -0
- package/dist/drivers/anthropic.d.ts +39 -0
- package/dist/drivers/anthropic.d.ts.map +1 -0
- package/dist/drivers/anthropic.js +394 -0
- package/dist/drivers/anthropic.js.map +1 -0
- package/dist/drivers/openai-compatible.d.ts +54 -0
- package/dist/drivers/openai-compatible.d.ts.map +1 -0
- package/dist/drivers/openai-compatible.js +663 -0
- package/dist/drivers/openai-compatible.js.map +1 -0
- package/dist/drivers/status.d.ts +8 -0
- package/dist/drivers/status.d.ts.map +1 -0
- package/dist/drivers/status.js +21 -0
- package/dist/drivers/status.js.map +1 -0
- package/dist/errors.d.ts +55 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +62 -0
- package/dist/errors.js.map +1 -0
- package/dist/extract.d.ts +38 -0
- package/dist/extract.d.ts.map +1 -0
- package/dist/extract.js +144 -0
- package/dist/extract.js.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +13 -0
- package/dist/index.js.map +1 -0
- package/dist/log.d.ts +47 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +33 -0
- package/dist/log.js.map +1 -0
- package/dist/meter.d.ts +57 -0
- package/dist/meter.d.ts.map +1 -0
- package/dist/meter.js +91 -0
- package/dist/meter.js.map +1 -0
- package/dist/providers.d.ts +23 -0
- package/dist/providers.d.ts.map +1 -0
- package/dist/providers.js +21 -0
- package/dist/providers.js.map +1 -0
- package/dist/redact.d.ts +11 -0
- package/dist/redact.d.ts.map +1 -0
- package/dist/redact.js +76 -0
- package/dist/redact.js.map +1 -0
- package/dist/response.d.ts +21 -0
- package/dist/response.d.ts.map +1 -0
- package/dist/response.js +45 -0
- package/dist/response.js.map +1 -0
- package/dist/schema.d.ts +45 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +43 -0
- package/dist/schema.js.map +1 -0
- package/dist/services/main.d.ts +23 -0
- package/dist/services/main.d.ts.map +1 -0
- package/dist/services/main.js +43 -0
- package/dist/services/main.js.map +1 -0
- package/dist/sse.d.ts +58 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +91 -0
- package/dist/sse.js.map +1 -0
- package/dist/testing/FakeProvider.d.ts +85 -0
- package/dist/testing/FakeProvider.d.ts.map +1 -0
- package/dist/testing/FakeProvider.js +213 -0
- package/dist/testing/FakeProvider.js.map +1 -0
- package/dist/testing/index.d.ts +7 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +7 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/tools.d.ts +68 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +107 -0
- package/dist/tools.js.map +1 -0
- package/dist/transport.d.ts +18 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +68 -0
- package/dist/transport.js.map +1 -0
- package/dist/types.d.ts +293 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +12 -0
- package/dist/types.js.map +1 -0
- package/package.json +76 -3
- package/src/Polaris.ts +280 -0
- package/src/PolarisClient.ts +591 -0
- package/src/PolarisProvider.ts +73 -0
- package/src/augmentations.ts +17 -0
- package/src/budget.ts +101 -0
- package/src/cost.ts +170 -0
- package/src/drivers/anthropic.ts +520 -0
- package/src/drivers/openai-compatible.ts +840 -0
- package/src/drivers/status.ts +30 -0
- package/src/errors.ts +161 -0
- package/src/extract.ts +214 -0
- package/src/index.ts +69 -0
- package/src/log.ts +84 -0
- package/src/meter.ts +188 -0
- package/src/providers.ts +25 -0
- package/src/redact.ts +78 -0
- package/src/response.ts +65 -0
- package/src/schema.ts +88 -0
- package/src/services/main.ts +49 -0
- package/src/sse.ts +128 -0
- package/src/testing/FakeProvider.ts +321 -0
- package/src/testing/index.ts +12 -0
- package/src/tools.ts +166 -0
- package/src/transport.ts +85 -0
- package/src/types.ts +328 -0
|
@@ -0,0 +1,591 @@
|
|
|
1
|
+
import type { Cost } from "./cost.js";
|
|
2
|
+
import { estimateChat, estimateEmbed } from "./cost.js";
|
|
3
|
+
import {
|
|
4
|
+
E_POLARIS_INVALID_CONFIG,
|
|
5
|
+
E_POLARIS_INVALID_REQUEST,
|
|
6
|
+
E_POLARIS_INVALID_RESPONSE,
|
|
7
|
+
E_POLARIS_STREAM_INCOMPLETE,
|
|
8
|
+
E_POLARIS_TIMEOUT,
|
|
9
|
+
E_POLARIS_UNSUPPORTED,
|
|
10
|
+
} from "./errors.js";
|
|
11
|
+
import { type ExtractRequest, type ExtractResult, extract } from "./extract.js";
|
|
12
|
+
import { addCost, type MeterConfig, openTicket, type Ticket } from "./meter.js";
|
|
13
|
+
import { scrub } from "./redact.js";
|
|
14
|
+
import { addUsage, NO_USAGE } from "./response.js";
|
|
15
|
+
import type { SchemaOutput, StandardSchema } from "./schema.js";
|
|
16
|
+
import {
|
|
17
|
+
ClientLeft,
|
|
18
|
+
pipeToSse,
|
|
19
|
+
type SseSink,
|
|
20
|
+
type StreamToResult,
|
|
21
|
+
} from "./sse.js";
|
|
22
|
+
import { type PolarisTool, runToolCalls, tooManySteps } from "./tools.js";
|
|
23
|
+
import { boundFetch, untilAborted } from "./transport.js";
|
|
24
|
+
import type {
|
|
25
|
+
ChatRequest,
|
|
26
|
+
ChatResponse,
|
|
27
|
+
DriverCall,
|
|
28
|
+
DriverFeatures,
|
|
29
|
+
EmbedRequest,
|
|
30
|
+
EmbedResponse,
|
|
31
|
+
Message,
|
|
32
|
+
PolarisDriver,
|
|
33
|
+
StreamEvent,
|
|
34
|
+
ToolCallPart,
|
|
35
|
+
Transport,
|
|
36
|
+
Usage,
|
|
37
|
+
} from "./types.js";
|
|
38
|
+
|
|
39
|
+
/** Options for one call. */
|
|
40
|
+
export interface CallOptions {
|
|
41
|
+
/** Cancels the call. */
|
|
42
|
+
readonly signal?: AbortSignal;
|
|
43
|
+
/**
|
|
44
|
+
* A key for this call only (an account's own key), used instead of the
|
|
45
|
+
* configured one. It never appears in an error polaris raises.
|
|
46
|
+
*/
|
|
47
|
+
readonly apiKey?: string;
|
|
48
|
+
/** Overrides the configured deadline for this call, in ms. */
|
|
49
|
+
readonly timeout?: number;
|
|
50
|
+
/**
|
|
51
|
+
* The budget scope this call is charged to (`user:42`, `tenant:7`): its
|
|
52
|
+
* estimated cost is reserved first, and the call refused if the scope's
|
|
53
|
+
* limit would be passed.
|
|
54
|
+
*/
|
|
55
|
+
readonly scope?: string;
|
|
56
|
+
/** The most this one request may cost, as a decimal string in the pricing currency. */
|
|
57
|
+
readonly maxCost?: string;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A request whose tools polaris runs itself. */
|
|
61
|
+
export type RunRequest = Omit<ChatRequest, "tools"> & {
|
|
62
|
+
readonly tools: readonly PolarisTool[];
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export interface RunOptions extends CallOptions {
|
|
66
|
+
/** Requests sent at most, the first included. Default 8. */
|
|
67
|
+
readonly maxSteps?: number;
|
|
68
|
+
/**
|
|
69
|
+
* Told of every failed tool call: invalid input, an unknown tool, a handler
|
|
70
|
+
* that threw. The model only reads a short message; this gets the error.
|
|
71
|
+
*/
|
|
72
|
+
readonly onToolError?: (error: unknown, call: ToolCallPart) => void;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface RunResult {
|
|
76
|
+
/** The last reply: the one that did not call tools. */
|
|
77
|
+
readonly response: ChatResponse;
|
|
78
|
+
/** The whole conversation: the request's messages, then every turn of the run. */
|
|
79
|
+
readonly messages: readonly Message[];
|
|
80
|
+
/** Requests sent. */
|
|
81
|
+
readonly steps: number;
|
|
82
|
+
/** Tokens of every request of the run, added up. */
|
|
83
|
+
readonly usage: Usage;
|
|
84
|
+
/** What every request of the run cost, added up, when each one is priced. */
|
|
85
|
+
readonly cost?: Cost;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const DEFAULT_MAX_STEPS = 8;
|
|
89
|
+
|
|
90
|
+
export interface StreamToOptions extends CallOptions {
|
|
91
|
+
/** Put before every event name: `polaris.` sends `polaris.text`… Default none. */
|
|
92
|
+
readonly prefix?: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export interface ExtractOptions extends CallOptions {
|
|
96
|
+
/** Requests sent again after an answer that failed the schema. Default 1. */
|
|
97
|
+
readonly retries?: number;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** The bounds every call of a client runs under. */
|
|
101
|
+
export interface ClientOptions {
|
|
102
|
+
readonly timeout: number;
|
|
103
|
+
readonly maxResponseBytes: number;
|
|
104
|
+
readonly fetch: Transport;
|
|
105
|
+
readonly meter: MeterConfig;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** `setTimeout`'s ceiling: a longer delay fires at once. */
|
|
109
|
+
export const MAX_TIMEOUT = 2_147_483_647;
|
|
110
|
+
/** Shorter than this, a string is not a key, and redacting it would garble every message. */
|
|
111
|
+
const MIN_KEY_LENGTH = 8;
|
|
112
|
+
|
|
113
|
+
/** Whether `value` is a usable deadline in ms. */
|
|
114
|
+
export function isTimeout(value: unknown): value is number {
|
|
115
|
+
return (
|
|
116
|
+
typeof value === "number" &&
|
|
117
|
+
Number.isInteger(value) &&
|
|
118
|
+
value > 0 &&
|
|
119
|
+
value <= MAX_TIMEOUT
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
interface PreparedCall {
|
|
124
|
+
readonly call: DriverCall;
|
|
125
|
+
readonly deadline: AbortSignal;
|
|
126
|
+
readonly timeout: number;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* One configured provider: what `polaris.use(name)` returns.
|
|
131
|
+
*
|
|
132
|
+
* Everything a request asks for is checked against what the driver declares
|
|
133
|
+
* before anything is sent, so an unsupported feature fails the same way on
|
|
134
|
+
* every provider. Every call runs under a deadline and a response size bound,
|
|
135
|
+
* and an error that mentions the call's own key is replaced before it leaves.
|
|
136
|
+
*/
|
|
137
|
+
export class PolarisClient {
|
|
138
|
+
readonly #name: string;
|
|
139
|
+
readonly #driver: PolarisDriver;
|
|
140
|
+
readonly #options: ClientOptions;
|
|
141
|
+
|
|
142
|
+
constructor(name: string, driver: PolarisDriver, options: ClientOptions) {
|
|
143
|
+
this.#name = name;
|
|
144
|
+
this.#driver = driver;
|
|
145
|
+
this.#options = options;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The name this provider has in the config. */
|
|
149
|
+
get name(): string {
|
|
150
|
+
return this.#name;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The provider behind it, as its driver names itself. */
|
|
154
|
+
get provider(): string {
|
|
155
|
+
return this.#driver.provider;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
get features(): DriverFeatures & {
|
|
159
|
+
readonly streaming: boolean;
|
|
160
|
+
readonly embeddings: boolean;
|
|
161
|
+
} {
|
|
162
|
+
return {
|
|
163
|
+
...this.#driver.features,
|
|
164
|
+
streaming: this.#driver.stream !== undefined,
|
|
165
|
+
embeddings: this.#driver.embed !== undefined,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Send a request and wait for the whole reply. */
|
|
170
|
+
async chat(
|
|
171
|
+
request: ChatRequest,
|
|
172
|
+
options: CallOptions = {},
|
|
173
|
+
): Promise<ChatResponse> {
|
|
174
|
+
this.#checkChat(request);
|
|
175
|
+
const prepared = this.#prepare(options, undefined);
|
|
176
|
+
const ticket = await this.#openChat("chat", request, options, false);
|
|
177
|
+
let response: ChatResponse;
|
|
178
|
+
try {
|
|
179
|
+
response = await untilAborted(
|
|
180
|
+
this.#driver.chat(request, prepared.call),
|
|
181
|
+
prepared.call.signal,
|
|
182
|
+
);
|
|
183
|
+
} catch (error) {
|
|
184
|
+
const translated = this.#translate(error, prepared, options);
|
|
185
|
+
await ticket.fail(translated, {
|
|
186
|
+
cancelled: options.signal?.aborted === true,
|
|
187
|
+
spent: false,
|
|
188
|
+
});
|
|
189
|
+
throw translated;
|
|
190
|
+
}
|
|
191
|
+
return this.#priced(response, ticket);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Send a request and read the reply as it is written. The stream ends with
|
|
196
|
+
* one `done` event holding the whole response. Leaving the loop early
|
|
197
|
+
* cancels the provider request.
|
|
198
|
+
*/
|
|
199
|
+
async *stream(
|
|
200
|
+
request: ChatRequest,
|
|
201
|
+
options: CallOptions = {},
|
|
202
|
+
): AsyncGenerator<StreamEvent, void, undefined> {
|
|
203
|
+
this.#checkChat(request);
|
|
204
|
+
const driver = this.#driver;
|
|
205
|
+
const open = driver.stream;
|
|
206
|
+
if (open === undefined) {
|
|
207
|
+
throw new E_POLARIS_UNSUPPORTED([driver.provider, "streaming"]);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const stop = new AbortController();
|
|
211
|
+
const prepared = this.#prepare(options, stop.signal);
|
|
212
|
+
const ticket = await this.#openChat("stream", request, options, true);
|
|
213
|
+
let finished = false;
|
|
214
|
+
let started = false;
|
|
215
|
+
let settled = false;
|
|
216
|
+
let iterator: AsyncIterator<StreamEvent> | undefined;
|
|
217
|
+
try {
|
|
218
|
+
iterator = open
|
|
219
|
+
.call(driver, request, prepared.call)
|
|
220
|
+
[Symbol.asyncIterator]();
|
|
221
|
+
while (true) {
|
|
222
|
+
const next = await untilAborted(iterator.next(), prepared.call.signal);
|
|
223
|
+
if (next.done) break;
|
|
224
|
+
if (finished) {
|
|
225
|
+
throw new E_POLARIS_INVALID_RESPONSE([
|
|
226
|
+
driver.provider,
|
|
227
|
+
"an event came after the final `done`",
|
|
228
|
+
]);
|
|
229
|
+
}
|
|
230
|
+
started = true;
|
|
231
|
+
if (next.value.type === "done") {
|
|
232
|
+
finished = true;
|
|
233
|
+
settled = true;
|
|
234
|
+
yield {
|
|
235
|
+
type: "done",
|
|
236
|
+
response: await this.#priced(next.value.response, ticket),
|
|
237
|
+
};
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
yield next.value;
|
|
241
|
+
}
|
|
242
|
+
if (!finished) throw new E_POLARIS_STREAM_INCOMPLETE([driver.provider]);
|
|
243
|
+
} catch (error) {
|
|
244
|
+
const translated = this.#translate(error, prepared, options);
|
|
245
|
+
settled = true;
|
|
246
|
+
await ticket.fail(translated, {
|
|
247
|
+
cancelled: options.signal?.aborted === true,
|
|
248
|
+
spent: started,
|
|
249
|
+
});
|
|
250
|
+
throw translated;
|
|
251
|
+
} finally {
|
|
252
|
+
if (!finished) stop.abort();
|
|
253
|
+
// A consumer that left early: the provider was asked, and may bill it.
|
|
254
|
+
if (!settled) {
|
|
255
|
+
await ticket.fail(new ClientLeft(), {
|
|
256
|
+
cancelled: true,
|
|
257
|
+
spent: started,
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
await iterator?.return?.().catch(() => undefined);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Send a request and run the tools the model calls, until it answers
|
|
266
|
+
* without calling one. Each turn's calls run at once and are answered in
|
|
267
|
+
* one message. Input that fails a tool's schema goes back to the model as
|
|
268
|
+
* an error it can correct. A reply cut at the output limit or refused is
|
|
269
|
+
* returned as it is: its tool calls may be incomplete.
|
|
270
|
+
*/
|
|
271
|
+
async run(request: RunRequest, options: RunOptions = {}): Promise<RunResult> {
|
|
272
|
+
const maxSteps = options.maxSteps ?? DEFAULT_MAX_STEPS;
|
|
273
|
+
if (!isCount(maxSteps)) {
|
|
274
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
275
|
+
"`maxSteps` must be a positive integer",
|
|
276
|
+
]);
|
|
277
|
+
}
|
|
278
|
+
const tools = new Map(request.tools.map((tool) => [tool.name, tool]));
|
|
279
|
+
const definitions = request.tools.map((tool) => tool.definition);
|
|
280
|
+
const signal = options.signal ?? new AbortController().signal;
|
|
281
|
+
const messages: Message[] = [...request.messages];
|
|
282
|
+
let usage: Usage = NO_USAGE;
|
|
283
|
+
let cost: Cost | undefined;
|
|
284
|
+
let priced = true;
|
|
285
|
+
|
|
286
|
+
for (let step = 1; step <= maxSteps; step++) {
|
|
287
|
+
// A copy per request: the history grows after it is sent, and what a
|
|
288
|
+
// request carried must stay what it was (a log, a driver keeping it).
|
|
289
|
+
const response = await this.chat(
|
|
290
|
+
{ ...request, messages: [...messages], tools: definitions },
|
|
291
|
+
options,
|
|
292
|
+
);
|
|
293
|
+
usage = addUsage(usage, response.usage);
|
|
294
|
+
cost = addCost(cost, response.cost);
|
|
295
|
+
priced = priced && response.cost !== undefined;
|
|
296
|
+
messages.push(response.message);
|
|
297
|
+
|
|
298
|
+
// A paused turn goes back as it is, and the provider carries on.
|
|
299
|
+
if (response.stopReason === "pause") continue;
|
|
300
|
+
if (
|
|
301
|
+
response.stopReason !== "tool_use" ||
|
|
302
|
+
response.toolCalls.length === 0
|
|
303
|
+
) {
|
|
304
|
+
return {
|
|
305
|
+
response,
|
|
306
|
+
messages,
|
|
307
|
+
steps: step,
|
|
308
|
+
usage,
|
|
309
|
+
...(priced && cost !== undefined ? { cost } : {}),
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
messages.push({
|
|
313
|
+
role: "user",
|
|
314
|
+
content: await runToolCalls(
|
|
315
|
+
response.toolCalls,
|
|
316
|
+
tools,
|
|
317
|
+
signal,
|
|
318
|
+
options.onToolError,
|
|
319
|
+
),
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
throw tooManySteps(maxSteps);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Ask for one value matching `schema`, and get it typed and validated.
|
|
327
|
+
* The provider's structured-output mode is used when it has one, a tool
|
|
328
|
+
* otherwise. An answer that fails the schema goes back to the model with
|
|
329
|
+
* the schema's issues, `retries` times at most, then raises
|
|
330
|
+
* `E_POLARIS_INVALID_OUTPUT`.
|
|
331
|
+
*/
|
|
332
|
+
async extract<S extends StandardSchema>(
|
|
333
|
+
request: ExtractRequest<S>,
|
|
334
|
+
options: ExtractOptions = {},
|
|
335
|
+
): Promise<ExtractResult<SchemaOutput<S>>> {
|
|
336
|
+
const retries = options.retries ?? 1;
|
|
337
|
+
if (!(Number.isInteger(retries) && retries >= 0)) {
|
|
338
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
339
|
+
"`retries` must be an integer, 0 or more",
|
|
340
|
+
]);
|
|
341
|
+
}
|
|
342
|
+
return extract(
|
|
343
|
+
request,
|
|
344
|
+
retries,
|
|
345
|
+
{ ...this.#driver.features, provider: this.#driver.provider },
|
|
346
|
+
(chat) => this.chat(chat, options),
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Stream a reply to the browser over an SSE stream, `ctx.response.sse()`
|
|
352
|
+
* in a ream route. Each event goes out named `text`, `reasoning`,
|
|
353
|
+
* `tool_call`, then `done`, and the stream is ended. When the client
|
|
354
|
+
* leaves, the provider request is cancelled. A failure sends an `error`
|
|
355
|
+
* event carrying only its polaris code. It never rejects: the outcome is
|
|
356
|
+
* in the result.
|
|
357
|
+
*
|
|
358
|
+
* In a ream route, do not await it: ream starts sending the response once
|
|
359
|
+
* the handler has returned, so an awaited stream would reach the client
|
|
360
|
+
* all at once at the end.
|
|
361
|
+
*
|
|
362
|
+
* router.post('/chat', async ({ response }) => {
|
|
363
|
+
* const sse = await response.sse()
|
|
364
|
+
* void polaris.use('claude').streamTo(sse, { messages }).then(logOutcome)
|
|
365
|
+
* })
|
|
366
|
+
*/
|
|
367
|
+
async streamTo(
|
|
368
|
+
sink: SseSink,
|
|
369
|
+
request: ChatRequest,
|
|
370
|
+
options: StreamToOptions = {},
|
|
371
|
+
): Promise<StreamToResult> {
|
|
372
|
+
const leave = new AbortController();
|
|
373
|
+
sink.onClose(() => {
|
|
374
|
+
if (!leave.signal.aborted) leave.abort(new ClientLeft());
|
|
375
|
+
});
|
|
376
|
+
const signal = options.signal
|
|
377
|
+
? AbortSignal.any([options.signal, leave.signal])
|
|
378
|
+
: leave.signal;
|
|
379
|
+
return pipeToSse(
|
|
380
|
+
this.stream(request, { ...options, signal }),
|
|
381
|
+
sink,
|
|
382
|
+
leave,
|
|
383
|
+
options.prefix ?? "",
|
|
384
|
+
);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** Turn texts into vectors, one per input, in input order. */
|
|
388
|
+
async embed(
|
|
389
|
+
request: EmbedRequest,
|
|
390
|
+
options: CallOptions = {},
|
|
391
|
+
): Promise<EmbedResponse> {
|
|
392
|
+
const driver = this.#driver;
|
|
393
|
+
const embed = driver.embed;
|
|
394
|
+
if (embed === undefined) {
|
|
395
|
+
throw new E_POLARIS_UNSUPPORTED([driver.provider, "embeddings"]);
|
|
396
|
+
}
|
|
397
|
+
if (request.inputs.length === 0) {
|
|
398
|
+
throw new E_POLARIS_INVALID_REQUEST(["`inputs` is empty"]);
|
|
399
|
+
}
|
|
400
|
+
if (request.dimensions !== undefined && !isCount(request.dimensions)) {
|
|
401
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
402
|
+
"`dimensions` must be a positive integer",
|
|
403
|
+
]);
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
const prepared = this.#prepare(options, undefined);
|
|
407
|
+
const ticket = await openTicket(this.#options.meter, {
|
|
408
|
+
operation: "embed",
|
|
409
|
+
provider: driver.provider,
|
|
410
|
+
request,
|
|
411
|
+
model: request.model ?? driver.defaults?.embeddingModel,
|
|
412
|
+
estimate: (price) => estimateEmbed(price, request),
|
|
413
|
+
...(options.scope !== undefined ? { scope: options.scope } : {}),
|
|
414
|
+
...(options.maxCost !== undefined ? { maxCost: options.maxCost } : {}),
|
|
415
|
+
});
|
|
416
|
+
let response: EmbedResponse;
|
|
417
|
+
try {
|
|
418
|
+
response = await untilAborted(
|
|
419
|
+
embed.call(driver, request, prepared.call),
|
|
420
|
+
prepared.call.signal,
|
|
421
|
+
);
|
|
422
|
+
} catch (error) {
|
|
423
|
+
const translated = this.#translate(error, prepared, options);
|
|
424
|
+
await ticket.fail(translated, {
|
|
425
|
+
cancelled: options.signal?.aborted === true,
|
|
426
|
+
spent: false,
|
|
427
|
+
});
|
|
428
|
+
throw translated;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
if (response.vectors.length !== request.inputs.length) {
|
|
432
|
+
throw new E_POLARIS_INVALID_RESPONSE([
|
|
433
|
+
driver.provider,
|
|
434
|
+
`${response.vectors.length} vectors for ${request.inputs.length} inputs`,
|
|
435
|
+
]);
|
|
436
|
+
}
|
|
437
|
+
if (
|
|
438
|
+
!isCount(response.dimensions) ||
|
|
439
|
+
response.vectors.some((vector) => vector.length !== response.dimensions)
|
|
440
|
+
) {
|
|
441
|
+
throw new E_POLARIS_INVALID_RESPONSE([
|
|
442
|
+
driver.provider,
|
|
443
|
+
`vectors do not all have the announced ${response.dimensions} dimensions`,
|
|
444
|
+
]);
|
|
445
|
+
}
|
|
446
|
+
const cost = await ticket.finish({
|
|
447
|
+
model: response.model,
|
|
448
|
+
usage: { ...NO_USAGE, inputTokens: response.usage.inputTokens },
|
|
449
|
+
response,
|
|
450
|
+
});
|
|
451
|
+
return cost !== undefined ? { ...response, cost } : response;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** Open the meter of a chat request: price it, check its budget, reserve. */
|
|
455
|
+
#openChat(
|
|
456
|
+
operation: "chat" | "stream",
|
|
457
|
+
request: ChatRequest,
|
|
458
|
+
options: CallOptions,
|
|
459
|
+
streaming: boolean,
|
|
460
|
+
): Promise<Ticket> {
|
|
461
|
+
const defaults = this.#driver.defaults;
|
|
462
|
+
const maxTokens =
|
|
463
|
+
request.maxTokens ??
|
|
464
|
+
(streaming ? defaults?.streamMaxTokens : defaults?.maxTokens);
|
|
465
|
+
return openTicket(this.#options.meter, {
|
|
466
|
+
operation,
|
|
467
|
+
provider: this.#driver.provider,
|
|
468
|
+
request,
|
|
469
|
+
model: request.model ?? defaults?.model,
|
|
470
|
+
estimate: (price) => {
|
|
471
|
+
if (maxTokens === undefined) {
|
|
472
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
473
|
+
"a budget applies: set `maxTokens`, the provider declares no default",
|
|
474
|
+
]);
|
|
475
|
+
}
|
|
476
|
+
return estimateChat(price, request, maxTokens);
|
|
477
|
+
},
|
|
478
|
+
...(options.scope !== undefined ? { scope: options.scope } : {}),
|
|
479
|
+
...(options.maxCost !== undefined ? { maxCost: options.maxCost } : {}),
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** Close the meter of an answered chat request, and put its cost on it. */
|
|
484
|
+
async #priced(response: ChatResponse, ticket: Ticket): Promise<ChatResponse> {
|
|
485
|
+
const cost = await ticket.finish({
|
|
486
|
+
model: response.model,
|
|
487
|
+
usage: response.usage,
|
|
488
|
+
responseId: response.id,
|
|
489
|
+
stopReason: response.stopReason,
|
|
490
|
+
response,
|
|
491
|
+
});
|
|
492
|
+
return cost !== undefined ? { ...response, cost } : response;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
#checkChat(request: ChatRequest): void {
|
|
496
|
+
const provider = this.#driver.provider;
|
|
497
|
+
const features = this.#driver.features;
|
|
498
|
+
if (request.messages.length === 0) {
|
|
499
|
+
throw new E_POLARIS_INVALID_REQUEST(["`messages` is empty"]);
|
|
500
|
+
}
|
|
501
|
+
if (request.maxTokens !== undefined && !isCount(request.maxTokens)) {
|
|
502
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
503
|
+
"`maxTokens` must be a positive integer",
|
|
504
|
+
]);
|
|
505
|
+
}
|
|
506
|
+
const tools = request.tools ?? [];
|
|
507
|
+
if (tools.length > 0) {
|
|
508
|
+
if (!features.tools) {
|
|
509
|
+
throw new E_POLARIS_UNSUPPORTED([provider, "tool calls"]);
|
|
510
|
+
}
|
|
511
|
+
const names = new Set<string>();
|
|
512
|
+
for (const tool of tools) {
|
|
513
|
+
if (names.has(tool.name)) {
|
|
514
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
515
|
+
`two tools are named '${tool.name}'`,
|
|
516
|
+
]);
|
|
517
|
+
}
|
|
518
|
+
names.add(tool.name);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
if (request.output !== undefined && !features.structuredOutput) {
|
|
522
|
+
throw new E_POLARIS_UNSUPPORTED([provider, "structured output"]);
|
|
523
|
+
}
|
|
524
|
+
if (!features.images && sendsImages(request)) {
|
|
525
|
+
throw new E_POLARIS_UNSUPPORTED([provider, "images"]);
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
#prepare(options: CallOptions, stop: AbortSignal | undefined): PreparedCall {
|
|
530
|
+
const timeout = options.timeout ?? this.#options.timeout;
|
|
531
|
+
if (!isTimeout(timeout)) {
|
|
532
|
+
throw new E_POLARIS_INVALID_CONFIG([
|
|
533
|
+
`timeout must be a positive integer of ms, at most ${MAX_TIMEOUT}`,
|
|
534
|
+
]);
|
|
535
|
+
}
|
|
536
|
+
const apiKey = options.apiKey;
|
|
537
|
+
if (
|
|
538
|
+
apiKey !== undefined &&
|
|
539
|
+
(apiKey.length < MIN_KEY_LENGTH || apiKey.trim() !== apiKey)
|
|
540
|
+
) {
|
|
541
|
+
throw new E_POLARIS_INVALID_REQUEST([
|
|
542
|
+
`\`apiKey\` must be at least ${MIN_KEY_LENGTH} characters, without surrounding spaces`,
|
|
543
|
+
]);
|
|
544
|
+
}
|
|
545
|
+
if (options.signal?.aborted) throw options.signal.reason;
|
|
546
|
+
|
|
547
|
+
const deadline = AbortSignal.timeout(timeout);
|
|
548
|
+
const signals = [deadline];
|
|
549
|
+
if (options.signal) signals.push(options.signal);
|
|
550
|
+
if (stop) signals.push(stop);
|
|
551
|
+
const signal = AbortSignal.any(signals);
|
|
552
|
+
return {
|
|
553
|
+
deadline,
|
|
554
|
+
timeout,
|
|
555
|
+
call: {
|
|
556
|
+
signal,
|
|
557
|
+
apiKey,
|
|
558
|
+
fetch: boundFetch(
|
|
559
|
+
this.#options.fetch,
|
|
560
|
+
signal,
|
|
561
|
+
this.#options.maxResponseBytes,
|
|
562
|
+
),
|
|
563
|
+
},
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** The error a failed call raises. */
|
|
568
|
+
#translate(
|
|
569
|
+
error: unknown,
|
|
570
|
+
prepared: PreparedCall,
|
|
571
|
+
options: CallOptions,
|
|
572
|
+
): unknown {
|
|
573
|
+
if (options.signal?.aborted) return options.signal.reason;
|
|
574
|
+
if (prepared.deadline.aborted)
|
|
575
|
+
return new E_POLARIS_TIMEOUT([prepared.timeout]);
|
|
576
|
+
return scrub(error, this.#driver.provider, [prepared.call.apiKey]);
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
function isCount(value: number): boolean {
|
|
581
|
+
return Number.isInteger(value) && value > 0;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function sendsImages(request: ChatRequest): boolean {
|
|
585
|
+
return request.messages.some(
|
|
586
|
+
(message) =>
|
|
587
|
+
message.role === "user" &&
|
|
588
|
+
typeof message.content !== "string" &&
|
|
589
|
+
message.content.some((part) => part.type === "image"),
|
|
590
|
+
);
|
|
591
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PolarisProvider: binds the provider manager built from `config/polaris.ts`.
|
|
3
|
+
*
|
|
4
|
+
* register() binds `polaris.manager`, built on first resolve, unless the
|
|
5
|
+
* application bound its own first.
|
|
6
|
+
* boot() builds it and publishes it to `@c9up/polaris/services/main`;
|
|
7
|
+
* a missing or invalid config fails the boot here.
|
|
8
|
+
* shutdown() releases the published manager, if it is still this one.
|
|
9
|
+
*
|
|
10
|
+
* Typed against the slice of ream's `AppContext` it uses rather than importing
|
|
11
|
+
* it, so ream stays an optional peer.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import "./augmentations.js";
|
|
15
|
+
import { E_POLARIS_MISSING_CONFIG } from "./errors.js";
|
|
16
|
+
import {
|
|
17
|
+
type DeclaredProviders,
|
|
18
|
+
Polaris,
|
|
19
|
+
type PolarisService,
|
|
20
|
+
} from "./Polaris.js";
|
|
21
|
+
import { clearPolaris, getPolaris, setPolaris } from "./services/main.js";
|
|
22
|
+
import type { PolarisConfig } from "./types.js";
|
|
23
|
+
|
|
24
|
+
const TOKEN = "polaris.manager";
|
|
25
|
+
|
|
26
|
+
interface ContainerLike {
|
|
27
|
+
singleton(token: string | symbol, factory: () => unknown): void;
|
|
28
|
+
/** Async, as in ream: a factory may be async. */
|
|
29
|
+
resolve<T = unknown>(token: string | symbol): Promise<T>;
|
|
30
|
+
has?(token: string | symbol): boolean;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface ConfigStoreLike {
|
|
34
|
+
get<T = unknown>(key: string): T | undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface PolarisAppContext {
|
|
38
|
+
container: ContainerLike;
|
|
39
|
+
config: ConfigStoreLike;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export default class PolarisProvider {
|
|
43
|
+
readonly #app: PolarisAppContext;
|
|
44
|
+
#owned: PolarisService | undefined;
|
|
45
|
+
|
|
46
|
+
constructor(app: PolarisAppContext) {
|
|
47
|
+
this.#app = app;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
register(): void {
|
|
51
|
+
const container = this.#app.container;
|
|
52
|
+
if (container.has?.(TOKEN)) return;
|
|
53
|
+
container.singleton(TOKEN, () => {
|
|
54
|
+
const config =
|
|
55
|
+
this.#app.config.get<PolarisConfig<DeclaredProviders>>("polaris");
|
|
56
|
+
if (config === undefined) throw new E_POLARIS_MISSING_CONFIG();
|
|
57
|
+
return new Polaris(config);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async boot(): Promise<void> {
|
|
62
|
+
const manager = await this.#app.container.resolve<PolarisService>(TOKEN);
|
|
63
|
+
this.#owned = manager;
|
|
64
|
+
setPolaris(manager);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async shutdown(): Promise<void> {
|
|
68
|
+
if (this.#owned !== undefined && getPolaris() === this.#owned) {
|
|
69
|
+
clearPolaris();
|
|
70
|
+
}
|
|
71
|
+
this.#owned = undefined;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tell ream's `ContainerBindings` what `container.resolve('polaris.manager')`
|
|
3
|
+
* returns. Loaded from the package barrel and from the provider, so an
|
|
4
|
+
* application writes no `declare module` of its own for it.
|
|
5
|
+
*
|
|
6
|
+
* Type-only: ream stays an optional peer.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type {} from "@c9up/ream/types";
|
|
10
|
+
import type { PolarisService } from "./Polaris.js";
|
|
11
|
+
|
|
12
|
+
declare module "@c9up/ream/types" {
|
|
13
|
+
interface ContainerBindings {
|
|
14
|
+
/** The provider manager, bound by `PolarisProvider`. */
|
|
15
|
+
"polaris.manager": PolarisService;
|
|
16
|
+
}
|
|
17
|
+
}
|