@yaks/model 0.0.0-stage → 0.2.36
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 +202 -0
- package/README.md +868 -2
- package/_dist/afford.d.ts +69 -0
- package/_dist/afford.d.ts.map +1 -0
- package/_dist/attribute.d.ts +52 -0
- package/_dist/attribute.d.ts.map +1 -0
- package/_dist/batch.d.ts +28 -0
- package/_dist/batch.d.ts.map +1 -0
- package/_dist/cache.d.ts +15 -0
- package/_dist/cache.d.ts.map +1 -0
- package/_dist/deferred.d.ts +9 -0
- package/_dist/deferred.d.ts.map +1 -0
- package/_dist/graph.d.ts +3 -0
- package/_dist/graph.d.ts.map +1 -0
- package/_dist/image.d.ts +46 -0
- package/_dist/image.d.ts.map +1 -0
- package/_dist/inference.d.ts +58 -0
- package/_dist/inference.d.ts.map +1 -0
- package/_dist/limits.d.ts +142 -0
- package/_dist/limits.d.ts.map +1 -0
- package/_dist/media.d.ts +28 -0
- package/_dist/media.d.ts.map +1 -0
- package/_dist/message.d.ts +5 -0
- package/_dist/message.d.ts.map +1 -0
- package/_dist/mod.d.ts +298 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/offers.d.ts +19 -0
- package/_dist/offers.d.ts.map +1 -0
- package/_dist/onward.d.ts +77 -0
- package/_dist/onward.d.ts.map +1 -0
- package/_dist/prices.d.ts +27 -0
- package/_dist/prices.d.ts.map +1 -0
- package/_dist/provider.d.ts +49 -0
- package/_dist/provider.d.ts.map +1 -0
- package/_dist/results.d.ts +21 -0
- package/_dist/results.d.ts.map +1 -0
- package/_dist/route.d.ts +189 -0
- package/_dist/route.d.ts.map +1 -0
- package/_dist/sse.d.ts +4 -0
- package/_dist/sse.d.ts.map +1 -0
- package/_dist/stall.d.ts +47 -0
- package/_dist/stall.d.ts.map +1 -0
- package/_dist/step.d.ts +71 -0
- package/_dist/step.d.ts.map +1 -0
- package/_dist/submission.d.ts +7 -0
- package/_dist/submission.d.ts.map +1 -0
- package/_dist/vocab.d.ts +82 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/_dist/windows.d.ts +6 -0
- package/_dist/windows.d.ts.map +1 -0
- package/afford.js +135 -0
- package/afford.js.map +1 -0
- package/afford.ts +208 -0
- package/attribute.js +109 -0
- package/attribute.js.map +1 -0
- package/attribute.ts +120 -0
- package/batch.js +8 -0
- package/batch.js.map +1 -0
- package/batch.ts +37 -0
- package/cache.js +28 -0
- package/cache.js.map +1 -0
- package/cache.ts +53 -0
- package/deferred.js +29 -0
- package/deferred.js.map +1 -0
- package/deferred.ts +54 -0
- package/deno.json +1 -0
- package/graph.js +8 -0
- package/graph.js.map +1 -0
- package/graph.ts +9 -0
- package/image.js +118 -0
- package/image.js.map +1 -0
- package/image.ts +108 -0
- package/inference.js +119 -0
- package/inference.js.map +1 -0
- package/inference.ts +223 -0
- package/limits.js +204 -0
- package/limits.js.map +1 -0
- package/limits.ts +230 -0
- package/media.js +76 -0
- package/media.js.map +1 -0
- package/media.ts +139 -0
- package/message.js +21 -0
- package/message.js.map +1 -0
- package/message.ts +17 -0
- package/mod.js +396 -0
- package/mod.js.map +1 -0
- package/mod.ts +695 -0
- package/offers.js +53 -0
- package/offers.js.map +1 -0
- package/offers.ts +84 -0
- package/onward.js +110 -0
- package/onward.js.map +1 -0
- package/onward.ts +123 -0
- package/package.json +53 -4
- package/prices.js +61 -0
- package/prices.js.map +1 -0
- package/prices.json +643 -0
- package/prices.ts +60 -0
- package/provider.js +6 -0
- package/provider.js.map +1 -0
- package/provider.ts +89 -0
- package/results.js +51 -0
- package/results.js.map +1 -0
- package/results.ts +47 -0
- package/route.js +263 -0
- package/route.js.map +1 -0
- package/route.ts +359 -0
- package/sse.js +71 -0
- package/sse.js.map +1 -0
- package/sse.ts +82 -0
- package/stall.js +166 -0
- package/stall.js.map +1 -0
- package/stall.ts +201 -0
- package/step.js +226 -0
- package/step.js.map +1 -0
- package/step.ts +265 -0
- package/submission.js +38 -0
- package/submission.js.map +1 -0
- package/submission.ts +38 -0
- package/vocab.js +83 -0
- package/vocab.js.map +1 -0
- package/vocab.json +613 -0
- package/vocab.ts +139 -0
- package/windows.js +35 -0
- package/windows.js.map +1 -0
- package/windows.ts +28 -0
package/README.md
CHANGED
|
@@ -1,3 +1,869 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @yaks/model
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Defines provider-neutral model request and reply types, vocabulary for providers
|
|
4
|
+
and models, and helpers for billing and recovering generated media. Use it
|
|
5
|
+
between a conversation and a provider adapter. It implements no provider's
|
|
6
|
+
transport; `@yaks/model/step` carries one model step from one host to another's
|
|
7
|
+
providers.
|
|
8
|
+
|
|
9
|
+
## Model interface
|
|
10
|
+
|
|
11
|
+
A **provider** is a service that runs models, described by the `provider`
|
|
12
|
+
[component](../graph/README.md#data-model). A **model** is what serves a model
|
|
13
|
+
request, independent of its provider; the `model` component describes it, and
|
|
14
|
+
`Model` is its callable TypeScript interface.
|
|
15
|
+
|
|
16
|
+
A **model request** (`Request`) is the model name, conversation items, tool
|
|
17
|
+
descriptions and options passed to `Model`. A **reply** (`Reply`) is the
|
|
18
|
+
provider's id, the model that served the model request and the items it
|
|
19
|
+
produced. An **item** (`Item`) is one input or output: `instruction`, `user`,
|
|
20
|
+
`assistant`, `image`, `call` or `result`. For example,
|
|
21
|
+
`{ kind: 'user', text: 'Hello' }` is an item.
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import type { Model } from '@yaks/model'
|
|
25
|
+
import { equal } from '@yaks/testing'
|
|
26
|
+
|
|
27
|
+
const model: Model = async (request) => ({
|
|
28
|
+
id: 'reply-1',
|
|
29
|
+
model: request.model,
|
|
30
|
+
items: [{ kind: 'assistant', text: 'Hello back' }],
|
|
31
|
+
})
|
|
32
|
+
const reply = await model({
|
|
33
|
+
model: 'example',
|
|
34
|
+
items: [{ kind: 'user', text: 'Hello' }],
|
|
35
|
+
tools: [],
|
|
36
|
+
})
|
|
37
|
+
equal(reply.items, [{ kind: 'assistant', text: 'Hello back' }])
|
|
38
|
+
equal(reply.model, 'example')
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`deferredModel(load, metadata)` constructs a model whose transport loads on its
|
|
42
|
+
first request or discovery call. Concurrent calls share that model; `mark`,
|
|
43
|
+
`vocab`, `anchor`, `lateResults` and `reads` (the media types it reads as they
|
|
44
|
+
are, beside text, each with the most bytes of one file) remain available
|
|
45
|
+
synchronously from `metadata`. Declare `info: true` or `recover: true` when the
|
|
46
|
+
provider supports those operations.
|
|
47
|
+
|
|
48
|
+
`onward(chain, passed?)` asks a chain of models in order: where a provider
|
|
49
|
+
refuses the step before producing output (`refused`: the model asked is retired
|
|
50
|
+
or unknown, `gone`, a `ModelError` coded `model` or OpenAI's `model_not_found`;
|
|
51
|
+
its own account is `dry`, its spend limit, billing quota, credit or plan window
|
|
52
|
+
used up, or its credential is unavailable), the step goes to the next model the
|
|
53
|
+
chain names, and `passed` hears the failure. A refusal ran nothing, so one the
|
|
54
|
+
provider acknowledged first passes on too. Once the provider produces output,
|
|
55
|
+
its failure ends the step. A caller's own ceiling (`limit`) is no refusal:
|
|
56
|
+
`spent` hears it with `dry`.
|
|
57
|
+
|
|
58
|
+
A provider is a plugin. Its package exports a `./provider` facet
|
|
59
|
+
(`ProviderFacet`): `providers(lent, options)` returns the models it serves,
|
|
60
|
+
keyed by the `provider.name` each serves under, built over what the host lends
|
|
61
|
+
(`Lent`: the shared `fetch`, the person's sign-in `key` and `refresh` by
|
|
62
|
+
integration, the artifact `store`, the host's `env` and, where the host keeps
|
|
63
|
+
them, the `receipts` an interrupted call is delivered from) and the plugin's
|
|
64
|
+
options from the config. `hosts(options)`, where a plugin offers it, names the
|
|
65
|
+
hosts those models call, so a host that puts a credential of its own in their
|
|
66
|
+
calls sends it nowhere else. `native(lent, options, spending)`, where a plugin
|
|
67
|
+
offers it, is the provider's own door (`Native`): one call as its API takes it,
|
|
68
|
+
held to what the host's `Spending` affords and settled at what it cost, for a
|
|
69
|
+
host that passes a caller's input through whole. A model priced by the call
|
|
70
|
+
rather than by its tokens quotes such a request itself (`Model.quote`). A model
|
|
71
|
+
whose provider runs tools of its own within a request (a web search, a page
|
|
72
|
+
fetch) says the most they add to one (`Model.hosted`: `searches`, and the
|
|
73
|
+
`input` tokens of what they read), which the provider enforces and a meter
|
|
74
|
+
reserves beside the request's own bound. A host running conversations
|
|
75
|
+
([@yaks/harness](../harness/README.md), the hosted model executor in
|
|
76
|
+
workers/model) asks every plugin its config names, so a config serves exactly
|
|
77
|
+
the providers it lists, and the host depends on none of them.
|
|
78
|
+
[@yaks/openai](../openai/README.md),
|
|
79
|
+
[@yaks/openrouter](../openrouter/README.md),
|
|
80
|
+
[@yaks/anthropic](../anthropic/README.md) and
|
|
81
|
+
[@yaks/claude](../claude/README.md) each export one.
|
|
82
|
+
|
|
83
|
+
## Install
|
|
84
|
+
|
|
85
|
+
```sh
|
|
86
|
+
deno add jsr:@yaks/model
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Exports
|
|
90
|
+
|
|
91
|
+
| Export | Provides |
|
|
92
|
+
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
93
|
+
| `@yaks/model` | `listPrice`, `deferredModel`, `message`; `gone`, `refused`, `onward`, `Link`; `dry`, `spent`; `Offer`, `offers`, `offerFor`, `serving`; `Lent`, `ProviderFacet`; `Executor`, `Inference`, `InferenceHost`, `InferenceReceipt`, `FrozenModelRequest`, `infer`, `inferenceReply`, `frozenRequest`, `thawedRequest`; `Model`, `Request`, `Reply`, `Item`, `Tool`, `TextDelta`, `Question`, `Questions`, `Answer`, `Usage`, `Price`, `Mark`, `Answered`, `Listed`; `ModelError`; `models`, `modelDoc`, `addressed`, `requesting`, `confirmed`; `weigh`, `billed`, `limitEid`, `dollars`, `hourly`, `attribute`, `generated`, `merged`, `Paid`, `Part`; `submitted`, `acknowledged`, `submitCall`; `MediaReceipt`, `MediaReceipts`, `MediaRecord`, `mediaReceipts`, `receivedMedia`, `recoveredMedia`; component-name constants `PROVIDER`, `MODEL`, `TOOL`, `QUESTIONS`, `ANSWER`, `USAGE`, `PRICE`, `COST`, `RATE_LIMIT`, `RESPONSE` |
|
|
94
|
+
| `@yaks/model/vocab` | `modelDoc`, `docs`, `description` |
|
|
95
|
+
| `@yaks/model/graph` | `plugins()`, returning `[models()]` |
|
|
96
|
+
| `@yaks/model/sse` | `jsonFrames(body, fault, check?, done?)`: the JSON events of a server-sent event stream |
|
|
97
|
+
| `@yaks/model/stall` | `STALL_TIMEOUT`, `stallMs(req)`, `Stalled`, `watchdog(ms, clock?, stop?)`, `watched(fetch, ms)`, `watchedBody(body, ms)`: a request whose stream goes quiet fails as stalled |
|
|
98
|
+
| `@yaks/model/step` | `PATH`, `BEAT`, `answering(serve, report, clock?)`, `forwarding(lent, options?)`, `forwarded(graph, reach)`: one model step forwarded by one host and answered from the providers of another |
|
|
99
|
+
| `@yaks/model/batch` | `Batches`, `Asked`, `Answered`, `BATCH`: a provider's batch API, many one-turn requests sent as one at half the price, each answer found by its request's `id` (@yaks/anthropic/batches, @yaks/openai/batches) |
|
|
100
|
+
| `@yaks/model/image` | `imageTool(models, words?)`, `imageMade(make, models, args)`: the `image_new` tool a model makes an image with, and the image it asks for |
|
|
101
|
+
|
|
102
|
+
## Items and delivery
|
|
103
|
+
|
|
104
|
+
An item's optional `from` names who supplied its words, independently of its
|
|
105
|
+
provider turn role. Prompt assembly calls `message(item)` before handing the
|
|
106
|
+
item to a provider. It renders `From <from>:` into text, tool output or a media
|
|
107
|
+
label and removes the metadata. The receiving model's own output needs no source
|
|
108
|
+
label. A user-role item can carry system context, a parent instruction, a helper
|
|
109
|
+
report or a tool refusal; its role does not make those the person's words.
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
import { message } from '@yaks/model'
|
|
113
|
+
import { equal } from '@yaks/testing'
|
|
114
|
+
|
|
115
|
+
equal(
|
|
116
|
+
message({
|
|
117
|
+
kind: 'user',
|
|
118
|
+
from: 'your parent session',
|
|
119
|
+
text: 'Read the file.',
|
|
120
|
+
}),
|
|
121
|
+
{
|
|
122
|
+
kind: 'user',
|
|
123
|
+
text: 'From your parent session:\nRead the file.',
|
|
124
|
+
},
|
|
125
|
+
)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
`Tool` describes a [tool](../graph/README.md#tools): its `name`, `description`
|
|
129
|
+
and JSON Schema `parameters`. A `call` item holds JSON arguments in `args`; a
|
|
130
|
+
`result` item answers that call by its `id`. The caller executes tools.
|
|
131
|
+
|
|
132
|
+
An `image` item holds `bytes`, `mediaType` and a textual `label`; a `document`
|
|
133
|
+
item holds the same for a document the model reads as it is, such as a PDF. The
|
|
134
|
+
caller resolves stored media into bytes before calling the model. A provider
|
|
135
|
+
adapter translates items into its protocol and determines which inputs it
|
|
136
|
+
supports, refusing a request with one it does not.
|
|
137
|
+
|
|
138
|
+
A **text delta** (`TextDelta`) is output text delivered to `Request.onText`; its
|
|
139
|
+
`index` identifies the final assistant item in `Reply.items`. It excludes
|
|
140
|
+
private reasoning and partial tool arguments. `Request.signal` cancels the model
|
|
141
|
+
request; adapters must implement propagation to their I/O. It does not cancel
|
|
142
|
+
independent tool processes.
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
import type { Item, Model, TextDelta, Tool } from '@yaks/model'
|
|
146
|
+
import { equal } from '@yaks/testing'
|
|
147
|
+
|
|
148
|
+
const tool: Tool = {
|
|
149
|
+
name: 'double',
|
|
150
|
+
description: 'Double a number',
|
|
151
|
+
parameters: { type: 'object', properties: { n: { type: 'number' } } },
|
|
152
|
+
}
|
|
153
|
+
const items: Item[] = [
|
|
154
|
+
{ kind: 'instruction', text: 'Use double' },
|
|
155
|
+
{
|
|
156
|
+
kind: 'image',
|
|
157
|
+
bytes: new Uint8Array([1]),
|
|
158
|
+
mediaType: 'image/png',
|
|
159
|
+
label: 'sample',
|
|
160
|
+
},
|
|
161
|
+
{ kind: 'call', id: 'c1', name: 'double', args: '{"n":2}' },
|
|
162
|
+
{ kind: 'result', id: 'c1', output: '4' },
|
|
163
|
+
]
|
|
164
|
+
const deltas: TextDelta[] = []
|
|
165
|
+
const model: Model = async (request) => {
|
|
166
|
+
equal(request.signal?.aborted, false)
|
|
167
|
+
equal(request.items.at(-1), { kind: 'result', id: 'c1', output: '4' })
|
|
168
|
+
request.onText?.({ index: 0, text: '4' })
|
|
169
|
+
return {
|
|
170
|
+
id: 'r1',
|
|
171
|
+
model: request.model,
|
|
172
|
+
items: [{ kind: 'assistant', text: '4' }],
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
await model({
|
|
176
|
+
model: 'example',
|
|
177
|
+
items,
|
|
178
|
+
tools: [tool],
|
|
179
|
+
signal: new AbortController().signal,
|
|
180
|
+
onText: (delta) => deltas.push(delta),
|
|
181
|
+
})
|
|
182
|
+
equal(deltas, [{ index: 0, text: '4' }])
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
`Request.instructions`, `effort` and `tokens` carry instructions, reasoning
|
|
186
|
+
effort and a reply token ceiling. `conversation` identifies the conversation for
|
|
187
|
+
provider caching. `input` carries explicit model-native inputs such as lyrics or
|
|
188
|
+
duration; providers validate supported inputs.
|
|
189
|
+
|
|
190
|
+
`Request.modalities` asks for `text`, `image` or `audio` output.
|
|
191
|
+
`Reply.artifacts` carries generated [artifacts](../blob/README.md), each with a
|
|
192
|
+
`call` and optional `revised_prompt`. These fields describe the interface;
|
|
193
|
+
[@yaks/openai](../openai/README.md) and
|
|
194
|
+
[@yaks/workers-ai](../workers-ai/README.md) implement provider calls.
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import type { Model } from '@yaks/model'
|
|
198
|
+
import { equal } from '@yaks/testing'
|
|
199
|
+
|
|
200
|
+
const model: Model = async (request) => {
|
|
201
|
+
equal(request.modalities, ['audio'])
|
|
202
|
+
equal(request.input, { lyrics: 'Hello', duration: 5 })
|
|
203
|
+
return {
|
|
204
|
+
id: 'r1',
|
|
205
|
+
model: request.model,
|
|
206
|
+
items: [],
|
|
207
|
+
artifacts: [{
|
|
208
|
+
call: request.call!,
|
|
209
|
+
address: 'stored-audio',
|
|
210
|
+
media_type: 'audio/wav',
|
|
211
|
+
size: 32,
|
|
212
|
+
}],
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
const reply = await model({
|
|
216
|
+
call: 'c1',
|
|
217
|
+
model: 'example',
|
|
218
|
+
items: [],
|
|
219
|
+
tools: [],
|
|
220
|
+
modalities: ['audio'],
|
|
221
|
+
input: { lyrics: 'Hello', duration: 5 },
|
|
222
|
+
})
|
|
223
|
+
equal(reply.artifacts?.[0].call, 'c1')
|
|
224
|
+
equal(reply.artifacts?.[0].media_type, 'audio/wav')
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
## Anchors and provider components
|
|
228
|
+
|
|
229
|
+
An **anchor** is an opaque provider reference to an earlier reply. With
|
|
230
|
+
`Request.anchor`, `items` contains only the items after that reply. Without an
|
|
231
|
+
anchor the caller supplies the needed items again. Anchors depend on the
|
|
232
|
+
provider retaining the earlier reply.
|
|
233
|
+
|
|
234
|
+
`Model.mark(reply)` returns provider-owned components (`Mark`) to attach to the
|
|
235
|
+
[entity](../graph/README.md#data-model) recording the reply. `Model.vocab`
|
|
236
|
+
declares them in a [vocabulary document](../vocab/README.md#vocabulary), and
|
|
237
|
+
`Model.anchor(components)` reads an anchor back. These optional members keep
|
|
238
|
+
provider-specific state out of the conversation interface.
|
|
239
|
+
|
|
240
|
+
```ts
|
|
241
|
+
import type { Model } from '@yaks/model'
|
|
242
|
+
import { equal } from '@yaks/testing'
|
|
243
|
+
|
|
244
|
+
const model: Model = Object.assign(
|
|
245
|
+
async (request: Parameters<Model>[0]) => ({
|
|
246
|
+
id: 'r1',
|
|
247
|
+
model: request.model,
|
|
248
|
+
items: [],
|
|
249
|
+
}),
|
|
250
|
+
{
|
|
251
|
+
mark: (reply: { id: string }) => ({ example_response: { id: reply.id } }),
|
|
252
|
+
anchor: (components: Record<string, unknown>) =>
|
|
253
|
+
(components.example_response as { id?: string } | undefined)?.id,
|
|
254
|
+
vocab: {
|
|
255
|
+
$defs: {
|
|
256
|
+
example_response: {
|
|
257
|
+
component: true,
|
|
258
|
+
type: 'object',
|
|
259
|
+
properties: { id: { type: 'string' } },
|
|
260
|
+
},
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
},
|
|
264
|
+
)
|
|
265
|
+
const reply = await model({ model: 'example', items: [], tools: [] })
|
|
266
|
+
equal(model.anchor!(model.mark!(reply)), 'r1')
|
|
267
|
+
equal(model.anchor!({}), undefined)
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
## Providers and models in a graph
|
|
271
|
+
|
|
272
|
+
`modelDoc` declares `provider`, `model`, `serves`, `routes`, `usage`, `price`,
|
|
273
|
+
`cost`, `response`, `questions`, `answer` and `submitted{at}`. `models()`
|
|
274
|
+
supplies a graph [plugin](../graph/README.md#data-model) with that vocabulary,
|
|
275
|
+
name addressing and the `requesting` normalization
|
|
276
|
+
[hook](../graph/README.md#data-model). `@yaks/model/graph` exports the same
|
|
277
|
+
plugin through `plugins()`.
|
|
278
|
+
|
|
279
|
+
Provider and model names are each an
|
|
280
|
+
[identity](../vocab/README.md#identity-and-indexes). `addressed` resolves those
|
|
281
|
+
names to [eids](../graph/README.md#data-model); a name held by both a provider
|
|
282
|
+
and a model is refused. A **serves** component records a provider's offering of
|
|
283
|
+
a model on an [edge](../edge/README.md); `serves.name` is the name that provider
|
|
284
|
+
accepts, which may differ from `model.name`.
|
|
285
|
+
|
|
286
|
+
`requesting` replaces a name in `using.model` with its eid and creates an
|
|
287
|
+
unknown model with `offered: false` and `pending: {}` before admission resolves
|
|
288
|
+
references. `confirmed(provider,
|
|
289
|
+
name, listing?)` returns
|
|
290
|
+
[bundles](../graph/README.md#data-model) that remove `pending`, set
|
|
291
|
+
`offered: true`, and record the provider's serves edge.
|
|
292
|
+
|
|
293
|
+
```ts
|
|
294
|
+
import { edgeDoc, edgeKeywords } from '@yaks/edge'
|
|
295
|
+
import { graph, identityEid } from '@yaks/graph'
|
|
296
|
+
import { kernelDoc, kernelKeywords } from '@yaks/kernel'
|
|
297
|
+
import { nameKeywords } from '@yaks/names'
|
|
298
|
+
import { ram } from '@yaks/ram'
|
|
299
|
+
import { loadVocab } from '@yaks/vocab'
|
|
300
|
+
import { confirmed, modelDoc, models } from '@yaks/model'
|
|
301
|
+
import { equal } from '@yaks/testing'
|
|
302
|
+
|
|
303
|
+
const using = {
|
|
304
|
+
$defs: {
|
|
305
|
+
using: {
|
|
306
|
+
component: true,
|
|
307
|
+
type: 'object',
|
|
308
|
+
properties: { model: { type: 'string', ref: 'model', death: 'keep' } },
|
|
309
|
+
},
|
|
310
|
+
},
|
|
311
|
+
}
|
|
312
|
+
const vocab = loadVocab([kernelDoc, edgeDoc, modelDoc, using], [
|
|
313
|
+
kernelKeywords,
|
|
314
|
+
nameKeywords,
|
|
315
|
+
edgeKeywords,
|
|
316
|
+
])
|
|
317
|
+
const g = graph({ storage: ram(vocab), vocab, plugins: [models()] })
|
|
318
|
+
await g.apply([{ entity: { eid: '$p' }, provider: { name: 'example' } }])
|
|
319
|
+
await g.apply([{ entity: { eid: 'request-1' }, using: { model: 'release' } }])
|
|
320
|
+
const eid = identityEid('model', ['release'])
|
|
321
|
+
equal((await g.get([eid]))[0].model, { name: 'release', offered: false })
|
|
322
|
+
equal(await g.address(['release']), new Map([['release', eid]]))
|
|
323
|
+
await g.apply(confirmed(identityEid('provider', ['example']), 'release', {
|
|
324
|
+
name: 'release',
|
|
325
|
+
context: 8192,
|
|
326
|
+
price: { input: 1, output: 2 },
|
|
327
|
+
}))
|
|
328
|
+
const [offered] = await g.get([eid])
|
|
329
|
+
equal(offered.model, { name: 'release', context: 8192, offered: true })
|
|
330
|
+
equal(offered.pending, undefined)
|
|
331
|
+
equal(offered.price, { input: 1, output: 2 })
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
`provider.base` is its HTTP root URL and `provider.api` names the protocol, such
|
|
335
|
+
as `ollama` or `openai`. A **context window** is the token capacity for input
|
|
336
|
+
and reply together: `model.context` declares it, `provider.context` provides a
|
|
337
|
+
fallback, and `model.enforced` records a provider-enforced ceiling.
|
|
338
|
+
`model.modalities` declares requested outputs and `model.effort` the default
|
|
339
|
+
reasoning effort. This package declares those properties; consumers such as
|
|
340
|
+
[@yaks/session](../session/README.md) implement their use.
|
|
341
|
+
|
|
342
|
+
`Model.list()` returns provider model descriptions (`Listed`), and
|
|
343
|
+
`Model.info(name)` returns one description or `undefined`.
|
|
344
|
+
|
|
345
|
+
```ts
|
|
346
|
+
import type { Listed, Model } from '@yaks/model'
|
|
347
|
+
import { equal } from '@yaks/testing'
|
|
348
|
+
|
|
349
|
+
const listing: Listed = { name: 'release', context: 8192, modalities: ['text'] }
|
|
350
|
+
const model: Model = Object.assign(
|
|
351
|
+
async (request: Parameters<Model>[0]) => ({
|
|
352
|
+
id: 'r1',
|
|
353
|
+
model: request.model,
|
|
354
|
+
items: [],
|
|
355
|
+
}),
|
|
356
|
+
{
|
|
357
|
+
list: async () => [listing],
|
|
358
|
+
info: async (name: string) => name === listing.name ? listing : undefined,
|
|
359
|
+
},
|
|
360
|
+
)
|
|
361
|
+
equal(await model.list!(), [listing])
|
|
362
|
+
equal(await model.info!('missing'), undefined)
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
## Usage, price and cost
|
|
366
|
+
|
|
367
|
+
**Usage** (`Usage`, `usage`) is token counts for one model request, and the web
|
|
368
|
+
searches its provider ran for it (`web_searches`). Cached input, input written
|
|
369
|
+
to the cache (`cache_write_tokens`, and of those the ones kept an hour,
|
|
370
|
+
`cache_write_1h_tokens`) and reasoning output are subsets of input and output,
|
|
371
|
+
not extra tokens; an absent count is unknown. **Price** (`Price`, `price`) is
|
|
372
|
+
dollars per million input, output and optional cached, cache-write and hour-long
|
|
373
|
+
cache-write tokens, and dollars per web search (`web_search`). **Cost** (`cost`)
|
|
374
|
+
is the dollars spent by one model request or tool call, with `reported` saying
|
|
375
|
+
whether the provider supplied that amount. A **rate limit**
|
|
376
|
+
(`rate_limit{provider, window, account, model, used, resets, at}`) is the latest
|
|
377
|
+
reading of how much of a provider's plan a window has used; with a `model`, of a
|
|
378
|
+
limit the plan sets on that model's requests alone, such as Claude's weekly cap
|
|
379
|
+
on Fable. Whoever hears a provider say so reports it as a
|
|
380
|
+
`Limit{provider, account, per, model, window, used, resets}` (a model on its
|
|
381
|
+
`Reply.limits`, or on the `ModelError.limits` of a refusal). A reader that hears
|
|
382
|
+
a limit on one model says `per: 'model'`, `metering(limits, model)` names the
|
|
383
|
+
model the request asked, and `limitRows(limits, at)` gives the rows that keep
|
|
384
|
+
them. `accountHome(runner, env)` is the directory of the account a CLI signs in
|
|
385
|
+
with, `signingIn(runner, home, env)` the environment that signs it in with
|
|
386
|
+
another, and `accountEid` its row.
|
|
387
|
+
|
|
388
|
+
## Routing a default
|
|
389
|
+
|
|
390
|
+
A **router** chooses which of several offerings a default runs on.
|
|
391
|
+
`route({routes, readings, now})` (`@yaks/model/route`) is pure: `routes` are the
|
|
392
|
+
offerings, each `{provider, model, name, plan, pinned}` with `plan` the provider
|
|
393
|
+
whose limits meter it, and `readings` are `rate_limit` rows. It answers
|
|
394
|
+
`{provider, model, why}`, or nothing where no rule can say. Each rule orders the
|
|
395
|
+
offerings it can speak for, best first, and the first rule that speaks for any
|
|
396
|
+
answers; `why` says in one line what it learned. There are two. A pinned
|
|
397
|
+
offering (`pinned`, the time it was pinned) is the answer whatever the plans
|
|
398
|
+
read. Otherwise the offerings whose plan has a reading are weighed, the one with
|
|
399
|
+
the most of its longest window left first, and a window that has reset since its
|
|
400
|
+
reading counts as unused. A parameter for a later rule (the work's kind) is
|
|
401
|
+
another property of what is asked.
|
|
402
|
+
|
|
403
|
+
`pace(window, now, back)` is a window's usage against its pace: the share of it
|
|
404
|
+
gone, the points used less `back`, the points a reset gives back, and the
|
|
405
|
+
difference (`{gone, spent, under}`). `freest({accounts, readings, now})` chooses
|
|
406
|
+
which of a provider's accounts a run signs in with: the one further under its
|
|
407
|
+
weekly pace, the week's reading less half its limit on one model (Claude's cap
|
|
408
|
+
on Fable is half the week, and a Fable reset gives that share back). A week that
|
|
409
|
+
has reset since its reading is unused, and an account nothing has read yet goes
|
|
410
|
+
first. An account whose five hours read 90% used or more, and have not reset,
|
|
411
|
+
goes after every account with room. It answers `{account, why}`, and `full`
|
|
412
|
+
where even the chosen account has no room. `bin/pace.ts` prints the same pace
|
|
413
|
+
for `claude-budget`, so the two agree.
|
|
414
|
+
|
|
415
|
+
In a graph the offerings are data: a **routes** edge from the row whose `using`
|
|
416
|
+
is the default to a `serves` edge, `routes{pinned}` on the one that is pinned,
|
|
417
|
+
and `provider{plan}` on a provider that spends another's plan. @yaks/harness
|
|
418
|
+
reads them for what a native session asks by default
|
|
419
|
+
([harness](../harness/README.md)).
|
|
420
|
+
|
|
421
|
+
A model a graph meets for the first time, by a request that names it or an
|
|
422
|
+
imported transcript, is given its vendor's list price (`listPrice(name)`), so
|
|
423
|
+
what Claude Code and Codex spent weighs in dollars without anyone writing a
|
|
424
|
+
price. The list is `prices.json`: Anthropic's and OpenAI's models, under the
|
|
425
|
+
names their transcripts use, from OpenRouter's public listing on the day it
|
|
426
|
+
names;
|
|
427
|
+
`deno run --allow-net=openrouter.ai --allow-write=packages/model bin/prices.ts`
|
|
428
|
+
fetches it again. A name's bracketed context window (`[1m]`) and release date
|
|
429
|
+
(`-20251001`) are dropped to find it. The price on a model's row is the one a
|
|
430
|
+
graph weighs at: change it there
|
|
431
|
+
(`price{input, output, cached, cache_write,
|
|
432
|
+
cache_write_1h, web_search}`,
|
|
433
|
+
dollars per million tokens and per search), and the list never writes over it.
|
|
434
|
+
|
|
435
|
+
`weigh(price, usage)` calculates dollars, treating missing counts as zero and
|
|
436
|
+
using the input price when the cached or cache-write price is absent.
|
|
437
|
+
`affordable(price, inputUpperTokens, remainingDollars, outputTokens?, searches?)`
|
|
438
|
+
returns the largest affordable output limit and its reserved dollars, or `null`,
|
|
439
|
+
reserving `searches` web searches beside the tokens. The input bound includes
|
|
440
|
+
provider framing, tools and retained conversation history; a token estimate is
|
|
441
|
+
insufficient. It reserves input at the highest applicable cache tariff, rounds
|
|
442
|
+
the maximum cost upward, and requires the provider to enforce the returned
|
|
443
|
+
output limit.
|
|
444
|
+
|
|
445
|
+
`promptBound(prompt, context, tools?)` is that bound for a text prompt and the
|
|
446
|
+
tools it declares, built before the call: twice their compact JSON's UTF-8 bytes
|
|
447
|
+
(a text token covers at least one byte; doubling covers a template's spaces and
|
|
448
|
+
indentation) plus `FRAMING` tokens, and never more than `context`. A prompt
|
|
449
|
+
carrying media is bounded by `context` alone; tools are declared as text, so an
|
|
450
|
+
argument named `document` or `image` is not media.
|
|
451
|
+
`requestBound(request,
|
|
452
|
+
context)` applies it to a `Request`'s instructions,
|
|
453
|
+
items, questions and input beside its tools, or gives `context` when an `anchor`
|
|
454
|
+
continues history the provider holds.
|
|
455
|
+
|
|
456
|
+
`retained(price, cacheRetention?)` is a request's price as it can be billed: a
|
|
457
|
+
provider keeps the longest cache lifetime it offers not over what the request
|
|
458
|
+
asks, or its default, so the hour's write tariff (`cache_write_1h`) applies only
|
|
459
|
+
to a request asking to keep its prefix an hour. A caller holds and charges a
|
|
460
|
+
request at this price.
|
|
461
|
+
|
|
462
|
+
`charged(reply, price, maximumReservedDollars)` settles reported dollars or
|
|
463
|
+
complete usage conservatively. Missing usage retains the reserved maximum;
|
|
464
|
+
unclassified input uses the highest cache tariff.
|
|
465
|
+
|
|
466
|
+
`billed(reply, price?)` uses `Reply.cost` first (provider-reported unless
|
|
467
|
+
`costReported: false`), then weighs usage if both usage and price exist, or
|
|
468
|
+
returns `undefined`.
|
|
469
|
+
|
|
470
|
+
A prompt is cached as a prefix in the order it is sent, so where a token sits
|
|
471
|
+
says how it was paid. `attribute(usage, parts)` lays a request's input parts out
|
|
472
|
+
in that order, scales their sizes to the reported input, and splits each into
|
|
473
|
+
`Paid` tokens: read from the cache, written to it, fresh, and generated.
|
|
474
|
+
`generated(tokens, parts)` splits output the same way by size, `merged` adds
|
|
475
|
+
splits together, and `dollars(price, paid, hour)` prices one.
|
|
476
|
+
|
|
477
|
+
```ts
|
|
478
|
+
import { billed, weigh } from '@yaks/model'
|
|
479
|
+
import { equal } from '@yaks/testing'
|
|
480
|
+
|
|
481
|
+
const price = { input: 1, output: 2, cached: 0.5 }
|
|
482
|
+
const usage = {
|
|
483
|
+
input_tokens: 1_000_000,
|
|
484
|
+
cached_tokens: 500_000,
|
|
485
|
+
output_tokens: 250_000,
|
|
486
|
+
}
|
|
487
|
+
equal(weigh(price, usage), 1.25)
|
|
488
|
+
const reply = { id: 'r1', model: 'release', items: [], usage }
|
|
489
|
+
equal(billed(reply, price), { dollars: 1.25, reported: false })
|
|
490
|
+
equal(billed({ ...reply, cost: 3 }, price), { dollars: 3, reported: true })
|
|
491
|
+
equal(billed(reply), undefined)
|
|
492
|
+
```
|
|
493
|
+
|
|
494
|
+
## Typed questions
|
|
495
|
+
|
|
496
|
+
A **question** (`Question`) asks for a typed answer rather than prose. A
|
|
497
|
+
**noul** asks for a probability that its statement holds; a **choice** asks for
|
|
498
|
+
one criterion's name; a **score** asks for a number along ordered criteria.
|
|
499
|
+
`Questions` maps names to questions with `type`, `instructions` and optional
|
|
500
|
+
`criteria`. An **answer** (`Answer`) carries the corresponding `noul`, `choice`
|
|
501
|
+
or `score`, with optional `confidence` and `probabilities`.
|
|
502
|
+
|
|
503
|
+
`Request.questions` asks the questions and `Reply.answers` maps their names to
|
|
504
|
+
answers. The `questions.asked` component stores questions; the `answer`
|
|
505
|
+
component stores one answer with its `question` name. The interface does not
|
|
506
|
+
validate answers; adapters implement typed-question support.
|
|
507
|
+
|
|
508
|
+
```ts
|
|
509
|
+
import type { Model, Questions } from '@yaks/model'
|
|
510
|
+
import { equal } from '@yaks/testing'
|
|
511
|
+
|
|
512
|
+
const questions: Questions = {
|
|
513
|
+
ready: { type: 'noul', instructions: 'Is the work ready?' },
|
|
514
|
+
route: {
|
|
515
|
+
type: 'choice',
|
|
516
|
+
instructions: 'Pick a route',
|
|
517
|
+
criteria: { fast: 'Fast', safe: 'Safe' },
|
|
518
|
+
},
|
|
519
|
+
quality: {
|
|
520
|
+
type: 'score',
|
|
521
|
+
instructions: 'Rate quality',
|
|
522
|
+
criteria: ['poor', 'good'],
|
|
523
|
+
},
|
|
524
|
+
}
|
|
525
|
+
const model: Model = async (request) => ({
|
|
526
|
+
id: 'r1',
|
|
527
|
+
model: request.model,
|
|
528
|
+
items: [],
|
|
529
|
+
answers: {
|
|
530
|
+
ready: { noul: 0.9 },
|
|
531
|
+
route: { choice: 'safe' },
|
|
532
|
+
quality: { score: 1 },
|
|
533
|
+
},
|
|
534
|
+
})
|
|
535
|
+
const reply = await model({ model: 'example', items: [], tools: [], questions })
|
|
536
|
+
equal(reply.answers, {
|
|
537
|
+
ready: { noul: 0.9 },
|
|
538
|
+
route: { choice: 'safe' },
|
|
539
|
+
quality: { score: 1 },
|
|
540
|
+
})
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
## Expected failures
|
|
544
|
+
|
|
545
|
+
A **ModelError** is an expected failure carrying a `code`, such as a refusal,
|
|
546
|
+
rate limit or missing credential. `retry` marks a failure that may pass;
|
|
547
|
+
`retry.after` is the provider's wait in milliseconds. `response` (`Answered`)
|
|
548
|
+
retains the provider's error body and limit headers, stored in the `response`
|
|
549
|
+
component. Other exceptions are unexpected failures.
|
|
550
|
+
|
|
551
|
+
```ts
|
|
552
|
+
import { ModelError } from '@yaks/model'
|
|
553
|
+
import { equal } from '@yaks/testing'
|
|
554
|
+
|
|
555
|
+
const error = new ModelError('rate_limit', 'Try later', { after: 1000 }, {
|
|
556
|
+
body: 'Too many requests',
|
|
557
|
+
headers: { 'retry-after': '1' },
|
|
558
|
+
})
|
|
559
|
+
equal(error.code, 'rate_limit')
|
|
560
|
+
equal(error.retry, { after: 1000 })
|
|
561
|
+
equal(error.response?.headers, { 'retry-after': '1' })
|
|
562
|
+
```
|
|
563
|
+
|
|
564
|
+
## Generated media recovery
|
|
565
|
+
|
|
566
|
+
A **media receipt** (`MediaReceipt`) is private delivery metadata attributed to
|
|
567
|
+
an original model request by `call`: its provider `id`, `model`, `input` and
|
|
568
|
+
`response`, optional cost, and optional delivered reply. `complete: false` marks
|
|
569
|
+
an incomplete recording, retained privately and refused by delivery. Media
|
|
570
|
+
receipts can also hold text responses. `MediaReceipts` provides `read(call)` and
|
|
571
|
+
`save(receipt)`. Keep media receipts private; provider responses can include
|
|
572
|
+
temporary URL credentials.
|
|
573
|
+
|
|
574
|
+
`provider` identifies the adapter that owns delivery; legacy Workers AI receipts
|
|
575
|
+
have no provider field.
|
|
576
|
+
|
|
577
|
+
`receivedMedia` saves a media receipt before awaiting `Request.onReceipt`, then
|
|
578
|
+
calls `Request.onMedia` for a complete recording. `recoveredMedia` returns a
|
|
579
|
+
saved reply, or calls `deliver` and saves its reply; it never generates media. A
|
|
580
|
+
provider implements that delivery through `Model.recover(call)`.
|
|
581
|
+
|
|
582
|
+
`mediaReceipts` adapts a private `read`/`update` interface. It refuses a second
|
|
583
|
+
provider id for the same call and verifies the saved media receipt. Its `update`
|
|
584
|
+
callback must receive the stored mutable data and durably save it.
|
|
585
|
+
|
|
586
|
+
Its optional second argument is a private `Blobs` store from `@yaks/blob`. With
|
|
587
|
+
it, the full receipt is saved and verified as a content-addressed payload before
|
|
588
|
+
the record stores only `call`, `id`, `model` and the payload address.
|
|
589
|
+
`MediaRecord` describes that pointer and existing inline receipts. Reading a
|
|
590
|
+
pointer verifies its payload and reconstructs the receipt; a missing or corrupt
|
|
591
|
+
payload fails rather than requesting another generation. Existing inline
|
|
592
|
+
receipts remain readable and become pointers only when normally saved during
|
|
593
|
+
delivery. Both the record store and the payload store must remain private.
|
|
594
|
+
|
|
595
|
+
```ts
|
|
596
|
+
import {
|
|
597
|
+
mediaReceipts,
|
|
598
|
+
type MediaRecord,
|
|
599
|
+
receivedMedia,
|
|
600
|
+
recoveredMedia,
|
|
601
|
+
} from '@yaks/model'
|
|
602
|
+
import { equal } from '@yaks/testing'
|
|
603
|
+
import { memoryBlobs } from '@yaks/blob'
|
|
604
|
+
|
|
605
|
+
const records = new Map<string, MediaRecord>()
|
|
606
|
+
const store = mediaReceipts({
|
|
607
|
+
read: async (call) => records.get(call),
|
|
608
|
+
update: async (call, fn) => {
|
|
609
|
+
const record = records.get(call) ?? {}
|
|
610
|
+
const result = await fn(record)
|
|
611
|
+
records.set(call, record)
|
|
612
|
+
return result
|
|
613
|
+
},
|
|
614
|
+
}, memoryBlobs())
|
|
615
|
+
let checkpoints = 0
|
|
616
|
+
await receivedMedia(
|
|
617
|
+
{
|
|
618
|
+
model: 'example',
|
|
619
|
+
items: [],
|
|
620
|
+
tools: [],
|
|
621
|
+
onMedia: async (receipt) => {
|
|
622
|
+
equal((await store.read(receipt.call))?.id, 'r1')
|
|
623
|
+
checkpoints++
|
|
624
|
+
},
|
|
625
|
+
},
|
|
626
|
+
{ call: 'c1', id: 'r1', model: 'example', input: {}, response: {} },
|
|
627
|
+
store,
|
|
628
|
+
)
|
|
629
|
+
let deliveries = 0
|
|
630
|
+
const deliver = async () => {
|
|
631
|
+
deliveries++
|
|
632
|
+
return { id: 'r1', model: 'example', items: [] }
|
|
633
|
+
}
|
|
634
|
+
const reply = await recoveredMedia('c1', store, deliver)
|
|
635
|
+
equal(await recoveredMedia('c1', store, deliver), reply)
|
|
636
|
+
equal([checkpoints, deliveries], [1, 1])
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
## Submission checkpoints
|
|
640
|
+
|
|
641
|
+
A **submission checkpoint** is the awaited `Request.onSubmit` callback at the
|
|
642
|
+
paid HTTP boundary. The host calls `submitCall(graph, call, at)` to write
|
|
643
|
+
server-only `submitted{at}` on the original ask, guarded against an existing
|
|
644
|
+
submission. A lost acknowledgement still counts as submitted. Adapters with a
|
|
645
|
+
submission checkpoint send at most one paid POST; retrying the original ask must
|
|
646
|
+
recover its receipt or report an uncertain outcome.
|
|
647
|
+
|
|
648
|
+
`Request.onAck` receives provider-owned components at the first acknowledgement,
|
|
649
|
+
before the adapter consumes more output. `Request.onReceipt` receives private
|
|
650
|
+
output before conversion, download, delivery or cost lookup, including partial
|
|
651
|
+
media. These callbacks finish before the adapter proceeds; a storage failure
|
|
652
|
+
stops it. `Request.onFirst` is told once, when the reply's first output arrives
|
|
653
|
+
(text, reasoning or a tool call, or the whole reply from a request that does not
|
|
654
|
+
stream); an adapter calls `began(req)` there, and the time to it is the
|
|
655
|
+
request's time to first token.
|
|
656
|
+
|
|
657
|
+
```ts
|
|
658
|
+
import { acknowledged, type Request, submitted } from '@yaks/model'
|
|
659
|
+
import { equal } from '@yaks/testing'
|
|
660
|
+
|
|
661
|
+
let order: string[] = []
|
|
662
|
+
const request: Request = {
|
|
663
|
+
call: 'ask-1',
|
|
664
|
+
model: 'example',
|
|
665
|
+
items: [],
|
|
666
|
+
tools: [],
|
|
667
|
+
onSubmit: async () => {
|
|
668
|
+
order.push('submitted')
|
|
669
|
+
},
|
|
670
|
+
onAck: async (mark) => {
|
|
671
|
+
order.push(String(mark.example.response_id))
|
|
672
|
+
},
|
|
673
|
+
}
|
|
674
|
+
await submitted(request)
|
|
675
|
+
await acknowledged(request, { example: { response_id: 'reply-1' } })
|
|
676
|
+
equal(order, ['submitted', 'reply-1'])
|
|
677
|
+
```
|
|
678
|
+
|
|
679
|
+
## Limits
|
|
680
|
+
|
|
681
|
+
The package stores no conversations, executes no tools and makes no provider
|
|
682
|
+
requests. [@yaks/session](../session/README.md) builds items from conversations;
|
|
683
|
+
provider adapters implement `Model`. The `tool` component belongs to
|
|
684
|
+
[@yaks/tools](../tools/README.md), and generated artifacts to
|
|
685
|
+
[@yaks/blob](../blob/README.md). Applications provide graph storage and private
|
|
686
|
+
media receipt storage.
|
|
687
|
+
|
|
688
|
+
## Cached-prefix expiry
|
|
689
|
+
|
|
690
|
+
A **cached-prefix expiry** is the instant a completed request's prompt cache is
|
|
691
|
+
expected to stop being reusable, not the lifetime of a stored response or a
|
|
692
|
+
credential. Providers record `cache_expires_at` on their own ask component.
|
|
693
|
+
`cachedPrefixExpires` reads that snapshot; absent or invalid expiry is unknown
|
|
694
|
+
and must not justify routing a reply to a settled session.
|
|
695
|
+
|
|
696
|
+
```ts
|
|
697
|
+
import { cachedPrefixExpires } from '@yaks/model'
|
|
698
|
+
import { equal } from '@yaks/testing'
|
|
699
|
+
|
|
700
|
+
equal(
|
|
701
|
+
cachedPrefixExpires({
|
|
702
|
+
openai: { cache_expires_at: '2026-10-03T10:05:00Z' },
|
|
703
|
+
}),
|
|
704
|
+
'2026-10-03T10:05:00.000Z',
|
|
705
|
+
)
|
|
706
|
+
equal(cachedPrefixExpires({ usage: { cached_tokens: 1000 } }), undefined)
|
|
707
|
+
```
|
|
708
|
+
|
|
709
|
+
The session provider resolver reads `provider.cache_retention` (seconds) at
|
|
710
|
+
request dispatch and snapshots dispatch plus retention when no explicit expiry
|
|
711
|
+
is returned. An invalid explicit expiry does not gain a fallback. Set retention
|
|
712
|
+
only from documentation applicable to that provider's endpoint and models; there
|
|
713
|
+
is no transport-wide default. A row naming no retention leaves the expiry to the
|
|
714
|
+
provider's own `mark`, which @yaks/session calls with the dispatch instant
|
|
715
|
+
(`CacheContext.requestedAt`): @yaks/anthropic knows its documented five minutes,
|
|
716
|
+
@yaks/openai's provider the five minutes OpenAI's own API documents at least,
|
|
717
|
+
and a provider that knows none records the expiry unknown. Existing asks without
|
|
718
|
+
expiry remain cold, so no backfill is needed.
|
|
719
|
+
|
|
720
|
+
A persona may ask for longer: `cache{retention}` on it is the seconds its
|
|
721
|
+
conversations ask their provider to keep the cached prefix
|
|
722
|
+
(`Request.cacheRetention`), in place of the provider's own. yaks.app's Operator
|
|
723
|
+
reads it off its persona.
|
|
724
|
+
|
|
725
|
+
## Stalls
|
|
726
|
+
|
|
727
|
+
Every provider stream fails as `stalled` (a `ModelError` coded `stalled`) once
|
|
728
|
+
its connection, its first byte or any gap after goes `Request.stallTimeout`
|
|
729
|
+
seconds without progress, five minutes (`STALL_TIMEOUT`) where the request names
|
|
730
|
+
none. The session provider resolver fills `stallTimeout` from the provider row's
|
|
731
|
+
`stall_timeout` at dispatch, so a row may name its own; 0 waits for ever. A
|
|
732
|
+
provider reads its stream through `watched(fetch, ms)` or
|
|
733
|
+
`watchedBody(body,
|
|
734
|
+
ms)` (@yaks/model/stall), or keeps a `watchdog` of its own
|
|
735
|
+
where its retries need one (@yaks/openai's transport), and a session reports an
|
|
736
|
+
exhausted stall as the failure it is.
|
|
737
|
+
|
|
738
|
+
A session keeps the instructions its newest ask sent while that ask's expiry is
|
|
739
|
+
in the future, so a context that changed mid-conversation does not rewrite a
|
|
740
|
+
prefix still in the cache. Once it has expired, or where it is unknown, the
|
|
741
|
+
instructions are read again and the conversation is replayed on them
|
|
742
|
+
(@yaks/session `cachedInstructions`).
|
|
743
|
+
|
|
744
|
+
## A provider served by a machine
|
|
745
|
+
|
|
746
|
+
A provider can be another machine:
|
|
747
|
+
`provider{name, transport: 'machine',
|
|
748
|
+
machine}`, where `machine` names the
|
|
749
|
+
`machine{address}` ([@yaks/machine](../machine/README.md)) whose own providers
|
|
750
|
+
answer. One host forwards each model request and the other answers it, so the
|
|
751
|
+
forwarding host needs none of the serving host's credentials or command lines.
|
|
752
|
+
|
|
753
|
+
The serving host mounts `answering(serve, report)` at `PATH` (`/model/step`): a
|
|
754
|
+
web handler that answers one model request from `serve` and streams the reply.
|
|
755
|
+
`serving(graph, implementations)` is the `serve` for a host's own providers. It
|
|
756
|
+
finds the model by its own name (`model.name`, the same row in every graph) and
|
|
757
|
+
asks the one of `implementations` whose provider the graph's `serves` edges say
|
|
758
|
+
serves it, under the name that provider calls it. Which providers answer is
|
|
759
|
+
therefore the serving host's choice of `implementations`. `offers` and
|
|
760
|
+
`offerFor` are the lookups beneath it. [@yaks/harness](../harness/README.md)
|
|
761
|
+
mounts it for a `yak` config, over the providers the config names to `serve`.
|
|
762
|
+
|
|
763
|
+
The forwarding host builds a `Model` with `forwarding(lent)`, which sends each
|
|
764
|
+
model request through `lent.fetch` to `PATH` under `options.base`. Where that
|
|
765
|
+
`fetch` goes (a tunnel, a private network, the same process) is the host's
|
|
766
|
+
concern. `forwarded(graph, reach)` builds one for every provider row a machine
|
|
767
|
+
serves, keyed by `provider.name`, from the `fetch` that `reach(machine)` gives;
|
|
768
|
+
a row naming no machine, or one `reach` gives nothing for, is left out.
|
|
769
|
+
|
|
770
|
+
```ts
|
|
771
|
+
import { type Model, ModelError } from '@yaks/model'
|
|
772
|
+
import { answering, forwarding } from '@yaks/model/step'
|
|
773
|
+
import { equal } from '@yaks/testing'
|
|
774
|
+
|
|
775
|
+
const local: Model = async (request) => {
|
|
776
|
+
request.onText?.({ index: 0, text: 'Hello' })
|
|
777
|
+
return {
|
|
778
|
+
id: 'r1',
|
|
779
|
+
model: request.model,
|
|
780
|
+
items: [{ kind: 'assistant', text: 'Hello' }],
|
|
781
|
+
usage: { input_tokens: 4, output_tokens: 1 },
|
|
782
|
+
cost: 0.01,
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
const answer = answering(local, console.error)
|
|
786
|
+
const model = forwarding({
|
|
787
|
+
fetch: (at, init) => answer(new Request(at, init)),
|
|
788
|
+
})
|
|
789
|
+
let text = ''
|
|
790
|
+
const reply = await model({
|
|
791
|
+
model: 'example',
|
|
792
|
+
items: [{ kind: 'user', text: 'Hi' }],
|
|
793
|
+
tools: [],
|
|
794
|
+
onText: (delta) => text += delta.text,
|
|
795
|
+
})
|
|
796
|
+
equal(text, 'Hello')
|
|
797
|
+
equal(reply.usage, { input_tokens: 4, output_tokens: 1 })
|
|
798
|
+
equal(reply.cost, undefined)
|
|
799
|
+
```
|
|
800
|
+
|
|
801
|
+
The reply keeps the `usage` the serving provider counted and drops its `cost`:
|
|
802
|
+
what a model request cost the serving host is not what it costs the forwarding
|
|
803
|
+
one, which weighs the usage at its own price for the model. Text reaches
|
|
804
|
+
`Request.onText` as it streams, and `Request.signal` stops the model request on
|
|
805
|
+
both hosts.
|
|
806
|
+
|
|
807
|
+
A `ModelError` the serving provider throws reaches the forwarding host with its
|
|
808
|
+
code, message, retry and response. Anything else is the serving host's bug: it
|
|
809
|
+
goes to `report` there, and the forwarding host is told only that the model
|
|
810
|
+
request failed (`serving`). A machine that does not answer, refuses the path or
|
|
811
|
+
drops the stream fails as `unreachable`, and one that goes quiet as `stalled`;
|
|
812
|
+
both may pass, so a caller can ask again or ask another provider. A quiet model
|
|
813
|
+
request sends a comment every `BEAT` milliseconds, so the forwarding host's
|
|
814
|
+
stall timeout measures the connection between the hosts while the serving host's
|
|
815
|
+
own measures its provider. A model request for image or audio output is refused
|
|
816
|
+
(`modalities`) before it is sent, since generated media would stay in the
|
|
817
|
+
serving host's store.
|
|
818
|
+
|
|
819
|
+
## Hosted inference
|
|
820
|
+
|
|
821
|
+
An **executor** (`Executor`) accepts an original ask by `submit(call, request)`
|
|
822
|
+
and reads its completed reply through `resume(call)`. Repeated submission keeps
|
|
823
|
+
that call's frozen request and execution identity. An absent reply means
|
|
824
|
+
pending; a terminal `ModelError` ends that ask. The session releases its runner
|
|
825
|
+
while pending and resumes when `inference.receipt` is written.
|
|
826
|
+
|
|
827
|
+
An executor's optional `available()` controls admission of new asks. An accepted
|
|
828
|
+
ask keeps its executor even while admission is unavailable. With `name` set, the
|
|
829
|
+
session records `inference.executor` when it creates the ask, so recovery can
|
|
830
|
+
distinguish it from an interrupted inline call before the request is frozen.
|
|
831
|
+
|
|
832
|
+
`inference{executor, request, receipt}` holds the pinned executor release and
|
|
833
|
+
private object references on the original ask. Its receipt reference is absent
|
|
834
|
+
until delivery can resume. Requests and receipts contain conversation data and
|
|
835
|
+
must stay private. `frozenRequest` removes process callbacks and serializes
|
|
836
|
+
image and document bytes; `thawedRequest` restores the model request.
|
|
837
|
+
|
|
838
|
+
```ts
|
|
839
|
+
import { frozenRequest, thawedRequest } from '@yaks/model'
|
|
840
|
+
import { equal } from '@yaks/testing'
|
|
841
|
+
|
|
842
|
+
const request = frozenRequest({
|
|
843
|
+
model: 'example',
|
|
844
|
+
tools: [],
|
|
845
|
+
items: [{
|
|
846
|
+
kind: 'image',
|
|
847
|
+
bytes: new Uint8Array([1, 2]),
|
|
848
|
+
mediaType: 'image/png',
|
|
849
|
+
label: 'input',
|
|
850
|
+
}],
|
|
851
|
+
onText: () => {},
|
|
852
|
+
})
|
|
853
|
+
const restored = thawedRequest(JSON.parse(JSON.stringify(request)))
|
|
854
|
+
equal(restored.items[0], {
|
|
855
|
+
kind: 'image',
|
|
856
|
+
bytes: new Uint8Array([1, 2]),
|
|
857
|
+
mediaType: 'image/png',
|
|
858
|
+
label: 'input',
|
|
859
|
+
})
|
|
860
|
+
equal(restored.onText, undefined)
|
|
861
|
+
```
|
|
862
|
+
|
|
863
|
+
`infer(job, host)` saves an `InferenceReceipt` before returning its reference.
|
|
864
|
+
The host atomically claims submission, supplies the provider adapter and private
|
|
865
|
+
storage, and awaits provider acknowledgement checkpoints. A repeated step reads
|
|
866
|
+
its receipt or calls `Model.recover` without generation. A complete provider
|
|
867
|
+
receipt permits delivery retries; an unrecoverable outcome records interruption.
|
|
868
|
+
`inferenceReply` reads that result and refuses to regenerate it. Billing and
|
|
869
|
+
transcript delivery belong to the host and each keep the original ask identity.
|