@ultimat3/ai 31.14.0 → 31.15.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/CLAUDE.md +8 -4
- package/README.md +2 -2
- package/package.json +11 -11
- package/src/answer-body.ts +34 -0
- package/src/anthropic-provider.ts +21 -3
- package/src/gateway.ts +36 -7
- package/src/openai-provider.ts +15 -4
- package/src/openai-wire-stream.ts +32 -1
- package/src/pg-vector-recall.ts +79 -0
- package/src/pg-vector.ts +14 -3
- package/src/stream-bill.ts +57 -0
- package/src/wire.ts +21 -0
package/CLAUDE.md
CHANGED
|
@@ -108,7 +108,9 @@ Why each is shaped this way: [`docs/history/ai.md`](../../docs/history/ai.md#bou
|
|
|
108
108
|
- **Cost is exact in bigint (`cost.ts`, `Money` at `costScale`), rounded UP once**: per call by
|
|
109
109
|
`costOf`, per ledger at `report()`, per run from the summed usage — never a sum of round-ups. A
|
|
110
110
|
price may state a `scale` (≤ `PRICE_SCALE_DIGITS` finer); it is always read through `minorAt`.
|
|
111
|
-
- **`Gateway.stream` routes BEFORE it reserves**; `
|
|
111
|
+
- **`Gateway.stream` routes BEFORE it reserves**; the `done` record is attempted ONCE (a throw is
|
|
112
|
+
never re-booked from the running bill). Unsettled: the wire's running bill (`stream-bill.ts`),
|
|
113
|
+
else the prompt once sent (`trackSent`) — an aborted `generate` too; released only if never sent.
|
|
112
114
|
|
|
113
115
|
## Invariants — `llm()`
|
|
114
116
|
|
|
@@ -141,7 +143,8 @@ Why each is shaped this way: [`docs/history/ai.md`](../../docs/history/ai.md#llm
|
|
|
141
143
|
- **`configureAi({ redact })` is the one seam between `vars()` and the provider**; a `Secret` in
|
|
142
144
|
`vars()` is `X_AI_PROMPT_SECRET` regardless.
|
|
143
145
|
- **Fallback is across PROVIDERS serving one model, never across models**; `GenerateResult.provider`
|
|
144
|
-
is stamped by the gateway. Server-side `fallbacks` (beta) are never sent.
|
|
146
|
+
is stamped by the gateway. Server-side `fallbacks` (beta) are never sent. Media generation:
|
|
147
|
+
absent, awaiting an owner decision (OD8).
|
|
145
148
|
- **A slot inside a tag pair is DATA** (`prompt-fence.ts`, #689): `render` breaks every fence closer
|
|
146
149
|
a fenced value wrote, in the ASSEMBLED prompt — never deletes, never touches a template's own.
|
|
147
150
|
- `definePrompt` refuses a re-registered version whose hash moved; the hash is over core's
|
|
@@ -258,14 +261,15 @@ Why each is shaped this way: [`docs/history/ai.md`](../../docs/history/ai.md#llm
|
|
|
258
261
|
|
|
259
262
|
## Invariants — provider prompt caching
|
|
260
263
|
|
|
261
|
-
One switch (`GenerateRequest.promptCache`), `promptCacheRule`: provider rows
|
|
264
|
+
One switch (`GenerateRequest.promptCache`), `promptCacheRule`: provider rows (`ProviderCacheRow`, screened by `prompt-cache-rows.ts`), then `PROMPT_CACHE_RULES`, then nothing; `agent()` `'auto'`, `llm()` `'off'`. In full: [`docs/history/ai.md`](../../docs/history/ai.md#moved-out-2026-11-03-plan-101-wave-3-the-claudemd-ceiling).
|
|
262
265
|
|
|
263
266
|
## Invariants — evals, retrieval, fix lines
|
|
264
267
|
|
|
265
268
|
In brief ([full text](../../docs/history/ai.md#evals-retrieval-fix-lines)): no fix line names
|
|
266
269
|
`x ai`; an eval gates on the DROP from its baseline, mean AND per case, and every prompt has one;
|
|
267
270
|
retrieval is hybrid only; an unbound store read under an org actor is `X_VECTOR_UNSCOPED`;
|
|
268
|
-
`postgresVectorStore()` filters tenant and policy in SQL on every statement
|
|
271
|
+
`postgresVectorStore()` filters tenant and policy in SQL on every statement (hnsw reads widen the
|
|
272
|
+
scan, `pg-vector-recall.ts`); `scoped()` TIGHTENS.
|
|
269
273
|
|
|
270
274
|
- **An eval never runs a real tool**: no double is `X_EVAL_TOOL_UNDOUBLED` (history, 2026-11-06).
|
|
271
275
|
|
package/README.md
CHANGED
|
@@ -402,7 +402,7 @@ invocation is an ordinary one, marked so the model half streams. Two consequence
|
|
|
402
402
|
|---|---|
|
|
403
403
|
| the `done` chunk carries the validated value; text increments are **unvalidated** | a schema cannot be checked until the last token has landed |
|
|
404
404
|
| **no repair turn** — a bad shape is `X_LLM_STREAM_INVALID` | the consumer has already read the tokens; a second answer over the top is two answers to one question. The fix names the non-streaming call |
|
|
405
|
-
| the budget is reserved **before the first token** and reconciled at `done` | unchanged from `generate()`; a stream that throws or is abandoned
|
|
405
|
+
| the budget is reserved **before the first token** and reconciled at `done` | unchanged from `generate()`; a stream that throws or is abandoned after the provider's first byte records the usage the wire reported, one aborted after its request was sent records the prompt's estimate, and only one never sent (or refused by the provider) releases (31.15.0) |
|
|
406
406
|
| no `respond` tool is offered | a tool call is emitted whole, so forcing one leaves nothing to stream — the answer is prose, and its JSON parse is what a non-string `output` validates |
|
|
407
407
|
| lazy | nothing is authorised, budgeted or sent until the first pull |
|
|
408
408
|
|
|
@@ -447,7 +447,7 @@ sub-agent in its own `tools` and the sub-agent runs under the same actor, throug
|
|
|
447
447
|
| Rule | Why |
|
|
448
448
|
|---|---|
|
|
449
449
|
| the actor is **`ctx.actor`**, read once, never from the model | this is the mistake a hand-rolled loop ships, and the reason the loop belongs in the framework |
|
|
450
|
-
| an aborted `ctx` unwinds the run — at the top of every turn, before every tool batch, and on the socket | the transcript IS the request, so a loop that keeps going after the caller disconnects re-sends it once per remaining turn, runs every remaining side effect and discards the answer. `ctx.signal` rides on `GenerateRequest` too, so a call already in flight is cut
|
|
450
|
+
| an aborted `ctx` unwinds the run — at the top of every turn, before every tool batch, and on the socket | the transcript IS the request, so a loop that keeps going after the caller disconnects re-sends it once per remaining turn, runs every remaining side effect and discards the answer. `ctx.signal` rides on `GenerateRequest` too, so a call already in flight is cut — and billed only the prompt the provider already read |
|
|
451
451
|
| the tools of **one turn** run concurrently, at most `maxToolConcurrency` at once (default 8), results paired by `tool_use` id | a turn asking for five tools cost 5x wall clock and nothing said so; a turn asking for fifty — a confused or injected model — was fifty concurrent invocations and pool checkouts. Order is positional, never by completion; a call waiting for a slot never starts after an abort or the deadline. `maxToolConcurrency: 1` runs a turn serially |
|
|
452
452
|
| `onTurn` reports each completed turn as it happens (and an `agent.turn` span event, always) | a 90-second run emitted nothing until it returned. Observation only — it cannot steer the loop, see the transcript or reach the actor — and a throw from it fails the run rather than being swallowed |
|
|
453
453
|
| a tool is an `mcp: { expose: true }` action or an `inProcessTool()`; anything else is `X_AGENT_TOOL_UNEXPOSED` **at declaration** | a silently dropped tool reads as offered and is not; `isMcpExposed` is the one predicate for ACTIONS, so an in-app agent and an external MCP client see the same catalogue of them — and a tool no MCP client may see is declared as one that is this process's alone |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/ai",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.15.0",
|
|
4
4
|
"description": "LLM gateway, versioned prompts, evals as tests, embeddings, hybrid vector search, RAG",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -45,17 +45,17 @@
|
|
|
45
45
|
"test": "bun test"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@ultimat3/action": "31.
|
|
49
|
-
"@ultimat3/cache": "31.
|
|
50
|
-
"@ultimat3/core": "31.
|
|
51
|
-
"@ultimat3/db": "31.
|
|
52
|
-
"@ultimat3/http": "31.
|
|
53
|
-
"@ultimat3/jobs": "31.
|
|
54
|
-
"@ultimat3/money": "31.
|
|
55
|
-
"@ultimat3/schema": "31.
|
|
56
|
-
"@ultimat3/time": "31.
|
|
48
|
+
"@ultimat3/action": "31.15.0",
|
|
49
|
+
"@ultimat3/cache": "31.15.0",
|
|
50
|
+
"@ultimat3/core": "31.15.0",
|
|
51
|
+
"@ultimat3/db": "31.15.0",
|
|
52
|
+
"@ultimat3/http": "31.15.0",
|
|
53
|
+
"@ultimat3/jobs": "31.15.0",
|
|
54
|
+
"@ultimat3/money": "31.15.0",
|
|
55
|
+
"@ultimat3/schema": "31.15.0",
|
|
56
|
+
"@ultimat3/time": "31.15.0"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
59
|
-
"@ultimat3/policy": "31.
|
|
59
|
+
"@ultimat3/policy": "31.15.0"
|
|
60
60
|
}
|
|
61
61
|
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Single responsibility: a non-streamed answer's 2xx body, read as JSON within a byte cap. A raw
|
|
2
|
+
// `response.json()` buffered the whole body before anything measured it, and a proxy's
|
|
3
|
+
// `<html>bad gateway</html>` escaped as a bare SyntaxError with no code and no fix.
|
|
4
|
+
|
|
5
|
+
import { readWithinLimit, renderThrowable } from '@ultimat3/core';
|
|
6
|
+
import { AiTransportError } from './errors';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 32 MiB, the cap `remoteEmbedder` holds a response to. The largest legitimate answer — 128k
|
|
10
|
+
* output tokens of JSON-escaped text plus its tool arguments — is a few MiB, so nothing real
|
|
11
|
+
* reaches it and nothing unreal is held.
|
|
12
|
+
*/
|
|
13
|
+
export const ANSWER_BODY_MAX_BYTES = 32 * 1024 * 1024;
|
|
14
|
+
|
|
15
|
+
/** The parsed body, `unknown` — the wire's parser decides whether it is an answer. */
|
|
16
|
+
export async function readAnswerBody(response: Response, provider: string): Promise<unknown> {
|
|
17
|
+
const read = await readWithinLimit(response.body, ANSWER_BODY_MAX_BYTES);
|
|
18
|
+
if ('over' in read) {
|
|
19
|
+
throw new AiTransportError({
|
|
20
|
+
provider,
|
|
21
|
+
status: response.status,
|
|
22
|
+
detail: `response body is at least ${read.over} bytes, limit is ${ANSWER_BODY_MAX_BYTES}`,
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(new TextDecoder().decode(read.bytes));
|
|
27
|
+
} catch (error) {
|
|
28
|
+
throw new AiTransportError({
|
|
29
|
+
provider,
|
|
30
|
+
status: response.status,
|
|
31
|
+
detail: `the response body is not valid JSON: ${renderThrowable(error)}`,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
// the one `fetch` it sends, and `parseMessage` for a non-streamed answer. The shared shapes are
|
|
3
3
|
// ./provider's; ./models owns the per-model rules and ./wire the streamed response half.
|
|
4
4
|
|
|
5
|
+
import { readAnswerBody } from './answer-body';
|
|
6
|
+
import { billedCall } from './billed';
|
|
5
7
|
import { assertMediaContent } from './content-blocks';
|
|
6
8
|
import { providerFailure } from './context-overflow';
|
|
7
9
|
import { costOf, exactCostOf } from './cost';
|
|
@@ -18,6 +20,7 @@ import { screenCacheRows } from './prompt-cache-rows';
|
|
|
18
20
|
import type { GenerateRequest, GenerateResult, Provider, StreamChunk } from './provider';
|
|
19
21
|
import { samplingBody } from './sampling';
|
|
20
22
|
import { readSse } from './sse';
|
|
23
|
+
import { trackSent, trackStreamBill } from './stream-bill';
|
|
21
24
|
import { assertToolArguments } from './tool-arguments';
|
|
22
25
|
import type { LlmToolCall } from './tools';
|
|
23
26
|
import {
|
|
@@ -123,8 +126,7 @@ export class AnthropicProvider implements Provider {
|
|
|
123
126
|
const model = this.modelOf(request);
|
|
124
127
|
if (requiresStreaming({ ...request, model })) return this.assemble(request);
|
|
125
128
|
const response = await this.send(model, request, false);
|
|
126
|
-
|
|
127
|
-
return parseMessage(model, raw);
|
|
129
|
+
return parseMessage(model, await readAnswerBody(response, this.name));
|
|
128
130
|
}
|
|
129
131
|
|
|
130
132
|
/** Drive `stream()` to its `done` chunk. It throws on a cut stream, so a partial never lands. */
|
|
@@ -154,6 +156,11 @@ export class AnthropicProvider implements Provider {
|
|
|
154
156
|
});
|
|
155
157
|
}
|
|
156
158
|
const message = new MessageStream();
|
|
159
|
+
// A stream that stops before `done` is billed what `message_start` and the deltas said.
|
|
160
|
+
trackStreamBill(request, () => {
|
|
161
|
+
const usage = message.partialUsage();
|
|
162
|
+
return usage === undefined ? undefined : billedCall(usage, exactCostOf(model, usage));
|
|
163
|
+
});
|
|
157
164
|
for await (const frame of readSse(response.body, this.name)) {
|
|
158
165
|
for (const chunk of message.push(frame)) yield chunk;
|
|
159
166
|
}
|
|
@@ -218,6 +225,8 @@ export class AnthropicProvider implements Provider {
|
|
|
218
225
|
}
|
|
219
226
|
const doFetch: AiFetch = this.config.fetch ?? fetch;
|
|
220
227
|
const url = `${this.config.baseUrl ?? 'https://api.anthropic.com'}/v1/messages`;
|
|
228
|
+
// From here an abort costs the prompt (`stream-bill.ts`): the request is on its way.
|
|
229
|
+
trackSent(request, model);
|
|
221
230
|
const response = await doFetch(url, {
|
|
222
231
|
method: 'POST',
|
|
223
232
|
headers: {
|
|
@@ -249,7 +258,16 @@ export class AnthropicProvider implements Provider {
|
|
|
249
258
|
}
|
|
250
259
|
|
|
251
260
|
/** Map a Messages API response onto `GenerateResult`. Exported so tests can drive it. */
|
|
252
|
-
export function parseMessage(model: ModelId,
|
|
261
|
+
export function parseMessage(model: ModelId, input: unknown): GenerateResult {
|
|
262
|
+
// `null`, an array or a string is no message: read as one it threw a bare TypeError, or
|
|
263
|
+
// resolved as an empty answer — `openai-wire.ts`'s `parseChatCompletion` refuses the same.
|
|
264
|
+
if (typeof input !== 'object' || input === null || Array.isArray(input)) {
|
|
265
|
+
throw new AiTransportError({
|
|
266
|
+
provider: 'anthropic',
|
|
267
|
+
detail: 'the response body is not a JSON object',
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
const raw = input as Record<string, unknown>;
|
|
253
271
|
// A 200 carrying an `error` object instead of an answer — how a gateway in front of a model
|
|
254
272
|
// reports a fault it noticed after the headers were sent. Read as a message it is an empty,
|
|
255
273
|
// successful answer, which is the one outcome nothing downstream can detect; the STREAMED half
|
package/src/gateway.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import type { Breaker, Random, RetryPolicy } from '@ultimat3/core';
|
|
8
8
|
import { fingerprint, finiteCount, finiteOption, logger, renderThrowable } from '@ultimat3/core';
|
|
9
9
|
import type { Money } from '@ultimat3/money';
|
|
10
|
+
import type { Billed } from './billed';
|
|
10
11
|
import { billedOf } from './billed';
|
|
11
12
|
import type { BudgetKeys, BudgetLimits, BudgetReservation, BudgetStore } from './budget';
|
|
12
13
|
import {
|
|
@@ -27,6 +28,7 @@ import { resolveModel } from './model-resolve';
|
|
|
27
28
|
import type { ModelId } from './models';
|
|
28
29
|
import type { GenerateRequest, GenerateResult, Provider, StreamChunk } from './provider';
|
|
29
30
|
import type { SamplingWire } from './sampling';
|
|
31
|
+
import { sentBillOf, streamBillOf } from './stream-bill';
|
|
30
32
|
import { ZERO_USAGE } from './wire';
|
|
31
33
|
|
|
32
34
|
/**
|
|
@@ -215,7 +217,9 @@ class GatewayImpl implements Gateway {
|
|
|
215
217
|
// A call that never landed must not go on holding its reservation — and one that DID land
|
|
216
218
|
// and still failed (`billedOf`: the provider answered with something unusable) is recorded
|
|
217
219
|
// as what it cost. Releasing it told the ledger a billed call was free.
|
|
218
|
-
|
|
220
|
+
// An abort after the request left the process is billed its prompt, never released.
|
|
221
|
+
const sentBill = abortedBy(resolved, error) ? sentBillOf(resolved) : undefined;
|
|
222
|
+
await settleFailure(ledger, reservation, error, sentBill);
|
|
219
223
|
throw error;
|
|
220
224
|
}
|
|
221
225
|
// The provider was PAID by now. Nothing below may turn that answer into a failure: a ledger
|
|
@@ -280,6 +284,9 @@ class GatewayImpl implements Gateway {
|
|
|
280
284
|
throw error;
|
|
281
285
|
}
|
|
282
286
|
let settled = false;
|
|
287
|
+
// Set BEFORE the `done` record is awaited: a store that throws there may have booked part of
|
|
288
|
+
// it, and settling again from the running bill would charge the call twice.
|
|
289
|
+
let recordAttempted = false;
|
|
283
290
|
try {
|
|
284
291
|
for await (const chunk of provider.stream(resolved)) {
|
|
285
292
|
// The first chunk is the provider's verdict for its breaker: it answered.
|
|
@@ -294,6 +301,7 @@ class GatewayImpl implements Gateway {
|
|
|
294
301
|
// Settled only once `record` has LANDED. Marking it first left a store that threw here
|
|
295
302
|
// holding the reservation and half the record — the `finally` saw a settled stream.
|
|
296
303
|
const { usage, cost, costExact } = chunk.result;
|
|
304
|
+
recordAttempted = true;
|
|
297
305
|
await ledger?.record(usage, costExact ?? cost, reservation);
|
|
298
306
|
settled = true;
|
|
299
307
|
yield { type: 'done', result: { ...chunk.result, provider: provider.name } };
|
|
@@ -306,15 +314,26 @@ class GatewayImpl implements Gateway {
|
|
|
306
314
|
// Thrown after the provider reported usage: the bill is recorded, exactly as `generate` does.
|
|
307
315
|
// Only when nothing settled yet — a provider that throws AFTER its `done` chunk was already
|
|
308
316
|
// recorded, and releasing again would credit the ledger a second time.
|
|
317
|
+
// A throw with no bill of its own — a cut socket, an abort — is billed what the wire reported.
|
|
318
|
+
// An abort before the first frame, once the request was sent, is billed its prompt.
|
|
309
319
|
if (!settled) {
|
|
310
320
|
settled = true;
|
|
311
|
-
|
|
321
|
+
const running = recordAttempted
|
|
322
|
+
? undefined
|
|
323
|
+
: (streamBillOf(resolved) ??
|
|
324
|
+
(abortedBy(resolved, error) ? sentBillOf(resolved) : undefined));
|
|
325
|
+
await settleFailure(ledger, reservation, error, running);
|
|
312
326
|
}
|
|
313
327
|
throw error;
|
|
314
328
|
} finally {
|
|
315
|
-
// A stream its consumer abandoned never reached `done
|
|
316
|
-
//
|
|
317
|
-
|
|
329
|
+
// A stream its consumer abandoned never reached `done`. Its prompt, and every token it
|
|
330
|
+
// streamed, were billed all the same: recorded from the provider's running usage, and
|
|
331
|
+
// released only when no provider byte arrived (or the provider reports none).
|
|
332
|
+
// Abandoned before its first frame, after the request was sent: the prompt.
|
|
333
|
+
if (!settled) {
|
|
334
|
+
const running = streamBillOf(resolved) ?? sentBillOf(resolved);
|
|
335
|
+
await settleFailure(ledger, reservation, undefined, running);
|
|
336
|
+
}
|
|
318
337
|
// Abandoned before a chunk: the probe goes back, counting nothing.
|
|
319
338
|
if (!answered) gate?.released(ticket);
|
|
320
339
|
}
|
|
@@ -334,17 +353,27 @@ class GatewayImpl implements Gateway {
|
|
|
334
353
|
}
|
|
335
354
|
}
|
|
336
355
|
|
|
337
|
-
/**
|
|
356
|
+
/**
|
|
357
|
+
* A failed call's reservation: reconciled against its bill when the failure carries one — else
|
|
358
|
+
* against `running`, what a stream's wire reported before it stopped — else given back.
|
|
359
|
+
*/
|
|
338
360
|
async function settleFailure(
|
|
339
361
|
ledger: BudgetLedger | undefined,
|
|
340
362
|
reservation: BudgetReservation | undefined,
|
|
341
363
|
error: unknown,
|
|
364
|
+
running?: Billed,
|
|
342
365
|
): Promise<void> {
|
|
343
|
-
const billed = billedOf(error);
|
|
366
|
+
const billed = billedOf(error) ?? running;
|
|
344
367
|
if (billed === undefined) return ledger?.release(reservation);
|
|
345
368
|
await ledger?.record(billed.usage, billed.cost, reservation);
|
|
346
369
|
}
|
|
347
370
|
|
|
371
|
+
/** The caller's abort — its signal, or the `AbortError` a fetch raises for it. */
|
|
372
|
+
function abortedBy(request: GenerateRequest, error: unknown): boolean {
|
|
373
|
+
if (request.signal?.aborted === true) return true;
|
|
374
|
+
return error instanceof Error && error.name === 'AbortError';
|
|
375
|
+
}
|
|
376
|
+
|
|
348
377
|
/** The stored answer as a hit delivers it: no token spent, no money, in the currency it named. */
|
|
349
378
|
const freeOf = (stored: GenerateResult): GenerateResult => ({
|
|
350
379
|
...stored,
|
package/src/openai-provider.ts
CHANGED
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
|
|
10
10
|
import type { Secret } from '@ultimat3/core';
|
|
11
11
|
import { isSecret, revealSecret } from '@ultimat3/core';
|
|
12
|
+
import { readAnswerBody } from './answer-body';
|
|
13
|
+
import { billedCall } from './billed';
|
|
12
14
|
import { providerFailure } from './context-overflow';
|
|
13
15
|
import { costOf, exactCostOf } from './cost';
|
|
14
16
|
import { detailOf, withoutKey } from './error-body';
|
|
@@ -32,6 +34,7 @@ import type {
|
|
|
32
34
|
} from './provider';
|
|
33
35
|
import { estimateInputTokens, estimateTextTokens, requiresStreaming } from './provider';
|
|
34
36
|
import { readSse } from './sse';
|
|
37
|
+
import { trackSent, trackStreamBill } from './stream-bill';
|
|
35
38
|
import { assertToolArguments } from './tool-arguments';
|
|
36
39
|
import type { LlmToolCall } from './tools';
|
|
37
40
|
|
|
@@ -143,10 +146,10 @@ class OpenAiProvider implements Provider {
|
|
|
143
146
|
model,
|
|
144
147
|
chatCompletionBody({ request, model, stream: false, provider: this.name, ...cache }),
|
|
145
148
|
false,
|
|
146
|
-
request
|
|
149
|
+
request,
|
|
147
150
|
sessionHeaders(request, cacheRule),
|
|
148
151
|
);
|
|
149
|
-
const answer = parseChatCompletion(
|
|
152
|
+
const answer = parseChatCompletion(await readAnswerBody(response, this.name), this.name);
|
|
150
153
|
return this.result(request, model, answer);
|
|
151
154
|
}
|
|
152
155
|
|
|
@@ -158,7 +161,7 @@ class OpenAiProvider implements Provider {
|
|
|
158
161
|
model,
|
|
159
162
|
chatCompletionBody({ request, model, stream: true, provider: this.name, ...cache }),
|
|
160
163
|
true,
|
|
161
|
-
request
|
|
164
|
+
request,
|
|
162
165
|
sessionHeaders(request, cacheRule),
|
|
163
166
|
);
|
|
164
167
|
if (response.body === null) {
|
|
@@ -169,6 +172,11 @@ class OpenAiProvider implements Provider {
|
|
|
169
172
|
});
|
|
170
173
|
}
|
|
171
174
|
const completion = new ChatCompletionStream(this.name);
|
|
175
|
+
// A stream that stops before `done` is billed what arrived; the prompt estimated only if read.
|
|
176
|
+
trackStreamBill(request, () => {
|
|
177
|
+
const usage = completion.partialUsage(estimateInputTokens(request));
|
|
178
|
+
return usage === undefined ? undefined : billedCall(usage, exactCostOf(model, usage));
|
|
179
|
+
});
|
|
172
180
|
for await (const frame of readSse(response.body, this.name)) {
|
|
173
181
|
for (const chunk of completion.push(frame)) yield chunk;
|
|
174
182
|
}
|
|
@@ -223,11 +231,14 @@ class OpenAiProvider implements Provider {
|
|
|
223
231
|
model: ModelId,
|
|
224
232
|
body: Record<string, unknown>,
|
|
225
233
|
streaming: boolean,
|
|
226
|
-
|
|
234
|
+
request: GenerateRequest,
|
|
227
235
|
extra: Readonly<Record<string, string>>,
|
|
228
236
|
): Promise<Response> {
|
|
237
|
+
const { signal } = request;
|
|
229
238
|
const apiKey = this.apiKey();
|
|
230
239
|
const doFetch: AiFetch = this.config.fetch ?? fetch;
|
|
240
|
+
// From here an abort costs the prompt (`stream-bill.ts`): the request is on its way.
|
|
241
|
+
trackSent(request, model);
|
|
231
242
|
const response = await doFetch(this.url(), {
|
|
232
243
|
method: 'POST',
|
|
233
244
|
headers: {
|
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
} from './openai-wire';
|
|
17
17
|
import type { StopDetails, StopReason, StreamChunk, TokenUsage } from './provider';
|
|
18
18
|
import type { SseFrame } from './sse';
|
|
19
|
+
import { streamedTokens } from './stream-bill';
|
|
19
20
|
|
|
20
21
|
interface PendingCall {
|
|
21
22
|
/** Where the call sorts among its turn's: the wire's `index`, else its order of arrival. */
|
|
@@ -48,6 +49,10 @@ export class ChatCompletionStream {
|
|
|
48
49
|
private readonly byIndex = new Map<number, PendingCall>();
|
|
49
50
|
private readonly read: ReadCalls = { calls: [], malformed: [] };
|
|
50
51
|
private readonly provider: string;
|
|
52
|
+
/** A completion frame arrived: the provider has billed the prompt from here on. */
|
|
53
|
+
private received = false;
|
|
54
|
+
/** Characters of content, reasoning and arguments streamed — output no `usage` has counted. */
|
|
55
|
+
private streamedChars = 0;
|
|
51
56
|
|
|
52
57
|
constructor(provider: string) {
|
|
53
58
|
this.provider = provider;
|
|
@@ -62,6 +67,7 @@ export class ChatCompletionStream {
|
|
|
62
67
|
}
|
|
63
68
|
const payload = this.payloadOf(frame);
|
|
64
69
|
throwInBandError(payload, this.provider);
|
|
70
|
+
this.received = true;
|
|
65
71
|
const usage = parseOpenAiUsage(payload['usage']);
|
|
66
72
|
if (usage !== undefined) this.usage = usage;
|
|
67
73
|
const choice = asRecord(Array.isArray(payload['choices']) ? payload['choices'][0] : undefined);
|
|
@@ -115,6 +121,26 @@ export class ChatCompletionStream {
|
|
|
115
121
|
return this.finished || (this.done && this.pending.length === 0);
|
|
116
122
|
}
|
|
117
123
|
|
|
124
|
+
/**
|
|
125
|
+
* What the provider has billed so far, for a stream that stops before it is complete — or
|
|
126
|
+
* `undefined` before the first completion frame, when nothing was. This format states usage once,
|
|
127
|
+
* in a trailing chunk; until it lands the prompt is `promptTokens` (the caller's estimate) and
|
|
128
|
+
* the output is estimated from the characters streamed.
|
|
129
|
+
*/
|
|
130
|
+
partialUsage(promptTokens: number): TokenUsage | undefined {
|
|
131
|
+
if (!this.received) return undefined;
|
|
132
|
+
const streamed = streamedTokens(this.streamedChars);
|
|
133
|
+
if (this.usage !== undefined) {
|
|
134
|
+
return { ...this.usage, outputTokens: Math.max(this.usage.outputTokens, streamed) };
|
|
135
|
+
}
|
|
136
|
+
return {
|
|
137
|
+
inputTokens: promptTokens,
|
|
138
|
+
outputTokens: streamed,
|
|
139
|
+
cacheReadTokens: 0,
|
|
140
|
+
cacheWriteTokens: 0,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
118
144
|
/** What the stream accumulated. `cost` is applied by the provider, which owns prices. */
|
|
119
145
|
state(): ChatAnswer {
|
|
120
146
|
// Idempotent, so a reader that never called `end()` still sees a finished turn's calls.
|
|
@@ -152,6 +178,7 @@ export class ChatCompletionStream {
|
|
|
152
178
|
const content = delta['content'];
|
|
153
179
|
if (typeof content === 'string' && content !== '') {
|
|
154
180
|
this.text += content;
|
|
181
|
+
this.streamedChars += content.length;
|
|
155
182
|
chunks.push({ type: 'text', text: content });
|
|
156
183
|
}
|
|
157
184
|
// `reasoning_content` is vLLM's and DeepSeek's; `reasoning` is the OpenRouter spelling. Neither
|
|
@@ -159,6 +186,7 @@ export class ChatCompletionStream {
|
|
|
159
186
|
// every chunk must not end up shipping the reasoning to the user.
|
|
160
187
|
const thinking = delta['reasoning_content'] ?? delta['reasoning'];
|
|
161
188
|
if (typeof thinking === 'string' && thinking !== '') {
|
|
189
|
+
this.streamedChars += thinking.length;
|
|
162
190
|
chunks.push({ type: 'thinking', text: thinking });
|
|
163
191
|
}
|
|
164
192
|
const refusal = delta['refusal'];
|
|
@@ -211,7 +239,10 @@ export class ChatCompletionStream {
|
|
|
211
239
|
// legal, and assigning would keep only the tail.
|
|
212
240
|
if (typeof name === 'string') call.name += name;
|
|
213
241
|
const args = fn?.['arguments'];
|
|
214
|
-
if (typeof args === 'string')
|
|
242
|
+
if (typeof args === 'string') {
|
|
243
|
+
call.args += args;
|
|
244
|
+
this.streamedChars += args.length;
|
|
245
|
+
}
|
|
215
246
|
}
|
|
216
247
|
}
|
|
217
248
|
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
// Single responsibility: an hnsw search that returns `k` rows for a small tenant. pgvector applies
|
|
2
|
+
// `where` AFTER the index scan, so a plain scan hands back the `ef_search` nearest rows of the
|
|
3
|
+
// whole table and a tenant holding 0.5% of it gets fewer than `k` — usually none. Each search runs
|
|
4
|
+
// in a read transaction whose first statements widen the scan, and the setting ends with it.
|
|
5
|
+
|
|
6
|
+
import type { DbClient, SqlFragment } from '@ultimat3/db';
|
|
7
|
+
import { currentTx, setLocal, sql, withReadTransaction } from '@ultimat3/db';
|
|
8
|
+
|
|
9
|
+
/** pgvector's ceiling on `hnsw.ef_search`. */
|
|
10
|
+
const EF_SEARCH_MAX = 1_000;
|
|
11
|
+
/** pgvector's default: never lowered below it. */
|
|
12
|
+
const EF_SEARCH_DEFAULT = 40;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* What each setting reads when this backend has not loaded pgvector yet (`current_setting` is
|
|
16
|
+
* `null` then) — restored as itself, since an empty string is no value of either.
|
|
17
|
+
*/
|
|
18
|
+
const DEFAULTS = new Map([
|
|
19
|
+
['hnsw.iterative_scan', 'off'],
|
|
20
|
+
['hnsw.ef_search', String(EF_SEARCH_DEFAULT)],
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
interface AppliedRow {
|
|
24
|
+
readonly name: string | null;
|
|
25
|
+
readonly value: string | null;
|
|
26
|
+
readonly prior: string | null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Which setting to widen, before the search: `hnsw.iterative_scan = relaxed_order` on pgvector
|
|
31
|
+
* ≥ 0.8 — the scan continues until `k` rows pass the filter — else `hnsw.ef_search = max(40,
|
|
32
|
+
* wanted × 10)`. The version is the server's (`pg_extension`), read in the same statement as the
|
|
33
|
+
* `prior` value, for a search that joined a caller's transaction to put back. The write itself is
|
|
34
|
+
* `setLocal`'s: `@ultimat3/db`'s `local-settings.ts` is the framework's one `set_config` sender.
|
|
35
|
+
*/
|
|
36
|
+
export function hnswRecallSql(wanted: number): SqlFragment {
|
|
37
|
+
const ef = String(Math.min(EF_SEARCH_MAX, Math.max(EF_SEARCH_DEFAULT, wanted * 10)));
|
|
38
|
+
return sql`select setting.name, setting.value, current_setting(setting.name, true) as prior
|
|
39
|
+
from (
|
|
40
|
+
select case when iterative then 'hnsw.iterative_scan' else 'hnsw.ef_search' end as name,
|
|
41
|
+
case when iterative then 'relaxed_order' else ${ef} end as value
|
|
42
|
+
from (
|
|
43
|
+
select string_to_array(split_part(extversion, '-', 1), '.')::int[] >= '{0,8}'::int[] as iterative
|
|
44
|
+
from pg_extension where extname = 'vector'
|
|
45
|
+
) version
|
|
46
|
+
) setting`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* `read` on `client`, with the recall setting in place. Outside a transaction it opens a read-only
|
|
51
|
+
* one, so the setting cannot outlive the search on a pooled connection. Inside one it joins it and
|
|
52
|
+
* puts the prior value back, so the rest of the caller's transaction is untouched. A store pinned
|
|
53
|
+
* to a client OTHER than the open transaction's reads as it always did, outside it, unwidened.
|
|
54
|
+
*/
|
|
55
|
+
export async function withHnswRecall<T>(
|
|
56
|
+
client: DbClient | undefined,
|
|
57
|
+
wanted: number,
|
|
58
|
+
read: (on: DbClient) => Promise<T>,
|
|
59
|
+
): Promise<T> {
|
|
60
|
+
const open = currentTx();
|
|
61
|
+
if (open !== undefined && client !== undefined && client !== open.origin) return read(client);
|
|
62
|
+
return withReadTransaction(
|
|
63
|
+
async (tx) => {
|
|
64
|
+
const [applied] = await tx.query<AppliedRow>(hnswRecallSql(wanted));
|
|
65
|
+
const name = applied?.name ?? undefined;
|
|
66
|
+
if (name !== undefined && applied?.value != null)
|
|
67
|
+
await setLocal(tx, { [name]: applied.value });
|
|
68
|
+
const prior = applied?.prior ?? (name === undefined ? undefined : DEFAULTS.get(name));
|
|
69
|
+
if (open === undefined || name === undefined || prior === undefined) return read(tx);
|
|
70
|
+
const restore = { [name]: prior };
|
|
71
|
+
try {
|
|
72
|
+
return await read(tx);
|
|
73
|
+
} finally {
|
|
74
|
+
await setLocal(tx, restore).catch(() => undefined);
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
{ client },
|
|
78
|
+
);
|
|
79
|
+
}
|
package/src/pg-vector.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { finiteCount, finiteOption } from '@ultimat3/core';
|
|
7
7
|
import { type DbClient, db, type SqlFragment } from '@ultimat3/db';
|
|
8
8
|
import { VectorDimMismatchError } from './errors';
|
|
9
|
+
import { withHnswRecall } from './pg-vector-recall';
|
|
9
10
|
import {
|
|
10
11
|
ddlSql,
|
|
11
12
|
deleteSql,
|
|
@@ -116,8 +117,10 @@ export class PostgresVectorStore implements VectorStore {
|
|
|
116
117
|
// `k` is the statement's `limit` and reaches Postgres as a bound parameter, so a `NaN` is the
|
|
117
118
|
// database's error to report rather than this store's — and a fractional one is an error there
|
|
118
119
|
// too. Refused here instead, before a connection is taken, naming the argument the caller wrote.
|
|
119
|
-
|
|
120
|
-
|
|
120
|
+
const wanted = finiteCount(HYBRID, 'k', k);
|
|
121
|
+
return this.recall(
|
|
122
|
+
wanted,
|
|
123
|
+
searchSql(this.target, vector, { scope: this.scope, filter, k: wanted }),
|
|
121
124
|
);
|
|
122
125
|
}
|
|
123
126
|
|
|
@@ -147,7 +150,7 @@ export class PostgresVectorStore implements VectorStore {
|
|
|
147
150
|
candidates: finiteCount(HYBRID, 'candidates', input.candidates ?? Math.max(k * 4, 20)),
|
|
148
151
|
rrfK: finiteOption(HYBRID, 'rrfK', input.rrfK ?? 60),
|
|
149
152
|
};
|
|
150
|
-
return this.
|
|
153
|
+
return this.recall(args.candidates, hybridSql(this.target, input.query, input.vector, args));
|
|
151
154
|
}
|
|
152
155
|
|
|
153
156
|
async prune(filter: MetadataFilter, keep: readonly string[]): Promise<void> {
|
|
@@ -168,6 +171,14 @@ export class PostgresVectorStore implements VectorStore {
|
|
|
168
171
|
return rows.map(toHit);
|
|
169
172
|
}
|
|
170
173
|
|
|
174
|
+
/** An hnsw read: `wanted` rows that pass the scope, not the scan's first 40 filtered down. */
|
|
175
|
+
private async recall(wanted: number, statement: SqlFragment): Promise<readonly SearchHit[]> {
|
|
176
|
+
const rows = await withHnswRecall(this.input.client, wanted, (on) =>
|
|
177
|
+
on.query<HitRow>(statement),
|
|
178
|
+
);
|
|
179
|
+
return rows.map(toHit);
|
|
180
|
+
}
|
|
181
|
+
|
|
171
182
|
private assertDimension(received: number): void {
|
|
172
183
|
if (received !== this.dimension) {
|
|
173
184
|
throw new VectorDimMismatchError({
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Single responsibility: what a stream in flight has been billed SO FAR, handed from the provider
|
|
2
|
+
// that reads the wire to the gateway that settles the budget — for the streams that never reach
|
|
3
|
+
// `done`: abandoned by their consumer, cut, or aborted after the provider's first byte.
|
|
4
|
+
//
|
|
5
|
+
// Keyed by the request object the gateway passed, and read lazily: no cost per frame.
|
|
6
|
+
|
|
7
|
+
import type { Billed } from './billed';
|
|
8
|
+
import { billedCall } from './billed';
|
|
9
|
+
import { exactCostOf } from './cost';
|
|
10
|
+
import type { ModelId } from './models';
|
|
11
|
+
import type { GenerateRequest } from './provider';
|
|
12
|
+
import { estimateInputTokens } from './provider';
|
|
13
|
+
import { ZERO_USAGE } from './wire';
|
|
14
|
+
|
|
15
|
+
const running = new WeakMap<GenerateRequest, () => Billed | undefined>();
|
|
16
|
+
/** Requests that left the process, with the model they were priced for. */
|
|
17
|
+
const sent = new WeakMap<GenerateRequest, ModelId>();
|
|
18
|
+
|
|
19
|
+
/** The provider's reader of its running usage, registered once when the stream opens. */
|
|
20
|
+
export function trackStreamBill(request: GenerateRequest, read: () => Billed | undefined): void {
|
|
21
|
+
running.set(request, read);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* What the stream for `request` was billed before it stopped — `undefined` when no provider byte
|
|
26
|
+
* arrived (or the provider is one an app wrote, which reports nothing): the reservation goes back.
|
|
27
|
+
*/
|
|
28
|
+
export function streamBillOf(request: GenerateRequest): Billed | undefined {
|
|
29
|
+
const read = running.get(request);
|
|
30
|
+
if (read === undefined) return undefined;
|
|
31
|
+
try {
|
|
32
|
+
return read();
|
|
33
|
+
} catch {
|
|
34
|
+
return undefined;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** ~4 characters a token, the estimate `estimateTextTokens` uses: output the wire has not counted. */
|
|
39
|
+
export const streamedTokens = (chars: number): number => Math.ceil(chars / 4);
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Called by a provider as its request leaves the process — never for a signal already aborted,
|
|
43
|
+
* which `fetch` refuses without sending a byte. From here an abort is not free: the provider
|
|
44
|
+
* has the prompt, and bills it.
|
|
45
|
+
*/
|
|
46
|
+
export function trackSent(request: GenerateRequest, model: ModelId): void {
|
|
47
|
+
if (request.signal?.aborted === true) return;
|
|
48
|
+
sent.set(request, model);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The prompt's estimate, priced, for a request that was sent — `undefined` for one never sent. */
|
|
52
|
+
export function sentBillOf(request: GenerateRequest): Billed | undefined {
|
|
53
|
+
const model = sent.get(request);
|
|
54
|
+
if (model === undefined) return undefined;
|
|
55
|
+
const usage = { ...ZERO_USAGE, inputTokens: estimateInputTokens(request) };
|
|
56
|
+
return billedCall(usage, exactCostOf(model, usage));
|
|
57
|
+
}
|
package/src/wire.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { renderThrowable } from '@ultimat3/core';
|
|
|
11
11
|
import { AiTransportError } from './errors';
|
|
12
12
|
import type { StopDetails, StopReason, StreamChunk, TokenUsage } from './provider';
|
|
13
13
|
import type { SseFrame } from './sse';
|
|
14
|
+
import { streamedTokens } from './stream-bill';
|
|
14
15
|
import type { MalformedToolCall } from './tool-arguments';
|
|
15
16
|
import { parseToolArguments } from './tool-arguments';
|
|
16
17
|
import type { LlmToolCall } from './tools';
|
|
@@ -164,6 +165,10 @@ export class MessageStream {
|
|
|
164
165
|
private usage: TokenUsage = ZERO_USAGE;
|
|
165
166
|
private readonly pending = new Map<number, PendingTool>();
|
|
166
167
|
private stopped = false;
|
|
168
|
+
/** `message_start` arrived: the provider has billed the prompt from here on. */
|
|
169
|
+
private started = false;
|
|
170
|
+
/** Characters of text, thinking and tool arguments streamed — output `usage` has not counted yet. */
|
|
171
|
+
private streamedChars = 0;
|
|
167
172
|
|
|
168
173
|
/** Chunks this frame produced, in order. Unknown events yield nothing — the API adds them. */
|
|
169
174
|
push(frame: SseFrame): readonly StreamChunk[] {
|
|
@@ -200,6 +205,18 @@ export class MessageStream {
|
|
|
200
205
|
return this.stopped && this.pending.size === 0;
|
|
201
206
|
}
|
|
202
207
|
|
|
208
|
+
/**
|
|
209
|
+
* What the provider has billed so far, for a stream that stops before `message_stop` — or
|
|
210
|
+
* `undefined` before `message_start`, when nothing was. The output count is the larger of the
|
|
211
|
+
* wire's own running figure and an estimate from the characters streamed: the wire states its
|
|
212
|
+
* output once, at the end, and a ceiling is not held by an undercount.
|
|
213
|
+
*/
|
|
214
|
+
partialUsage(): TokenUsage | undefined {
|
|
215
|
+
if (!this.started) return undefined;
|
|
216
|
+
const streamed = streamedTokens(this.streamedChars);
|
|
217
|
+
return { ...this.usage, outputTokens: Math.max(this.usage.outputTokens, streamed) };
|
|
218
|
+
}
|
|
219
|
+
|
|
203
220
|
state(): StreamState {
|
|
204
221
|
return {
|
|
205
222
|
text: this.text,
|
|
@@ -238,6 +255,7 @@ export class MessageStream {
|
|
|
238
255
|
|
|
239
256
|
private onMessageStart(payload: Record<string, unknown>): readonly StreamChunk[] {
|
|
240
257
|
const message = asRecord(payload['message']);
|
|
258
|
+
this.started = true;
|
|
241
259
|
this.usage = { ...this.usage, ...parsePartialUsage(message?.['usage']) };
|
|
242
260
|
return [];
|
|
243
261
|
}
|
|
@@ -259,12 +277,14 @@ export class MessageStream {
|
|
|
259
277
|
const text = delta['text'];
|
|
260
278
|
if (delta['type'] === 'text_delta' && typeof text === 'string') {
|
|
261
279
|
this.text += text;
|
|
280
|
+
this.streamedChars += text.length;
|
|
262
281
|
return [{ type: 'text', text }];
|
|
263
282
|
}
|
|
264
283
|
const thinking = delta['thinking'];
|
|
265
284
|
if (delta['type'] === 'thinking_delta' && typeof thinking === 'string') {
|
|
266
285
|
// Deliberately NOT appended to `text`: thinking is not the answer, and a caller that
|
|
267
286
|
// concatenated every chunk would otherwise ship the reasoning to the user.
|
|
287
|
+
this.streamedChars += thinking.length;
|
|
268
288
|
return [{ type: 'thinking', text: thinking }];
|
|
269
289
|
}
|
|
270
290
|
const partial = delta['partial_json'];
|
|
@@ -276,6 +296,7 @@ export class MessageStream {
|
|
|
276
296
|
) {
|
|
277
297
|
const tool = this.pending.get(index);
|
|
278
298
|
if (tool !== undefined) tool.json += partial;
|
|
299
|
+
this.streamedChars += partial.length;
|
|
279
300
|
}
|
|
280
301
|
return [];
|
|
281
302
|
}
|