@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/provider.js ADDED
@@ -0,0 +1,190 @@
1
+ // @yaks/openai as a provider a config names (@yaks/model `ProviderFacet`):
2
+ // `openai`, signed in with an API key from the host's settings or the ChatGPT
3
+ // grant in the person's OpenAI connection, generating images into the host's
4
+ // artifact store and searching the web. A config may aim it at another
5
+ // OpenAI-compatible endpoint instead (`base`), or reach OpenAI through a
6
+ // Cloudflare AI Gateway (`gateway`), and pay with a key of its own (`key`).
7
+ // Its transport loads on the first ask. Its own door (`native`) answers the
8
+ // names a config aliases to OpenAI models, one Chat Completions call each.
9
+ import { Refused } from "@yaks/graph/errors";
10
+ import { accountEid, accountHome, deferredModel } from "@yaks/model";
11
+ import { CODEX, fromChatGPT, fromEnv, OPENAI } from "./credential.js";
12
+ import { generations, image, imageListed, imageQuote } from "./generations.js";
13
+ import { openaiDoc, responseAnchor } from "./vocab.js";
14
+ import { marking } from "./mark.js";
15
+ import { native as door } from "./native.js";
16
+ import { reads } from "./reads.js";
17
+ /** OpenAI's credential: `OPENAI_API_KEY`, else the person's ChatGPT grant,
18
+ * refreshed through their connection when the Codex backend refuses it. */ export let signedIn = (lent, own)=>{
19
+ let keyed = ()=>{
20
+ let token = typeof own == 'function' ? own() : own;
21
+ return token ? {
22
+ token,
23
+ base: OPENAI
24
+ } : fromEnv(lent.env);
25
+ };
26
+ let credential = async ()=>{
27
+ let key = keyed();
28
+ if (key) return key;
29
+ let token = await lent.key('openai');
30
+ if (!token) {
31
+ throw new Refused('OpenAI is not connected. Authorize OpenAI or set OPENAI_API_KEY.');
32
+ }
33
+ return fromChatGPT(token);
34
+ };
35
+ return {
36
+ credential,
37
+ refresh: async (stale)=>{
38
+ let key = keyed();
39
+ if (key || stale.base != CODEX) return key ?? await credential();
40
+ let token = await lent.refresh('openai', stale.token);
41
+ if (!token) {
42
+ throw new Refused('OpenAI is not connected. Authorize OpenAI again.');
43
+ }
44
+ return fromChatGPT(token);
45
+ }
46
+ };
47
+ };
48
+ // How a configured endpoint is opened (Options `base`, `gateway`).
49
+ let opened = (lent, base, key)=>({
50
+ credential: async ()=>({
51
+ token: key() ?? fromEnv(lent.env)?.token ?? await lent.key('openai') ?? '',
52
+ base: base.replace(/\/+$/, '')
53
+ })
54
+ });
55
+ // The endpoint options aim at, or none for OpenAI's own.
56
+ let aimed = (options)=>{
57
+ let { account, id } = options.gateway ?? {};
58
+ return options.base || (account && id ? `https://gateway.ai.cloudflare.com/v1/${account}/${id}/openai` : undefined);
59
+ };
60
+ /** Where the models `providers` makes with `options` call, so a host may
61
+ * send a credential it lends them there and nowhere else. */ export let hosts = (options = {})=>[
62
+ new URL(aimed(options) ?? OPENAI).host
63
+ ];
64
+ /** A single request only needs the key of the model it calls. Keep it
65
+ * under `key` so existing executors can read it. */ export let modelOptions = (options, model)=>{
66
+ let { textKey, ...shared } = options;
67
+ return {
68
+ ...shared,
69
+ key: image(model) ? shared.key : textKey ?? shared.key
70
+ };
71
+ };
72
+ /** Explicit options override the setting; otherwise images are on. */ export let configuredImages = (store, options, setting)=>{
73
+ if (options === false) return undefined;
74
+ if (options) return {
75
+ ...options,
76
+ store
77
+ };
78
+ if (setting == '0') return undefined;
79
+ if (setting != null && setting != '' && setting != '1') {
80
+ throw new Error('HARNESS_IMAGES must be 0 (disabled) or 1 (enabled)');
81
+ }
82
+ return {
83
+ store
84
+ };
85
+ };
86
+ let configuredOnly = {
87
+ env: ()=>undefined,
88
+ key: ()=>Promise.resolve(undefined),
89
+ refresh: ()=>Promise.resolve(undefined)
90
+ };
91
+ let authOf = (lent, options)=>options.credentialFallback === false ? configuredOnly : lent;
92
+ /** `openai`, served over what the host lends: a GPT Image model's name
93
+ * answers with an image kept in the lent store (generations.ts), any other
94
+ * with the Responses API. */ export let providers = (lent, options = {})=>{
95
+ let images = configuredImages(lent.store, options.images, lent.env('HARNESS_IMAGES'));
96
+ let base = aimed(options), token = options.gateway?.token;
97
+ let auth = authOf(lent, options);
98
+ let textKey = ()=>options.textKey ?? options.key;
99
+ let imageKey = ()=>options.key;
100
+ // OpenAI's own API keeps each reply (`store`), so the next request sends
101
+ // only what followed it and names it (`previous_response_id`): on a key,
102
+ // or through the AI Gateway to OpenAI. The Codex backend a ChatGPT grant
103
+ // reaches keeps nothing, and another endpoint (`base`) may not either, so
104
+ // through those the conversation is sent whole.
105
+ let store = options.base ? false : base ? true : !!(textKey() || fromEnv(auth.env));
106
+ // OpenAI's own API keeps a cached prefix for at least its documented
107
+ // model's retention, so each reply records when its prefix expires, and a session
108
+ // sends the instructions it cached until then. Nothing documents a lifetime
109
+ // for the Codex backend or another endpoint: unknown there.
110
+ let retention = store ? 'openai-default' : undefined;
111
+ let signing = (key)=>base ? {
112
+ ...opened(auth, base, key),
113
+ ...options.credentialFallback === false ? {} : {
114
+ authentication: 'optional'
115
+ }
116
+ } : signedIn(auth, key);
117
+ let headers = {
118
+ ...options.headers,
119
+ ...token ? {
120
+ 'cf-aig-authorization': `Bearer ${token}`
121
+ } : {}
122
+ };
123
+ // A ChatGPT grant spends the plan Codex reports, which this machine keeps
124
+ // under the account the Codex CLI signs in with.
125
+ let dir = accountHome('codex', lent.env);
126
+ let text = deferredModel(()=>import("./responses.js").then(({ responses })=>responses({
127
+ ...signing(textKey),
128
+ account: dir ? accountEid(dir) : undefined,
129
+ headers,
130
+ fetch: lent.fetch,
131
+ redact: true,
132
+ images,
133
+ web: options.web ?? lent.env('HARNESS_WEB') != '0',
134
+ background: options.background,
135
+ receipts: lent.receipts,
136
+ scope: lent.scope,
137
+ hold: lent.hold,
138
+ store,
139
+ retention
140
+ })), {
141
+ vocab: openaiDoc,
142
+ mark: marking('openai', retention),
143
+ anchor: (comps)=>store ? responseAnchor(comps) : undefined,
144
+ lateResults: true,
145
+ recover: true,
146
+ ...options.background ? {
147
+ retrieve: true
148
+ } : {},
149
+ info: true,
150
+ // OpenAI's own API counts a request's input, anchored history and all.
151
+ ...store ? {
152
+ count: true
153
+ } : {},
154
+ reads
155
+ });
156
+ let pictures = generations({
157
+ credential: signing(imageKey).credential,
158
+ headers,
159
+ fetch: lent.fetch,
160
+ media: {
161
+ store: lent.store,
162
+ maxBytes: images?.maxBytes
163
+ },
164
+ receipts: lent.receipts
165
+ });
166
+ return {
167
+ openai: Object.assign((req)=>image(req.model) ? pictures(req) : text(req), text, {
168
+ quote: (req, remaining)=>image(req.model) ? imageQuote(req, remaining) : undefined,
169
+ info: (name)=>image(name) ? Promise.resolve(imageListed(name)) : text.info(name),
170
+ recover: async (call)=>image(String((await lent.receipts?.read(call))?.model)) ? pictures.recover(call) : text.recover(call)
171
+ })
172
+ };
173
+ };
174
+ /** Its own door (native.ts): one Chat Completions call for each name
175
+ * `aliases` gives an OpenAI model, on the key and endpoint `providers` calls
176
+ * with, held to what `spending` affords. */ export let native = (lent, options, spending)=>{
177
+ let token = options.gateway?.token;
178
+ return door(lent, {
179
+ aliases: options.aliases,
180
+ base: aimed(options),
181
+ key: options.textKey ?? options.key ?? fromEnv(authOf(lent, options).env)?.token,
182
+ headers: {
183
+ ...options.headers,
184
+ ...token ? {
185
+ 'cf-aig-authorization': `Bearer ${token}`
186
+ } : {}
187
+ }
188
+ }, spending);
189
+ };
190
+ //# sourceMappingURL=provider.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.js","sources":["./provider.ts"],"names":[],"mappings":"AAAA,2EAA2E;AAC3E,8EAA8E;AAC9E,6EAA6E;AAC7E,uEAAuE;AACvE,yEAAyE;AACzE,4EAA4E;AAC5E,4EAA4E;AAC5E,2EAA2E;AAE3E,SAAS,OAAO,kCAAuC;AACvD,SACE,UAAU,EACV,WAAW,EACX,aAAa,2BAKgB;AAC/B,SACE,KAAK,EAEL,WAAW,EACX,OAAO,EACP,MAAM,0BACgB;AAExB,SAAS,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,UAAU,2BAA0B;AAE9E,SAAS,SAAS,EAAE,cAAc,qBAAoB;AACtD,SAAS,OAAO,oBAAmB;AACnC,SAAS,UAAU,IAAI,sBAAqB;AAC5C,SAAS,KAAK,qBAAoB;AAUlC;yEACyE,GACzE,OAAO,IAAI,WAAW,CACpB,MACA;EAEA,IAAI,QAAQ;IACV,IAAI,QAAQ,OAAO,OAAO,aAAa,QAAQ;IAC/C,OAAO,QAAQ;MAAE;MAAO,MAAM;IAAO,IAAI,QAAQ,KAAK,GAAG;EAC3D;EACA,IAAI,aAAa;IACf,IAAI,MAAM;IACV,IAAI,KAAK,OAAO;IAChB,IAAI,QAAQ,MAAM,KAAK,GAAG,CAAC;IAC3B,IAAI,CAAC,OAAO;MACV,MAAM,IAAI,QACR;IAEJ;IACA,OAAO,YAAY;EACrB;EACA,OAAO;IACL;IACA,SAAS,OAAO;MACd,IAAI,MAAM;MACV,IAAI,OAAO,MAAM,IAAI,IAAI,OAAO,OAAO,OAAO,MAAM;MACpD,IAAI,QAAQ,MAAM,KAAK,OAAO,CAAC,UAAU,MAAM,KAAK;MACpD,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,QAAQ;MACpB;MACA,OAAO,YAAY;IACrB;EACF;AACF,EAAC;AAED,mEAAmE;AACnE,IAAI,SAAS,CACX,MACA,M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AAG;IACtC,SAAS;MACP,GAAG,QAAQ,OAAO;MAClB,GAAG,QAAQ;QAAE,wBAAwB,CAAC,OAAO,EAAE,OAAO;MAAC,IAAI,CAAC,CAAC;IAC/D;EACF,GAAG;AACL,EAAC"}
package/provider.ts ADDED
@@ -0,0 +1,292 @@
1
+ // @yaks/openai as a provider a config names (@yaks/model `ProviderFacet`):
2
+ // `openai`, signed in with an API key from the host's settings or the ChatGPT
3
+ // grant in the person's OpenAI connection, generating images into the host's
4
+ // artifact store and searching the web. A config may aim it at another
5
+ // OpenAI-compatible endpoint instead (`base`), or reach OpenAI through a
6
+ // Cloudflare AI Gateway (`gateway`), and pay with a key of its own (`key`).
7
+ // Its transport loads on the first ask. Its own door (`native`) answers the
8
+ // names a config aliases to OpenAI models, one Chat Completions call each.
9
+
10
+ import { Refused } from '@yaks/graph/errors'
11
+ import {
12
+ accountEid,
13
+ accountHome,
14
+ deferredModel,
15
+ type Lent,
16
+ type Model,
17
+ type Native,
18
+ type Spending,
19
+ } from '@yaks/model'
20
+ import {
21
+ CODEX,
22
+ type Credential,
23
+ fromChatGPT,
24
+ fromEnv,
25
+ OPENAI,
26
+ } from './credential.js'
27
+ import type { ImageGeneration, Images } from './images.ts'
28
+ import { generations, image, imageListed, imageQuote } from './generations.js'
29
+ import type { TransportCredential } from './transport.ts'
30
+ import { openaiDoc, responseAnchor } from './vocab.js'
31
+ import { marking } from './mark.js'
32
+ import { native as door } from './native.js'
33
+ import { reads } from './reads.js'
34
+
35
+ /** How the harness signs in to OpenAI over what it was lent. */
36
+ export type SignedIn = {
37
+ credential: () => Promise<Credential>
38
+ refresh: (stale: TransportCredential) => Promise<Credential>
39
+ }
40
+
41
+ type Key = () => string | undefined
42
+
43
+ /** OpenAI's credential: `OPENAI_API_KEY`, else the person's ChatGPT grant,
44
+ * refreshed through their connection when the Codex backend refuses it. */
45
+ export let signedIn = (
46
+ lent: Pick<Lent, 'env' | 'key' | 'refresh'>,
47
+ own?: string | Key,
48
+ ): SignedIn => {
49
+ let keyed = (): Credential | undefined => {
50
+ let token = typeof own == 'function' ? own() : own
51
+ return token ? { token, base: OPENAI } : fromEnv(lent.env)
52
+ }
53
+ let credential = async (): Promise<Credential> => {
54
+ let key = keyed()
55
+ if (key) return key
56
+ let token = await lent.key('openai')
57
+ if (!token) {
58
+ throw new Refused(
59
+ 'OpenAI is not connected. Authorize OpenAI or set OPENAI_API_KEY.',
60
+ )
61
+ }
62
+ return fromChatGPT(token)
63
+ }
64
+ return {
65
+ credential,
66
+ refresh: async (stale) => {
67
+ let key = keyed()
68
+ if (key || stale.base != CODEX) return key ?? await credential()
69
+ let token = await lent.refresh('openai', stale.token)
70
+ if (!token) {
71
+ throw new Refused('OpenAI is not connected. Authorize OpenAI again.')
72
+ }
73
+ return fromChatGPT(token)
74
+ },
75
+ }
76
+ }
77
+
78
+ // How a configured endpoint is opened (Options `base`, `gateway`).
79
+ let opened = (
80
+ lent: Pick<Lent, 'env' | 'key'>,
81
+ base: string,
82
+ key: Key,
83
+ ): Pick<SignedIn, 'credential'> => ({
84
+ credential: async () => ({
85
+ token: key() ?? fromEnv(lent.env)?.token ?? await lent.key('openai') ?? '',
86
+ base: base.replace(/\/+$/, ''),
87
+ }),
88
+ })
89
+
90
+ /** The image tool's settings, or `false` for none. */
91
+ export type ImageOptions = { tool?: ImageGeneration; maxBytes?: number }
92
+
93
+ /** The plugin's options in a config. */
94
+ export type Options = {
95
+ /** generate images (default on, unless `HARNESS_IMAGES=0`) */
96
+ images?: ImageOptions | false
97
+ /** offer hosted web search (default on, unless `HARNESS_WEB=0`) */
98
+ web?: boolean
99
+ /** allow acknowledged Responses calls to be recovered after a disconnect */
100
+ background?: boolean
101
+ /** an OpenAI-compatible endpoint to call instead of OpenAI's own, opened
102
+ * by `OPENAI_API_KEY`, else the lent `openai` key, else by nothing, which
103
+ * leaves the endpoint to authenticate the call (an AI Gateway's own key) */
104
+ base?: string
105
+ /** headers every request carries */
106
+ headers?: Record<string, string>
107
+ /** a Cloudflare AI Gateway to reach OpenAI through, where no `base` is
108
+ * given: its account and its id, and the token of a gateway that keeps
109
+ * OpenAI's key itself (sent as `cf-aig-authorization`) */
110
+ gateway?: { account?: string; id?: string; token?: string }
111
+ /** the API key to call with, before `OPENAI_API_KEY` and the lent key */
112
+ key?: string
113
+ /** the API key for conversational models when images use a separate key */
114
+ textKey?: string
115
+ /** Whether a missing configured key can use an environment key or grant */
116
+ credentialFallback?: boolean
117
+ /** names its own door answers (`native`), each the OpenAI model that
118
+ * answers it */
119
+ aliases?: Record<string, string>
120
+ }
121
+
122
+ // The endpoint options aim at, or none for OpenAI's own.
123
+ let aimed = (options: Options): string | undefined => {
124
+ let { account, id } = options.gateway ?? {}
125
+ return options.base ||
126
+ (account && id
127
+ ? `https://gateway.ai.cloudflare.com/v1/${account}/${id}/openai`
128
+ : undefined)
129
+ }
130
+
131
+ /** Where the models `providers` makes with `options` call, so a host may
132
+ * send a credential it lends them there and nowhere else. */
133
+ export let hosts = (options: Options = {}): string[] => [
134
+ new URL(aimed(options) ?? OPENAI).host,
135
+ ]
136
+
137
+ /** A single request only needs the key of the model it calls. Keep it
138
+ * under `key` so existing executors can read it. */
139
+ export let modelOptions = (options: Options, model: string): Options => {
140
+ let { textKey, ...shared } = options
141
+ return { ...shared, key: image(model) ? shared.key : textKey ?? shared.key }
142
+ }
143
+
144
+ /** Explicit options override the setting; otherwise images are on. */
145
+ export let configuredImages = (
146
+ store: Lent['store'],
147
+ options: ImageOptions | false | undefined,
148
+ setting: string | undefined,
149
+ ): Images | undefined => {
150
+ if (options === false) return undefined
151
+ if (options) return { ...options, store }
152
+ if (setting == '0') return undefined
153
+ if (setting != null && setting != '' && setting != '1') {
154
+ throw new Error('HARNESS_IMAGES must be 0 (disabled) or 1 (enabled)')
155
+ }
156
+ return { store }
157
+ }
158
+
159
+ let configuredOnly = {
160
+ env: () => undefined,
161
+ key: () => Promise.resolve(undefined),
162
+ refresh: () => Promise.resolve(undefined),
163
+ }
164
+
165
+ let authOf = (lent: Lent, options: Options) =>
166
+ options.credentialFallback === false ? configuredOnly : lent
167
+
168
+ /** `openai`, served over what the host lends: a GPT Image model's name
169
+ * answers with an image kept in the lent store (generations.ts), any other
170
+ * with the Responses API. */
171
+ export let providers = (
172
+ lent: Lent,
173
+ options: Options = {},
174
+ ): Record<string, Model> => {
175
+ let images = configuredImages(
176
+ lent.store,
177
+ options.images,
178
+ lent.env('HARNESS_IMAGES'),
179
+ )
180
+ let base = aimed(options), token = options.gateway?.token
181
+ let auth = authOf(lent, options)
182
+ let textKey = () => options.textKey ?? options.key
183
+ let imageKey = () => options.key
184
+ // OpenAI's own API keeps each reply (`store`), so the next request sends
185
+ // only what followed it and names it (`previous_response_id`): on a key,
186
+ // or through the AI Gateway to OpenAI. The Codex backend a ChatGPT grant
187
+ // reaches keeps nothing, and another endpoint (`base`) may not either, so
188
+ // through those the conversation is sent whole.
189
+ let store = options.base
190
+ ? false
191
+ : base
192
+ ? true
193
+ : !!(textKey() || fromEnv(auth.env))
194
+ // OpenAI's own API keeps a cached prefix for at least its documented
195
+ // model's retention, so each reply records when its prefix expires, and a session
196
+ // sends the instructions it cached until then. Nothing documents a lifetime
197
+ // for the Codex backend or another endpoint: unknown there.
198
+ let retention = store ? 'openai-default' as const : undefined
199
+ let signing = (key: Key) =>
200
+ base
201
+ ? {
202
+ ...opened(auth, base, key),
203
+ ...options.credentialFallback === false
204
+ ? {}
205
+ : { authentication: 'optional' as const },
206
+ }
207
+ : signedIn(auth, key)
208
+ let headers = {
209
+ ...options.headers,
210
+ ...token ? { 'cf-aig-authorization': `Bearer ${token}` } : {},
211
+ }
212
+ // A ChatGPT grant spends the plan Codex reports, which this machine keeps
213
+ // under the account the Codex CLI signs in with.
214
+ let dir = accountHome('codex', lent.env)
215
+ let text = deferredModel(
216
+ () =>
217
+ import('./responses.js').then(({ responses }) =>
218
+ responses({
219
+ ...signing(textKey),
220
+ account: dir ? accountEid(dir) : undefined,
221
+ headers,
222
+ fetch: lent.fetch,
223
+ redact: true,
224
+ images,
225
+ web: options.web ?? lent.env('HARNESS_WEB') != '0',
226
+ background: options.background,
227
+ receipts: lent.receipts,
228
+ scope: lent.scope,
229
+ hold: lent.hold,
230
+ store,
231
+ retention,
232
+ })
233
+ ),
234
+ {
235
+ vocab: openaiDoc,
236
+ mark: marking('openai', retention),
237
+ anchor: (comps) => store ? responseAnchor(comps) : undefined,
238
+ lateResults: true,
239
+ recover: true,
240
+ ...options.background ? { retrieve: true } : {},
241
+ info: true,
242
+ // OpenAI's own API counts a request's input, anchored history and all.
243
+ ...store ? { count: true as const } : {},
244
+ reads,
245
+ },
246
+ )
247
+ let pictures = generations({
248
+ credential: signing(imageKey).credential,
249
+ headers,
250
+ fetch: lent.fetch,
251
+ media: { store: lent.store, maxBytes: images?.maxBytes },
252
+ receipts: lent.receipts,
253
+ })
254
+ return {
255
+ openai: Object.assign(
256
+ (req: Parameters<Model>[0]) =>
257
+ image(req.model) ? pictures(req) : text(req),
258
+ text,
259
+ {
260
+ quote: (req: Parameters<Model>[0], remaining: number) =>
261
+ image(req.model) ? imageQuote(req, remaining) : undefined,
262
+ info: (name: string) =>
263
+ image(name) ? Promise.resolve(imageListed(name)) : text.info!(name),
264
+ recover: async (call: string) =>
265
+ image(String((await lent.receipts?.read(call))?.model))
266
+ ? pictures.recover(call)
267
+ : text.recover!(call),
268
+ },
269
+ ),
270
+ }
271
+ }
272
+
273
+ /** Its own door (native.ts): one Chat Completions call for each name
274
+ * `aliases` gives an OpenAI model, on the key and endpoint `providers` calls
275
+ * with, held to what `spending` affords. */
276
+ export let native = (
277
+ lent: Lent,
278
+ options: Options,
279
+ spending: Spending,
280
+ ): Native => {
281
+ let token = options.gateway?.token
282
+ return door(lent, {
283
+ aliases: options.aliases,
284
+ base: aimed(options),
285
+ key: options.textKey ?? options.key ??
286
+ fromEnv(authOf(lent, options).env)?.token,
287
+ headers: {
288
+ ...options.headers,
289
+ ...token ? { 'cf-aig-authorization': `Bearer ${token}` } : {},
290
+ },
291
+ }, spending)
292
+ }
package/reads.js ADDED
@@ -0,0 +1,167 @@
1
+ // Responses accepts these MIME types as input_file, including office files.
2
+ // https://developers.openai.com/api/docs/guides/file-inputs
3
+ // Files are under 50 MB each and together per request. PDF and images require
4
+ // vision; non-PDF documents contribute extracted text or spreadsheet metadata.
5
+ // https://developers.openai.com/api/docs/models/o3-mini documents a text-only
6
+ // Responses model: it receives those non-PDF inputs without PDF page images.
7
+ /** Every non-PDF MIME type in the Responses file-input guide. */ export let FILES = Object.fromEntries([
8
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
9
+ 'application/vnd.ms-excel',
10
+ 'text/csv',
11
+ 'application/csv',
12
+ 'text/tsv',
13
+ 'text/x-iif',
14
+ 'application/x-iif',
15
+ 'application/vnd.google-apps.spreadsheet',
16
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
17
+ 'application/msword',
18
+ 'application/rtf',
19
+ 'text/rtf',
20
+ 'application/vnd.oasis.opendocument.text',
21
+ 'application/vnd.apple.pages',
22
+ 'application/vnd.google-apps.document',
23
+ 'application/vnd.apple.iwork',
24
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
25
+ 'application/vnd.ms-powerpoint',
26
+ 'application/vnd.apple.keynote',
27
+ 'application/vnd.google-apps.presentation',
28
+ 'application/javascript',
29
+ 'application/typescript',
30
+ 'text/xml',
31
+ 'text/x-shellscript',
32
+ 'text/x-rst',
33
+ 'text/x-makefile',
34
+ 'text/x-lisp',
35
+ 'text/x-asm',
36
+ 'text/vbscript',
37
+ 'text/css',
38
+ 'message/rfc822',
39
+ 'application/x-sql',
40
+ 'application/x-scala',
41
+ 'application/x-rust',
42
+ 'application/x-powershell',
43
+ 'text/x-diff',
44
+ 'text/x-patch',
45
+ 'application/x-patch',
46
+ 'text/plain',
47
+ 'text/markdown',
48
+ 'text/x-java',
49
+ 'text/x-script.python',
50
+ 'text/x-python',
51
+ 'text/x-c',
52
+ 'text/x-c++',
53
+ 'text/x-golang',
54
+ 'text/html',
55
+ 'text/x-php',
56
+ 'application/x-php',
57
+ 'application/x-httpd-php',
58
+ 'application/x-httpd-php-source',
59
+ 'text/x-ruby',
60
+ 'text/x-sh',
61
+ 'text/x-bash',
62
+ 'application/x-bash',
63
+ 'text/x-zsh',
64
+ 'text/x-tex',
65
+ 'text/x-csharp',
66
+ 'application/json',
67
+ 'text/x-typescript',
68
+ 'text/javascript',
69
+ 'text/x-go',
70
+ 'text/x-rust',
71
+ 'text/x-scala',
72
+ 'text/x-kotlin',
73
+ 'text/x-swift',
74
+ 'text/x-lua',
75
+ 'text/x-r',
76
+ 'text/x-R',
77
+ 'text/x-julia',
78
+ 'text/x-perl',
79
+ 'text/x-objectivec',
80
+ 'text/x-objectivec++',
81
+ 'text/x-erlang',
82
+ 'text/x-elixir',
83
+ 'text/x-haskell',
84
+ 'text/x-clojure',
85
+ 'text/x-groovy',
86
+ 'text/x-dart',
87
+ 'text/x-awk',
88
+ 'application/x-awk',
89
+ 'text/jsx',
90
+ 'text/tsx',
91
+ 'text/x-handlebars',
92
+ 'text/x-mustache',
93
+ 'text/x-ejs',
94
+ 'text/x-jinja2',
95
+ 'text/x-liquid',
96
+ 'text/x-erb',
97
+ 'text/x-twig',
98
+ 'text/x-pug',
99
+ 'text/x-jade',
100
+ 'text/x-tmpl',
101
+ 'text/x-cmake',
102
+ 'text/x-dockerfile',
103
+ 'text/x-gradle',
104
+ 'text/x-ini',
105
+ 'text/x-properties',
106
+ 'text/x-protobuf',
107
+ 'application/x-protobuf',
108
+ 'text/x-sql',
109
+ 'text/x-sass',
110
+ 'text/x-scss',
111
+ 'text/x-less',
112
+ 'text/x-hcl',
113
+ 'text/x-terraform',
114
+ 'application/x-terraform',
115
+ 'text/x-toml',
116
+ 'application/x-toml',
117
+ 'application/graphql',
118
+ 'application/x-graphql',
119
+ 'text/x-graphql',
120
+ 'application/x-ndjson',
121
+ 'application/json5',
122
+ 'application/x-json5',
123
+ 'text/x-yaml',
124
+ 'application/toml',
125
+ 'application/x-yaml',
126
+ 'application/yaml',
127
+ 'text/x-astro',
128
+ 'text/srt',
129
+ 'application/x-subrip',
130
+ 'text/x-subrip',
131
+ 'text/vtt',
132
+ 'text/x-vcard',
133
+ 'text/calendar'
134
+ ].map((type)=>[
135
+ type,
136
+ 50 * 1024 * 1024 - 1
137
+ ]));
138
+ // https://developers.openai.com/api/docs/guides/images-vision
139
+ // PNG/JPEG/WebP/non-animated GIF; 512 MB total request payload, including base64.
140
+ let references = Object.fromEntries([
141
+ 'image/png',
142
+ 'image/jpeg',
143
+ 'image/webp'
144
+ ].map((type)=>[
145
+ type,
146
+ 14 * 1024 * 1024
147
+ ]));
148
+ let images = Object.fromEntries([
149
+ 'image/png',
150
+ 'image/jpeg',
151
+ 'image/webp',
152
+ 'image/gif'
153
+ ].map((type)=>[
154
+ type,
155
+ 384 * 1024 * 1024
156
+ ]));
157
+ /** Responses file inputs, keeping text-only and specialized endpoints apart. */ export let reads = (name)=>{
158
+ if (/^gpt-image-2\.[56](?:-|$)/.test(name)) return references;
159
+ let text = /^(gpt-(4o|4\.1|5|6)(?:[.-]|$)|o[134](?:-|$)|chatgpt-4o)/.test(name) && !/^(o1-(mini|preview))/.test(name) && !/(audio|transcribe|tts|realtime|search-api)/.test(name);
160
+ let vision = /^(gpt-(4o|4\.1|5|6)(?:[.-]|$)|o1(?:-|$)|o3(?:-|$)|o4-mini(?:-|$)|chatgpt-4o)/.test(name) && !/^(o1-(mini|preview)|o3-mini)/.test(name) && !/(audio|transcribe|tts|realtime|search-api)/.test(name);
161
+ return !text ? {} : vision ? {
162
+ ...FILES,
163
+ ...images,
164
+ 'application/pdf': 50 * 1024 * 1024 - 1
165
+ } : FILES;
166
+ };
167
+ //# sourceMappingURL=reads.js.map
package/reads.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reads.js","sources":["./reads.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,4DAA4D;AAC5D,8EAA8E;AAC9E,+EAA+E;AAC/E,8EAA8E;AAC9E,6EAA6E;AAE7E,+DAA+D,GAC/D,OAAO,IAAI,QAAgC,OAAO,WAAW,CAAC;EAC5D;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,CAAC,GAAG,CAAC,CAAC,OAAS;IAAC;IAAM,KAAK,OAAO,OAAO;GAAE,GAAE;AAE9C,8DAA8D;AAC9D,kFAAkF;AAClF,IAAI,aAAa,OAAO,WAAW,CACjC;EAAC;EAAa;EAAc;CAAa,CAAC,GAAG,CAAC,CAC5C,OACG;IAAC;IAAM,KAAK,OAAO;GAAK;AAG/B,IAAI,SAAS,OAAO,WAAW,CAC7B;EAAC;EAAa;EAAc;EAAc;CAAY,CAAC,GAAG,CAAC,CACzD,OACG;IAAC;IAAM,MAAM,OAAO;GAAK;AAGhC,8EAA8E,GAC9E,OAAO,IAAI,QAAQ,CAAC;EAClB,IAAI,4BAA4B,IAAI,CAAC,OAAO,OAAO;EACnD,IAAI,OACF,0DAA0D,IAAI,CAAC,SAC/D,CAAC,uBAAuB,IAAI,CAAC,SAC7B,CAAC,6CAA6C,IAAI,CAAC;EACrD,IAAI,SACF,+EACG,IAAI,CAAC,SACR,CAAC,+BAA+B,IAAI,CAAC,SACrC,CAAC,6CAA6C,IAAI,CAAC;EACrD,OAAO,CAAC,OACJ,CAAC,IACD,SACA;IAAE,GAAG,KAAK;IAAE,GAAG,MAAM;IAAE,mBAAmB,KAAK,OAAO,OAAO;EAAE,IAC/D;AACN,EAAC"}