@yaks/openai 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 (78) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +389 -2
  3. package/_dist/batches.d.ts +77 -0
  4. package/_dist/batches.d.ts.map +1 -0
  5. package/_dist/credential.d.ts +13 -0
  6. package/_dist/credential.d.ts.map +1 -0
  7. package/_dist/images.d.ts +15 -0
  8. package/_dist/images.d.ts.map +1 -0
  9. package/_dist/list.d.ts +8 -0
  10. package/_dist/list.d.ts.map +1 -0
  11. package/_dist/media.d.ts +11 -0
  12. package/_dist/media.d.ts.map +1 -0
  13. package/_dist/mod.d.ts +30 -0
  14. package/_dist/mod.d.ts.map +1 -0
  15. package/_dist/project-keys.d.ts +4 -0
  16. package/_dist/project-keys.d.ts.map +1 -0
  17. package/_dist/provider.d.ts +48 -0
  18. package/_dist/provider.d.ts.map +1 -0
  19. package/_dist/responses.d.ts +51 -0
  20. package/_dist/responses.d.ts.map +1 -0
  21. package/_dist/transport.d.ts +121 -0
  22. package/_dist/transport.d.ts.map +1 -0
  23. package/_dist/vocab.d.ts +10 -0
  24. package/_dist/vocab.d.ts.map +1 -0
  25. package/batches.js +145 -0
  26. package/batches.js.map +1 -0
  27. package/batches.ts +194 -0
  28. package/credential.js +30 -0
  29. package/credential.js.map +1 -0
  30. package/credential.ts +40 -0
  31. package/deno.json +1 -0
  32. package/generations.js +288 -0
  33. package/generations.js.map +1 -0
  34. package/generations.ts +365 -0
  35. package/images.js +37 -0
  36. package/images.js.map +1 -0
  37. package/images.ts +63 -0
  38. package/info.js +55 -0
  39. package/info.js.map +1 -0
  40. package/info.ts +59 -0
  41. package/limits.js +50 -0
  42. package/limits.js.map +1 -0
  43. package/limits.ts +48 -0
  44. package/list.js +88 -0
  45. package/list.js.map +1 -0
  46. package/list.ts +127 -0
  47. package/mark.js +29 -0
  48. package/mark.js.map +1 -0
  49. package/mark.ts +50 -0
  50. package/media.js +60 -0
  51. package/media.js.map +1 -0
  52. package/media.ts +94 -0
  53. package/mod.js +28 -0
  54. package/mod.js.map +1 -0
  55. package/mod.ts +64 -0
  56. package/native.js +176 -0
  57. package/native.js.map +1 -0
  58. package/native.ts +221 -0
  59. package/package.json +36 -4
  60. package/project-keys.js +32 -0
  61. package/project-keys.js.map +1 -0
  62. package/project-keys.ts +43 -0
  63. package/provider.js +190 -0
  64. package/provider.js.map +1 -0
  65. package/provider.ts +292 -0
  66. package/reads.js +167 -0
  67. package/reads.js.map +1 -0
  68. package/reads.ts +169 -0
  69. package/responses.js +612 -0
  70. package/responses.js.map +1 -0
  71. package/responses.ts +706 -0
  72. package/transport.js +646 -0
  73. package/transport.js.map +1 -0
  74. package/transport.ts +972 -0
  75. package/vocab.js +23 -0
  76. package/vocab.js.map +1 -0
  77. package/vocab.json +25 -0
  78. package/vocab.ts +29 -0
package/generations.ts ADDED
@@ -0,0 +1,365 @@
1
+ /** GPT Image models over the Image API: one prompt in, one stored image out.
2
+ * Binary persistence is injected; the price is OpenAI's published tariff. */
3
+ import {
4
+ acknowledged,
5
+ type Affordable,
6
+ type Listed,
7
+ type MediaReceipt,
8
+ type MediaReceipts,
9
+ ModelError,
10
+ receivedMedia,
11
+ recoveredMedia,
12
+ type Reply,
13
+ type Request,
14
+ submitted,
15
+ } from '@yaks/model'
16
+ import { mediaTypeOf, sizeOf } from '@yaks/blob'
17
+ import { CODEX, type Credential } from './credential.js'
18
+ import { dataUrl, generatedMedia, mediaRoom, type MediaStore } from './media.js'
19
+
20
+ // Each family's output tokens per quality at a square of 2,000,000 pixels'
21
+ // weight, and GPT Image 2.6's own scale on them: OpenAI's cost calculator
22
+ // (developers.openai.com, guides/image-generation#calculating-costs).
23
+ let STEPS = { low: 16, medium: 24, high: 48, xhigh: 64, max: 96 }
24
+ let SCALE: Record<string, number> = { low: 4.2, medium: 3.3 }
25
+ let FAMILIES: Record<string, Record<string, number>> = {
26
+ 'gpt-image-2.5': STEPS,
27
+ 'gpt-image-2.6': STEPS,
28
+ }
29
+ // Dollars per million tokens, the same for both families (pricing page).
30
+ let PRICE = { text: 5, image: 8, output: 30 }
31
+ // The largest image either family makes: 8,294,400 pixels, square.
32
+ let LARGEST = 2880
33
+ let FORMATS = ['png', 'jpeg', 'webp']
34
+ let MAX_REFERENCE = 14 * 1024 * 1024
35
+ let OPTIONS = [
36
+ 'size',
37
+ 'quality',
38
+ 'background',
39
+ 'output_format',
40
+ 'output_compression',
41
+ 'moderation',
42
+ 'complexity',
43
+ ]
44
+
45
+ let family = (model: string) =>
46
+ Object.keys(FAMILIES).find((f) => model == f || model.startsWith(f + '-'))
47
+
48
+ /** Whether `model` is a GPT Image model this adapter prices. */
49
+ export let image = (model: string): boolean => !!family(model)
50
+
51
+ /** What OpenAI's calculator says one image of `width` by `height` at
52
+ * `quality` makes, in output tokens. */
53
+ export let imageTokens = (
54
+ model: string,
55
+ width: number,
56
+ height: number,
57
+ quality: string,
58
+ ): number => {
59
+ let base = FAMILIES[family(model)!][quality]
60
+ let long = Math.max(width, height), short = Math.min(width, height)
61
+ let s = base / (long / short), whole = Math.floor(s)
62
+ let side = s - whole == 0.5 ? whole + whole % 2 : Math.round(s)
63
+ let tiles = width >= height ? base * side : side * base
64
+ let tokens = Math.ceil(tiles * (2e6 + width * height) / 4e6)
65
+ return family(model) == 'gpt-image-2.6'
66
+ ? Math.round(tokens * (SCALE[quality] ?? 1))
67
+ : tokens
68
+ }
69
+
70
+ let prompt = (req: Request): string => {
71
+ let input = req.items.findLast((item) => item.kind == 'user')
72
+ if (!input || input.kind != 'user' || !input.text.trim()) {
73
+ throw new ModelError('input', 'Image models need a text prompt')
74
+ }
75
+ return input.text
76
+ }
77
+
78
+ let references = (req: Request) => {
79
+ let images = req.items.filter((item) => item.kind == 'image')
80
+ if (images.length > 16 || req.items.some((item) => item.kind == 'document')) {
81
+ throw new ModelError(
82
+ 'bad_request',
83
+ 'Image models take up to 16 reference images and no documents',
84
+ )
85
+ }
86
+ for (let image of images) {
87
+ if (
88
+ !['image/png', 'image/jpeg', 'image/webp'].includes(image.mediaType) ||
89
+ image.bytes.length > MAX_REFERENCE ||
90
+ mediaTypeOf(image.bytes) != image.mediaType || !sizeOf(image.bytes)
91
+ ) {
92
+ throw new ModelError(
93
+ 'bad_request',
94
+ 'References must be PNG, JPEG or WebP images under 14 MiB',
95
+ )
96
+ }
97
+ }
98
+ return images
99
+ }
100
+
101
+ let imagePrompt = (req: Request, images: ReturnType<typeof references>) =>
102
+ [
103
+ ...images.map((item, i) => `Reference image ${i + 1}: ${item.label}`),
104
+ prompt(req),
105
+ ].join('\n\n')
106
+
107
+ let requestBody = (req: Request) => {
108
+ let images = references(req)
109
+ return {
110
+ model: req.model,
111
+ prompt: imagePrompt(req, images),
112
+ n: 1,
113
+ ...settings(req),
114
+ ...images.length
115
+ ? {
116
+ images: images.map((item) => ({
117
+ image_url: dataUrl(item),
118
+ })),
119
+ }
120
+ : {},
121
+ }
122
+ }
123
+
124
+ // What a receipt keeps of a request: everything but the reference pixels,
125
+ // each said by its type and size. A 2400×3040 reference is megabytes of
126
+ // base64, and a store keeping, writing and reading back copies of several
127
+ // went over its memory (T-2685).
128
+ let recorded = (body: ReturnType<typeof requestBody>, req: Request) =>
129
+ body.images
130
+ ? {
131
+ ...body,
132
+ images: references(req).map((item) => ({
133
+ media_type: item.mediaType,
134
+ bytes: item.bytes.length,
135
+ })),
136
+ }
137
+ : body
138
+
139
+ // What a receipt keeps of an answer once its image is kept as an artifact the
140
+ // reply names: the answer without its base64.
141
+ let delivered = (answer: Answer): Answer => ({
142
+ ...answer,
143
+ data: answer.data?.map(({ b64_json: _, ...rest }) => rest),
144
+ })
145
+
146
+ let settings = (req: Request): Record<string, unknown> => {
147
+ let input = req.input ?? {}
148
+ let extra = Object.keys(input).filter((k) => !OPTIONS.includes(k))
149
+ if (extra.length) {
150
+ throw new ModelError(
151
+ 'bad_request',
152
+ `Image models take ${OPTIONS.join(', ')}; not ${extra.join(', ')}`,
153
+ )
154
+ }
155
+ let format = input.output_format ?? 'png'
156
+ if (!FORMATS.includes(String(format))) {
157
+ throw new ModelError(
158
+ 'bad_request',
159
+ `Image models make ${FORMATS.join(', ')} here; not ${format}`,
160
+ )
161
+ }
162
+ let quality = input.quality ?? 'auto'
163
+ if (quality != 'auto' && !(String(quality) in FAMILIES[family(req.model)!])) {
164
+ throw new ModelError(
165
+ 'bad_request',
166
+ `No ${quality} quality for ${req.model}`,
167
+ )
168
+ }
169
+ let size = input.size ?? 'auto'
170
+ if (size != 'auto' && !/^\d+x\d+$/.test(String(size))) {
171
+ throw new ModelError('bad_request', 'An image size is auto or WIDTHxHEIGHT')
172
+ }
173
+ return { ...input, output_format: format, quality, size }
174
+ }
175
+
176
+ /** A reservation estimate: its prompt's bytes as text tokens, and twice
177
+ * the calculator's output at its quality (at most `max`) and size (at most the
178
+ * largest), plus a reference-input estimate at max-quality token weight. */
179
+ export let imageQuote = (
180
+ req: Request,
181
+ remaining: number,
182
+ ): Affordable | null => {
183
+ let sent = settings(req)
184
+ let quality = sent.quality == 'auto' ? 'max' : String(sent.quality)
185
+ let [width, height] = sent.size == 'auto'
186
+ ? [LARGEST, LARGEST]
187
+ : String(sent.size).split('x').map(Number)
188
+ let images = references(req)
189
+ let text = new TextEncoder().encode(imagePrompt(req, images)).length
190
+ // There is no published input calculator for these families. Use the
191
+ // existing max-quality token calculator as an estimate for each reference.
192
+ // The meter settles the provider's measured usage, even above this estimate.
193
+ let input = images.reduce((sum, item) => {
194
+ let { w, h } = sizeOf(item.bytes)!
195
+ return sum + imageTokens(req.model, w, h, 'max')
196
+ }, 0)
197
+ let dollars = (text * PRICE.text +
198
+ 2 * imageTokens(req.model, width, height, quality) * PRICE.output +
199
+ input * PRICE.image) / 1e6
200
+ return dollars <= remaining ? { dollars, tokens: 0 } : null
201
+ }
202
+
203
+ type Usage = {
204
+ input_tokens_details?: { text_tokens?: number; image_tokens?: number }
205
+ output_tokens?: number
206
+ }
207
+
208
+ /** What an Image API answer cost: its text and image input and all its
209
+ * output, at the published rates. */
210
+ export let imageCost = (usage: Usage | undefined): number => {
211
+ let { text_tokens = 0, image_tokens = 0 } = usage?.input_tokens_details ?? {}
212
+ let output = usage?.output_tokens
213
+ if (
214
+ ![text_tokens, image_tokens, output].every((n) =>
215
+ Number.isSafeInteger(n) && n! >= 0
216
+ )
217
+ ) {
218
+ throw new ModelError('media_cost', 'The image answer reported no usage')
219
+ }
220
+ return (text_tokens * PRICE.text + image_tokens * PRICE.image +
221
+ output! * PRICE.output) / 1e6
222
+ }
223
+
224
+ /** How an image model is listed: image out, at its image rates. */
225
+ export let imageListed = (name: string): Listed => ({
226
+ name,
227
+ label: name,
228
+ modalities: ['image'],
229
+ price: { input: PRICE.image, output: PRICE.output },
230
+ })
231
+
232
+ export type Generations = {
233
+ credential: () => Promise<Credential>
234
+ headers?: Record<string, string>
235
+ fetch?: typeof fetch
236
+ media?: MediaStore
237
+ receipts?: MediaReceipts
238
+ }
239
+
240
+ type Answer = {
241
+ data?: { b64_json?: unknown }[]
242
+ output_format?: string
243
+ usage?: Usage
244
+ }
245
+
246
+ let deliver = async (
247
+ receipt: MediaReceipt,
248
+ media?: MediaStore,
249
+ ): Promise<Reply> => {
250
+ let answer = receipt.response as Answer
251
+ let format = answer.output_format ?? 'png'
252
+ if (!FORMATS.includes(format)) {
253
+ throw new ModelError('image_format', 'Unsupported image format')
254
+ }
255
+ let artifact = await generatedMedia(
256
+ answer.data?.[0]?.b64_json,
257
+ 'image/' + format,
258
+ receipt.id,
259
+ media,
260
+ )
261
+ return {
262
+ id: receipt.id,
263
+ model: receipt.model,
264
+ items: [],
265
+ artifacts: [artifact],
266
+ cost: receipt.cost!,
267
+ costReported: false,
268
+ }
269
+ }
270
+
271
+ type Refusal = { error?: { code?: string; param?: string; message?: string } }
272
+
273
+ /** OpenAI's refusal in its own words: the status, its code, the parameter it
274
+ * names and its message, so a caller can fix its request. */
275
+ let refusal = (status: number, body: unknown) => {
276
+ let { code, param, message } = (body as Refusal)?.error ?? {}
277
+ let head = [status, code, param && 'param ' + param].filter(Boolean)
278
+ return `OpenAI refused the image (${head.join(', ')})` +
279
+ (message ? ': ' + message : '')
280
+ }
281
+
282
+ /** The Image API as a model: the newest user text is the prompt, image items
283
+ * its references, and `req.input` its settings. The answer is kept as a private
284
+ * receipt before its bytes are stored, so a stored image is never bought twice. */
285
+ export let generations = (options: Generations) => {
286
+ let ask = async (req: Request): Promise<Reply> => {
287
+ if (!options.media) {
288
+ throw new ModelError(
289
+ 'media_storage',
290
+ 'Image output requires artifact storage',
291
+ )
292
+ }
293
+ if (req.questions) {
294
+ throw new ModelError(
295
+ 'questions',
296
+ 'Image models answer no typed questions',
297
+ )
298
+ }
299
+ let body = requestBody(req)
300
+ let credential = await options.credential()
301
+ if (credential.base == CODEX) {
302
+ throw new ModelError('model', 'Image models need an OpenAI API key')
303
+ }
304
+ await mediaRoom(options.media)
305
+ await submitted(req)
306
+ let res: Response
307
+ try {
308
+ res = await (options.fetch ?? fetch)(
309
+ credential.base +
310
+ (body.images ? '/images/edits' : '/images/generations'),
311
+ {
312
+ method: 'POST',
313
+ headers: {
314
+ ...options.headers,
315
+ ...credential.token
316
+ ? { authorization: 'Bearer ' + credential.token }
317
+ : {},
318
+ 'content-type': 'application/json',
319
+ },
320
+ body: JSON.stringify(body),
321
+ signal: req.signal,
322
+ },
323
+ )
324
+ } catch (error) {
325
+ if (req.signal?.aborted) throw error
326
+ throw new ModelError('transport', 'OpenAI image connection failed')
327
+ }
328
+ if (!res.ok) {
329
+ throw new ModelError(
330
+ res.status == 400 ? 'bad_request' : 'http_' + res.status,
331
+ refusal(res.status, await res.json().catch(() => undefined)),
332
+ res.status == 429 || res.status >= 500 ? { after: 0 } : undefined,
333
+ )
334
+ }
335
+ let answer = await res.json() as Answer
336
+ let id = req.call ?? crypto.randomUUID()
337
+ await acknowledged(req, { openai: { response_id: id } })
338
+ let receipt: MediaReceipt = {
339
+ provider: 'openai',
340
+ call: id,
341
+ id,
342
+ model: req.model,
343
+ input: recorded(body, req),
344
+ response: answer,
345
+ cost: imageCost(answer.usage),
346
+ costReported: false,
347
+ }
348
+ await receivedMedia(req, receipt, options.receipts)
349
+ let reply = await deliver(receipt, options.media)
350
+ await options.receipts?.save({
351
+ ...receipt,
352
+ response: delivered(answer),
353
+ reply,
354
+ })
355
+ return reply
356
+ }
357
+ return Object.assign(ask, {
358
+ recover: (call: string) =>
359
+ recoveredMedia(
360
+ call,
361
+ options.receipts,
362
+ (receipt) => deliver(receipt, options.media),
363
+ ),
364
+ })
365
+ }
package/images.js ADDED
@@ -0,0 +1,37 @@
1
+ /** Native Responses image-generation output. Binary persistence is injected. */ import { ModelError } from "@yaks/model";
2
+ import { generatedMedia } from "./media.js";
3
+ export let generatedImages = async (items, options)=>{
4
+ let artifacts = [];
5
+ for (let item of items){
6
+ if (item.type != 'image_generation_call') continue;
7
+ if (!options) {
8
+ throw new ModelError('image_storage', 'Image output requires configured artifact storage');
9
+ }
10
+ if (item.status != 'completed') {
11
+ throw new ModelError('image_incomplete', 'Image generation did not complete');
12
+ }
13
+ let format = item.output_format ?? options.tool?.output_format ?? 'png';
14
+ if (![
15
+ 'png',
16
+ 'jpeg',
17
+ 'webp'
18
+ ].includes(String(format))) {
19
+ throw new ModelError('image_format', 'Unsupported image format');
20
+ }
21
+ if (typeof item.id != 'string' || !item.id) {
22
+ throw new ModelError('image_call', 'Image output has no call ID');
23
+ }
24
+ let artifact = await generatedMedia(item.result, 'image/' + format, item.id, {
25
+ store: options.store,
26
+ maxBytes: options.maxBytes ?? 32 * 1024 * 1024
27
+ });
28
+ artifacts.push({
29
+ ...artifact,
30
+ ...typeof item.revised_prompt == 'string' && item.revised_prompt.length <= 32768 ? {
31
+ revised_prompt: item.revised_prompt
32
+ } : {}
33
+ });
34
+ }
35
+ return artifacts;
36
+ };
37
+ //# sourceMappingURL=images.js.map
package/images.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"images.js","sources":["./images.ts"],"names":[],"mappings":"AAAA,8EAA8E,GAC9E,SAAS,UAAU,2BAA4C;AAE/D,SAAS,cAAc,qBAAoB;AAkB3C,OAAO,IAAI,kBAAkB,OAC3B,OACA;EAEA,IAAI,YAA6C,EAAE;EACnD,KAAK,IAAI,QAAQ,MAAO;IACtB,IAAI,KAAK,IAAI,IAAI,yBAAyB;IAC1C,IAAI,CAAC,SAAS;MACZ,MAAM,IAAI,WACR,iBACA;IAEJ;IACA,IAAI,KAAK,MAAM,IAAI,aAAa;MAC9B,MAAM,IAAI,WACR,oBACA;IAEJ;IACA,IAAI,SAAS,KAAK,aAAa,IAAI,QAAQ,IAAI,EAAE,iBAAiB;IAClE,IAAI,CAAC;MAAC;MAAO;MAAQ;KAAO,CAAC,QAAQ,CAAC,OAAO,UAAU;MACrD,MAAM,IAAI,WAAW,gBAAgB;IACvC;IACA,IAAI,OAAO,KAAK,EAAE,IAAI,YAAY,CAAC,KAAK,EAAE,EAAE;MAC1C,MAAM,IAAI,WAAW,cAAc;IACrC;IACA,IAAI,WAAW,MAAM,eACnB,KAAK,MAAM,EACX,WAAW,QACX,KAAK,EAAE,EACP;MAAE,OAAO,QAAQ,KAAK;MAAE,UAAU,QAAQ,QAAQ,IAAI,KAAK,OAAO;IAAK;IAEzE,UAAU,IAAI,CAAC;MACb,GAAG,QAAQ;MACX,GAAI,OAAO,KAAK,cAAc,IAAI,YAC9B,KAAK,cAAc,CAAC,MAAM,IAAI,QAC9B;QAAE,gBAAgB,KAAK,cAAc;MAAC,IACtC,CAAC,CAAC;IACR;EACF;EACA,OAAO;AACT,EAAC"}
package/images.ts ADDED
@@ -0,0 +1,63 @@
1
+ /** Native Responses image-generation output. Binary persistence is injected. */
2
+ import { ModelError, type Reply } from '@yaks/model'
3
+ import type { ArtifactStore } from 'jsr:@yaks/blob@0.2.36'
4
+ import { generatedMedia } from './media.js'
5
+
6
+ export type ImageGeneration = {
7
+ type?: 'image_generation'
8
+ output_format?: 'png' | 'jpeg' | 'webp'
9
+ quality?: 'auto' | 'low' | 'medium' | 'high'
10
+ size?: 'auto' | '1024x1024' | '1536x1024' | '1024x1536'
11
+ background?: 'auto' | 'opaque' | 'transparent'
12
+ }
13
+ export type Images = {
14
+ /** @deprecated Ignored. Configured image tools are offered on every endpoint. */
15
+ auto?: boolean
16
+ tool?: ImageGeneration
17
+ store: ArtifactStore
18
+ /** Maximum decoded image bytes, default 32 MiB. */
19
+ maxBytes?: number
20
+ }
21
+
22
+ export let generatedImages = async (
23
+ items: Record<string, unknown>[],
24
+ options?: Images,
25
+ ): Promise<NonNullable<Reply['artifacts']>> => {
26
+ let artifacts: NonNullable<Reply['artifacts']> = []
27
+ for (let item of items) {
28
+ if (item.type != 'image_generation_call') continue
29
+ if (!options) {
30
+ throw new ModelError(
31
+ 'image_storage',
32
+ 'Image output requires configured artifact storage',
33
+ )
34
+ }
35
+ if (item.status != 'completed') {
36
+ throw new ModelError(
37
+ 'image_incomplete',
38
+ 'Image generation did not complete',
39
+ )
40
+ }
41
+ let format = item.output_format ?? options.tool?.output_format ?? 'png'
42
+ if (!['png', 'jpeg', 'webp'].includes(String(format))) {
43
+ throw new ModelError('image_format', 'Unsupported image format')
44
+ }
45
+ if (typeof item.id != 'string' || !item.id) {
46
+ throw new ModelError('image_call', 'Image output has no call ID')
47
+ }
48
+ let artifact = await generatedMedia(
49
+ item.result,
50
+ 'image/' + format,
51
+ item.id,
52
+ { store: options.store, maxBytes: options.maxBytes ?? 32 * 1024 * 1024 },
53
+ )
54
+ artifacts.push({
55
+ ...artifact,
56
+ ...(typeof item.revised_prompt == 'string' &&
57
+ item.revised_prompt.length <= 32768
58
+ ? { revised_prompt: item.revised_prompt }
59
+ : {}),
60
+ })
61
+ }
62
+ return artifacts
63
+ }
package/info.js ADDED
@@ -0,0 +1,55 @@
1
+ // The credential's catalogue establishes availability. OpenAI's public model
2
+ // page supplies token limits the /models API does not return; our shared tariff
3
+ // table supplies pricing, as it does for Anthropic's own model descriptions.
4
+ import { listPrice, ModelError } from "@yaks/model";
5
+ let number = (body, patterns)=>{
6
+ let found = patterns.map((pattern)=>body.match(pattern)?.[1]).find(Boolean);
7
+ return found ? Number(found.replaceAll(',', '')) : undefined;
8
+ };
9
+ /** The total context window takes precedence over the model's input-only cap. */ export let limits = (body)=>{
10
+ let context = number(body, [
11
+ /([\d,]+)\s+context window/i,
12
+ /Context window:\s*([\d,]+)/i,
13
+ /Maximum input tokens:\s*([\d,]+)/i,
14
+ /Max input:\s*([\d,]+)/i
15
+ ]);
16
+ let output = number(body, [
17
+ /([\d,]+)\s+max output tokens/i,
18
+ /Max output:\s*([\d,]+)/i
19
+ ]);
20
+ return {
21
+ ...context ? {
22
+ context
23
+ } : {},
24
+ ...output ? {
25
+ output
26
+ } : {}
27
+ };
28
+ };
29
+ let page = async (name, fetcher)=>{
30
+ let res = await fetcher(`https://developers.openai.com/api/docs/models/${encodeURIComponent(name)}.md`);
31
+ if (res.status == 404) {
32
+ await res.body?.cancel();
33
+ let alias = name.replace(/-\d{4}-\d{2}-\d{2}$/, '');
34
+ return alias == name ? '' : page(alias, fetcher);
35
+ }
36
+ // The page is public documentation, not the credential's answer: one that
37
+ // fails may pass, and meanwhile a session goes on without its limits.
38
+ if (!res.ok) {
39
+ await res.body?.cancel();
40
+ throw new ModelError('metadata', `OpenAI model page says ${res.status}`, {});
41
+ }
42
+ return res.text();
43
+ };
44
+ /** Enrich a model the credential already listed, keeping API limits first. */ export let described = async (model, fetcher = fetch)=>{
45
+ let price = model.price ?? listPrice(model.name);
46
+ let published = model.context != null ? {} : limits(await page(model.name, fetcher));
47
+ return {
48
+ ...published,
49
+ ...model,
50
+ ...price ? {
51
+ price
52
+ } : {}
53
+ };
54
+ };
55
+ //# sourceMappingURL=info.js.map
package/info.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"info.js","sources":["./info.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,gFAAgF;AAChF,6EAA6E;AAC7E,SAAsB,SAAS,EAAE,UAAU,2BAAgC;AAE3E,IAAI,SAAS,CAAC,MAAc;EAC1B,IAAI,QAAQ,SAAS,GAAG,CAAC,CAAC,UAAY,KAAK,KAAK,CAAC,UAAU,CAAC,EAAE,EAAE,IAAI,CAAC;EACrE,OAAO,QAAQ,OAAO,MAAM,UAAU,CAAC,KAAK,OAAO;AACrD;AAEA,+EAA+E,GAC/E,OAAO,IAAI,SAAS,CAAC;EACnB,IAAI,UAAU,OAAO,MAAM;IACzB;IACA;IACA;IACA;GACD;EACD,IAAI,SAAS,OAAO,MAAM;IACxB;IACA;GACD;EACD,OAAO;IACL,GAAG,UAAU;MAAE;IAAQ,IAAI,CAAC,CAAC;IAC7B,GAAG,SAAS;MAAE;IAAO,IAAI,CAAC,CAAC;EAC7B;AACF,EAAC;AAED,IAAI,OAAO,OAAO,MAAc;EAC9B,IAAI,MAAM,MAAM,QACd,CAAC,8CAA8C,EAC7C,mBAAmB,MACpB,GAAG,CAAC;EAEP,IAAI,IAAI,MAAM,IAAI,KAAK;IACrB,MAAM,IAAI,IAAI,EAAE;IAChB,IAAI,QAAQ,KAAK,OAAO,CAAC,uBAAuB;IAChD,OAAO,SAAS,OAAO,KAAK,KAAK,OAAO;EAC1C;EACA,0EAA0E;EAC1E,sEAAsE;EACtE,IAAI,CAAC,IAAI,EAAE,EAAE;IACX,MAAM,IAAI,IAAI,EAAE;IAChB,MAAM,IAAI,WAAW,YAAY,CAAC,uBAAuB,EAAE,IAAI,MAAM,EAAE,EAAE,CAAC;EAC5E;EACA,OAAO,IAAI,IAAI;AACjB;AAEA,4EAA4E,GAC5E,OAAO,IAAI,YAAY,OACrB,OACA,UAAwB,KAAK;EAE7B,IAAI,QAAQ,MAAM,KAAK,IAAI,UAAU,MAAM,IAAI;EAC/C,IAAI,YAAY,MAAM,OAAO,IAAI,OAC7B,CAAC,IACD,OAAO,MAAM,KAAK,MAAM,IAAI,EAAE;EAClC,OAAO;IAAE,GAAG,SAAS;IAAE,GAAG,KAAK;IAAE,GAAG,QAAQ;MAAE;IAAM,IAAI,CAAC,CAAC;EAAC;AAC7D,EAAC"}
package/info.ts ADDED
@@ -0,0 +1,59 @@
1
+ // The credential's catalogue establishes availability. OpenAI's public model
2
+ // page supplies token limits the /models API does not return; our shared tariff
3
+ // table supplies pricing, as it does for Anthropic's own model descriptions.
4
+ import { type Listed, listPrice, ModelError } from '@yaks/model'
5
+
6
+ let number = (body: string, patterns: RegExp[]): number | undefined => {
7
+ let found = patterns.map((pattern) => body.match(pattern)?.[1]).find(Boolean)
8
+ return found ? Number(found.replaceAll(',', '')) : undefined
9
+ }
10
+
11
+ /** The total context window takes precedence over the model's input-only cap. */
12
+ export let limits = (body: string): Pick<Listed, 'context' | 'output'> => {
13
+ let context = number(body, [
14
+ /([\d,]+)\s+context window/i,
15
+ /Context window:\s*([\d,]+)/i,
16
+ /Maximum input tokens:\s*([\d,]+)/i,
17
+ /Max input:\s*([\d,]+)/i,
18
+ ])
19
+ let output = number(body, [
20
+ /([\d,]+)\s+max output tokens/i,
21
+ /Max output:\s*([\d,]+)/i,
22
+ ])
23
+ return {
24
+ ...context ? { context } : {},
25
+ ...output ? { output } : {},
26
+ }
27
+ }
28
+
29
+ let page = async (name: string, fetcher: typeof fetch): Promise<string> => {
30
+ let res = await fetcher(
31
+ `https://developers.openai.com/api/docs/models/${
32
+ encodeURIComponent(name)
33
+ }.md`,
34
+ )
35
+ if (res.status == 404) {
36
+ await res.body?.cancel()
37
+ let alias = name.replace(/-\d{4}-\d{2}-\d{2}$/, '')
38
+ return alias == name ? '' : page(alias, fetcher)
39
+ }
40
+ // The page is public documentation, not the credential's answer: one that
41
+ // fails may pass, and meanwhile a session goes on without its limits.
42
+ if (!res.ok) {
43
+ await res.body?.cancel()
44
+ throw new ModelError('metadata', `OpenAI model page says ${res.status}`, {})
45
+ }
46
+ return res.text()
47
+ }
48
+
49
+ /** Enrich a model the credential already listed, keeping API limits first. */
50
+ export let described = async (
51
+ model: Listed,
52
+ fetcher: typeof fetch = fetch,
53
+ ): Promise<Listed> => {
54
+ let price = model.price ?? listPrice(model.name)
55
+ let published = model.context != null
56
+ ? {}
57
+ : limits(await page(model.name, fetcher))
58
+ return { ...published, ...model, ...price ? { price } : {} }
59
+ }
package/limits.js ADDED
@@ -0,0 +1,50 @@
1
+ // The ChatGPT plan's limits, as the Codex backend's response headers report
2
+ // them: a primary window and perhaps a secondary one, each a percentage used
3
+ // and when it resets. The plan is the one Codex reports (`codex`), whoever
4
+ // asked.
5
+ /**
6
+ * The readings in a response's limit headers, of `account`'s plan where the
7
+ * caller knows whose it is. A window of no minutes is no window.
8
+ *
9
+ * ```ts
10
+ * import { planLimits } from './limits.ts'
11
+ * import { equal } from '@yaks/testing'
12
+ *
13
+ * equal(
14
+ * planLimits({
15
+ * 'x-codex-primary-window-minutes': '10080',
16
+ * 'x-codex-primary-used-percent': '9',
17
+ * 'x-codex-primary-reset-at': '1792967691',
18
+ * 'x-codex-secondary-window-minutes': '0',
19
+ * 'x-codex-secondary-used-percent': '0',
20
+ * 'x-codex-secondary-reset-at': '',
21
+ * }),
22
+ * [{ provider: 'codex', window: 10080, used: 9, resets: '2026-10-25T22:34:51.000Z' }],
23
+ * )
24
+ * equal(planLimits({ 'x-ratelimit-remaining-requests': '99' }), [])
25
+ * ```
26
+ */ export let planLimits = (headers, account)=>[
27
+ 'primary',
28
+ 'secondary'
29
+ ].flatMap((name)=>{
30
+ let at = (part)=>headers[`x-codex-${name}-${part}`] ?? '';
31
+ let window = Number(at('window-minutes')), used = Number(at('used-percent'));
32
+ if (!(window > 0) || at('used-percent') == '' || !Number.isFinite(used)) {
33
+ return [];
34
+ }
35
+ let resets = Number(at('reset-at'));
36
+ return [
37
+ {
38
+ provider: 'codex',
39
+ ...account ? {
40
+ account
41
+ } : {},
42
+ window,
43
+ used,
44
+ ...resets > 0 ? {
45
+ resets: new Date(resets * 1000).toISOString()
46
+ } : {}
47
+ }
48
+ ];
49
+ });
50
+ //# sourceMappingURL=limits.js.map
package/limits.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limits.js","sources":["./limits.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,6EAA6E;AAC7E,2EAA2E;AAC3E,SAAS;AAIT;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,OAAO,IAAI,aAAa,CACtB,SACA,UAEA;IAAC;IAAW;GAAY,CAAC,OAAO,CAAC,CAAC;IAChC,IAAI,KAAK,CAAC,OAAiB,OAAO,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,EAAE,MAAM,CAAC,IAAI;IACjE,IAAI,SAAS,OAAO,GAAG,oBAAoB,OAAO,OAAO,GAAG;IAC5D,IAAI,CAAC,CAAC,SAAS,CAAC,KAAK,GAAG,mBAAmB,MAAM,CAAC,OAAO,QAAQ,CAAC,OAAO;MACvE,OAAO,EAAE;IACX;IACA,IAAI,SAAS,OAAO,GAAG;IACvB,OAAO;MAAC;QACN,UAAU;QACV,GAAG,UAAU;UAAE;QAAQ,IAAI,CAAC,CAAC;QAC7B;QACA;QACA,GAAG,SAAS,IAAI;UAAE,QAAQ,IAAI,KAAK,SAAS,MAAM,WAAW;QAAG,IAAI,CAAC,CAAC;MACxE;KAAE;EACJ,GAAE"}