@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/afford.ts ADDED
@@ -0,0 +1,208 @@
1
+ // A caller supplies an upper bound on every input token the provider may bill,
2
+ // including retained history and provider framing. Estimates are not bounds.
3
+ import type { Request } from './mod.ts'
4
+ import { type Price, type Usage, weigh } from './vocab.js'
5
+
6
+ export type Affordable = { tokens: number; dollars: number }
7
+
8
+ /** Tokens a provider may add around a prompt: role markers, a chat template's
9
+ * own system text, tool framing. */
10
+ export let FRAMING = 1024
11
+
12
+ let media = new Set([
13
+ 'image',
14
+ 'document',
15
+ 'image_url',
16
+ 'input_image',
17
+ 'audio',
18
+ 'input_audio',
19
+ 'video',
20
+ ])
21
+ let textual = (value: unknown): boolean =>
22
+ value == null || typeof value != 'object' ||
23
+ !ArrayBuffer.isView(value) && !(value instanceof ArrayBuffer) &&
24
+ (Array.isArray(value) ? value.every(textual) : Object.entries(value).every(
25
+ ([k, v]) =>
26
+ !media.has(k) && !(k == 'kind' && media.has(String(v))) && textual(v),
27
+ ))
28
+
29
+ let size = (value: unknown) =>
30
+ new TextEncoder().encode(JSON.stringify(value) ?? '').length
31
+
32
+ /** An upper bound on the input tokens a text prompt and the tools it declares
33
+ * can bill, never above the model's context window. A text token covers at
34
+ * least one UTF-8 byte, so the compact JSON bounds the text; doubling it
35
+ * covers a template that re-renders that JSON with spaces and indentation,
36
+ * and FRAMING the markers around it. Media is tokenized by its pixels or
37
+ * samples, not its bytes, so a prompt carrying any is bounded by the context
38
+ * window alone. Only the prompt is searched for media: a tool is declared as
39
+ * text, whatever its arguments are named. */
40
+ export let promptBound = (
41
+ prompt: unknown,
42
+ context: number,
43
+ tools?: unknown,
44
+ ): number =>
45
+ textual(prompt)
46
+ ? Math.min(context, 2 * (size(prompt) + size(tools)) + FRAMING)
47
+ : context
48
+
49
+ /** Bytes of compact JSON a text token covers on average, where
50
+ * {@link promptBound} takes one byte a token to bound it. */
51
+ let BYTES = 4
52
+
53
+ type Prompt = Pick<Request, 'instructions' | 'questions' | 'input'> & {
54
+ items: unknown[]
55
+ turnContext?: unknown[]
56
+ }
57
+
58
+ let promptOf = (req: Prompt): unknown[] => [
59
+ req.instructions,
60
+ req.items,
61
+ ...req.turnContext?.length ? [req.turnContext] : [],
62
+ req.questions,
63
+ req.input,
64
+ ]
65
+
66
+ /**
67
+ * What a request that failed with nothing measured most likely cost, never
68
+ * above `most`, its hold: the text it sent at the input tariff, its anchored
69
+ * history uncounted since a cut request reads little of it, and the `output`
70
+ * tokens it was seen writing at the output tariff. An estimate, not a bound:
71
+ * it settles a hold the provider said nothing of, where the worst case would
72
+ * charge a space for money never spent.
73
+ *
74
+ * ```ts
75
+ * import { likely } from '@yaks/model'
76
+ * import { equal } from '@yaks/testing'
77
+ * let price = { input: 1, output: 10 }
78
+ * // 1,003 tokens of text sent, about four bytes each
79
+ * let req = { instructions: 'x'.repeat(3990), items: [], tools: [] }
80
+ * equal(likely(req, price, 5), 0.001003)
81
+ * equal(likely(req, price, 5, 100), 0.002003)
82
+ * equal(likely(req, price, 0.0005), 0.0005)
83
+ * ```
84
+ */
85
+ export let likely = (
86
+ req: Prompt & Pick<Request, 'tools'>,
87
+ price: Price,
88
+ most: number,
89
+ output = 0,
90
+ ): number => {
91
+ let input = Math.ceil(
92
+ (size(promptOf(req)) + size(req.tools)) / BYTES,
93
+ )
94
+ let dollars = upward((input * price.input + output * price.output) / 1e6)
95
+ return Math.min(most, dollars)
96
+ }
97
+
98
+ /** A request's input bound. An anchor continues a conversation the provider
99
+ * holds, whose earlier turns this side cannot measure. */
100
+ export let requestBound = (
101
+ req: Prompt & Pick<Request, 'anchor' | 'tools'>,
102
+ context: number,
103
+ ): number =>
104
+ req.anchor ? context : promptBound(
105
+ promptOf(req),
106
+ context,
107
+ req.tools,
108
+ )
109
+
110
+ /** A request's price as it can be billed. A provider keeps the longest cache
111
+ * lifetime it offers that is not over what the request asks
112
+ * (`Request.cacheRetention`), or its default, so only a request asking an
113
+ * hour can write to the hour's cache at its dearer tariff. */
114
+ export let retained = (price: Price, seconds = 0, shared = 0): Price => ({
115
+ ...price,
116
+ ...Math.max(seconds, shared) >= HOUR ? {} : { cache_write_1h: undefined },
117
+ ...shared >= 43_200 ? {} : { cache_write_12h: undefined },
118
+ })
119
+ let HOUR = 3600
120
+
121
+ let valid = (n: number) => Number.isFinite(n) && n >= 0
122
+ let upward = (dollars: number) => Math.ceil(dollars * 1e12) / 1e12
123
+
124
+ /** The most output affordable after reserving every input token at its highest
125
+ * possible tariff, and `searches` web searches at theirs. The returned dollars
126
+ * cover that entire call; a provider must enforce the returned output token
127
+ * limit before it spends anything. */
128
+ export let affordable = (
129
+ price: Price,
130
+ input: number,
131
+ remaining: number,
132
+ tokens = 4096,
133
+ searches = 0,
134
+ ): Affordable | null => {
135
+ let rates = [
136
+ price.input,
137
+ price.cached ?? price.input,
138
+ price.cache_write ?? price.input,
139
+ price.cache_write_1h ?? price.cache_write ?? price.input,
140
+ price.cache_write_12h ?? price.cache_write ?? price.input,
141
+ ]
142
+ if (
143
+ !rates.every(valid) || !valid(price.output) || !valid(input) ||
144
+ !valid(remaining) || !valid(price.web_search ?? 0) ||
145
+ !Number.isSafeInteger(searches) || searches < 0 ||
146
+ !Number.isSafeInteger(input) || !Number.isSafeInteger(tokens) ||
147
+ tokens < 0 ||
148
+ tokens == 0 && price.output > 0
149
+ ) return null
150
+ let fixed = upward(
151
+ input * Math.max(...rates) / 1e6 + searches * (price.web_search ?? 0),
152
+ )
153
+ if (fixed > remaining) return null
154
+ let output = price.output
155
+ ? Math.min(tokens, Math.floor((remaining - fixed) * 1e6 / price.output))
156
+ : tokens
157
+ let dollars = upward(fixed + output * price.output / 1e6)
158
+ // Floating point division can round the quotient up by one output token.
159
+ if (dollars > remaining && output > 0) {
160
+ output--
161
+ dollars = upward(fixed + output * price.output / 1e6)
162
+ }
163
+ return dollars <= remaining && (output > 0 || tokens == 0)
164
+ ? { tokens: output, dollars }
165
+ : null
166
+ }
167
+
168
+ /** Measured dollars require reported cost or complete usage. Input the
169
+ * provider classified (it said how many tokens it wrote to the cache, none
170
+ * included) is weighed as it said; unclassified input uses its highest cache
171
+ * tariff; missing usage stays unknown. */
172
+ export let measured = (
173
+ reply: { cost?: number; costReported?: boolean; usage?: Usage },
174
+ price: Price | undefined,
175
+ ): { dollars: number; reported: boolean } | undefined => {
176
+ if (reply.cost != null) {
177
+ return { dollars: reply.cost, reported: reply.costReported ?? true }
178
+ }
179
+ let n = reply.usage
180
+ if (
181
+ !price || n?.input_tokens == null ||
182
+ price.output > 0 && n.output_tokens == null ||
183
+ !Object.values(n ?? {}).every((count) =>
184
+ count == null || Number.isSafeInteger(count) && count >= 0
185
+ )
186
+ ) {
187
+ return undefined
188
+ }
189
+ if (n.cache_write_tokens != null) {
190
+ return { dollars: weigh(price, n), reported: false }
191
+ }
192
+ let input = Math.max(
193
+ price.input,
194
+ price.cached ?? price.input,
195
+ price.cache_write ?? price.input,
196
+ price.cache_write_1h ?? price.cache_write ?? price.input,
197
+ price.cache_write_12h ?? price.cache_write ?? price.input,
198
+ )
199
+ return { dollars: weigh({ ...price, input }, n), reported: false }
200
+ }
201
+
202
+ /** A conservative charge where the caller explicitly accounts unknown usage. */
203
+ export let charged = (
204
+ reply: { cost?: number; costReported?: boolean; usage?: Usage },
205
+ price: Price | undefined,
206
+ maximum: number,
207
+ ): { dollars: number; reported: boolean } =>
208
+ measured(reply, price) ?? { dollars: maximum, reported: false }
package/attribute.js ADDED
@@ -0,0 +1,109 @@
1
+ // How one request's tokens were paid, part by part. A provider reports a
2
+ // request's usage whole: so many input tokens read from its prompt cache, so
3
+ // many written to it, the rest of the input fresh, and the output. A prompt is
4
+ // cached as a prefix, in the order it is sent (tools, system, then the
5
+ // conversation), so the tier a token was paid in follows from where it sits:
6
+ // the first `cached_tokens` of the input were read, the next
7
+ // `cache_write_tokens` written, the rest were fresh. Laying a request's parts
8
+ // out in that order, each sized by its text and scaled so the sizes sum to the
9
+ // reported input, says what each part cost. The totals are measured; the split
10
+ // across parts is an estimate from their sizes.
11
+ let add = (to, key, i, n)=>{
12
+ if (!n) return;
13
+ let p = to[key] ??= [
14
+ 0,
15
+ 0,
16
+ 0,
17
+ 0
18
+ ];
19
+ p[i] += n;
20
+ };
21
+ /**
22
+ * A request's input tokens, split across its parts in prompt order: each part
23
+ * scaled from its size to its share of `input_tokens`, then paid by where it
24
+ * sits. Parts with one key add up; an input with no sized part is all
25
+ * `unseen`.
26
+ *
27
+ * ```ts
28
+ * import { attribute } from '@yaks/model'
29
+ * import { equal } from '@yaks/testing'
30
+ *
31
+ * let usage = { input_tokens: 100, cached_tokens: 60, cache_write_tokens: 30 }
32
+ * equal(attribute(usage, [['tools', 50], ['chat', 30], ['tools', 0], ['new', 20]]), {
33
+ * tools: [50, 0, 0, 0],
34
+ * chat: [10, 20, 0, 0],
35
+ * new: [0, 10, 10, 0],
36
+ * })
37
+ * equal(attribute({ input_tokens: 5 }, []), { unseen: [0, 0, 5, 0] })
38
+ * ```
39
+ */ export let attribute = (u, parts)=>{
40
+ let total = Math.max(0, u.input_tokens ?? 0);
41
+ let read = Math.min(Math.max(0, u.cached_tokens ?? 0), total);
42
+ let write = Math.min(Math.max(0, u.cache_write_tokens ?? 0), total - read);
43
+ let size = parts.reduce((n, [, s])=>n + Math.max(0, s), 0);
44
+ if (!size) parts = [
45
+ [
46
+ 'unseen',
47
+ size = 1
48
+ ]
49
+ ];
50
+ let out = {};
51
+ let at = 0;
52
+ for (let [key, s] of parts){
53
+ let n = total * Math.max(0, s) / size;
54
+ let end = at + n;
55
+ add(out, key, 0, Math.max(0, Math.min(end, read) - at));
56
+ add(out, key, 1, Math.max(0, Math.min(end, read + write) - Math.max(at, read)));
57
+ add(out, key, 2, Math.max(0, end - Math.max(at, read + write)));
58
+ at = end;
59
+ }
60
+ return out;
61
+ };
62
+ /**
63
+ * Generated tokens split across what a request generated, by size; with
64
+ * nothing sized, all of it is `fallback`'s.
65
+ *
66
+ * ```ts
67
+ * import { generated } from '@yaks/model'
68
+ * import { equal } from '@yaks/testing'
69
+ *
70
+ * equal(generated(90, [['output', 20], ['call Bash', 10]]), {
71
+ * output: [0, 0, 0, 60],
72
+ * 'call Bash': [0, 0, 0, 30],
73
+ * })
74
+ * equal(generated(7, [], 'reasoning'), { reasoning: [0, 0, 0, 7] })
75
+ * ```
76
+ */ export let generated = (tokens, parts, fallback = 'output')=>{
77
+ let size = parts.reduce((n, [, s])=>n + Math.max(0, s), 0);
78
+ if (!size) parts = [
79
+ [
80
+ fallback,
81
+ size = 1
82
+ ]
83
+ ];
84
+ let out = {};
85
+ for (let [key, s] of parts)add(out, key, 3, tokens * Math.max(0, s) / size);
86
+ return out;
87
+ };
88
+ /**
89
+ * Several splits as one, adding what they share.
90
+ *
91
+ * ```ts
92
+ * import { merged } from '@yaks/model'
93
+ * import { equal } from '@yaks/testing'
94
+ *
95
+ * equal(merged({ a: [1, 0, 0, 0] }, { a: [0, 0, 0, 2], b: [0, 1, 0, 0] }), {
96
+ * a: [1, 0, 0, 2],
97
+ * b: [0, 1, 0, 0],
98
+ * })
99
+ * ```
100
+ */ export let merged = (...splits)=>{
101
+ let out = {};
102
+ for (let s of splits){
103
+ for (let [key, p] of Object.entries(s)){
104
+ p.forEach((n, i)=>add(out, key, i, n));
105
+ }
106
+ }
107
+ return out;
108
+ };
109
+ //# sourceMappingURL=attribute.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attribute.js","sources":["./attribute.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,+EAA+E;AAC/E,uEAAuE;AACvE,6EAA6E;AAC7E,6DAA6D;AAC7D,8EAA8E;AAC9E,+EAA+E;AAC/E,+EAA+E;AAC/E,gDAAgD;AAWhD,IAAI,MAAM,CAAC,IAA0B,KAAa,GAAW;EAC3D,IAAI,CAAC,GAAG;EACR,IAAI,IAAI,EAAE,CAAC,IAAI,KAAK;IAAC;IAAG;IAAG;IAAG;GAAE;EAChC,CAAC,CAAC,EAAE,IAAI;AACV;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,IAAI,YAAY,CAAC,GAAU;EAChC,IAAI,QAAQ,KAAK,GAAG,CAAC,GAAG,EAAE,YAAY,IAAI;EAC1C,IAAI,OAAO,KAAK,GAAG,CAAC,KAAK,GAAG,CAAC,GAAG,EAAE,aAAa,IAAI,IAAI;EACvD,IAAI,QAAQ,KAAK,GAAG,CAAC,KAAK,GAAG,CAAC,GAAG,EAAE,kBAAkB,IAAI,IAAI,QAAQ;EACrE,IAAI,OAAO,MAAM,MAAM,CAAC,CAAC,GAAG,GAAG,EAAE,GAAK,IAAI,KAAK,GAAG,CAAC,GAAG,IAAI;EAC1D,IAAI,CAAC,MAAM,QAAQ;IAAC;MAAC;MAAU,OAAO;KAAE;GAAC;EACzC,IAAI,MAA4B,CAAC;EACjC,IAAI,KAAK;EACT,KAAK,IAAI,CAAC,KAAK,EAAE,IAAI,MAAO;IAC1B,IAAI,IAAI,QAAQ,KAAK,GAAG,CAAC,GAAG,KAAK;IACjC,IAAI,MAAM,KAAK;IACf,IAAI,KAAK,KAAK,GAAG,KAAK,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,KAAK,QAAQ;IACnD,IACE,KACA,KACA,GACA,KAAK,GAAG,CAAC,GAAG,KAAK,GAAG,CAAC,KAAK,OAAO,SAAS,KAAK,GAAG,CAAC,IAAI;IAEzD,IAAI,KAAK,KAAK,GAAG,KAAK,GAAG,CAAC,GAAG,MAAM,KAAK,GAAG,CAAC,IAAI,OAAO;IACvD,KAAK;EACP;EACA,OAAO;AACT,EAAC;AAED;;;;;;;;;;;;;;CAcC,GACD,OAAO,IAAI,YAAY,CACrB,QACA,OACA,WAAW,QAAQ;EAEnB,IAAI,OAAO,MAAM,MAAM,CAAC,CAAC,GAAG,GAAG,EAAE,GAAK,IAAI,KAAK,GAAG,CAAC,GAAG,IAAI;EAC1D,IAAI,CAAC,MAAM,QAAQ;IAAC;MAAC;MAAU,OAAO;KAAE;GAAC;EACzC,IAAI,MAA4B,CAAC;EACjC,KAAK,IAAI,CAAC,KAAK,EAAE,IAAI,MAAO,IAAI,KAAK,KAAK,GAAG,SAAS,KAAK,GAAG,CAAC,GAAG,KAAK;EACvE,OAAO;AACT,EAAC;AAED;;;;;;;;;;;;CAYC,GACD,OAAO,IAAI,SAAS,CAClB,GAAG;EAEH,IAAI,MAA4B,CAAC;EACjC,KAAK,IAAI,KAAK,OAAQ;IACpB,KAAK,IAAI,CAAC,KAAK,EAAE,IAAI,OAAO,OAAO,CAAC,GAAI;MACtC,EAAE,OAAO,CAAC,CAAC,GAAG,IAAM,IAAI,KAAK,KAAK,GAAG;IACvC;EACF;EACA,OAAO;AACT,EAAC"}
package/attribute.ts ADDED
@@ -0,0 +1,120 @@
1
+ // How one request's tokens were paid, part by part. A provider reports a
2
+ // request's usage whole: so many input tokens read from its prompt cache, so
3
+ // many written to it, the rest of the input fresh, and the output. A prompt is
4
+ // cached as a prefix, in the order it is sent (tools, system, then the
5
+ // conversation), so the tier a token was paid in follows from where it sits:
6
+ // the first `cached_tokens` of the input were read, the next
7
+ // `cache_write_tokens` written, the rest were fresh. Laying a request's parts
8
+ // out in that order, each sized by its text and scaled so the sizes sum to the
9
+ // reported input, says what each part cost. The totals are measured; the split
10
+ // across parts is an estimate from their sizes.
11
+
12
+ import type { Usage } from './vocab.ts'
13
+
14
+ /** One part of a request: its key, and its size in any unit (characters). */
15
+ export type Part = [key: string, size: number]
16
+
17
+ /** A part's tokens by how they were paid: read from the cache, written to it,
18
+ * sent fresh, and generated. */
19
+ export type Paid = [read: number, write: number, fresh: number, output: number]
20
+
21
+ let add = (to: Record<string, Paid>, key: string, i: number, n: number) => {
22
+ if (!n) return
23
+ let p = to[key] ??= [0, 0, 0, 0]
24
+ p[i] += n
25
+ }
26
+
27
+ /**
28
+ * A request's input tokens, split across its parts in prompt order: each part
29
+ * scaled from its size to its share of `input_tokens`, then paid by where it
30
+ * sits. Parts with one key add up; an input with no sized part is all
31
+ * `unseen`.
32
+ *
33
+ * ```ts
34
+ * import { attribute } from '@yaks/model'
35
+ * import { equal } from '@yaks/testing'
36
+ *
37
+ * let usage = { input_tokens: 100, cached_tokens: 60, cache_write_tokens: 30 }
38
+ * equal(attribute(usage, [['tools', 50], ['chat', 30], ['tools', 0], ['new', 20]]), {
39
+ * tools: [50, 0, 0, 0],
40
+ * chat: [10, 20, 0, 0],
41
+ * new: [0, 10, 10, 0],
42
+ * })
43
+ * equal(attribute({ input_tokens: 5 }, []), { unseen: [0, 0, 5, 0] })
44
+ * ```
45
+ */
46
+ export let attribute = (u: Usage, parts: Part[]): Record<string, Paid> => {
47
+ let total = Math.max(0, u.input_tokens ?? 0)
48
+ let read = Math.min(Math.max(0, u.cached_tokens ?? 0), total)
49
+ let write = Math.min(Math.max(0, u.cache_write_tokens ?? 0), total - read)
50
+ let size = parts.reduce((n, [, s]) => n + Math.max(0, s), 0)
51
+ if (!size) parts = [['unseen', size = 1]]
52
+ let out: Record<string, Paid> = {}
53
+ let at = 0
54
+ for (let [key, s] of parts) {
55
+ let n = total * Math.max(0, s) / size
56
+ let end = at + n
57
+ add(out, key, 0, Math.max(0, Math.min(end, read) - at))
58
+ add(
59
+ out,
60
+ key,
61
+ 1,
62
+ Math.max(0, Math.min(end, read + write) - Math.max(at, read)),
63
+ )
64
+ add(out, key, 2, Math.max(0, end - Math.max(at, read + write)))
65
+ at = end
66
+ }
67
+ return out
68
+ }
69
+
70
+ /**
71
+ * Generated tokens split across what a request generated, by size; with
72
+ * nothing sized, all of it is `fallback`'s.
73
+ *
74
+ * ```ts
75
+ * import { generated } from '@yaks/model'
76
+ * import { equal } from '@yaks/testing'
77
+ *
78
+ * equal(generated(90, [['output', 20], ['call Bash', 10]]), {
79
+ * output: [0, 0, 0, 60],
80
+ * 'call Bash': [0, 0, 0, 30],
81
+ * })
82
+ * equal(generated(7, [], 'reasoning'), { reasoning: [0, 0, 0, 7] })
83
+ * ```
84
+ */
85
+ export let generated = (
86
+ tokens: number,
87
+ parts: Part[],
88
+ fallback = 'output',
89
+ ): Record<string, Paid> => {
90
+ let size = parts.reduce((n, [, s]) => n + Math.max(0, s), 0)
91
+ if (!size) parts = [[fallback, size = 1]]
92
+ let out: Record<string, Paid> = {}
93
+ for (let [key, s] of parts) add(out, key, 3, tokens * Math.max(0, s) / size)
94
+ return out
95
+ }
96
+
97
+ /**
98
+ * Several splits as one, adding what they share.
99
+ *
100
+ * ```ts
101
+ * import { merged } from '@yaks/model'
102
+ * import { equal } from '@yaks/testing'
103
+ *
104
+ * equal(merged({ a: [1, 0, 0, 0] }, { a: [0, 0, 0, 2], b: [0, 1, 0, 0] }), {
105
+ * a: [1, 0, 0, 2],
106
+ * b: [0, 1, 0, 0],
107
+ * })
108
+ * ```
109
+ */
110
+ export let merged = (
111
+ ...splits: Record<string, Paid>[]
112
+ ): Record<string, Paid> => {
113
+ let out: Record<string, Paid> = {}
114
+ for (let s of splits) {
115
+ for (let [key, p] of Object.entries(s)) {
116
+ p.forEach((n, i) => add(out, key, i, n))
117
+ }
118
+ }
119
+ return out
120
+ }
package/batch.js ADDED
@@ -0,0 +1,8 @@
1
+ // A provider's batch API, the same for every provider: many one-turn requests
2
+ // sent as one, answered within a day at half the price. Requests that begin
3
+ // with the same system text share their provider's cache of it, so a long
4
+ // prefix every request carries is paid in full once and read cheaply by the
5
+ // rest. Each provider implements it over its own wire (@yaks/anthropic/batches,
6
+ // @yaks/openai/batches).
7
+ /** What a batch costs against the same requests sent one by one. */ export let BATCH = 0.5;
8
+ //# sourceMappingURL=batch.js.map
package/batch.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"batch.js","sources":["./batch.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,4EAA4E;AAC5E,0EAA0E;AAC1E,4EAA4E;AAC5E,gFAAgF;AAChF,yBAAyB;AAGzB,kEAAkE,GAClE,OAAO,IAAI,QAAQ,IAAG"}
package/batch.ts ADDED
@@ -0,0 +1,37 @@
1
+ // A provider's batch API, the same for every provider: many one-turn requests
2
+ // sent as one, answered within a day at half the price. Requests that begin
3
+ // with the same system text share their provider's cache of it, so a long
4
+ // prefix every request carries is paid in full once and read cheaply by the
5
+ // rest. Each provider implements it over its own wire (@yaks/anthropic/batches,
6
+ // @yaks/openai/batches).
7
+ import type { Usage } from './vocab.ts'
8
+
9
+ /** What a batch costs against the same requests sent one by one. */
10
+ export let BATCH = 0.5
11
+
12
+ /** One request of a batch: the system text it shares with the others, then
13
+ * its own text, answered by `model` in at most `max` tokens. `id` names its
14
+ * answer, which comes back in any order. `cache` names the shared prefix,
15
+ * where a provider routes requests by it. */
16
+ export type Asked = {
17
+ id: string
18
+ model: string
19
+ system: string
20
+ text: string
21
+ max: number
22
+ cache?: string
23
+ }
24
+
25
+ /** One request's answer: its text and what it used, or why there is none. */
26
+ export type Answered =
27
+ | { id: string; text: string; usage: Usage }
28
+ | { id: string; error: string }
29
+
30
+ /** A provider's batches: send one, ask whether it has ended, read its
31
+ * answers. */
32
+ export type Batches = {
33
+ /** sends the requests as one batch, and answers its id */
34
+ submit: (asked: Asked[]) => Promise<string>
35
+ ended: (id: string) => Promise<boolean>
36
+ results: (id: string) => Promise<Answered[]>
37
+ }
package/cache.js ADDED
@@ -0,0 +1,28 @@
1
+ // Cached-prefix expiry is provider bookkeeping, not response storage or token
2
+ // usage. Writers snapshot the effective expiry on each ask; readers never
3
+ // recalculate it from a provider row that may have changed since the request.
4
+ /** An ISO instant, or a provider's Unix seconds, normalized to an ISO instant.
5
+ * Dates without a timezone, durations, and nonfinite numbers are unknown. */ export let cacheExpiry = (value)=>{
6
+ let ms = typeof value == 'number' ? value * 1000 : typeof value == 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(value) ? Date.parse(value) : NaN;
7
+ if (!Number.isFinite(ms) || ms < 0 || ms > 8.64e15) return;
8
+ return new Date(ms).toISOString();
9
+ };
10
+ /** Provider expiry wins, including an expired or invalid explicit value.
11
+ * Unknown retention clears a prior mark rather than implying a warm cache. */ export let prefixCacheMark = (reply, cache)=>{
12
+ let expiry;
13
+ if (reply.cacheExpiresAt !== undefined) {
14
+ expiry = cacheExpiry(reply.cacheExpiresAt);
15
+ } else if (cache && Number.isFinite(cache.requestedAt) && cache.requestedAt >= 0 && typeof cache.retention == 'number' && Number.isSafeInteger(cache.retention) && cache.retention > 0) {
16
+ expiry = cacheExpiry((cache.requestedAt + cache.retention * 1000) / 1000);
17
+ }
18
+ return {
19
+ cache_expires_at: expiry ?? null
20
+ };
21
+ };
22
+ /** Read only the recorded request expiry from provider components. Missing,
23
+ * malformed, or ambiguous provider bookkeeping is cold. Callers also require
24
+ * a completed ask and known usage/model context before deciding to reuse it. */ export let cachedPrefixExpires = (comps)=>{
25
+ let values = Object.values(comps).filter((value)=>value != null && typeof value == 'object' && !Array.isArray(value) && 'cache_expires_at' in value);
26
+ return values.length == 1 ? cacheExpiry(values[0].cache_expires_at) : undefined;
27
+ };
28
+ //# sourceMappingURL=cache.js.map
package/cache.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","sources":["./cache.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,0EAA0E;AAC1E,8EAA8E;AAM9E;2EAC2E,GAC3E,OAAO,IAAI,cAAc,CAAC;EACxB,IAAI,KAAK,OAAO,SAAS,WAAW,QAAQ,OAAO,OAAO,SAAS,YAC/D,uEACG,IAAI,CAAC,SACR,KAAK,KAAK,CAAC,SACX;EACJ,IAAI,CAAC,OAAO,QAAQ,CAAC,OAAO,KAAK,KAAK,KAAK,SAAS;EACpD,OAAO,IAAI,KAAK,IAAI,WAAW;AACjC,EAAC;AAED;4EAC4E,GAC5E,OAAO,IAAI,kBAAkB,CAC3B,OACA;EAEA,IAAI;EACJ,IAAI,MAAM,cAAc,KAAK,WAAW;IACtC,SAAS,YAAY,MAAM,cAAc;EAC3C,OAAO,IACL,SAAS,OAAO,QAAQ,CAAC,MAAM,WAAW,KAAK,MAAM,WAAW,IAAI,KACpE,OAAO,MAAM,SAAS,IAAI,YAC1B,OAAO,aAAa,CAAC,MAAM,SAAS,KAAK,MAAM,SAAS,GAAG,GAC3D;IACA,SAAS,YAAY,CAAC,MAAM,WAAW,GAAG,MAAM,SAAS,GAAG,IAAI,IAAI;EACtE;EACA,OAAO;IAAE,kBAAkB,UAAU;EAAK;AAC5C,EAAC;AAED;;8EAE8E,GAC9E,OAAO,IAAI,sBAAsB,CAC/B;EAEA,IAAI,SAAS,OAAO,MAAM,CAAC,OAAO,MAAM,CAAC,CAAC,QACxC,SAAS,QAAQ,OAAO,SAAS,YAAY,CAAC,MAAM,OAAO,CAAC,UAC5D,sBAAsB;EAExB,OAAO,OAAO,MAAM,IAAI,IACpB,YAAY,MAAM,CAAC,EAAE,CAAC,gBAAgB,IACtC;AACN,EAAC"}
package/cache.ts ADDED
@@ -0,0 +1,53 @@
1
+ // Cached-prefix expiry is provider bookkeeping, not response storage or token
2
+ // usage. Writers snapshot the effective expiry on each ask; readers never
3
+ // recalculate it from a provider row that may have changed since the request.
4
+ import type { Reply } from './mod.ts'
5
+
6
+ /** The dispatch instant and the provider's documented retention in seconds. */
7
+ export type CacheContext = { requestedAt: number; retention?: unknown }
8
+
9
+ /** An ISO instant, or a provider's Unix seconds, normalized to an ISO instant.
10
+ * Dates without a timezone, durations, and nonfinite numbers are unknown. */
11
+ export let cacheExpiry = (value: unknown): string | undefined => {
12
+ let ms = typeof value == 'number' ? value * 1000 : typeof value == 'string' &&
13
+ /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/
14
+ .test(value)
15
+ ? Date.parse(value)
16
+ : NaN
17
+ if (!Number.isFinite(ms) || ms < 0 || ms > 8.64e15) return
18
+ return new Date(ms).toISOString()
19
+ }
20
+
21
+ /** Provider expiry wins, including an expired or invalid explicit value.
22
+ * Unknown retention clears a prior mark rather than implying a warm cache. */
23
+ export let prefixCacheMark = (
24
+ reply: Reply,
25
+ cache?: CacheContext,
26
+ ): { cache_expires_at: string | null } => {
27
+ let expiry: string | undefined
28
+ if (reply.cacheExpiresAt !== undefined) {
29
+ expiry = cacheExpiry(reply.cacheExpiresAt)
30
+ } else if (
31
+ cache && Number.isFinite(cache.requestedAt) && cache.requestedAt >= 0 &&
32
+ typeof cache.retention == 'number' &&
33
+ Number.isSafeInteger(cache.retention) && cache.retention > 0
34
+ ) {
35
+ expiry = cacheExpiry((cache.requestedAt + cache.retention * 1000) / 1000)
36
+ }
37
+ return { cache_expires_at: expiry ?? null }
38
+ }
39
+
40
+ /** Read only the recorded request expiry from provider components. Missing,
41
+ * malformed, or ambiguous provider bookkeeping is cold. Callers also require
42
+ * a completed ask and known usage/model context before deciding to reuse it. */
43
+ export let cachedPrefixExpires = (
44
+ comps: Record<string, unknown>,
45
+ ): string | undefined => {
46
+ let values = Object.values(comps).filter((value) =>
47
+ value != null && typeof value == 'object' && !Array.isArray(value) &&
48
+ 'cache_expires_at' in value
49
+ ) as Record<string, unknown>[]
50
+ return values.length == 1
51
+ ? cacheExpiry(values[0].cache_expires_at)
52
+ : undefined
53
+ }
package/deferred.js ADDED
@@ -0,0 +1,29 @@
1
+ // Unused provider transports cost no module loading. Their synchronous recorders
2
+ // are still available before a request, as on a directly constructed Model.
3
+ import { lazy } from "@yaks/fp";
4
+ import { modelReads } from "./mod.js";
5
+ export let deferredModel = (load, meta)=>{
6
+ let get = lazy(load);
7
+ let { recover, retrieve, info, count, reads, ...record } = meta;
8
+ return Object.assign(async (...args)=>(await get())(...args), record, {
9
+ list: async ()=>await (await get()).list?.() ?? [],
10
+ ...reads === true ? {
11
+ reads: async (name)=>modelReads(await get(), name)
12
+ } : reads ? {
13
+ reads
14
+ } : {},
15
+ ...info ? {
16
+ info: async (name)=>await (await get()).info?.(name)
17
+ } : {},
18
+ ...count ? {
19
+ count: async (req)=>await (await get()).count(req)
20
+ } : {},
21
+ ...recover ? {
22
+ recover: async (call)=>(await get()).recover(call)
23
+ } : {},
24
+ ...retrieve ? {
25
+ retrieve: async (...args)=>(await get()).retrieve?.(...args)
26
+ } : {}
27
+ });
28
+ };
29
+ //# sourceMappingURL=deferred.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deferred.js","sources":["./deferred.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,4EAA4E;AAC5E,SAAS,IAAI,wBAA6B;AAC1C,SAAqB,UAAU,mBAAkB;AAEjD,OAAO,IAAI,gBAAgB,CACzB,MACA;EAaA,IAAI,MAAM,KAAK;EACf,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,QAAQ,GAAG;EAC3D,OAAO,OAAO,MAAM,CAClB,OAAO,GAAG,OAA4B,CAAC,MAAM,KAAK,KAAK,OACvD,QACA;IACE,MAAM,UAAY,MAAM,CAAC,MAAM,KAAK,EAAE,IAAI,QAAQ,EAAE;IACpD,GAAG,UAAU,OACT;MAAE,OAAO,OAAO,OAAiB,WAAW,MAAM,OAAO;IAAM,IAC/D,QACA;MAAE;IAAM,IACR,CAAC,CAAC;IACN,GAAG,OACC;MAAE,MAAM,OAAO,OAAiB,MAAM,CAAC,MAAM,KAAK,EAAE,IAAI,GAAG;IAAM,IACjE,CAAC,CAAC;IACN,GAAG,QACC;MACA,OAAO,OAAO,MACZ,MAAM,CAAC,MAAM,KAAK,EAAE,KAAK,CAAE;IAC/B,IACE,CAAC,CAAC;IACN,GAAG,UACC;MAAE,SAAS,OAAO,OAAiB,CAAC,MAAM,KAAK,EAAE,OAAO,CAAE;IAAM,IAChE,CAAC,CAAC;IACN,GAAG,WACC;MACA,UAAU,OACR,GAAG,OACA,CAAC,MAAM,KAAK,EAAE,QAAQ,MAAM;IACnC,IACE,CAAC,CAAC;EACR;AAEJ,EAAC"}
package/deferred.ts ADDED
@@ -0,0 +1,54 @@
1
+ // Unused provider transports cost no module loading. Their synchronous recorders
2
+ // are still available before a request, as on a directly constructed Model.
3
+ import { lazy } from '@yaks/fp'
4
+ import { type Model, modelReads } from './mod.js'
5
+
6
+ export let deferredModel = (
7
+ load: () => Promise<Model>,
8
+ meta:
9
+ & Pick<
10
+ Model,
11
+ 'mark' | 'vocab' | 'anchor' | 'lateResults' | 'hosted'
12
+ >
13
+ & {
14
+ recover?: true
15
+ retrieve?: true
16
+ info?: true
17
+ count?: true
18
+ reads?: Model['reads'] | true
19
+ },
20
+ ): Model => {
21
+ let get = lazy(load)
22
+ let { recover, retrieve, info, count, reads, ...record } = meta
23
+ return Object.assign(
24
+ async (...args: Parameters<Model>) => (await get())(...args),
25
+ record,
26
+ {
27
+ list: async () => await (await get()).list?.() ?? [],
28
+ ...reads === true
29
+ ? { reads: async (name: string) => modelReads(await get(), name) }
30
+ : reads
31
+ ? { reads }
32
+ : {},
33
+ ...info
34
+ ? { info: async (name: string) => await (await get()).info?.(name) }
35
+ : {},
36
+ ...count
37
+ ? {
38
+ count: async (req: Parameters<Model>[0]) =>
39
+ await (await get()).count!(req),
40
+ }
41
+ : {},
42
+ ...recover
43
+ ? { recover: async (call: string) => (await get()).recover!(call) }
44
+ : {},
45
+ ...retrieve
46
+ ? {
47
+ retrieve: async (
48
+ ...args: Parameters<NonNullable<Model['retrieve']>>
49
+ ) => (await get()).retrieve?.(...args),
50
+ }
51
+ : {},
52
+ },
53
+ )
54
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/model","version":"0.2.36","license":"Apache-2.0","description":"Defines provider-neutral model request and reply types, vocabulary for providers and models, and helpers for billing and recovering generated media. Implements no provider's transport, but decodes the server-sent events providers stream and carries one model step from one host to another's providers.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./batch":"./batch.ts","./graph":"./graph.ts","./sse":"./sse.ts","./stall":"./stall.ts","./step":"./step.ts","./route":"./route.ts","./image":"./image.ts"},"imports":{"@yaks/model":"./mod.ts","@yaks/model/vocab":"./vocab.ts","@yaks/model/batch":"./batch.ts","@yaks/model/graph":"./graph.ts","@yaks/model/sse":"./sse.ts","@yaks/model/stall":"./stall.ts","@yaks/model/step":"./step.ts","@yaks/model/route":"./route.ts","@yaks/model/image":"./image.ts"}}