@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/batches.ts ADDED
@@ -0,0 +1,194 @@
1
+ // OpenAI's Batch API as @yaks/model's `Batches`: many Responses requests
2
+ // uploaded as one JSON-lines file and answered within a day at half the
3
+ // price. OpenAI caches a prompt's prefix on its own; requests that name the
4
+ // same `prompt_cache_key` are routed to the same cache, so a prefix every
5
+ // request shares is read cheaply by all but the first few.
6
+ import type { Answered, Asked, Batches } from 'jsr:@yaks/model@0.2.36/batch'
7
+ import { ModelError } from '@yaks/model'
8
+ import { OPENAI } from './credential.js'
9
+
10
+ /** Where a key's batches are sent. */
11
+ export type Options = {
12
+ key: () => string | Promise<string>
13
+ /** the API's root, OpenAI's own by default */
14
+ base?: string
15
+ fetch?: typeof globalThis.fetch
16
+ }
17
+
18
+ /** A Responses request as one line of a batch's file. */
19
+ export let lineOf = (a: Asked): string =>
20
+ JSON.stringify({
21
+ custom_id: a.id,
22
+ method: 'POST',
23
+ url: '/v1/responses',
24
+ body: {
25
+ model: a.model,
26
+ instructions: a.system,
27
+ input: a.text,
28
+ max_output_tokens: a.max,
29
+ store: false,
30
+ ...a.cache ? { prompt_cache_key: a.cache } : {},
31
+ },
32
+ })
33
+
34
+ type Output = { type: string; content?: { type: string; text?: string }[] }
35
+ type Body = {
36
+ output?: Output[]
37
+ usage?: {
38
+ input_tokens?: number
39
+ input_tokens_details?: { cached_tokens?: number }
40
+ output_tokens?: number
41
+ output_tokens_details?: { reasoning_tokens?: number }
42
+ }
43
+ error?: { message?: string } | null
44
+ status?: string
45
+ }
46
+ /** One line of a batch's output or error file. */
47
+ export type Line = {
48
+ custom_id: string
49
+ response?: { status_code: number; body: Body } | null
50
+ error?: { code?: string; message?: string } | null
51
+ }
52
+
53
+ /**
54
+ * A line of a batch's output as an answer: the response's text and what it
55
+ * used, or why there is none.
56
+ *
57
+ * ```ts
58
+ * import { answerOf } from '@yaks/openai/batches'
59
+ * import { assertEquals } from '@std/assert'
60
+ *
61
+ * assertEquals(answerOf({
62
+ * custom_id: 'a',
63
+ * response: {
64
+ * status_code: 200,
65
+ * body: {
66
+ * status: 'completed',
67
+ * output: [{ type: 'message', content: [{ type: 'output_text', text: 'hi' }] }],
68
+ * usage: { input_tokens: 100, input_tokens_details: { cached_tokens: 90 }, output_tokens: 5 },
69
+ * },
70
+ * },
71
+ * }), { id: 'a', text: 'hi', usage: { input_tokens: 100, cached_tokens: 90, output_tokens: 5, reasoning_tokens: 0 } })
72
+ * assertEquals(answerOf({ custom_id: 'b', error: { code: 'x', message: 'no' } }), { id: 'b', error: 'x: no' })
73
+ * ```
74
+ */
75
+ export let answerOf = (l: Line): Answered => {
76
+ let body = l.response?.body
77
+ if (l.error || !body || l.response!.status_code != 200 || body.error) {
78
+ let e: { code?: string; message?: string } = l.error ?? body?.error ?? {}
79
+ let said = [e.code ?? l.response?.status_code, e.message]
80
+ .filter((s) => s != null && s !== '')
81
+ return { id: l.custom_id, error: said.join(': ') || 'no answer' }
82
+ }
83
+ let text = (body.output ?? []).filter((o) => o.type == 'message')
84
+ .flatMap((o) => o.content ?? [])
85
+ .filter((c) => c.type == 'output_text')
86
+ .map((c) => c.text ?? '').join('')
87
+ let u = body.usage ?? {}
88
+ return {
89
+ id: l.custom_id,
90
+ text,
91
+ usage: {
92
+ input_tokens: u.input_tokens ?? 0,
93
+ cached_tokens: u.input_tokens_details?.cached_tokens ?? 0,
94
+ output_tokens: u.output_tokens ?? 0,
95
+ reasoning_tokens: u.output_tokens_details?.reasoning_tokens ?? 0,
96
+ },
97
+ }
98
+ }
99
+
100
+ // How a batch stands once it will change no more.
101
+ let ENDED = ['completed', 'failed', 'expired', 'cancelled']
102
+
103
+ /**
104
+ * The batches of one key.
105
+ *
106
+ * ```ts
107
+ * import { batches } from '@yaks/openai/batches'
108
+ * import { assertEquals } from '@std/assert'
109
+ *
110
+ * let fetch = () => Promise.resolve(Response.json({ id: 'b1', status: 'finalizing' }))
111
+ * let api = batches({ fetch, key: () => 'k' })
112
+ * assertEquals(await api.ended('b1'), false)
113
+ * ```
114
+ */
115
+ export let batches = (options: Options): Batches => {
116
+ let base = (options.base ?? OPENAI).replace(/\/$/, '')
117
+ let call = async (path: string, init: RequestInit = {}) => {
118
+ let response = await (options.fetch ?? fetch)(base + path, {
119
+ ...init,
120
+ headers: {
121
+ authorization: `Bearer ${await options.key()}`,
122
+ ...typeof init.body == 'string'
123
+ ? { 'content-type': 'application/json' }
124
+ : {},
125
+ },
126
+ })
127
+ if (response.ok) return response
128
+ let said = await response.json()
129
+ .catch(() => ({})) as { error?: { message?: string } }
130
+ throw new ModelError(
131
+ response.status == 429 ? 'rate' : `http ${response.status}`,
132
+ `OpenAI ${path.split('/')[1]}: ${
133
+ said?.error?.message ?? response.statusText
134
+ }`,
135
+ response.status == 429 || response.status >= 500 ? {} : undefined,
136
+ )
137
+ }
138
+ let read = async (id: string) =>
139
+ await (await call(`/batches/${encodeURIComponent(id)}`)).json() as {
140
+ status: string
141
+ output_file_id?: string | null
142
+ error_file_id?: string | null
143
+ errors?: { data?: { code?: string; message?: string }[] } | null
144
+ }
145
+ let lines = async (file?: string | null): Promise<Line[]> =>
146
+ file
147
+ ? (await (await call(`/files/${encodeURIComponent(file)}/content`))
148
+ .text())
149
+ .split('\n').filter((l) => l.trim()).map((l) => JSON.parse(l))
150
+ : []
151
+ return {
152
+ submit: async (asked) => {
153
+ let form = new FormData()
154
+ form.append('purpose', 'batch')
155
+ form.append(
156
+ 'file',
157
+ new Blob([asked.map(lineOf).join('\n') + '\n'], {
158
+ type: 'application/jsonl',
159
+ }),
160
+ 'batch.jsonl',
161
+ )
162
+ let file: { id: string } =
163
+ await (await call('/files', { method: 'POST', body: form })).json()
164
+ let batch: { id: string } = await (await call('/batches', {
165
+ method: 'POST',
166
+ body: JSON.stringify({
167
+ input_file_id: file.id,
168
+ endpoint: '/v1/responses',
169
+ completion_window: '24h',
170
+ }),
171
+ })).json()
172
+ return batch.id
173
+ },
174
+ ended: async (id) => ENDED.includes((await read(id)).status),
175
+ // Every request's line, from the output file and the error file. A batch
176
+ // refused whole (`failed`) has neither, and its errors say why.
177
+ results: async (id) => {
178
+ let b = await read(id)
179
+ let all = [
180
+ ...await lines(b.output_file_id),
181
+ ...await lines(b.error_file_id),
182
+ ]
183
+ if (!all.length && b.errors?.data?.length) {
184
+ throw new ModelError(
185
+ 'batch failed',
186
+ `OpenAI batch ${id} ${b.status}: ${
187
+ b.errors.data.map((e) => e.message ?? e.code).join('; ')
188
+ }`,
189
+ )
190
+ }
191
+ return all.map(answerOf)
192
+ },
193
+ }
194
+ }
package/credential.js ADDED
@@ -0,0 +1,30 @@
1
+ // A bearer and the endpoint it opens. An API key reaches the public API;
2
+ // a ChatGPT OAuth token reaches the Codex backend under its account.
3
+ /** A bearer and the endpoint it is good for. */ export let OPENAI = 'https://api.openai.com/v1';
4
+ export let CODEX = 'https://chatgpt.com/backend-api/codex';
5
+ /** An API key from the environment. */ export let fromEnv = (env)=>{
6
+ let token = env('OPENAI_API_KEY')?.trim();
7
+ return token ? {
8
+ token,
9
+ base: OPENAI
10
+ } : undefined;
11
+ };
12
+ /** The account claim in a ChatGPT OAuth bearer. The bearer never leaves the
13
+ * caller, and a malformed one fails before it can be sent to the backend. */ export let fromChatGPT = (token)=>{
14
+ let account;
15
+ try {
16
+ let part = token.split('.')[1];
17
+ let decoded = atob(part.replaceAll('-', '+').replaceAll('_', '/'));
18
+ let claims = JSON.parse(decoded);
19
+ account = claims?.['https://api.openai.com/auth']?.chatgpt_account_id;
20
+ } catch {}
21
+ if (typeof account != 'string' || !account) {
22
+ throw new Error('the ChatGPT sign-in has no account; authorize OpenAI again');
23
+ }
24
+ return {
25
+ token,
26
+ account,
27
+ base: CODEX
28
+ };
29
+ };
30
+ //# sourceMappingURL=credential.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"credential.js","sources":["./credential.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,qEAAqE;AAErE,8CAA8C,GAS9C,OAAO,IAAI,SAAS,4BAA2B;AAC/C,OAAO,IAAI,QAAQ,wCAAuC;AAI1D,qCAAqC,GACrC,OAAO,IAAI,UAAU,CAAC;EACpB,IAAI,QAAQ,IAAI,mBAAmB;EACnC,OAAO,QAAQ;IAAE;IAAO,MAAM;EAAO,IAAI;AAC3C,EAAC;AAED;2EAC2E,GAC3E,OAAO,IAAI,cAAc,CAAC;EACxB,IAAI;EACJ,IAAI;IACF,IAAI,OAAO,MAAM,KAAK,CAAC,IAAI,CAAC,EAAE;IAC9B,IAAI,UAAU,KAAK,KAAK,UAAU,CAAC,KAAK,KAAK,UAAU,CAAC,KAAK;IAC7D,IAAI,SAAS,KAAK,KAAK,CAAC;IACxB,UAAU,QAAQ,CAAC,8BAA8B,EAAE;EACrD,EAAE,OAAM,CAA+C;EACvD,IAAI,OAAO,WAAW,YAAY,CAAC,SAAS;IAC1C,MAAM,IAAI,MACR;EAEJ;EACA,OAAO;IAAE;IAAO;IAAS,MAAM;EAAM;AACvC,EAAC"}
package/credential.ts ADDED
@@ -0,0 +1,40 @@
1
+ // A bearer and the endpoint it opens. An API key reaches the public API;
2
+ // a ChatGPT OAuth token reaches the Codex backend under its account.
3
+
4
+ /** A bearer and the endpoint it is good for. */
5
+ export type Credential = {
6
+ token: string
7
+ /** the ChatGPT account the token was issued to; the Codex backend wants it
8
+ * beside the bearer */
9
+ account?: string
10
+ base: string
11
+ }
12
+
13
+ export let OPENAI = 'https://api.openai.com/v1'
14
+ export let CODEX = 'https://chatgpt.com/backend-api/codex'
15
+
16
+ type Env = (name: string) => string | undefined
17
+
18
+ /** An API key from the environment. */
19
+ export let fromEnv = (env: Env): Credential | undefined => {
20
+ let token = env('OPENAI_API_KEY')?.trim()
21
+ return token ? { token, base: OPENAI } : undefined
22
+ }
23
+
24
+ /** The account claim in a ChatGPT OAuth bearer. The bearer never leaves the
25
+ * caller, and a malformed one fails before it can be sent to the backend. */
26
+ export let fromChatGPT = (token: string): Credential => {
27
+ let account: unknown
28
+ try {
29
+ let part = token.split('.')[1]
30
+ let decoded = atob(part.replaceAll('-', '+').replaceAll('_', '/'))
31
+ let claims = JSON.parse(decoded)
32
+ account = claims?.['https://api.openai.com/auth']?.chatgpt_account_id
33
+ } catch { /* A malformed bearer carries no account. */ }
34
+ if (typeof account != 'string' || !account) {
35
+ throw new Error(
36
+ 'the ChatGPT sign-in has no account; authorize OpenAI again',
37
+ )
38
+ }
39
+ return { token, account, base: CODEX }
40
+ }
package/deno.json ADDED
@@ -0,0 +1 @@
1
+ {"publish":{"exclude":["**/*_test.ts"]},"name":"@yaks/openai","version":"0.2.36","license":"Apache-2.0","description":"Implements the model interface over OpenAI's streaming Responses API using fetch, with API-key or Codex sign-in authentication.","exports":{".":"./mod.ts","./vocab":"./vocab.ts","./provider":"./provider.ts","./batches":"./batches.ts","./project-keys":"./project-keys.ts"},"imports":{"@yaks/openai":"./mod.ts","@yaks/openai/vocab":"./vocab.ts","@yaks/openai/provider":"./provider.ts","@yaks/openai/batches":"./batches.ts","@yaks/openai/project-keys":"./project-keys.ts"}}
package/generations.js ADDED
@@ -0,0 +1,288 @@
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. */ import { acknowledged, ModelError, receivedMedia, recoveredMedia, submitted } from "@yaks/model";
3
+ import { mediaTypeOf, sizeOf } from "@yaks/blob";
4
+ import { CODEX } from "./credential.js";
5
+ import { dataUrl, generatedMedia, mediaRoom } from "./media.js";
6
+ // Each family's output tokens per quality at a square of 2,000,000 pixels'
7
+ // weight, and GPT Image 2.6's own scale on them: OpenAI's cost calculator
8
+ // (developers.openai.com, guides/image-generation#calculating-costs).
9
+ let STEPS = {
10
+ low: 16,
11
+ medium: 24,
12
+ high: 48,
13
+ xhigh: 64,
14
+ max: 96
15
+ };
16
+ let SCALE = {
17
+ low: 4.2,
18
+ medium: 3.3
19
+ };
20
+ let FAMILIES = {
21
+ 'gpt-image-2.5': STEPS,
22
+ 'gpt-image-2.6': STEPS
23
+ };
24
+ // Dollars per million tokens, the same for both families (pricing page).
25
+ let PRICE = {
26
+ text: 5,
27
+ image: 8,
28
+ output: 30
29
+ };
30
+ // The largest image either family makes: 8,294,400 pixels, square.
31
+ let LARGEST = 2880;
32
+ let FORMATS = [
33
+ 'png',
34
+ 'jpeg',
35
+ 'webp'
36
+ ];
37
+ let MAX_REFERENCE = 14 * 1024 * 1024;
38
+ let OPTIONS = [
39
+ 'size',
40
+ 'quality',
41
+ 'background',
42
+ 'output_format',
43
+ 'output_compression',
44
+ 'moderation',
45
+ 'complexity'
46
+ ];
47
+ let family = (model)=>Object.keys(FAMILIES).find((f)=>model == f || model.startsWith(f + '-'));
48
+ /** Whether `model` is a GPT Image model this adapter prices. */ export let image = (model)=>!!family(model);
49
+ /** What OpenAI's calculator says one image of `width` by `height` at
50
+ * `quality` makes, in output tokens. */ export let imageTokens = (model, width, height, quality)=>{
51
+ let base = FAMILIES[family(model)][quality];
52
+ let long = Math.max(width, height), short = Math.min(width, height);
53
+ let s = base / (long / short), whole = Math.floor(s);
54
+ let side = s - whole == 0.5 ? whole + whole % 2 : Math.round(s);
55
+ let tiles = width >= height ? base * side : side * base;
56
+ let tokens = Math.ceil(tiles * (2e6 + width * height) / 4e6);
57
+ return family(model) == 'gpt-image-2.6' ? Math.round(tokens * (SCALE[quality] ?? 1)) : tokens;
58
+ };
59
+ let prompt = (req)=>{
60
+ let input = req.items.findLast((item)=>item.kind == 'user');
61
+ if (!input || input.kind != 'user' || !input.text.trim()) {
62
+ throw new ModelError('input', 'Image models need a text prompt');
63
+ }
64
+ return input.text;
65
+ };
66
+ let references = (req)=>{
67
+ let images = req.items.filter((item)=>item.kind == 'image');
68
+ if (images.length > 16 || req.items.some((item)=>item.kind == 'document')) {
69
+ throw new ModelError('bad_request', 'Image models take up to 16 reference images and no documents');
70
+ }
71
+ for (let image of images){
72
+ if (![
73
+ 'image/png',
74
+ 'image/jpeg',
75
+ 'image/webp'
76
+ ].includes(image.mediaType) || image.bytes.length > MAX_REFERENCE || mediaTypeOf(image.bytes) != image.mediaType || !sizeOf(image.bytes)) {
77
+ throw new ModelError('bad_request', 'References must be PNG, JPEG or WebP images under 14 MiB');
78
+ }
79
+ }
80
+ return images;
81
+ };
82
+ let imagePrompt = (req, images)=>[
83
+ ...images.map((item, i)=>`Reference image ${i + 1}: ${item.label}`),
84
+ prompt(req)
85
+ ].join('\n\n');
86
+ let requestBody = (req)=>{
87
+ let images = references(req);
88
+ return {
89
+ model: req.model,
90
+ prompt: imagePrompt(req, images),
91
+ n: 1,
92
+ ...settings(req),
93
+ ...images.length ? {
94
+ images: images.map((item)=>({
95
+ image_url: dataUrl(item)
96
+ }))
97
+ } : {}
98
+ };
99
+ };
100
+ // What a receipt keeps of a request: everything but the reference pixels,
101
+ // each said by its type and size. A 2400×3040 reference is megabytes of
102
+ // base64, and a store keeping, writing and reading back copies of several
103
+ // went over its memory (T-2685).
104
+ let recorded = (body, req)=>body.images ? {
105
+ ...body,
106
+ images: references(req).map((item)=>({
107
+ media_type: item.mediaType,
108
+ bytes: item.bytes.length
109
+ }))
110
+ } : body;
111
+ // What a receipt keeps of an answer once its image is kept as an artifact the
112
+ // reply names: the answer without its base64.
113
+ let delivered = (answer)=>({
114
+ ...answer,
115
+ data: answer.data?.map(({ b64_json: _, ...rest })=>rest)
116
+ });
117
+ let settings = (req)=>{
118
+ let input = req.input ?? {};
119
+ let extra = Object.keys(input).filter((k)=>!OPTIONS.includes(k));
120
+ if (extra.length) {
121
+ throw new ModelError('bad_request', `Image models take ${OPTIONS.join(', ')}; not ${extra.join(', ')}`);
122
+ }
123
+ let format = input.output_format ?? 'png';
124
+ if (!FORMATS.includes(String(format))) {
125
+ throw new ModelError('bad_request', `Image models make ${FORMATS.join(', ')} here; not ${format}`);
126
+ }
127
+ let quality = input.quality ?? 'auto';
128
+ if (quality != 'auto' && !(String(quality) in FAMILIES[family(req.model)])) {
129
+ throw new ModelError('bad_request', `No ${quality} quality for ${req.model}`);
130
+ }
131
+ let size = input.size ?? 'auto';
132
+ if (size != 'auto' && !/^\d+x\d+$/.test(String(size))) {
133
+ throw new ModelError('bad_request', 'An image size is auto or WIDTHxHEIGHT');
134
+ }
135
+ return {
136
+ ...input,
137
+ output_format: format,
138
+ quality,
139
+ size
140
+ };
141
+ };
142
+ /** A reservation estimate: its prompt's bytes as text tokens, and twice
143
+ * the calculator's output at its quality (at most `max`) and size (at most the
144
+ * largest), plus a reference-input estimate at max-quality token weight. */ export let imageQuote = (req, remaining)=>{
145
+ let sent = settings(req);
146
+ let quality = sent.quality == 'auto' ? 'max' : String(sent.quality);
147
+ let [width, height] = sent.size == 'auto' ? [
148
+ LARGEST,
149
+ LARGEST
150
+ ] : String(sent.size).split('x').map(Number);
151
+ let images = references(req);
152
+ let text = new TextEncoder().encode(imagePrompt(req, images)).length;
153
+ // There is no published input calculator for these families. Use the
154
+ // existing max-quality token calculator as an estimate for each reference.
155
+ // The meter settles the provider's measured usage, even above this estimate.
156
+ let input = images.reduce((sum, item)=>{
157
+ let { w, h } = sizeOf(item.bytes);
158
+ return sum + imageTokens(req.model, w, h, 'max');
159
+ }, 0);
160
+ let dollars = (text * PRICE.text + 2 * imageTokens(req.model, width, height, quality) * PRICE.output + input * PRICE.image) / 1e6;
161
+ return dollars <= remaining ? {
162
+ dollars,
163
+ tokens: 0
164
+ } : null;
165
+ };
166
+ /** What an Image API answer cost: its text and image input and all its
167
+ * output, at the published rates. */ export let imageCost = (usage)=>{
168
+ let { text_tokens = 0, image_tokens = 0 } = usage?.input_tokens_details ?? {};
169
+ let output = usage?.output_tokens;
170
+ if (![
171
+ text_tokens,
172
+ image_tokens,
173
+ output
174
+ ].every((n)=>Number.isSafeInteger(n) && n >= 0)) {
175
+ throw new ModelError('media_cost', 'The image answer reported no usage');
176
+ }
177
+ return (text_tokens * PRICE.text + image_tokens * PRICE.image + output * PRICE.output) / 1e6;
178
+ };
179
+ /** How an image model is listed: image out, at its image rates. */ export let imageListed = (name)=>({
180
+ name,
181
+ label: name,
182
+ modalities: [
183
+ 'image'
184
+ ],
185
+ price: {
186
+ input: PRICE.image,
187
+ output: PRICE.output
188
+ }
189
+ });
190
+ let deliver = async (receipt, media)=>{
191
+ let answer = receipt.response;
192
+ let format = answer.output_format ?? 'png';
193
+ if (!FORMATS.includes(format)) {
194
+ throw new ModelError('image_format', 'Unsupported image format');
195
+ }
196
+ let artifact = await generatedMedia(answer.data?.[0]?.b64_json, 'image/' + format, receipt.id, media);
197
+ return {
198
+ id: receipt.id,
199
+ model: receipt.model,
200
+ items: [],
201
+ artifacts: [
202
+ artifact
203
+ ],
204
+ cost: receipt.cost,
205
+ costReported: false
206
+ };
207
+ };
208
+ /** OpenAI's refusal in its own words: the status, its code, the parameter it
209
+ * names and its message, so a caller can fix its request. */ let refusal = (status, body)=>{
210
+ let { code, param, message } = body?.error ?? {};
211
+ let head = [
212
+ status,
213
+ code,
214
+ param && 'param ' + param
215
+ ].filter(Boolean);
216
+ return `OpenAI refused the image (${head.join(', ')})` + (message ? ': ' + message : '');
217
+ };
218
+ /** The Image API as a model: the newest user text is the prompt, image items
219
+ * its references, and `req.input` its settings. The answer is kept as a private
220
+ * receipt before its bytes are stored, so a stored image is never bought twice. */ export let generations = (options)=>{
221
+ let ask = async (req)=>{
222
+ if (!options.media) {
223
+ throw new ModelError('media_storage', 'Image output requires artifact storage');
224
+ }
225
+ if (req.questions) {
226
+ throw new ModelError('questions', 'Image models answer no typed questions');
227
+ }
228
+ let body = requestBody(req);
229
+ let credential = await options.credential();
230
+ if (credential.base == CODEX) {
231
+ throw new ModelError('model', 'Image models need an OpenAI API key');
232
+ }
233
+ await mediaRoom(options.media);
234
+ await submitted(req);
235
+ let res;
236
+ try {
237
+ res = await (options.fetch ?? fetch)(credential.base + (body.images ? '/images/edits' : '/images/generations'), {
238
+ method: 'POST',
239
+ headers: {
240
+ ...options.headers,
241
+ ...credential.token ? {
242
+ authorization: 'Bearer ' + credential.token
243
+ } : {},
244
+ 'content-type': 'application/json'
245
+ },
246
+ body: JSON.stringify(body),
247
+ signal: req.signal
248
+ });
249
+ } catch (error) {
250
+ if (req.signal?.aborted) throw error;
251
+ throw new ModelError('transport', 'OpenAI image connection failed');
252
+ }
253
+ if (!res.ok) {
254
+ throw new ModelError(res.status == 400 ? 'bad_request' : 'http_' + res.status, refusal(res.status, await res.json().catch(()=>undefined)), res.status == 429 || res.status >= 500 ? {
255
+ after: 0
256
+ } : undefined);
257
+ }
258
+ let answer = await res.json();
259
+ let id = req.call ?? crypto.randomUUID();
260
+ await acknowledged(req, {
261
+ openai: {
262
+ response_id: id
263
+ }
264
+ });
265
+ let receipt = {
266
+ provider: 'openai',
267
+ call: id,
268
+ id,
269
+ model: req.model,
270
+ input: recorded(body, req),
271
+ response: answer,
272
+ cost: imageCost(answer.usage),
273
+ costReported: false
274
+ };
275
+ await receivedMedia(req, receipt, options.receipts);
276
+ let reply = await deliver(receipt, options.media);
277
+ await options.receipts?.save({
278
+ ...receipt,
279
+ response: delivered(answer),
280
+ reply
281
+ });
282
+ return reply;
283
+ };
284
+ return Object.assign(ask, {
285
+ recover: (call)=>recoveredMedia(call, options.receipts, (receipt)=>deliver(receipt, options.media))
286
+ });
287
+ };
288
+ //# sourceMappingURL=generations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generations.js","sources":["./generations.ts"],"names":[],"mappings":"AAAA;2EAC2E,GAC3E,SACE,YAAY,EAKZ,UAAU,EACV,aAAa,EACb,cAAc,EAGd,SAAS,2BACoB;AAC/B,SAAS,WAAW,EAAE,MAAM,0BAA+B;AAC3D,SAAS,KAAK,0BAA0C;AACxD,SAAS,OAAO,EAAE,cAAc,EAAE,SAAS,qBAAqC;AAEhF,2EAA2E;AAC3E,0EAA0E;AAC1E,sEAAsE;AACtE,IAAI,QAAQ;EAAE,KAAK;EAAI,QAAQ;EAAI,MAAM;EAAI,OAAO;EAAI,KAAK;AAAG;AAChE,IAAI,QAAgC;EAAE,KAAK;EAAK,QAAQ;AAAI;AAC5D,IAAI,WAAmD;EACrD,iBAAiB;EACjB,iBAAiB;AACnB;AACA,yEAAyE;AACzE,IAAI,QAAQ;EAAE,MAAM;EAAG,OAAO;EAAG,QAAQ;AAAG;AAC5C,mEAAmE;AACnE,IAAI,UAAU;AACd,IAAI,UAAU;EAAC;EAAO;EAAQ;CAAO;AACrC,IAAI,gBAAgB,KAAK,OAAO;AAChC,IAAI,UAAU;EACZ;EACA;EACA;EACA;EACA;EACA;EACA;CACD;AAED,IAAI,SAAS,CAAC,QACZ,OAAO,IAAI,CAAC,UAAU,IAAI,CAAC,CAAC,IAAM,SAAS,KAAK,MAAM,UAAU,CAAC,IAAI;AAEvE,8DAA8D,GAC9D,OAAO,IAAI,QAAQ,CAAC,QAA2B,CAAC,CAAC,OAAO,OAAM;AAE9D;sCACsC,GACtC,OAAO,IAAI,cAAc,CACvB,OACA,OACA,QACA;EAEA,IAAI,OAAO,QAAQ,CAAC,OAAO,OAAQ,CAAC,QAAQ;EAC5C,IAAI,OAAO,KAAK,GAAG,CAAC,OAAO,SAAS,QAAQ,KAAK,GAAG,CAAC,OAAO;EAC5D,IAAI,IAAI,OAAO,CAAC,OAAO,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