@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.
Files changed (126) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +868 -2
  3. package/_dist/afford.d.ts +69 -0
  4. package/_dist/afford.d.ts.map +1 -0
  5. package/_dist/attribute.d.ts +52 -0
  6. package/_dist/attribute.d.ts.map +1 -0
  7. package/_dist/batch.d.ts +28 -0
  8. package/_dist/batch.d.ts.map +1 -0
  9. package/_dist/cache.d.ts +15 -0
  10. package/_dist/cache.d.ts.map +1 -0
  11. package/_dist/deferred.d.ts +9 -0
  12. package/_dist/deferred.d.ts.map +1 -0
  13. package/_dist/graph.d.ts +3 -0
  14. package/_dist/graph.d.ts.map +1 -0
  15. package/_dist/image.d.ts +46 -0
  16. package/_dist/image.d.ts.map +1 -0
  17. package/_dist/inference.d.ts +58 -0
  18. package/_dist/inference.d.ts.map +1 -0
  19. package/_dist/limits.d.ts +142 -0
  20. package/_dist/limits.d.ts.map +1 -0
  21. package/_dist/media.d.ts +28 -0
  22. package/_dist/media.d.ts.map +1 -0
  23. package/_dist/message.d.ts +5 -0
  24. package/_dist/message.d.ts.map +1 -0
  25. package/_dist/mod.d.ts +298 -0
  26. package/_dist/mod.d.ts.map +1 -0
  27. package/_dist/offers.d.ts +19 -0
  28. package/_dist/offers.d.ts.map +1 -0
  29. package/_dist/onward.d.ts +77 -0
  30. package/_dist/onward.d.ts.map +1 -0
  31. package/_dist/prices.d.ts +27 -0
  32. package/_dist/prices.d.ts.map +1 -0
  33. package/_dist/provider.d.ts +49 -0
  34. package/_dist/provider.d.ts.map +1 -0
  35. package/_dist/results.d.ts +21 -0
  36. package/_dist/results.d.ts.map +1 -0
  37. package/_dist/route.d.ts +189 -0
  38. package/_dist/route.d.ts.map +1 -0
  39. package/_dist/sse.d.ts +4 -0
  40. package/_dist/sse.d.ts.map +1 -0
  41. package/_dist/stall.d.ts +47 -0
  42. package/_dist/stall.d.ts.map +1 -0
  43. package/_dist/step.d.ts +71 -0
  44. package/_dist/step.d.ts.map +1 -0
  45. package/_dist/submission.d.ts +7 -0
  46. package/_dist/submission.d.ts.map +1 -0
  47. package/_dist/vocab.d.ts +82 -0
  48. package/_dist/vocab.d.ts.map +1 -0
  49. package/_dist/windows.d.ts +6 -0
  50. package/_dist/windows.d.ts.map +1 -0
  51. package/afford.js +135 -0
  52. package/afford.js.map +1 -0
  53. package/afford.ts +208 -0
  54. package/attribute.js +109 -0
  55. package/attribute.js.map +1 -0
  56. package/attribute.ts +120 -0
  57. package/batch.js +8 -0
  58. package/batch.js.map +1 -0
  59. package/batch.ts +37 -0
  60. package/cache.js +28 -0
  61. package/cache.js.map +1 -0
  62. package/cache.ts +53 -0
  63. package/deferred.js +29 -0
  64. package/deferred.js.map +1 -0
  65. package/deferred.ts +54 -0
  66. package/deno.json +1 -0
  67. package/graph.js +8 -0
  68. package/graph.js.map +1 -0
  69. package/graph.ts +9 -0
  70. package/image.js +118 -0
  71. package/image.js.map +1 -0
  72. package/image.ts +108 -0
  73. package/inference.js +119 -0
  74. package/inference.js.map +1 -0
  75. package/inference.ts +223 -0
  76. package/limits.js +204 -0
  77. package/limits.js.map +1 -0
  78. package/limits.ts +230 -0
  79. package/media.js +76 -0
  80. package/media.js.map +1 -0
  81. package/media.ts +139 -0
  82. package/message.js +21 -0
  83. package/message.js.map +1 -0
  84. package/message.ts +17 -0
  85. package/mod.js +396 -0
  86. package/mod.js.map +1 -0
  87. package/mod.ts +695 -0
  88. package/offers.js +53 -0
  89. package/offers.js.map +1 -0
  90. package/offers.ts +84 -0
  91. package/onward.js +110 -0
  92. package/onward.js.map +1 -0
  93. package/onward.ts +123 -0
  94. package/package.json +53 -4
  95. package/prices.js +61 -0
  96. package/prices.js.map +1 -0
  97. package/prices.json +643 -0
  98. package/prices.ts +60 -0
  99. package/provider.js +6 -0
  100. package/provider.js.map +1 -0
  101. package/provider.ts +89 -0
  102. package/results.js +51 -0
  103. package/results.js.map +1 -0
  104. package/results.ts +47 -0
  105. package/route.js +263 -0
  106. package/route.js.map +1 -0
  107. package/route.ts +359 -0
  108. package/sse.js +71 -0
  109. package/sse.js.map +1 -0
  110. package/sse.ts +82 -0
  111. package/stall.js +166 -0
  112. package/stall.js.map +1 -0
  113. package/stall.ts +201 -0
  114. package/step.js +226 -0
  115. package/step.js.map +1 -0
  116. package/step.ts +265 -0
  117. package/submission.js +38 -0
  118. package/submission.js.map +1 -0
  119. package/submission.ts +38 -0
  120. package/vocab.js +83 -0
  121. package/vocab.js.map +1 -0
  122. package/vocab.json +613 -0
  123. package/vocab.ts +139 -0
  124. package/windows.js +35 -0
  125. package/windows.js.map +1 -0
  126. package/windows.ts +28 -0
package/mod.ts ADDED
@@ -0,0 +1,695 @@
1
+ /**
2
+ * @yaks/model is the interface between a conversation and whoever serves it:
3
+ * the shape of a request, the shape of a reply, and the two entities a graph
4
+ * stores about serving — `provider` and `model`. It implements no provider's
5
+ * transport (`@yaks/model/step` carries a step between two hosts instead),
6
+ * and it declares no component another package owns: `tool` belongs to
7
+ * @yaks/tools and `artifact` to @yaks/blob, each composed beside this one.
8
+ * A provider package ({@link https://jsr.io/@yaks/openai | @yaks/openai},
9
+ * {@link https://jsr.io/@yaks/workers-ai | @yaks/workers-ai}) implements
10
+ * {@link Model}; a conversation package (`@yaks/session`) turns its stored
11
+ * transcript into {@link Item}s and calls it. Neither needs the other.
12
+ *
13
+ * ```ts
14
+ * import { type Model, ModelError } from '@yaks/model'
15
+ *
16
+ * let fake: Model = (req) =>
17
+ * Promise.resolve({
18
+ * id: 'r1',
19
+ * model: req.model,
20
+ * items: [{ kind: 'assistant', text: `${req.items.length} items` }],
21
+ * })
22
+ * ```
23
+ *
24
+ * An {@link Item} is provider-neutral on purpose: a user turn, an assistant
25
+ * turn, a call the model asked for, the result it was given. The Responses API
26
+ * encodes those four one way; a chat-completions API encodes them another; the
27
+ * conversation should not have to know.
28
+ *
29
+ * A request may also ask typed {@link Questions} about the conversation, in
30
+ * Jev's terms (a `noul`, a `choice`, a `score`), and the reply answers each by
31
+ * name in {@link Reply.answers}. A graph records them as `questions` on the
32
+ * asking entry and one `answer` per question.
33
+ *
34
+ * What a provider stores about a reply — an id that anchors the next request,
35
+ * say — is that provider's own component, declared and written by its package
36
+ * ({@link Model.mark}, {@link Model.vocab}) and read back by it
37
+ * ({@link Model.anchor}). This interface carries the request, never the
38
+ * provider's own bookkeeping.
39
+ *
40
+ * A model that throws a {@link ModelError} failed in a way the caller expects —
41
+ * a refused request, a rate limit, a missing credential. Anything else it
42
+ * throws is a bug, and the caller records it as one.
43
+ *
44
+ * @module
45
+ */
46
+
47
+ import { after } from '@yaks/fp'
48
+ import type {
49
+ Bundle,
50
+ Comp,
51
+ Derive,
52
+ Eid,
53
+ Hook,
54
+ Plugin,
55
+ ReadTx,
56
+ } from 'jsr:@yaks/graph@0.2.36'
57
+ import { dead } from '@yaks/graph/bundle'
58
+ import { eidOf, identityEid, minted } from '@yaks/graph/identity'
59
+ import { Refused } from '@yaks/graph/errors'
60
+ import type { VocabDoc } from 'jsr:@yaks/vocab@0.2.36'
61
+ import { edgeEid } from '@yaks/edge'
62
+ import type { Artifact } from 'jsr:@yaks/blob@0.2.36'
63
+ import {
64
+ MODEL,
65
+ modelDoc,
66
+ type Price,
67
+ PROVIDER,
68
+ type Usage,
69
+ weigh,
70
+ } from './vocab.js'
71
+ import type { MediaReceipt } from './media.js'
72
+ import { listLabel, listPrice } from './prices.js'
73
+ export { listLabel, listPrice } from './prices.js'
74
+ export { deferredModel } from './deferred.js'
75
+ export { windows } from './windows.js'
76
+ export { gone, type Link, onward, refused } from './onward.js'
77
+ export { type ModelResult, type ModelResults, modelResults } from './results.js'
78
+ export { message } from './message.js'
79
+ export { type Offer, offerFor, offers, serving } from './offers.js'
80
+ export type { Lent, Native, ProviderFacet, Spending } from './provider.ts'
81
+ export {
82
+ type Executor,
83
+ type FrozenModelRequest,
84
+ frozenRequest,
85
+ infer,
86
+ type Inference,
87
+ type InferenceHost,
88
+ type InferenceReceipt,
89
+ inferenceReply,
90
+ thawedRequest,
91
+ } from './inference.js'
92
+ export {
93
+ type MediaReceipt,
94
+ type MediaReceipts,
95
+ mediaReceipts,
96
+ type MediaRecord,
97
+ receivedMedia,
98
+ recoveredMedia,
99
+ } from './media.js'
100
+
101
+ export {
102
+ COST,
103
+ dollars,
104
+ hourly,
105
+ MODEL,
106
+ modelDoc,
107
+ PRICE,
108
+ type Price,
109
+ PROVIDER,
110
+ RATE_LIMIT,
111
+ USAGE,
112
+ type Usage,
113
+ weigh,
114
+ } from './vocab.js'
115
+ export {
116
+ attribute,
117
+ generated,
118
+ merged,
119
+ type Paid,
120
+ type Part,
121
+ } from './attribute.js'
122
+ export {
123
+ type Affordable,
124
+ affordable,
125
+ charged,
126
+ FRAMING,
127
+ likely,
128
+ measured,
129
+ promptBound,
130
+ requestBound,
131
+ retained,
132
+ } from './afford.js'
133
+ export { cachedPrefixExpires, cacheExpiry, prefixCacheMark } from './cache.js'
134
+ export { acknowledged, began, submitCall, submitted } from './submission.js'
135
+ export type { CacheContext } from './cache.js'
136
+ import type { CacheContext } from './cache.js'
137
+ import type { Affordable } from './afford.js'
138
+
139
+ export {
140
+ accountEid,
141
+ accountHome,
142
+ ACCOUNTS,
143
+ dry,
144
+ limitEid,
145
+ limitRows,
146
+ metering,
147
+ signingIn,
148
+ spent,
149
+ } from './limits.js'
150
+ export type { Limit, Runner } from './limits.js'
151
+ import type { Limit } from './limits.js'
152
+ export let TOOL = 'tool'
153
+ export let QUESTIONS = 'questions'
154
+ export let ANSWER = 'answer'
155
+ export let RESPONSE = 'response'
156
+ /** The {@link ModelError} code of a request whose {@link Request.anchor} the
157
+ * provider no longer holds: asked again with the whole conversation, it
158
+ * passes. */
159
+ export let UNANCHORED = 'unanchored'
160
+
161
+ let byName = {
162
+ [PROVIDER]: eidOf(modelDoc, PROVIDER),
163
+ [MODEL]: eidOf(modelDoc, MODEL),
164
+ }
165
+ let modelIds = (comp: string, name: string): Eid[] => [
166
+ byName[comp](name),
167
+ identityEid(comp, [name]),
168
+ ]
169
+ let namedRow = (held: Map<Eid, Bundle>, comp: string, name: string) =>
170
+ modelIds(comp, name).map((eid) => held.get(eid)).find((row) => row?.[comp])
171
+
172
+ /**
173
+ * A provider or a model named where an eid is expected: `gpt-6-astra` in
174
+ * `using.model`. Each one's eid is derived from its name (the `identity`
175
+ * keyword), so the lookup is one read of the ids the name would have, no scan.
176
+ * A name both a provider and a model hold is refused rather than guessed.
177
+ */
178
+ export let addressed = (
179
+ tx: ReadTx,
180
+ ids: string[],
181
+ ): Map<string, Eid> | Promise<Map<string, Eid>> => {
182
+ let ask = [...new Set(ids)].filter((id) =>
183
+ id && !id.startsWith('$') && !minted(id)
184
+ )
185
+ let at = (id: string) => modelIds(PROVIDER, id).concat(modelIds(MODEL, id))
186
+ return after(tx.get(ask.flatMap(at), [PROVIDER, MODEL]), (rows) => {
187
+ let live = new Map(
188
+ rows.filter((b) => !dead(b)).map((b) => [b.entity.eid, b]),
189
+ )
190
+ let found = new Map<string, Eid>()
191
+ for (let id of ask) {
192
+ let provider = namedRow(live, PROVIDER, id)
193
+ let model = namedRow(live, MODEL, id)
194
+ if (provider && model) {
195
+ throw new Refused(`${id} names both a provider and a model`)
196
+ }
197
+ let row = provider ?? model
198
+ if (row) found.set(id, row.entity.eid)
199
+ }
200
+ return found
201
+ })
202
+ }
203
+
204
+ // Callers send catalogue eids in using{model, provider}. Keep their published
205
+ // addresses during expansion, and recognize UUID-derived rows already held.
206
+ let catalogueId = (comp: string): Derive => {
207
+ let by = (f: (name: string) => Eid): Derive => ({ name }) =>
208
+ typeof name == 'string' && name ? f(name) : ''
209
+ return Object.assign(by((name) => identityEid(comp, [name])), {
210
+ former: by(byName[comp]),
211
+ })
212
+ }
213
+
214
+ /** Model vocabulary and catalogue name resolution. */
215
+ export let models = (): Plugin => ({
216
+ name: '@yaks/model',
217
+ vocab: [modelDoc],
218
+ address: addressed,
219
+ derive: { [MODEL]: catalogueId(MODEL), [PROVIDER]: catalogueId(PROVIDER) },
220
+ hooks: { normalize: requesting },
221
+ })
222
+
223
+ /** One line of a conversation as a model sees it. */
224
+ export type Item =
225
+ & (
226
+ | { kind: 'image'; bytes: Uint8Array; mediaType: string; label: string }
227
+ /** a document the model reads as it is, such as a PDF; a provider that
228
+ * reads none refuses the request */
229
+ | {
230
+ kind: 'document'
231
+ bytes: Uint8Array
232
+ mediaType: string
233
+ label: string
234
+ /** Original filename, including its extension, separate from display text. */
235
+ filename?: string
236
+ }
237
+ | { kind: 'instruction'; text: string }
238
+ | { kind: 'user'; text: string }
239
+ | { kind: 'assistant'; text: string; id?: string }
240
+ /** a tool call the model asked for: its id, the tool, the arguments as JSON */
241
+ | { kind: 'call'; id: string; name: string; args: string }
242
+ /** what the tool answered, by the call's id */
243
+ | { kind: 'result'; id: string; output: string }
244
+ )
245
+ & {
246
+ /** Who supplied these words, independent of the provider's turn role.
247
+ * Prompt assembly renders this before handing items to any provider. */
248
+ from?: string
249
+ }
250
+
251
+ /** A tool as it is declared to the model. */
252
+ export type Tool = {
253
+ name: string
254
+ description: string
255
+ /** its arguments, as JSON Schema: an object, with no `oneOf`, `anyOf` or
256
+ * `allOf` at its root, which Claude's API and MCP refuse; a choice between
257
+ * arguments is said in the description and checked when the tool runs */
258
+ parameters: Record<string, unknown>
259
+ }
260
+
261
+ /** One request to a model. */
262
+ /** Output text only; never private reasoning or partial tool arguments.
263
+ * Index identifies the final assistant item order in Reply.items. */
264
+ export type TextDelta = { index: number; id?: string; text: string }
265
+ export type Request = {
266
+ /** The original request entity, stable across delivery recovery. */
267
+ call?: string
268
+ /** Durably guard submission before the paid POST. Presence disables replay. */
269
+ onSubmit?: () => Promise<void>
270
+ /** Persist the provider's first acknowledgement before consuming more output. */
271
+ onAck?: (mark: Mark) => Promise<void>
272
+ /** Durably checkpoint private output, including incomplete streamed media. */
273
+ onReceipt?: (receipt: MediaReceipt) => Promise<void>
274
+ /** A private receipt is already durable when this checkpoint runs. */
275
+ onMedia?: (receipt: MediaReceipt) => Promise<void>
276
+ /** The reply's first output reached us: a token of text, reasoning or a
277
+ * tool call, or the whole reply from a request that does not stream. Called
278
+ * once, so the time to it is the request's time to first token. */
279
+ onFirst?: () => void
280
+ /** Optional cancellation of this request, not of independent tool processes. */
281
+ signal?: AbortSignal
282
+ onText?: (delta: TextDelta) => void
283
+ model: string
284
+ /** Explicit model-native inputs, such as lyrics or duration. A provider
285
+ * supporting native inputs validates them; never inferred from prose. */
286
+ input?: Record<string, unknown>
287
+ /** Output modalities requested of a model that can generate media. */
288
+ modalities?: ('text' | 'image' | 'audio')[]
289
+ effort?: string
290
+ instructions?: string
291
+ items: Item[]
292
+ tools: Tool[]
293
+ /** typed questions about the conversation, answered in
294
+ * {@link Reply.answers} rather than in prose; a model that answers none
295
+ * refuses the request with a {@link ModelError} coded `questions` */
296
+ questions?: Questions
297
+ /** the most tokens the reply may write; the provider's own limit where
298
+ * absent */
299
+ tokens?: number
300
+ /** an anchor to continue from, in which case `items` holds only what
301
+ * followed it: whatever the same model's {@link Model.anchor} returned for an
302
+ * earlier reply. Opaque to the caller. A provider that no longer holds that
303
+ * reply (it expired, or was never kept) refuses with a {@link ModelError}
304
+ * coded {@link UNANCHORED}, and the caller asks again with the whole
305
+ * conversation. */
306
+ anchor?: string
307
+ /** with an `anchor`, the tools by name the conversation it continues
308
+ * already declares: what the anchor's own request was sent. A provider
309
+ * that keeps declarations in the conversation declares only the others, so
310
+ * a tool loaded mid-conversation leaves the cached prefix whole. Unknown
311
+ * where absent. */
312
+ held?: string[]
313
+ /** the conversation this request continues, the same for each of its
314
+ * requests, so a provider that keys its prompt cache by conversation finds
315
+ * the prefix the last one cached */
316
+ conversation?: string
317
+ /** the only sites the provider's own web tools may read, by hostname (a
318
+ * name under one included), with no search; where absent, the web they
319
+ * offer is the provider's whole web */
320
+ sites?: string[]
321
+ /** how long, in seconds, the request asks its provider to keep the prefix
322
+ * it caches; a provider offers a few lifetimes and keeps the longest one
323
+ * not over this, or its default where none fits or this is absent */
324
+ cacheRetention?: number
325
+ /** The leading characters of instructions shared by this application's
326
+ * requests, its cache key, and their independent retention preference. */
327
+ cachePrefix?: {
328
+ length: number
329
+ key: string
330
+ retention: number
331
+ /** Tool declarations shared by all requests using this prefix. */
332
+ tools?: string[]
333
+ }
334
+ /** Context supplied for this request only, after the transcript. */
335
+ turnContext?: Item[]
336
+ /** how long, in seconds, the reply's stream may go without progress (the
337
+ * connection, its first byte, any gap after) before the request fails as
338
+ * `stalled`; `@yaks/model/stall` `STALL_TIMEOUT` where absent, 0 for no
339
+ * limit. Its provider's row may name its own (`provider{stall_timeout}`). */
340
+ stallTimeout?: number
341
+ }
342
+
343
+ /** One typed question, in Jev's terms: a `noul` is answered with the
344
+ * probability that it holds, a `choice` with one of its criteria's names, and
345
+ * a `score` with a number along its criteria, which are ordered. */
346
+ export type Question = {
347
+ type: 'noul' | 'choice' | 'score'
348
+ instructions: unknown
349
+ /** a noul's `{true, false}`, a choice's options by name, a score's ordered
350
+ * list */
351
+ criteria?: unknown
352
+ }
353
+
354
+ /** The questions a request asks, by name. */
355
+ export type Questions = Record<string, Question>
356
+
357
+ /** A model's answer to one question: whichever of `noul`, `choice` and
358
+ * `score` its type calls for, how sure it is, and each option's probability. */
359
+ export type Answer = {
360
+ type?: Question['type']
361
+ noul?: number
362
+ choice?: string
363
+ score?: number
364
+ confidence?: number
365
+ probabilities?: Record<string, number>
366
+ }
367
+
368
+ /** One reply: the provider's id, the model that served it, and the items it
369
+ * produced. */
370
+ export type Reply = {
371
+ id: string
372
+ model: string
373
+ items: Item[]
374
+ /** what the model said of its reasoning before these items, as its
375
+ * provider returns it (a summary, or its thinking): for a person to read,
376
+ * never sent back to a model */
377
+ thought?: string
378
+ /** the answer to each of the request's questions, by the question's name */
379
+ answers?: Record<string, Answer>
380
+ usage?: Usage
381
+ /** Effective cached-prefix expiry, not response/credential retention. Adapters
382
+ * supply explicit expiry; the resolver applies documented retention. Null
383
+ * means the provider sent an invalid value; it must not gain a fallback. */
384
+ cacheExpiresAt?: string | null
385
+ /** the dollars the provider reported this request cost, where it reports
386
+ * them; a caller weighs `usage` at the model's {@link Price} otherwise */
387
+ cost?: number
388
+ /** False for an adapter-measured tariff; provider-reported by default. */
389
+ costReported?: boolean
390
+ artifacts?: (Artifact & { call: string; revised_prompt?: string })[]
391
+ /** The reply stopped at its output token limit (`Request.tokens`): what it
392
+ * was writing last is unfinished, a tool call's arguments included. */
393
+ cut?: boolean
394
+ /** the plan limits the provider answered with, where it meters a plan */
395
+ limits?: Limit[]
396
+ }
397
+
398
+ /** The components a provider writes on the entry that records a reply. */
399
+ export type Mark = Record<string, Record<string, unknown>>
400
+
401
+ /**
402
+ * A model: one request in, one reply out. A provider that stores something
403
+ * about a reply does so through three optional members, so that the
404
+ * conversation never has to know that provider's components: `mark` returns
405
+ * what to write on the entry recording the reply, `anchor` reads an anchor back
406
+ * off such an entry's components (or returns nothing, in which case the caller
407
+ * replays the conversation), and `vocab` declares the components `mark` writes.
408
+ * A plain function is a model that stores nothing.
409
+ */
410
+ export type Model = ((req: Request) => Promise<Reply>) & {
411
+ /** Download/store a saved recording only; never calls generation. */
412
+ recover?: (call: string) => Promise<Reply>
413
+ /** A saved complete answer, with any original accounting finished; never generation. */
414
+ result?: (
415
+ call: string,
416
+ signal?: AbortSignal,
417
+ ) => Promise<import('./results.js').ModelResult | undefined>
418
+ /** Retrieve the original generation using its durable acknowledgement. */
419
+ retrieve?: (mark: Mark, signal?: AbortSignal) => Promise<Reply | undefined>
420
+ list?: () => Promise<Listed[]>
421
+ /** The input tokens its provider counts a request at, anchored history and
422
+ * framing included: what it will bill as that request's input. A meter
423
+ * holds this in place of a bound it works out (./afford.ts). */
424
+ count?: (req: Request) => Promise<number>
425
+ info?: (name: string) => Promise<Listed | undefined>
426
+ mark?: (reply: Reply, cache?: CacheContext) => Mark
427
+ anchor?: (comps: Record<string, unknown>) => string | undefined
428
+ vocab?: VocabDoc
429
+ /** Takes a later output of a tool call it already has one for. Without it,
430
+ * a call that finishes after its first output is told as user text. */
431
+ lateResults?: true
432
+ /** The media types it reads as they are, beside text, each with the most
433
+ * raw bytes of one file it takes, or Infinity for no published byte cap.
434
+ * A function selects the requested model's capabilities. Request-wide limits
435
+ * still apply. Without it, a file is read as its text. */
436
+ reads?:
437
+ | Record<string, number>
438
+ | ((
439
+ name: string,
440
+ ) => Record<string, number> | Promise<Record<string, number>>)
441
+ /** What a request priced by the call rather than by its tokens (a track of
442
+ * music) would cost within `remaining` dollars, null where it would not
443
+ * fit; undefined for a request its tokens price. */
444
+ quote?: (req: Request, remaining: number) => Affordable | null | undefined
445
+ /** The most its provider-run tools (a hosted web search or page fetch) add
446
+ * to one request, which a meter reserves beside the request's own bound. */
447
+ hosted?: Hosted
448
+ }
449
+
450
+ /** Native file inputs for the selected model, including a provider's lazy lookup. */
451
+ export let modelReads = async (
452
+ model: Model,
453
+ name: string,
454
+ ): Promise<Record<string, number>> =>
455
+ typeof model.reads == 'function' ? await model.reads(name) : model.reads ?? {}
456
+
457
+ /** What a model's provider-run tools may add to one request: at most
458
+ * `searches` web searches, billed at {@link Price} `web_search`, and `input`
459
+ * tokens of what they read fed back as input. The provider enforces both. */
460
+ export type Hosted = { searches: number; input: number }
461
+
462
+ /** What a provider answered a failed request with, as it arrived: the body of
463
+ * an error status, or the event that ended its stream, and the headers that
464
+ * speak of its limits. Stored as `response{body, headers}` beside the line
465
+ * recording the failure. */
466
+ export type Answered = {
467
+ body?: string
468
+ headers?: Record<string, string>
469
+ }
470
+
471
+ /** A failure the caller expects: `code` is the provider's own error code when
472
+ * it gave one, otherwise a name for the kind of failure. */
473
+ export class ModelError extends Error {
474
+ code: string
475
+ /** The failure may pass: the caller can ask again, no sooner than `after`
476
+ * milliseconds where the provider said how long to wait. With `defer`, it
477
+ * is no failure but a wait for something outside: asked again as the same
478
+ * attempt, however long that takes (@yaks/effects spends no try on it). */
479
+ retry?: { after?: number; defer?: boolean; resume_on?: string }
480
+ /** what the provider sent, where it sent anything */
481
+ response?: Answered
482
+ /** the plan limits the provider answered with, where it meters a plan */
483
+ limits?: Limit[]
484
+ /** what the provider said the request used before it failed, where it
485
+ * said: a meter settles the request's hold at it */
486
+ usage?: Usage
487
+ constructor(
488
+ code: string,
489
+ message = code,
490
+ retry?: { after?: number; defer?: boolean; resume_on?: string },
491
+ response?: Answered,
492
+ ) {
493
+ super(message)
494
+ this.name = 'ModelError'
495
+ this.code = code
496
+ this.retry = retry
497
+ this.response = response
498
+ }
499
+ }
500
+
501
+ /**
502
+ * What a person sees a model called: its row's `label` ("Sonnet 5.5"), else
503
+ * the label the list gives its name ({@link listLabel}), as a row that has
504
+ * none takes it when next asked; never its id. A model neither labels, or one
505
+ * with no row, is called by its name or its id, and `missing` hears an error
506
+ * to report, so the row gets one.
507
+ *
508
+ * ```ts
509
+ * import { labelOf } from '@yaks/model'
510
+ * import { equal } from '@yaks/testing'
511
+ *
512
+ * let heard: string[] = []
513
+ * let missing = (e: Error) => heard.push(e.message)
514
+ * equal(labelOf({ name: 'gpt-6.2-sol', label: 'Sol' }, missing), 'Sol')
515
+ * equal(labelOf({ name: 'claude-sonnet-5-5' }, missing), 'Sonnet 5.5')
516
+ * equal(labelOf({ name: 'glm-5.3' }, missing), 'glm-5.3')
517
+ * equal(labelOf(undefined, missing, 'O-9'), 'O-9')
518
+ * equal(heard, ['model glm-5.3 has no label', 'model O-9 has no row'])
519
+ * ```
520
+ */
521
+ export let labelOf = (
522
+ model: { name?: unknown; label?: unknown } | null | undefined,
523
+ missing?: (error: Error) => void,
524
+ id?: string,
525
+ ): string => {
526
+ if (model?.label) return String(model.label)
527
+ let name = String(model?.name ?? id ?? '')
528
+ let listed = model?.name ? listLabel(name) : undefined
529
+ if (listed) return listed
530
+ if (name) {
531
+ missing?.(new Error(`model ${name} has no ${model ? 'label' : 'row'}`))
532
+ }
533
+ return name
534
+ }
535
+
536
+ /** What a provider says about one of its models, in graph vocabulary. */
537
+ export type Listed = {
538
+ name: string
539
+ label?: string
540
+ context?: number
541
+ output?: number
542
+ modalities?: string[]
543
+ price?: Price
544
+ }
545
+
546
+ /** A requested name exists before dispatch, but is not offered until answered.
547
+ * A model with no price, met for the first time or held since before the
548
+ * table knew it, is weighed at its list price ({@link listPrice}) unless the
549
+ * batch prices it; a price on a stored row stands. A model with no label
550
+ * takes its list label ({@link listLabel}) the same way. A provider a `using`
551
+ * names that no row holds is a row of that name from then on: the host lent it
552
+ * is the one that answers it. */
553
+ export let requesting: Hook = (bundles, tx) => {
554
+ let names = new Map<string, string>()
555
+ let providers = new Map<string, string>()
556
+ // A name where an eid goes: `using.model` or `using.provider` naming a row
557
+ // by what it is called rather than by its id.
558
+ let called = (v: unknown): v is string =>
559
+ typeof v == 'string' && !minted(v) && !v.startsWith('$')
560
+ let out: Bundle[] = bundles.map((b) => {
561
+ let using = b.using as Comp | undefined
562
+ let { model: name, provider: from } = using ?? {}
563
+ if (!called(name) && !called(from)) return b
564
+ let named = { ...using }
565
+ if (called(name)) {
566
+ named.model = identityEid(MODEL, [name])
567
+ names.set(named.model as string, name)
568
+ }
569
+ if (called(from)) {
570
+ named.provider = identityEid(PROVIDER, [from])
571
+ providers.set(named.provider as string, from)
572
+ }
573
+ return { ...b, using: named }
574
+ })
575
+ // a row the batch writes itself is priced, never stubbed over
576
+ let written = new Map<Eid, Eid>()
577
+ let writingProvider = new Map<Eid, Eid>()
578
+ for (let b of out) {
579
+ let name = (b.model as Comp | undefined)?.name
580
+ let provider = (b.provider as Comp | undefined)?.name
581
+ if (typeof name == 'string' && b.pending !== null) {
582
+ let eid = identityEid(MODEL, [name])
583
+ names.set(eid, name)
584
+ written.set(eid, b.entity.eid)
585
+ }
586
+ if (typeof provider == 'string') {
587
+ writingProvider.set(identityEid(PROVIDER, [provider]), b.entity.eid)
588
+ }
589
+ }
590
+ // by name: a batch's new row is still an alias here, minted after
591
+ let rowOf = (b: Bundle) =>
592
+ identityEid(MODEL, [String((b.model as Comp | undefined)?.name)])
593
+ let priced = new Set(out.filter((b) => b.price).map(rowOf))
594
+ let labeled = new Set(
595
+ out.filter((b) => (b.model as Comp | undefined)?.label).map(rowOf),
596
+ )
597
+ return after(
598
+ tx.get([
599
+ ...[...names.values()].flatMap((name) => modelIds(MODEL, name)),
600
+ ...[...providers.values()].flatMap((name) => modelIds(PROVIDER, name)),
601
+ ], [
602
+ MODEL,
603
+ PROVIDER,
604
+ 'pending',
605
+ 'price',
606
+ ]),
607
+ (rows) => {
608
+ let held = new Map(rows.map((b) => [b.entity.eid, b]))
609
+ let at = new Map<Eid, Eid>()
610
+ let take = (comp: string, name: string, eid: Eid, said?: Eid) => {
611
+ let row = namedRow(held, comp, name)
612
+ let chosen = row?.entity.eid ?? said
613
+ if (chosen && chosen != eid) at.set(eid, chosen)
614
+ return row
615
+ }
616
+ let added = [
617
+ ...[...providers].flatMap(([eid, name]): Bundle[] =>
618
+ take(PROVIDER, name, eid, writingProvider.get(eid)) ||
619
+ writingProvider.has(eid)
620
+ ? []
621
+ : [{ entity: { eid }, [PROVIDER]: { name } }]
622
+ ),
623
+ ...[...names].flatMap(([eid, name]): Bundle[] => {
624
+ let row = take(MODEL, name, eid, written.get(eid))
625
+ let target = { eid: at.get(eid) ?? eid }
626
+ let price = !priced.has(eid) && !row?.price && listPrice(name)
627
+ let label = !labeled.has(eid) &&
628
+ !(row?.[MODEL] as Comp | undefined)?.label && listLabel(name)
629
+ if (row?.model || written.has(eid)) {
630
+ return price || label
631
+ ? [{
632
+ entity: target,
633
+ ...price ? { price } : {},
634
+ ...label ? { [MODEL]: { name, label } } : {},
635
+ }]
636
+ : []
637
+ }
638
+ return [{
639
+ entity: target,
640
+ model: { name, offered: false, ...label ? { label } : {} },
641
+ pending: {},
642
+ ...price ? { price } : {},
643
+ }]
644
+ }),
645
+ ]
646
+ let usingRow = (b: Bundle): Bundle => {
647
+ let using = b.using as Comp | undefined
648
+ let model = at.get(String(using?.model))
649
+ let provider = at.get(String(using?.provider))
650
+ return model || provider
651
+ ? {
652
+ ...b,
653
+ using: {
654
+ ...using,
655
+ ...model && { model },
656
+ ...provider && { provider },
657
+ },
658
+ }
659
+ : b
660
+ }
661
+ return [...out.map(usingRow), ...added]
662
+ },
663
+ )
664
+ }
665
+
666
+ /** A provider's answer confirms a requested model; old asks keep their row. */
667
+ export let confirmed = (
668
+ provider: string,
669
+ name: string,
670
+ listing?: Listed,
671
+ ): Bundle[] => {
672
+ let eid = identityEid(MODEL, [name])
673
+ let { price, ...model } = listing ?? { name }
674
+ return [{
675
+ entity: { eid },
676
+ model: { ...model, name, offered: true },
677
+ pending: null,
678
+ ...price ? { price } : {},
679
+ }, {
680
+ entity: { eid: edgeEid(provider, 'serves', eid) },
681
+ edge: { from: provider, to: eid },
682
+ serves: { name },
683
+ }]
684
+ }
685
+
686
+ /** Reported dollars win; otherwise usage is weighed at the model row's price. */
687
+ export let billed = (
688
+ reply: Reply,
689
+ price?: Price,
690
+ ): { dollars: number; reported: boolean } | undefined =>
691
+ reply.cost != null
692
+ ? { dollars: reply.cost, reported: reply.costReported ?? true }
693
+ : price && reply.usage
694
+ ? { dollars: weigh(price, reply.usage), reported: false }
695
+ : undefined