@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.
- package/LICENSE +202 -0
- package/README.md +389 -2
- package/_dist/batches.d.ts +77 -0
- package/_dist/batches.d.ts.map +1 -0
- package/_dist/credential.d.ts +13 -0
- package/_dist/credential.d.ts.map +1 -0
- package/_dist/images.d.ts +15 -0
- package/_dist/images.d.ts.map +1 -0
- package/_dist/list.d.ts +8 -0
- package/_dist/list.d.ts.map +1 -0
- package/_dist/media.d.ts +11 -0
- package/_dist/media.d.ts.map +1 -0
- package/_dist/mod.d.ts +30 -0
- package/_dist/mod.d.ts.map +1 -0
- package/_dist/project-keys.d.ts +4 -0
- package/_dist/project-keys.d.ts.map +1 -0
- package/_dist/provider.d.ts +48 -0
- package/_dist/provider.d.ts.map +1 -0
- package/_dist/responses.d.ts +51 -0
- package/_dist/responses.d.ts.map +1 -0
- package/_dist/transport.d.ts +121 -0
- package/_dist/transport.d.ts.map +1 -0
- package/_dist/vocab.d.ts +10 -0
- package/_dist/vocab.d.ts.map +1 -0
- package/batches.js +145 -0
- package/batches.js.map +1 -0
- package/batches.ts +194 -0
- package/credential.js +30 -0
- package/credential.js.map +1 -0
- package/credential.ts +40 -0
- package/deno.json +1 -0
- package/generations.js +288 -0
- package/generations.js.map +1 -0
- package/generations.ts +365 -0
- package/images.js +37 -0
- package/images.js.map +1 -0
- package/images.ts +63 -0
- package/info.js +55 -0
- package/info.js.map +1 -0
- package/info.ts +59 -0
- package/limits.js +50 -0
- package/limits.js.map +1 -0
- package/limits.ts +48 -0
- package/list.js +88 -0
- package/list.js.map +1 -0
- package/list.ts +127 -0
- package/mark.js +29 -0
- package/mark.js.map +1 -0
- package/mark.ts +50 -0
- package/media.js +60 -0
- package/media.js.map +1 -0
- package/media.ts +94 -0
- package/mod.js +28 -0
- package/mod.js.map +1 -0
- package/mod.ts +64 -0
- package/native.js +176 -0
- package/native.js.map +1 -0
- package/native.ts +221 -0
- package/package.json +36 -4
- package/project-keys.js +32 -0
- package/project-keys.js.map +1 -0
- package/project-keys.ts +43 -0
- package/provider.js +190 -0
- package/provider.js.map +1 -0
- package/provider.ts +292 -0
- package/reads.js +167 -0
- package/reads.js.map +1 -0
- package/reads.ts +169 -0
- package/responses.js +612 -0
- package/responses.js.map +1 -0
- package/responses.ts +706 -0
- package/transport.js +646 -0
- package/transport.js.map +1 -0
- package/transport.ts +972 -0
- package/vocab.js +23 -0
- package/vocab.js.map +1 -0
- package/vocab.json +25 -0
- package/vocab.ts +29 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright 2026 Jeff Peterson
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,390 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @yaks/openai
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An OpenAI Responses API client and an adapter for `@yaks/model`. The client
|
|
4
|
+
handles streamed responses, credentials, retries, and errors. It does not open a
|
|
5
|
+
database or persist conversations. Applications can call it directly, or use
|
|
6
|
+
`@yaks/session` to save requests, replies, usage, and response IDs in a graph.
|
|
7
|
+
Optional generated images are written through a storage callback supplied by the
|
|
8
|
+
application.
|
|
9
|
+
|
|
10
|
+
## Exports
|
|
11
|
+
|
|
12
|
+
- `responses(options)` returns a provider-neutral `Model` from `@yaks/model`.
|
|
13
|
+
- `transport(options)` returns the lower-level Responses client, with `run()`
|
|
14
|
+
and `reach()` methods. `frames(stream)` decodes server-sent events (SSE).
|
|
15
|
+
- `fromEnv` reads an API key from an application-supplied environment function;
|
|
16
|
+
`fromChatGPT` takes an OAuth bearer and derives its account. `OPENAI` and
|
|
17
|
+
`CODEX` identify the two default endpoints.
|
|
18
|
+
- `input`, `body`, and `items` convert between model requests/replies and
|
|
19
|
+
Responses API data. `ResponseError` describes transport failures; exported
|
|
20
|
+
types describe options, credentials, events, results, usage, and images.
|
|
21
|
+
- `listing(credential, fetch?, refresh?, headers?, options?)` reads the
|
|
22
|
+
credential's `/models` catalog. Transient HTTP failures (408, 409, 429, 5xx,
|
|
23
|
+
and provider capacity codes) and dropped connections retry at the fetch
|
|
24
|
+
boundary, twice by default. `options.retries` and `options.pause` configure
|
|
25
|
+
that bounded retry. Backoff grows from one second to at most a minute;
|
|
26
|
+
`Retry-After` seconds or HTTP dates are a lower bound, even above a minute.
|
|
27
|
+
Exhausted transient failures remain retryable `ModelError`s; authentication,
|
|
28
|
+
validation, and spent quota fail fast. A supplied Codex refresh runs once on
|
|
29
|
+
401. Catalog error messages never repeat the provider's response body.
|
|
30
|
+
- `@yaks/openai/batches` is `@yaks/model/batch`'s `Batches` over OpenAI's Batch
|
|
31
|
+
API: the requests are uploaded as one JSON-lines file of Responses requests
|
|
32
|
+
(their system text as `instructions`) and run at half the price within a day;
|
|
33
|
+
`results` reads the output and error files back as answers. Requests naming
|
|
34
|
+
the same `cache` are sent with it as `prompt_cache_key`, so the prefix they
|
|
35
|
+
share is read from OpenAI's cache. `lineOf` and `answerOf` turn one request
|
|
36
|
+
and one line between the neutral shapes and the API's.
|
|
37
|
+
- `openaiDoc` and `OPENAI_COMP` describe the `openai{response_id}` component.
|
|
38
|
+
- `./provider` is the plugin a config names (@yaks/model `ProviderFacet`): it
|
|
39
|
+
serves `openai`, signed in with its own `key`, `OPENAI_API_KEY` or the
|
|
40
|
+
person's ChatGPT grant. Its options turn `images` and `web` off, or aim it at
|
|
41
|
+
another OpenAI-compatible endpoint (`base`, with `headers` on every request)
|
|
42
|
+
or at OpenAI through a Cloudflare AI Gateway (`gateway`: its `account` and
|
|
43
|
+
`id`, and the `token` of a gateway that keeps OpenAI's key itself). An
|
|
44
|
+
endpoint is opened by the key, the lent `openai` key, or by nothing, which
|
|
45
|
+
leaves the gateway to authenticate the call. `hosts(options)` says where those
|
|
46
|
+
models call, so a host sends a credential it lends them nowhere else.
|
|
47
|
+
`native(lent, options, spending)` is its own door (@yaks/model `Native`) for a
|
|
48
|
+
host that passes a caller's chat input on: it answers only the names
|
|
49
|
+
`options.aliases` maps to OpenAI models, as one Chat Completions call each,
|
|
50
|
+
taking the dialect OpenAI-compatible servers share (`prompt`, `max_tokens`,
|
|
51
|
+
flat tools, a bare JSON schema; sampling and template settings dropped, no
|
|
52
|
+
reasoning unless asked) and answering OpenAI's completion with the text as
|
|
53
|
+
`response` and its calls flat beside it. Each call is held to the model's list
|
|
54
|
+
price and published window before it is made and settled at its usage; nothing
|
|
55
|
+
OpenAI refused is paid for. `@yaks/openai/vocab` exports `openaiDoc` and
|
|
56
|
+
`docs` for schema loading.
|
|
57
|
+
|
|
58
|
+
## Install
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
deno add jsr:@yaks/openai
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## Use
|
|
65
|
+
|
|
66
|
+
```ts ignore
|
|
67
|
+
import { fromEnv, responses } from '@yaks/openai'
|
|
68
|
+
|
|
69
|
+
let model = responses({
|
|
70
|
+
credential: () => fromEnv(Deno.env.get)!,
|
|
71
|
+
web: false, // Enable provider-hosted search when the application needs it.
|
|
72
|
+
})
|
|
73
|
+
let reply = await model({
|
|
74
|
+
model: 'your-model-id',
|
|
75
|
+
items: [{ kind: 'user', text: 'hi' }],
|
|
76
|
+
tools: [],
|
|
77
|
+
})
|
|
78
|
+
console.log(reply.items)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
An application owns credential storage and refresh. API keys use the public API.
|
|
82
|
+
A ChatGPT OAuth grant can use the Codex backend: `fromChatGPT` derives the
|
|
83
|
+
account from its access token, and the application passes a refresh function to
|
|
84
|
+
`responses`. The native harness keeps its grant in a graph connection.
|
|
85
|
+
|
|
86
|
+
Every HTTP request streams and is read to the end. The returned reply contains
|
|
87
|
+
completed model items. Supply `request.onText` to receive text deltas while the
|
|
88
|
+
request runs. Reasoning and other provider-specific items are available through
|
|
89
|
+
the lower-level transport rather than the neutral model item list.
|
|
90
|
+
|
|
91
|
+
`store` defaults to `false`. The model's `mark(reply)` returns
|
|
92
|
+
`openai{response_id}` for the caller to persist; it does not write the graph
|
|
93
|
+
itself. With `store: true`, `anchor(components)` returns that ID so a session
|
|
94
|
+
can continue from a stored response and send only subsequent context. Without
|
|
95
|
+
storage, `anchor` returns nothing and the caller replays the conversation. The
|
|
96
|
+
Codex backend requires `store: false`. A request whose anchor the API no longer
|
|
97
|
+
holds (past OpenAI's retention, 30 days by default) is refused with a
|
|
98
|
+
`ModelError` coded `UNANCHORED` (@yaks/model), and the caller sends the whole
|
|
99
|
+
conversation again.
|
|
100
|
+
|
|
101
|
+
A request with a cache prefix (`Request.cachePrefix`) sends its instructions as
|
|
102
|
+
the conversation's first items, the shared part ending at a 12-hour breakpoint,
|
|
103
|
+
then declares the tools only some requests have in an `additional_tools` item
|
|
104
|
+
after them. An anchored one sends neither again: the conversation OpenAI holds
|
|
105
|
+
already has them. It declares only the tools its anchor's request lacked
|
|
106
|
+
(`Request.held`), so loading a tool mid-conversation keeps the cached prefix,
|
|
107
|
+
and @yaks/session anchors such a request only while its instructions read as the
|
|
108
|
+
anchor's did. Measured on GPT-6.2 Sol (T-2432): a later request with a different
|
|
109
|
+
roster read the shared prefix, and an anchored request that added a tool read
|
|
110
|
+
22,958 of its 24,323 tokens from the cache.
|
|
111
|
+
|
|
112
|
+
Don't run such requests in background mode (`background`). There OpenAI also
|
|
113
|
+
declares the `additional_tools` ahead of the breakpoint: the same request
|
|
114
|
+
counted 33,328 input tokens against 21,805 in the foreground, nothing after a
|
|
115
|
+
changed roster was read from the cache, and an anchored request that added a
|
|
116
|
+
tool read none of it.
|
|
117
|
+
|
|
118
|
+
The `openai` provider a config names (`./provider`) stores on OpenAI's own API,
|
|
119
|
+
reached on a key (`key`, `OPENAI_API_KEY`) or through the AI Gateway
|
|
120
|
+
(`gateway`), and anchors each request on the reply before it. Through the Codex
|
|
121
|
+
backend a ChatGPT grant reaches, or another endpoint a config names (`base`), it
|
|
122
|
+
stores nothing and replays.
|
|
123
|
+
|
|
124
|
+
Operational transport failures are mapped to `ModelError`, except a provider
|
|
125
|
+
`invalid_request_error`, which remains a `ResponseError` so callers can inspect
|
|
126
|
+
invalid request history. The `ModelError` keeps the provider's message, the
|
|
127
|
+
transport's `retry` for a failure that may pass, and `response{body, headers}`:
|
|
128
|
+
the redacted body and the limit headers, never the request's. Other exceptions,
|
|
129
|
+
including application callback failures, propagate unchanged.
|
|
130
|
+
|
|
131
|
+
## Submission checkpoints and recovery
|
|
132
|
+
|
|
133
|
+
The adapter awaits `request.onSubmit` immediately before the paid POST and
|
|
134
|
+
`request.onAck` with `openai{response_id}` at the first provider
|
|
135
|
+
acknowledgement. Supplying `onSubmit` prevents automatic paid retries, including
|
|
136
|
+
a 401 credential refresh. Credential loading may retry before submission. The
|
|
137
|
+
low-level transport offers the same boundary through `run(request, { submit })`,
|
|
138
|
+
passing the wire request body to the callback. Its `event` callback is awaited
|
|
139
|
+
before the next frame; a callback failure propagates without a provider retry.
|
|
140
|
+
|
|
141
|
+
Supply `receipts` to save private
|
|
142
|
+
[media receipts](../model/README.md#generated-media-recovery) before image
|
|
143
|
+
conversion or reply delivery. The adapter records text responses too. It retains
|
|
144
|
+
partial image events with `complete: false`; these cannot be recovered as a
|
|
145
|
+
finished reply. Complete receipts contain the original call, wire request,
|
|
146
|
+
provider response, completed output items and any reported cost. `onReceipt`
|
|
147
|
+
runs after saving each receipt; `onMedia` runs only for a complete receipt. Keep
|
|
148
|
+
both callbacks and storage private, since they contain image payloads.
|
|
149
|
+
|
|
150
|
+
`model.recover(call)` delivers a complete receipt without another paid POST and
|
|
151
|
+
saves the reply for repeated recovery. A missing receipt remains missing;
|
|
152
|
+
recovery does not ask the provider to generate a replacement. This example uses
|
|
153
|
+
a scripted provider and memory storage:
|
|
154
|
+
|
|
155
|
+
```ts
|
|
156
|
+
import { equal } from '@yaks/testing'
|
|
157
|
+
import type { MediaReceipt } from '@yaks/model'
|
|
158
|
+
import { responses } from '@yaks/openai'
|
|
159
|
+
|
|
160
|
+
let receipt: MediaReceipt | undefined
|
|
161
|
+
let posts = 0
|
|
162
|
+
let model = responses({
|
|
163
|
+
credential: () => ({ token: 'example' }),
|
|
164
|
+
receipts: {
|
|
165
|
+
read: async () => receipt,
|
|
166
|
+
save: async (value) => {
|
|
167
|
+
receipt = value
|
|
168
|
+
},
|
|
169
|
+
},
|
|
170
|
+
fetch: async () => {
|
|
171
|
+
posts++
|
|
172
|
+
return new Response(
|
|
173
|
+
'data: ' + JSON.stringify({
|
|
174
|
+
type: 'response.completed',
|
|
175
|
+
response: {
|
|
176
|
+
id: 'response-1',
|
|
177
|
+
model: 'example',
|
|
178
|
+
status: 'completed',
|
|
179
|
+
output: [],
|
|
180
|
+
},
|
|
181
|
+
}) + '\n\n',
|
|
182
|
+
)
|
|
183
|
+
},
|
|
184
|
+
})
|
|
185
|
+
let reply = await model({
|
|
186
|
+
call: 'ask-1',
|
|
187
|
+
model: 'example',
|
|
188
|
+
items: [],
|
|
189
|
+
tools: [],
|
|
190
|
+
})
|
|
191
|
+
equal(await model.recover!('ask-1'), reply)
|
|
192
|
+
equal(posts, 1)
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Provider-native transport
|
|
196
|
+
|
|
197
|
+
`responses` adapts the shared `transport` to neutral model items. A caller that
|
|
198
|
+
needs encrypted reasoning replay, usage, rate limits, unknown provider events,
|
|
199
|
+
or the details of a partial failure can use that same HTTP transport directly:
|
|
200
|
+
|
|
201
|
+
```ts ignore
|
|
202
|
+
import { fromEnv, transport } from '@yaks/openai'
|
|
203
|
+
|
|
204
|
+
let client = transport({
|
|
205
|
+
credentials: {
|
|
206
|
+
get: () => fromEnv(Deno.env.get)!,
|
|
207
|
+
// refresh: renewBearer, // invoked at most once after a 401 per run
|
|
208
|
+
},
|
|
209
|
+
stallMs: 60_000,
|
|
210
|
+
redact: true,
|
|
211
|
+
})
|
|
212
|
+
let result = await client.run({ model: 'your-model-id', input: [] }, {
|
|
213
|
+
// signal: controller.signal,
|
|
214
|
+
event: (frame) => {
|
|
215
|
+
if (frame.type == 'response.output_text.delta') {
|
|
216
|
+
// A transient delta; completed items come back in result.items.
|
|
217
|
+
}
|
|
218
|
+
},
|
|
219
|
+
})
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
The watchdog covers connection, first frame, and gaps between frames (also an
|
|
223
|
+
HTTP error body). Each frame resets it; `0` (the default) disables it. Caller
|
|
224
|
+
cancellation stays an abort, not a stall. The frame hook runs after redaction,
|
|
225
|
+
before terminal-item collection; it includes unknown events too. The transport
|
|
226
|
+
reads through EOF and requires a completed response naming its serving model.
|
|
227
|
+
|
|
228
|
+
Redaction is opt-in: it scrubs credential token/account values from provider
|
|
229
|
+
frames and HTTP error reasons, remembers old credentials across refresh and
|
|
230
|
+
later runs, and hides credential-loader exception messages. It is not a general
|
|
231
|
+
PII filter. Observation vocabulary is not part of this package.
|
|
232
|
+
|
|
233
|
+
The native transport defaults to two bounded retries for credential loading and
|
|
234
|
+
for transient request failures: an unestablished connection, a truncated body, a
|
|
235
|
+
stalled stream, a stream ending without completion or in `response.failed` or
|
|
236
|
+
`error`, a 5xx or 429, and any failure whose provider `code` indicates capacity
|
|
237
|
+
(`server_is_overloaded`, `server_error`, `overloaded`, `overloaded_error`,
|
|
238
|
+
`rate_limit_exceeded`) whatever its status. Auth and validation refusals, and a
|
|
239
|
+
code that says the request itself cannot succeed (a spent allowance, a prompt
|
|
240
|
+
too long or refused), fail fast. `Retry-After`, or a rate limit's "try again
|
|
241
|
+
in", extends the backoff, up to 60s. One refresh on 401 when supplied. `retries`
|
|
242
|
+
sets the attempt limit and `pause` supplies the delay function. `patienceMs` can
|
|
243
|
+
extend HTTP retries beyond that limit; its default of zero keeps the attempt
|
|
244
|
+
limit. `clock` (an @yaks/fp `Clock`, the runtime's by default) is the time the
|
|
245
|
+
watchdog, the backoff, a `Retry-After` date and `reach()`'s timeout keep, so a
|
|
246
|
+
test hands the transport a clock of its own. `run(request, { noRetry: true })`
|
|
247
|
+
prevents replay; a function can defer that decision until partial output is
|
|
248
|
+
exposed. `shape` replaces the default request shaping for compatible providers;
|
|
249
|
+
otherwise requests always stream, default to `store: false`, and request
|
|
250
|
+
encrypted reasoning. `reach()` probes `/models` with a five-second timeout: any
|
|
251
|
+
HTTP answer proves connectivity, not authorization.
|
|
252
|
+
|
|
253
|
+
Native failures are `ResponseError`s with a stable `kind` and optional provider
|
|
254
|
+
`code` (the error body's or event's `code`, or its `type` when the code is
|
|
255
|
+
null), HTTP `status`, rate `limits` (Retry-After, `x-ratelimit-*` and the Codex
|
|
256
|
+
backend's `x-codex-*` plan windows), the redacted `body` the provider sent (an
|
|
257
|
+
error status's body, or the event that ended the stream), and partial
|
|
258
|
+
`items`/`evidence`. Its message is the provider's own: the code and message it
|
|
259
|
+
sent, and `(rate limited; asked to wait 2s)` for a rate limit. Fetch failures
|
|
260
|
+
include a bounded, redacted cause chain with URL parameters removed. The model
|
|
261
|
+
adapter uses the same retry defaults and stops replay after it has delivered a
|
|
262
|
+
public text delta, preventing duplicate streamed text. It accepts the transport
|
|
263
|
+
policies plus `refresh`, `signal`, and `event`; error mapping and continuation
|
|
264
|
+
behavior are described above. `frames(stream)` exposes the same SSE decoder
|
|
265
|
+
without transport policies or redaction and releases its reader on exit.
|
|
266
|
+
|
|
267
|
+
Completed Responses usage is returned as provider-neutral `Reply.usage` and
|
|
268
|
+
persisted by the session on the model-request entry's `usage` component. Counts
|
|
269
|
+
include input, output, total, cached input, and reasoning output tokens when
|
|
270
|
+
reported. Cached tokens are part of input, and reasoning tokens are part of
|
|
271
|
+
output; neither should be added again. Missing counts remain unknown, not zero.
|
|
272
|
+
The provider does not report a cache expiration timestamp here; a cache hit
|
|
273
|
+
records past reuse, not a promise that the next request will hit the cache.
|
|
274
|
+
|
|
275
|
+
## Native image generation
|
|
276
|
+
|
|
277
|
+
Image generation is opt-in. Supply an external binary store through the existing
|
|
278
|
+
`@yaks/blob` backend interface:
|
|
279
|
+
|
|
280
|
+
```ts
|
|
281
|
+
import { artifactStore } from '@yaks/blob/identify'
|
|
282
|
+
import { fileBlobs } from '@yaks/file/blobs'
|
|
283
|
+
import { responses } from '@yaks/openai'
|
|
284
|
+
|
|
285
|
+
const apiKey = Deno.env.get('OPENAI_API_KEY')!
|
|
286
|
+
const model = responses({
|
|
287
|
+
credential: () => ({ token: apiKey, base: 'https://api.openai.com/v1' }),
|
|
288
|
+
images: {
|
|
289
|
+
tool: { output_format: 'png', quality: 'auto' },
|
|
290
|
+
store: artifactStore(fileBlobs('/private/artifacts')),
|
|
291
|
+
},
|
|
292
|
+
})
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
The option adds OpenAI's native `image_generation` tool alongside function
|
|
296
|
+
tools. It is not a function tool implemented by the application. Use a Responses
|
|
297
|
+
model that supports it (for example `gpt-4.1`), with API access to image
|
|
298
|
+
generation. The adapter does not assume every model or the Codex subscription
|
|
299
|
+
endpoint supports the tool. See the current
|
|
300
|
+
[OpenAI image generation guide](https://developers.openai.com/api/docs/guides/tools-image-generation)
|
|
301
|
+
for model availability, permissions, settings, and pricing.
|
|
302
|
+
|
|
303
|
+
Completed `image_generation_call` items are decoded, checked against a default
|
|
304
|
+
32 MiB per-image limit and their PNG/JPEG/WebP signature, then persisted before
|
|
305
|
+
returning the reply. `reply.artifacts` contains addresses and metadata, never
|
|
306
|
+
base64. Partial or incomplete images are not published. Image payloads are
|
|
307
|
+
removed from the adapter's event callback, including nested completion events.
|
|
308
|
+
The low-level transport is still a raw protocol interface: consumers using it
|
|
309
|
+
directly must not log raw image events.
|
|
310
|
+
|
|
311
|
+
The check validates format signatures, not full image decoding. Dimensions are
|
|
312
|
+
not inferred. A storage error fails the response rather than claiming an image
|
|
313
|
+
was saved. A failed graph write after a successful external write can leave an
|
|
314
|
+
unreferenced blob; cleanup is not automatic. No live-provider generation was
|
|
315
|
+
used in the automated tests.
|
|
316
|
+
|
|
317
|
+
When `images` provides a storage callback, the tool is offered on every request,
|
|
318
|
+
including OAuth, unknown models, and custom endpoints. Omitting `images`
|
|
319
|
+
disables it. The legacy `auto` option is deprecated and ignored; it no longer
|
|
320
|
+
filters models or endpoints. The server decides whether the tool is supported.
|
|
321
|
+
|
|
322
|
+
Provider errors propagate without a speculative retry that removes the tool.
|
|
323
|
+
There is no reliable structured capability-rejection contract across these
|
|
324
|
+
endpoints, so the adapter does not infer support from error-message substrings
|
|
325
|
+
or cache negative observations. No paid capability probes are performed.
|
|
326
|
+
|
|
327
|
+
## GPT Image models
|
|
328
|
+
|
|
329
|
+
The `openai` provider answers a GPT Image model's name
|
|
330
|
+
(`gpt-image-2.6-sunburst`, `gpt-image-2.6-flare`, `gpt-image-2.5-sunburst`,
|
|
331
|
+
`gpt-image-2.5-flare` and their snapshots) through the Image API's
|
|
332
|
+
`/images/generations` door instead of Responses. With `kind: 'image'` items it
|
|
333
|
+
uses `/images/edits`, passing the bytes as data URLs in `images`. References are
|
|
334
|
+
PNG, JPEG or WebP, up to 16, at most 14 MiB each. Their labels precede the
|
|
335
|
+
newest user text in the prompt. Invalid references fail before submission; no
|
|
336
|
+
reference is silently dropped. Without image items the newest user text is the
|
|
337
|
+
prompt, as before. `Request.input` may carry `size`, `quality`, `background`,
|
|
338
|
+
`output_format` (`png`, `jpeg` or `webp`), `output_compression`, `moderation`
|
|
339
|
+
and `complexity`, and anything else is refused as `bad_request` before a call.
|
|
340
|
+
One image is made. Its answer is saved as a private media receipt before its
|
|
341
|
+
bytes are stored in the lent store, so `recover(call)` delivers it again without
|
|
342
|
+
buying it twice; `reply.artifacts` carries its address, never the payload.
|
|
343
|
+
`info(name)` lists it with image output.
|
|
344
|
+
|
|
345
|
+
`quote(req, remaining)` reserves twice what OpenAI's cost calculator says the
|
|
346
|
+
image makes at its quality and size (`max` and 2880x2880 where `auto`), plus the
|
|
347
|
+
prompt's bytes as text tokens. For reference inputs, it uses the same calculator
|
|
348
|
+
at each reference's dimensions and max quality as a finite estimate. OpenAI
|
|
349
|
+
publishes no input-token estimator for these image families; this estimate is
|
|
350
|
+
not a spending limit. The host settles measured usage even when it exceeds the
|
|
351
|
+
quote, and later calls see that full debit. `reply.cost` is what the answer's
|
|
352
|
+
`usage` says it used at OpenAI's published rates: $5 per million text input
|
|
353
|
+
tokens, $8 per million image input tokens and $30 per million output tokens. A
|
|
354
|
+
ChatGPT grant cannot use the Image API and is refused.
|
|
355
|
+
|
|
356
|
+
## Hosted web tools
|
|
357
|
+
|
|
358
|
+
`responses()` offers OpenAI's native `web_search` tool by default, alongside
|
|
359
|
+
function and image tools. Set `web: false` to disable it. The provider executes
|
|
360
|
+
search actions; supported reasoning models can also open pages (`open_page`) and
|
|
361
|
+
find text within them (`find_in_page`). There is no separate generic fetch tool
|
|
362
|
+
in this integration. These actions do not run as local function calls.
|
|
363
|
+
|
|
364
|
+
Final response URL citations are preserved as clickable Markdown source links.
|
|
365
|
+
During streaming, source links become available when the final response arrives.
|
|
366
|
+
Provider/model support and account permissions still apply; an unsupported-tool
|
|
367
|
+
error is reported rather than silently retrying without web access. This was
|
|
368
|
+
validated with mocked responses, not a paid live request.
|
|
369
|
+
|
|
370
|
+
See the
|
|
371
|
+
[OpenAI web search guide](https://developers.openai.com/api/docs/guides/tools-web-search)
|
|
372
|
+
for provider behavior and supported models.
|
|
373
|
+
|
|
374
|
+
## Cached-prefix expiry
|
|
375
|
+
|
|
376
|
+
Each reply's mark records when its cached prefix expires as
|
|
377
|
+
`openai.cache_expires_at`: the response's own `cache_expires_at` (ISO instant or
|
|
378
|
+
Unix seconds) where it sends one, else the request's start plus a retention
|
|
379
|
+
(`responses({ retention })`, or a provider row's `cache_retention`), else
|
|
380
|
+
unknown. See [cached-prefix expiry](../model/README.md#cached-prefix-expiry) for
|
|
381
|
+
the reader. A session keeps sending the instructions its newest ask cached until
|
|
382
|
+
then, so a prompt that changed meanwhile does not change the prefix.
|
|
383
|
+
|
|
384
|
+
OpenAI's
|
|
385
|
+
[prompt caching documentation](https://developers.openai.com/api/docs/guides/prompt-caching)
|
|
386
|
+
keeps a prefix 5–10 minutes for earlier models and at least 30 minutes for
|
|
387
|
+
GPT-5.6 and later. The `openai` provider (`./provider`) marks replies from
|
|
388
|
+
OpenAI's own API, on a key or through the AI Gateway, with the shortest of
|
|
389
|
+
these, 300 seconds. Nothing documents a lifetime for the Codex backend or
|
|
390
|
+
another endpoint (`base`), so there the expiry stays unknown.
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { Answered, Asked, Batches } from "@yaks/model/batch";
|
|
2
|
+
/** Where a key's batches are sent. */ export type Options = {
|
|
3
|
+
key: () => string | Promise<string>;
|
|
4
|
+
/** the API's root, OpenAI's own by default */ base?: string;
|
|
5
|
+
fetch?: typeof globalThis.fetch;
|
|
6
|
+
};
|
|
7
|
+
/** A Responses request as one line of a batch's file. */ export declare let lineOf: (a: Asked) => string;
|
|
8
|
+
type Output = {
|
|
9
|
+
type: string;
|
|
10
|
+
content?: {
|
|
11
|
+
type: string;
|
|
12
|
+
text?: string;
|
|
13
|
+
}[];
|
|
14
|
+
};
|
|
15
|
+
type Body = {
|
|
16
|
+
output?: Output[];
|
|
17
|
+
usage?: {
|
|
18
|
+
input_tokens?: number;
|
|
19
|
+
input_tokens_details?: {
|
|
20
|
+
cached_tokens?: number;
|
|
21
|
+
};
|
|
22
|
+
output_tokens?: number;
|
|
23
|
+
output_tokens_details?: {
|
|
24
|
+
reasoning_tokens?: number;
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
error?: {
|
|
28
|
+
message?: string;
|
|
29
|
+
} | null;
|
|
30
|
+
status?: string;
|
|
31
|
+
};
|
|
32
|
+
/** One line of a batch's output or error file. */ export type Line = {
|
|
33
|
+
custom_id: string;
|
|
34
|
+
response?: {
|
|
35
|
+
status_code: number;
|
|
36
|
+
body: Body;
|
|
37
|
+
} | null;
|
|
38
|
+
error?: {
|
|
39
|
+
code?: string;
|
|
40
|
+
message?: string;
|
|
41
|
+
} | null;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* A line of a batch's output as an answer: the response's text and what it
|
|
45
|
+
* used, or why there is none.
|
|
46
|
+
*
|
|
47
|
+
* ```ts
|
|
48
|
+
* import { answerOf } from '@yaks/openai/batches'
|
|
49
|
+
* import { assertEquals } from '@std/assert'
|
|
50
|
+
*
|
|
51
|
+
* assertEquals(answerOf({
|
|
52
|
+
* custom_id: 'a',
|
|
53
|
+
* response: {
|
|
54
|
+
* status_code: 200,
|
|
55
|
+
* body: {
|
|
56
|
+
* status: 'completed',
|
|
57
|
+
* output: [{ type: 'message', content: [{ type: 'output_text', text: 'hi' }] }],
|
|
58
|
+
* usage: { input_tokens: 100, input_tokens_details: { cached_tokens: 90 }, output_tokens: 5 },
|
|
59
|
+
* },
|
|
60
|
+
* },
|
|
61
|
+
* }), { id: 'a', text: 'hi', usage: { input_tokens: 100, cached_tokens: 90, output_tokens: 5, reasoning_tokens: 0 } })
|
|
62
|
+
* assertEquals(answerOf({ custom_id: 'b', error: { code: 'x', message: 'no' } }), { id: 'b', error: 'x: no' })
|
|
63
|
+
* ```
|
|
64
|
+
*/ export declare let answerOf: (l: Line) => Answered;
|
|
65
|
+
/**
|
|
66
|
+
* The batches of one key.
|
|
67
|
+
*
|
|
68
|
+
* ```ts
|
|
69
|
+
* import { batches } from '@yaks/openai/batches'
|
|
70
|
+
* import { assertEquals } from '@std/assert'
|
|
71
|
+
*
|
|
72
|
+
* let fetch = () => Promise.resolve(Response.json({ id: 'b1', status: 'finalizing' }))
|
|
73
|
+
* let api = batches({ fetch, key: () => 'k' })
|
|
74
|
+
* assertEquals(await api.ended('b1'), false)
|
|
75
|
+
* ```
|
|
76
|
+
*/ export declare let batches: (options: Options) => Batches;
|
|
77
|
+
//# sourceMappingURL=batches.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"batches.d.ts","sources":["../batches.ts"],"names":[],"mappings":"AAKA,cAAc,QAAQ,EAAE,KAAK,EAAE,OAAO,iCAAsC;AAI5E,oCAAoC,GACpC,YAAY;EACV,WAAW,MAAM,GAAG,QAAQ,MAAM;EAClC,4CAA4C,GAC5C,OAAO,MAAM;EACb,eAAe,WAAW;;AAG5B,uDAAuD,GACvD,OAAO,YAAI,SAAU,GAAG,UAAQ,MAAM,CAalC;KAEC;EAAW,MAAM,MAAM;EAAE;IAAY,MAAM,MAAM;IAAE,OAAO,MAAM;;;KAChE;EACH,SAAS;EACT;IACE,eAAe,MAAM;IACrB;MAAyB,gBAAgB,MAAM;;IAC/C,gBAAgB,MAAM;IACtB;MAA0B,mBAAmB,MAAM;;;EAErD;IAAU,UAAU,MAAM;MAAK,IAAI;EACnC,SAAS,MAAM;;AAEjB,gDAAgD,GAChD,YAAY;EACV,WAAW,MAAM;EACjB;IAAa,aAAa,MAAM;IAAE,MAAM;MAAS,IAAI;EACrD;IAAU,OAAO,MAAM;IAAE,UAAU,MAAM;MAAK,IAAI;;AAGpD;;;;;;;;;;;;;;;;;;;;;CAqBC,GACD,OAAO,YAAI,WAAY,GAAG,SAAO,SAuBhC;AAKD;;;;;;;;;;;CAWC,GACD,OAAO,YAAI,UAAW,SAAS,YAAU,QA+ExC"}
|