@opencode/ai 2.2.2 → 2.2.4
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/README.md +159 -144
- package/dist/decision.d.ts +0 -1
- package/dist/effect.d.ts +47 -17
- package/dist/effect.js +25 -13
- package/dist/experimental/testing.d.ts +3 -0
- package/dist/experimental/testing.js +3 -0
- package/dist/experimental.d.ts +12 -0
- package/dist/experimental.js +9 -0
- package/dist/index.d.ts +637 -1323
- package/dist/index.js +60 -56
- package/dist/llm.d.ts +4 -3
- package/dist/llm.js +21 -29
- package/dist/protocols/alibaba-responses.d.ts +2 -2
- package/dist/protocols/assemblyai-transcription.js +3 -3
- package/dist/protocols/meta-responses.d.ts +4 -4
- package/dist/protocols/open-responses.d.ts +18 -18
- package/dist/protocols/open-responses.js +4 -2
- package/dist/protocols/openai-compatible-responses.d.ts +2 -2
- package/dist/protocols/openai-responses.d.ts +12 -12
- package/dist/protocols/runway-video.js +2 -2
- package/dist/protocols/xai-responses.d.ts +2 -2
- package/dist/protocols/xai-responses.js +1 -1
- package/dist/protocols/xai-video.js +2 -2
- package/dist/providers/alibaba.d.ts +2 -2
- package/dist/providers/amazon-bedrock-mantle.d.ts +2 -2
- package/dist/providers/azure.d.ts +4 -4
- package/dist/providers/cloudflare-ai-gateway.d.ts +4 -4
- package/dist/providers/digitalocean.d.ts +2 -2
- package/dist/providers/google-vertex-responses.d.ts +2 -2
- package/dist/providers/meta.d.ts +2 -2
- package/dist/providers/minimax.d.ts +2 -2
- package/dist/providers/moonshot.d.ts +2 -2
- package/dist/providers/openai-compatible-responses.d.ts +2 -2
- package/dist/providers/openai.d.ts +2 -2
- package/dist/providers/openrouter/responses.d.ts +1 -2
- package/dist/providers/openrouter.d.ts +36 -23
- package/dist/providers/openrouter.js +29 -10
- package/dist/providers/venice.d.ts +2 -2
- package/dist/providers/zai-coding-plan.d.ts +2 -2
- package/dist/route/client.d.ts +3 -2
- package/dist/route/client.js +6 -9
- package/dist/route/media-protocol.d.ts +2 -3
- package/dist/route/media-protocol.js +2 -6
- package/dist/schema/errors.d.ts +6 -0
- package/dist/schema/errors.js +8 -0
- package/dist/schema/events.d.ts +2 -0
- package/dist/schema/events.js +4 -0
- package/dist/testing.d.ts +1 -4
- package/dist/testing.js +4 -12
- package/dist/tool.d.ts +40 -73
- package/dist/tool.js +27 -18
- package/package.json +7 -3
package/README.md
CHANGED
|
@@ -1,39 +1,39 @@
|
|
|
1
1
|
# @opencode/ai
|
|
2
2
|
|
|
3
|
-
Schema-first APIs for text, images,
|
|
3
|
+
Schema-first APIs for text, images, and decisions, built with Effect. Video, speech, transcription, extraction, and
|
|
4
|
+
realtime voice are [experimental](#experimental).
|
|
4
5
|
|
|
5
6
|
`@opencode/ai` is the Promise API: one managed runtime behind the LLM and media methods, plus asset helpers. `ai.file`
|
|
6
7
|
and `ai.write` load `node:fs/promises` on first use, so no Effect `FileSystem` is needed:
|
|
7
8
|
|
|
8
9
|
```ts
|
|
9
|
-
import {
|
|
10
|
+
import { ai } from "@opencode/ai"
|
|
10
11
|
import { OpenAI } from "@opencode/ai/providers"
|
|
11
12
|
|
|
12
13
|
const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
|
|
13
14
|
|
|
14
|
-
const ai = AI.make()
|
|
15
15
|
const input = { model: openai.responses("gpt-4o-mini"), prompt: "Say hello." }
|
|
16
|
-
const response = await ai.
|
|
16
|
+
const response = await ai.generate(input)
|
|
17
17
|
console.log(response.text)
|
|
18
18
|
const generated = await ai.image.generate({ model: openai.image("gpt-image-2"), prompt: "A lighthouse" })
|
|
19
19
|
await ai.write(generated.image, "./lighthouse.png") // also ai.file(path), ai.bytes(asset), ai.base64(asset), ai.materialize(asset)
|
|
20
|
-
for await (const event of ai.
|
|
20
|
+
for await (const event of ai.stream(ai.request(input))) {
|
|
21
21
|
// LLMEvent
|
|
22
22
|
}
|
|
23
|
-
await ai.dispose()
|
|
24
23
|
```
|
|
25
24
|
|
|
26
|
-
The Effect API lives at `@opencode/ai/effect`. Its methods
|
|
25
|
+
The Effect API lives at `@opencode/ai/effect`. Its `ai` has the same namespaces and methods, returning `Effect` or
|
|
26
|
+
`Stream`:
|
|
27
27
|
|
|
28
28
|
```ts
|
|
29
29
|
import { Effect } from "effect"
|
|
30
|
-
import {
|
|
30
|
+
import { ai, AIClient } from "@opencode/ai/effect"
|
|
31
31
|
import { OpenAI } from "@opencode/ai/providers"
|
|
32
32
|
|
|
33
33
|
const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
|
|
34
34
|
|
|
35
35
|
const program = Effect.gen(function* () {
|
|
36
|
-
const response = yield*
|
|
36
|
+
const response = yield* ai.generate({
|
|
37
37
|
model: openai.responses("gpt-4o-mini"), // `.chat(...)` selects the Chat Completions API instead
|
|
38
38
|
system: "You are concise.",
|
|
39
39
|
prompt: "Say hello in one short sentence.",
|
|
@@ -46,8 +46,8 @@ const program = Effect.gen(function* () {
|
|
|
46
46
|
await Effect.runPromise(program.pipe(Effect.provide(AIClient.layer)))
|
|
47
47
|
```
|
|
48
48
|
|
|
49
|
-
Run `
|
|
50
|
-
`
|
|
49
|
+
Run `ai.stream(...)` instead of `generate` when you want incremental `LLMEvent`s. Both accept input or a prebuilt
|
|
50
|
+
`ai.request(...)`. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses,
|
|
51
51
|
Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
|
|
52
52
|
|
|
53
53
|
### Tool loop
|
|
@@ -55,22 +55,22 @@ Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployme
|
|
|
55
55
|
`stream` runs one model call; `loop` runs the model's tool calls and calls the model again until it stops calling
|
|
56
56
|
tools. Events from every step arrive on one stream, with a `tool-result` after each tool runs. `until` is checked
|
|
57
57
|
after each step that has tool calls, with every step's `LLMResponse`; returning `true` ends the loop without running
|
|
58
|
-
them. `
|
|
58
|
+
them. `tool` takes a plain `async` execute; a throw or rejection goes back to the model as an error result, and
|
|
59
59
|
`signal` aborts when the loop is interrupted.
|
|
60
|
-
`
|
|
60
|
+
`tool` from `@opencode/ai/effect` takes the same options (including an optional `success` schema) with an Effect execute:
|
|
61
61
|
|
|
62
62
|
```ts
|
|
63
63
|
import { readFile } from "node:fs/promises"
|
|
64
64
|
import { Schema } from "effect"
|
|
65
|
-
import {
|
|
65
|
+
import { ai, tool } from "@opencode/ai"
|
|
66
66
|
|
|
67
|
-
const read_file =
|
|
67
|
+
const read_file = tool({
|
|
68
68
|
description: "Read a UTF-8 file.",
|
|
69
69
|
parameters: Schema.Struct({ path: Schema.String }),
|
|
70
70
|
execute: ({ path }, { signal }) => readFile(path, { encoding: "utf8", signal }),
|
|
71
71
|
})
|
|
72
72
|
|
|
73
|
-
const events = ai.
|
|
73
|
+
const events = ai.loop({
|
|
74
74
|
model,
|
|
75
75
|
prompt: "Summarize package.json.",
|
|
76
76
|
tools: { read_file },
|
|
@@ -87,7 +87,7 @@ A tool with exactly one required string parameter can set `freeform`, so the mod
|
|
|
87
87
|
instead of JSON arguments: unconstrained `text`, or text matching a `regex` or `lark` grammar.
|
|
88
88
|
|
|
89
89
|
```ts
|
|
90
|
-
const run_code =
|
|
90
|
+
const run_code = tool({
|
|
91
91
|
description: "Run JavaScript",
|
|
92
92
|
parameters: Schema.Struct({ code: Schema.String }),
|
|
93
93
|
freeform: { type: "lark", grammar: JS_GRAMMAR },
|
|
@@ -108,7 +108,7 @@ history works with or without `freeform`.
|
|
|
108
108
|
unvalidated `unknown` object:
|
|
109
109
|
|
|
110
110
|
```ts
|
|
111
|
-
const { object } = await ai.
|
|
111
|
+
const { object } = await ai.generateObject({
|
|
112
112
|
model,
|
|
113
113
|
prompt: "Pick a city.",
|
|
114
114
|
schema: Schema.Struct({ city: Schema.String }),
|
|
@@ -123,12 +123,12 @@ are visible too. Raw events are off by default, and `generate` ignores them. Tra
|
|
|
123
123
|
|
|
124
124
|
```ts
|
|
125
125
|
import { Stream } from "effect"
|
|
126
|
-
import {
|
|
126
|
+
import { ai, LLMEvent } from "@opencode/ai/effect"
|
|
127
127
|
|
|
128
128
|
const flagged = (data: unknown) =>
|
|
129
129
|
typeof data === "object" && data !== null && "type" in data && data.type === "moderation.flagged"
|
|
130
130
|
|
|
131
|
-
const events =
|
|
131
|
+
const events = ai.stream({ model, prompt: "Say hello.", includeRaw: true }).pipe(
|
|
132
132
|
Stream.map((event) =>
|
|
133
133
|
event.type === "raw" && flagged(event.data) ? LLMEvent.providerError({ message: "Flagged by moderation" }) : event,
|
|
134
134
|
),
|
|
@@ -147,7 +147,7 @@ live under `providerMetadata.vertex`. The default is still full-history replay w
|
|
|
147
147
|
|
|
148
148
|
```ts
|
|
149
149
|
const model = Google.configure({ apiKey }).interactions("gemini-3.8-flash")
|
|
150
|
-
const response = yield*
|
|
150
|
+
const response = yield* ai.generate({
|
|
151
151
|
model,
|
|
152
152
|
prompt: "Say hello.",
|
|
153
153
|
providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto", store: true },
|
|
@@ -165,15 +165,15 @@ Raw usage is preserved in `usage.providerMetadata.google`. `inputTokens` follows
|
|
|
165
165
|
`contextTokens` uses its full `raw_prompt_token` count when supplied. These can differ substantially with server-side
|
|
166
166
|
continuation. Explicit caches, hosted tools, and generated media are not supported by this initial protocol.
|
|
167
167
|
|
|
168
|
-
The same configured facade names image
|
|
169
|
-
provider's image route from the model and returns `Media.Asset`s with lazily decoded bytes:
|
|
168
|
+
The same configured facade names image models (and the experimental video, speech, and transcription models).
|
|
169
|
+
`ai.image.generate` resolves the provider's image route from the model and returns `Media.Asset`s with lazily decoded bytes:
|
|
170
170
|
|
|
171
171
|
```ts
|
|
172
172
|
import { NodeFileSystem } from "@effect/platform-node"
|
|
173
|
-
import {
|
|
173
|
+
import { ai, Media } from "@opencode/ai/effect"
|
|
174
174
|
|
|
175
175
|
const image = Effect.gen(function* () {
|
|
176
|
-
const response = yield*
|
|
176
|
+
const response = yield* ai.image.generate({
|
|
177
177
|
model: openai.image("gpt-image-2"),
|
|
178
178
|
prompt: "A robot tending a rooftop garden",
|
|
179
179
|
aspect: "1:1",
|
|
@@ -209,12 +209,12 @@ const everything = AIClient.layerWith(logged) // or AI.make({ layer: logged })
|
|
|
209
209
|
select the same API, and `responses` selects its Responses API; credentials default to `VENICE_API_KEY`.
|
|
210
210
|
|
|
211
211
|
```ts
|
|
212
|
-
import {
|
|
212
|
+
import { ai } from "@opencode/ai/effect"
|
|
213
213
|
import { Venice } from "@opencode/ai/providers"
|
|
214
214
|
import { Effect } from "effect"
|
|
215
215
|
|
|
216
216
|
const program = Effect.gen(function* () {
|
|
217
|
-
const response = yield*
|
|
217
|
+
const response = yield* ai.generate({
|
|
218
218
|
model: Venice.configure({ apiKey: process.env.VENICE_API_KEY }).chat("qwen3-6-27b"),
|
|
219
219
|
prompt: "Explain this design.",
|
|
220
220
|
providerOptions: {
|
|
@@ -245,10 +245,10 @@ values, or a `score` on ordered levels, each with the probability of every optio
|
|
|
245
245
|
|
|
246
246
|
```ts
|
|
247
247
|
import { Effect } from "effect"
|
|
248
|
-
import {
|
|
248
|
+
import { ai, DecisionClient, Media } from "@opencode/ai/effect"
|
|
249
249
|
import { OpenAI } from "@opencode/ai/providers"
|
|
250
250
|
|
|
251
|
-
const program =
|
|
251
|
+
const program = ai.decision.generate({
|
|
252
252
|
model: OpenAI.configure().decision("gpt-6-luna"),
|
|
253
253
|
input: [
|
|
254
254
|
{ type: "text", text: "I was charged twice. Please refund the duplicate payment." },
|
|
@@ -309,38 +309,6 @@ CloudflareAIGateway.configure({ accountId }).decision("typesafe/jev")
|
|
|
309
309
|
OpenAI and Vercel AI Gateway use OpenAI's `/v1/decisions` API. TypeSafe, OpenCode, OpenRouter, Baseten and
|
|
310
310
|
DigitalOcean use System One (`/systemone`), and Cloudflare sends the System One body through `/ai/run`.
|
|
311
311
|
|
|
312
|
-
### Extraction (experimental)
|
|
313
|
-
|
|
314
|
-
Extraction models read typed values out of text instead of answering questions with probabilities. A field of type
|
|
315
|
-
`text`, `number`, `date`, `time`, `datetime`, `duration`, `list`, `estimate` or `forecast` gets an answer typed to
|
|
316
|
-
match; other types are sent and answered as-is. Only Cloudflare's Clairic serves it today, so it lives under
|
|
317
|
-
`@opencode/ai/experimental`.
|
|
318
|
-
|
|
319
|
-
```ts
|
|
320
|
-
import { ai } from "@opencode/ai"
|
|
321
|
-
import { Extraction } from "@opencode/ai/experimental"
|
|
322
|
-
import { CloudflareWorkersAI } from "@opencode/ai/providers"
|
|
323
|
-
|
|
324
|
-
const response = await ai.run(
|
|
325
|
-
Extraction.generate({
|
|
326
|
-
model: CloudflareWorkersAI.configure({ accountId }).experimental.extraction("@cf/cloudflare/clairic"),
|
|
327
|
-
input: "Invoice INV-2291, issued 2026-09-02, net 30. Total $1,080.00. Contact: Dana Ruiz, Priya Shah.",
|
|
328
|
-
fields: {
|
|
329
|
-
invoiceNumber: { type: "text" },
|
|
330
|
-
dueDate: { type: "date", instructions: "Issue date plus the net payment days" },
|
|
331
|
-
total: { type: "number", decimals: 2, unit: "USD" },
|
|
332
|
-
contacts: { type: "list", items: "text" },
|
|
333
|
-
},
|
|
334
|
-
}),
|
|
335
|
-
)
|
|
336
|
-
response.answers.total.value // 1080, or null when the input does not say
|
|
337
|
-
```
|
|
338
|
-
|
|
339
|
-
Value answers carry `guess`, `nullProbability` and `confidence`; text answers carry a `span` into `input`. Estimates and
|
|
340
|
-
forecasts return `median`, `p10` and `p90`. Field options other than `type`, `instructions` and `nullThreshold` go to
|
|
341
|
-
Clairic as written. Effect users provide `RequestExecutor.fetchLayer` (or `AIClient.layer`). Images are not supported
|
|
342
|
-
yet.
|
|
343
|
-
|
|
344
312
|
## Alibaba Cloud Model Studio
|
|
345
313
|
|
|
346
314
|
`Alibaba` provides standard Model Studio inference. Configure a region explicitly, then select
|
|
@@ -348,7 +316,7 @@ Chat Completions (`.model` or `.chat`), Anthropic-compatible Messages (`.message
|
|
|
348
316
|
Responses (`.responses`). These routes use HTTP/SSE.
|
|
349
317
|
|
|
350
318
|
```ts
|
|
351
|
-
import {
|
|
319
|
+
import { ai } from "@opencode/ai/effect"
|
|
352
320
|
import { Alibaba } from "@opencode/ai/providers"
|
|
353
321
|
|
|
354
322
|
const alibaba = Alibaba.configure({
|
|
@@ -357,7 +325,7 @@ const alibaba = Alibaba.configure({
|
|
|
357
325
|
// workspaceID: "llm-your-workspace", // use a workspace-dedicated endpoint
|
|
358
326
|
})
|
|
359
327
|
|
|
360
|
-
const request =
|
|
328
|
+
const request = ai.request({
|
|
361
329
|
model: alibaba.model("qwen3.8-max"),
|
|
362
330
|
prompt: "Explain this design.",
|
|
363
331
|
providerOptions: { reasoningEffort: "medium" },
|
|
@@ -428,11 +396,11 @@ hours. A complete `baseURL` for images includes `/api/v1`.
|
|
|
428
396
|
the existing `.image(...)` selector provides image generation.
|
|
429
397
|
|
|
430
398
|
```ts
|
|
431
|
-
import {
|
|
399
|
+
import { ai } from "@opencode/ai/effect"
|
|
432
400
|
import { ZAI, ZAICodingPlan } from "@opencode/ai/providers"
|
|
433
401
|
|
|
434
402
|
const zai = ZAI.configure({ apiKey: process.env.ZAI_API_KEY })
|
|
435
|
-
const request =
|
|
403
|
+
const request = ai.request({
|
|
436
404
|
model: zai.model("glm-5.3"), // also zai.chat("glm-5.3")
|
|
437
405
|
prompt: "Explain this design.",
|
|
438
406
|
providerOptions: {
|
|
@@ -442,7 +410,7 @@ const request = LLM.request({
|
|
|
442
410
|
})
|
|
443
411
|
|
|
444
412
|
const coding = ZAICodingPlan.configure({ apiKey: process.env.ZAI_API_KEY })
|
|
445
|
-
const messages =
|
|
413
|
+
const messages = ai.request({
|
|
446
414
|
model: coding.messages("glm-5.3"),
|
|
447
415
|
prompt: "Explain this design.",
|
|
448
416
|
providerOptions: { effort: "high" },
|
|
@@ -494,24 +462,24 @@ Package entrypoints are `@opencode/ai/providers/zai`, `zai/chat`, `zai-coding-pl
|
|
|
494
462
|
Moonshot defaults to Chat Completions, with Messages and Responses selectors for Kimi K3:
|
|
495
463
|
|
|
496
464
|
```ts
|
|
497
|
-
import {
|
|
465
|
+
import { ai } from "@opencode/ai/effect"
|
|
498
466
|
import { Moonshot } from "@opencode/ai/providers"
|
|
499
467
|
|
|
500
468
|
const moonshot = Moonshot.configure({ apiKey: process.env.MOONSHOT_API_KEY })
|
|
501
469
|
|
|
502
|
-
const request =
|
|
470
|
+
const request = ai.request({
|
|
503
471
|
model: moonshot.model("kimi-k3"), // also moonshot.chat("kimi-k3")
|
|
504
472
|
prompt: "Explain the tradeoffs in this design.",
|
|
505
473
|
providerOptions: { reasoningEffort: "high" },
|
|
506
474
|
})
|
|
507
475
|
|
|
508
|
-
const messages =
|
|
476
|
+
const messages = ai.request({
|
|
509
477
|
model: moonshot.messages("kimi-k3"),
|
|
510
478
|
prompt: "Explain the tradeoffs in this design.",
|
|
511
479
|
providerOptions: { effort: "high" },
|
|
512
480
|
})
|
|
513
481
|
|
|
514
|
-
const responses =
|
|
482
|
+
const responses = ai.request({
|
|
515
483
|
model: moonshot.responses("kimi-k3"),
|
|
516
484
|
prompt: "Explain the tradeoffs in this design.",
|
|
517
485
|
providerOptions: { reasoningEffort: "high" },
|
|
@@ -556,18 +524,18 @@ MiniMax defaults to its Messages API and reads `MINIMAX_API_KEY` when `apiKey` i
|
|
|
556
524
|
|
|
557
525
|
```ts
|
|
558
526
|
import { Effect } from "effect"
|
|
559
|
-
import {
|
|
527
|
+
import { ai, AIClient } from "@opencode/ai/effect"
|
|
560
528
|
import { MiniMax } from "@opencode/ai/providers"
|
|
561
529
|
|
|
562
530
|
const minimax = MiniMax.configure({ apiKey: process.env.MINIMAX_API_KEY })
|
|
563
|
-
const request =
|
|
531
|
+
const request = ai.request({
|
|
564
532
|
model: minimax.model("MiniMax-M3"), // also minimax.messages("MiniMax-M3")
|
|
565
533
|
prompt: "What is 173 multiplied by 219?",
|
|
566
534
|
providerOptions: { thinking: { type: "adaptive" } },
|
|
567
535
|
generation: { maxTokens: 1536 },
|
|
568
536
|
})
|
|
569
537
|
|
|
570
|
-
const response = await Effect.runPromise(
|
|
538
|
+
const response = await Effect.runPromise(ai.generate(request).pipe(Effect.provide(AIClient.layer)))
|
|
571
539
|
console.log(response.text)
|
|
572
540
|
```
|
|
573
541
|
|
|
@@ -598,7 +566,7 @@ Use Meta's direct [Model API](https://dev.meta.ai/docs/overview) with `META_API_
|
|
|
598
566
|
import { Meta } from "@opencode/ai/providers"
|
|
599
567
|
|
|
600
568
|
const meta = Meta.configure() // or Meta.configure({ apiKey })
|
|
601
|
-
const request =
|
|
569
|
+
const request = ai.request({
|
|
602
570
|
model: meta.responses("muse-spark-1.3"), // meta.model(...) also selects Responses
|
|
603
571
|
prompt: "What is 173 multiplied by 219? Reply with the integer.",
|
|
604
572
|
providerOptions: { reasoningEffort: "low" },
|
|
@@ -632,19 +600,19 @@ To include search result lists, set `include: ["reasoning.encrypted_content", "w
|
|
|
632
600
|
Messages exposes hosted search calls; the recorded Messages API stream does not supply structured
|
|
633
601
|
citations or separate result blocks. Retain `response.message` for either API's continuation.
|
|
634
602
|
|
|
635
|
-
Use `
|
|
603
|
+
Use `ai.image.generate` for one-off generation or editing:
|
|
636
604
|
|
|
637
605
|
```ts
|
|
638
|
-
import {
|
|
606
|
+
import { ai, Media } from "@opencode/ai/effect"
|
|
639
607
|
|
|
640
|
-
const generation =
|
|
608
|
+
const generation = ai.image.generate({
|
|
641
609
|
model: meta.image("muse-image-1.0"),
|
|
642
610
|
prompt: "A flat black square on a white background.",
|
|
643
611
|
n: 1,
|
|
644
612
|
providerOptions: { reasoningStrength: "low" },
|
|
645
613
|
})
|
|
646
614
|
|
|
647
|
-
const edit =
|
|
615
|
+
const edit = ai.image.generate({
|
|
648
616
|
model: meta.image("muse-image-1.0"),
|
|
649
617
|
prompt: "Make the square purple.",
|
|
650
618
|
images: [Media.bytes(imageBytes, "image/webp")],
|
|
@@ -664,20 +632,20 @@ Meta Responses is explicitly HTTP/SSE-only and does not use WebSockets, even whe
|
|
|
664
632
|
|
|
665
633
|
## Image generation
|
|
666
634
|
|
|
667
|
-
Use `
|
|
635
|
+
Use `ai.image.generate` with an image model for direct asset generation. `ai.image.request` mirrors `ai.request`: the
|
|
668
636
|
model comes from the facade's `.image(...)` selector (mirroring `.responses(...)`), common fields
|
|
669
637
|
(`images`, `n`, `aspect`, `resolution`) lower natively or fail typed, and `providerOptions` is inferred from the
|
|
670
638
|
selected model. `aspect` is a ratio such as `"16:9"`; `resolution` is a size tier (`"1K"` is about 1024×1024 pixels
|
|
671
639
|
at that ratio, `"2K"` about 2048×2048). Exact sizes, seeds, masks, and output formats are provider options:
|
|
672
640
|
|
|
673
641
|
```ts
|
|
674
|
-
import {
|
|
642
|
+
import { ai, Media } from "@opencode/ai/effect"
|
|
675
643
|
import { OpenAI } from "@opencode/ai/providers"
|
|
676
644
|
|
|
677
645
|
const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
|
|
678
646
|
|
|
679
647
|
const program = Effect.gen(function* () {
|
|
680
|
-
const response = yield*
|
|
648
|
+
const response = yield* ai.image.generate({
|
|
681
649
|
model: openai.image("gpt-image-2"),
|
|
682
650
|
prompt: "A robot tending a rooftop garden",
|
|
683
651
|
n: 2,
|
|
@@ -712,7 +680,7 @@ table before swapping only the `model`:
|
|
|
712
680
|
| Cloudflare Workers AI | 1 | width × height² | width × height² | ✗ | `width`, `height`, `seed` |
|
|
713
681
|
|
|
714
682
|
✓ lowers natively; ✗ fails whenever the field is set (including `n: 1`); `1` means `n > 1` fails. "width × height"
|
|
715
|
-
computes a size the provider accepts and fails when the request falls outside its limits. ¹ `
|
|
683
|
+
computes a size the provider accepts and fails when the request falls outside its limits. ¹ `ai.image.stream` on OpenAI
|
|
716
684
|
generates one image. On OpenAI, `gpt-image-2` and later get a computed size; older models get the nearest of their
|
|
717
685
|
fixed sizes. `providerOptions.size` replaces `aspect` and `resolution`, so setting both fails. Vercel AI Gateway
|
|
718
686
|
forwards `outputFormat` but does not apply it, so the returned bytes keep the upstream model's own format. ² Workers AI
|
|
@@ -734,7 +702,7 @@ Pass ordered image inputs to the same method for editing, composition, or image-
|
|
|
734
702
|
|
|
735
703
|
```ts
|
|
736
704
|
const composed = Effect.gen(function* () {
|
|
737
|
-
const response = yield*
|
|
705
|
+
const response = yield* ai.image.generate({
|
|
738
706
|
model,
|
|
739
707
|
prompt: "Combine these product photos into one studio scene",
|
|
740
708
|
images: [
|
|
@@ -758,7 +726,7 @@ uses multipart for byte/data-URL edits and its JSON reference body for URL or fi
|
|
|
758
726
|
provider option on the routes that support it (OpenAI):
|
|
759
727
|
|
|
760
728
|
```ts
|
|
761
|
-
const inpainted =
|
|
729
|
+
const inpainted = ai.image.generate({
|
|
762
730
|
model: openai.image("gpt-image-2"),
|
|
763
731
|
prompt,
|
|
764
732
|
images: [Media.bytes(sourceBytes, "image/png")],
|
|
@@ -774,7 +742,7 @@ not accept image inputs. These cases fail with a typed `AIError` before network
|
|
|
774
742
|
Provider-native image options belong to each request. Raw `http.body` fields have final precedence over them:
|
|
775
743
|
|
|
776
744
|
```ts
|
|
777
|
-
const medium =
|
|
745
|
+
const medium = ai.image.generate({
|
|
778
746
|
model: openai.image("gpt-image-2"),
|
|
779
747
|
prompt,
|
|
780
748
|
providerOptions: { quality: "medium" },
|
|
@@ -787,7 +755,7 @@ xAI image models use the same request API with xAI-native controls:
|
|
|
787
755
|
```ts
|
|
788
756
|
import { XAI } from "@opencode/ai/providers"
|
|
789
757
|
|
|
790
|
-
const xai =
|
|
758
|
+
const xai = ai.image.generate({
|
|
791
759
|
model: XAI.configure({ apiKey }).image("any-model-id"),
|
|
792
760
|
prompt,
|
|
793
761
|
n: 2,
|
|
@@ -807,7 +775,7 @@ Google's current Gemini image models use the same direct API:
|
|
|
807
775
|
import { Google } from "@opencode/ai/providers"
|
|
808
776
|
|
|
809
777
|
const googleProgram = Effect.gen(function* () {
|
|
810
|
-
const response = yield*
|
|
778
|
+
const response = yield* ai.image.generate({
|
|
811
779
|
model: Google.configure({ apiKey }).image("any-model-id"),
|
|
812
780
|
prompt: "A robot tending a rooftop garden",
|
|
813
781
|
aspect: "16:9",
|
|
@@ -835,7 +803,7 @@ Z.ai image models infer open Z.ai-native options from the selected model:
|
|
|
835
803
|
```ts
|
|
836
804
|
import { ZAI } from "@opencode/ai/providers"
|
|
837
805
|
|
|
838
|
-
const zai =
|
|
806
|
+
const zai = ai.image.generate({
|
|
839
807
|
model: ZAI.configure({ apiKey }).image("any-model-id"),
|
|
840
808
|
prompt,
|
|
841
809
|
providerOptions: {
|
|
@@ -856,7 +824,7 @@ persist the bytes promptly if they must remain available.
|
|
|
856
824
|
```ts
|
|
857
825
|
import { MiniMax } from "@opencode/ai/providers"
|
|
858
826
|
|
|
859
|
-
const minimax =
|
|
827
|
+
const minimax = ai.image.generate({
|
|
860
828
|
model: MiniMax.configure({ apiKey }).image("image-01"),
|
|
861
829
|
prompt,
|
|
862
830
|
n: 2,
|
|
@@ -873,14 +841,14 @@ error.
|
|
|
873
841
|
|
|
874
842
|
### Partial images
|
|
875
843
|
|
|
876
|
-
OpenAI's GPT image models stream previews. `
|
|
877
|
-
and emits `image-partial` events before each final `image`; `
|
|
844
|
+
OpenAI's GPT image models stream previews. `ai.image.stream` sends `stream: true` with `partialImages` (0–3, default 2)
|
|
845
|
+
and emits `image-partial` events before each final `image`; `ai.image.generate` keeps the plain JSON request:
|
|
878
846
|
|
|
879
847
|
```ts
|
|
880
848
|
import { Stream } from "effect"
|
|
881
849
|
import { ImageEvent } from "@opencode/ai/effect"
|
|
882
850
|
|
|
883
|
-
const previews =
|
|
851
|
+
const previews = ai.image.stream({
|
|
884
852
|
model: openai.image("gpt-image-2"),
|
|
885
853
|
prompt: "A lighthouse at dusk",
|
|
886
854
|
providerOptions: { partialImages: 2 },
|
|
@@ -896,8 +864,8 @@ Conversational image generation remains part of the LLM interaction. OpenAI Resp
|
|
|
896
864
|
|
|
897
865
|
```ts
|
|
898
866
|
const program = Effect.gen(function* () {
|
|
899
|
-
const response = yield*
|
|
900
|
-
|
|
867
|
+
const response = yield* ai.generate(
|
|
868
|
+
ai.request({
|
|
901
869
|
model: OpenAI.configure({ apiKey }).responses("gpt-5"),
|
|
902
870
|
prompt: "Design a solarpunk rooftop garden, then show me.",
|
|
903
871
|
tools: [OpenAI.imageGeneration({ quality: "high" })],
|
|
@@ -910,7 +878,42 @@ const program = Effect.gen(function* () {
|
|
|
910
878
|
|
|
911
879
|
The hosted result is represented as a provider-executed tool call and a tool result whose content carries the generated image as a file. Gemini image-capable models instead emit a first-class `media` `LLMEvent` for inline image output (`response.message` then carries a `media` part). Retaining `response.message` preserves the generated image for continuation on both routes.
|
|
912
880
|
|
|
913
|
-
##
|
|
881
|
+
## Public API
|
|
882
|
+
|
|
883
|
+
Everything below is exported from `@opencode/ai/effect` unless noted.
|
|
884
|
+
|
|
885
|
+
- **`ai.request({...})`** — build a provider-neutral `LLMRequest`. Accepts ergonomic inputs (`system: string`, `prompt: string`) that normalize into the canonical Schema classes.
|
|
886
|
+
- **`ai.generate` / `ai.stream`** — run direct input or an `LLMRequest` through `LLMClient` for one-import use.
|
|
887
|
+
- **`ai.loop`** — stream model calls, running `tool(...)` tools between them until the model stops calling tools.
|
|
888
|
+
- **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
|
|
889
|
+
- **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
|
|
890
|
+
- **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
|
|
891
|
+
- **`ai.image.request` / `generate` / `stream` / `start` / `resume`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model.
|
|
892
|
+
- **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
|
|
893
|
+
- **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
|
|
894
|
+
- **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
|
|
895
|
+
- **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input; `DecisionClient` is its Effect service and layer.
|
|
896
|
+
- **`AIClient.layer` / `AIClient.layerWith(executor)`** — every modality client plus the request executor in one layer.
|
|
897
|
+
- **`@opencode/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `generateObject`, `compact`, `canCompact`) at the top level plus `image` and `decision` (plus `experimental.video`, `experimental.speech`, and `experimental.transcription`) as Promise / `AsyncIterable` APIs, `run(effect)` for any package Effect, plus `file`, `write`, `bytes`, `base64`, and `materialize` for assets. `AI.make({ layer?, clients? })` builds a client over a custom executor or test layers. The same `ai` from `@opencode/ai/effect` returns `Effect` and `Stream`.
|
|
898
|
+
- **`@opencode/ai/experimental`** — APIs that may change without compatibility guarantees: `Video`, `Speech`, `Transcription`, `Extraction`, and `Realtime`. See [Experimental](#experimental).
|
|
899
|
+
|
|
900
|
+
## Experimental
|
|
901
|
+
|
|
902
|
+
These APIs may change without compatibility guarantees. The Effect API is exported from `@opencode/ai/experimental`,
|
|
903
|
+
the Promise client exposes it under `ai.experimental`, and test layers come from `@opencode/ai/experimental/testing`.
|
|
904
|
+
|
|
905
|
+
- **`Video`**, **`Speech`**, and **`Transcription`** — media generation and speech-to-text, with `VideoClient`,
|
|
906
|
+
`SpeechClient`, and `TranscriptionClient` as their Effect services. Promise: `ai.experimental.video`, `.speech`, and
|
|
907
|
+
`.transcription`. Testing: `TestVideo`, `TestSpeech`, and `TestTranscription`.
|
|
908
|
+
- **`Extraction`** — typed values read out of text.
|
|
909
|
+
- **`Realtime`** — `Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or
|
|
910
|
+
a short-lived WebSocket URL and token.
|
|
911
|
+
|
|
912
|
+
The provider selectors for these modalities (`.video(...)`, `.speech(...)`, `.transcription(...)`,
|
|
913
|
+
`.experimental.extraction(...)`) and their protocol entrypoints (such as `@opencode/ai/protocols/openai-speech`) are
|
|
914
|
+
part of the same experimental surface.
|
|
915
|
+
|
|
916
|
+
### Video generation
|
|
914
917
|
|
|
915
918
|
Video mirrors `Image` with one difference: every provider is asynchronous, so the route is a submit-then-poll
|
|
916
919
|
`Generation`. Models come from `.video(...)` selectors on the `Google` (Veo), `XAI`, and `Runway` facades.
|
|
@@ -919,7 +922,7 @@ Common fields (`frames`, `references`, `video`, `durationSeconds`, `aspect`, `re
|
|
|
919
922
|
under `providerOptions`, inferred from the selected model.
|
|
920
923
|
|
|
921
924
|
```ts
|
|
922
|
-
import { Video } from "@opencode/ai/
|
|
925
|
+
import { Video } from "@opencode/ai/experimental"
|
|
923
926
|
import { Google, Runway } from "@opencode/ai/providers"
|
|
924
927
|
|
|
925
928
|
const google = Google.configure({ apiKey: process.env.GOOGLE_GENERATIVE_AI_API_KEY })
|
|
@@ -981,9 +984,9 @@ Provider notes:
|
|
|
981
984
|
- **Runway** expects pixel ratios in `aspect` for most models (`"1280:720"`), pins `X-Runway-Version`, reports
|
|
982
985
|
`usage: { type: "credits" }`, and its output URLs expire after 24–48 hours.
|
|
983
986
|
|
|
984
|
-
The promise client exposes the same surface: `ai.video.start(...)` resolves to a handle with `await`, `events`,
|
|
985
|
-
`result`, `refresh`, `cancel`, and `token`; `ai.video.generate`, `ai.video.resume(model, token)`, and
|
|
986
|
-
`ai.video.stream` mirror the Effect API. The handle's `status` and `progress` are a snapshot from when it was
|
|
987
|
+
The promise client exposes the same surface: `ai.experimental.video.start(...)` resolves to a handle with `await`, `events`,
|
|
988
|
+
`result`, `refresh`, `cancel`, and `token`; `ai.experimental.video.generate`, `ai.experimental.video.resume(model, token)`, and
|
|
989
|
+
`ai.experimental.video.stream` mirror the Effect API. The handle's `status` and `progress` are a snapshot from when it was
|
|
987
990
|
created; `refresh()` resolves to a new handle. Every promise method and stream accepts `{ signal }`: like `fetch`,
|
|
988
991
|
aborting rejects the Promise or throws from the `for await` loop with `signal.reason` (an `AbortError` `DOMException`
|
|
989
992
|
unless `abort(reason)` passed one), while `break` stops a stream without throwing.
|
|
@@ -991,13 +994,13 @@ unless `abort(reason)` passed one), while `break` stops a stream without throwin
|
|
|
991
994
|
```ts
|
|
992
995
|
import { ai } from "@opencode/ai"
|
|
993
996
|
|
|
994
|
-
const generation = await ai.video.start({ model, prompt })
|
|
997
|
+
const generation = await ai.experimental.video.start({ model, prompt })
|
|
995
998
|
for await (const event of generation.events({ poll: { interval: 10_000 } })) console.log(event.type)
|
|
996
999
|
const video = await generation.result({ signal })
|
|
997
1000
|
await ai.write(video.video, "./kite.mp4")
|
|
998
1001
|
```
|
|
999
1002
|
|
|
1000
|
-
|
|
1003
|
+
### Speech generation
|
|
1001
1004
|
|
|
1002
1005
|
Speech (text-to-speech) is one request whose response is parsed incrementally, so every route supports both
|
|
1003
1006
|
`Speech.generate` (the whole file) and `Speech.stream` (audio chunks as they arrive). Models come from `.speech(...)`
|
|
@@ -1006,7 +1009,8 @@ selectors on the `OpenAI`, `Google` (Gemini TTS), `ElevenLabs`, `Cartesia`, and
|
|
|
1006
1009
|
before any network call; provider-native controls live under `providerOptions`, inferred from the selected model.
|
|
1007
1010
|
|
|
1008
1011
|
```ts
|
|
1009
|
-
import { Media
|
|
1012
|
+
import { Media } from "@opencode/ai/effect"
|
|
1013
|
+
import { Speech, SpeechEvent } from "@opencode/ai/experimental"
|
|
1010
1014
|
import { ElevenLabs, OpenAI } from "@opencode/ai/providers"
|
|
1011
1015
|
|
|
1012
1016
|
const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
|
|
@@ -1068,20 +1072,20 @@ Provider notes:
|
|
|
1068
1072
|
and `providerOptions` lower to query parameters (`encoding`, `container`, `sample_rate`, `bit_rate`); `pcm` is
|
|
1069
1073
|
`linear16` without a container. Auth is `Authorization: Token <DEEPGRAM_API_KEY>`.
|
|
1070
1074
|
|
|
1071
|
-
The promise client mirrors the Effect API; `ai.speech.stream` is an `AsyncIterable`.
|
|
1075
|
+
The promise client mirrors the Effect API; `ai.experimental.speech.stream` is an `AsyncIterable`.
|
|
1072
1076
|
|
|
1073
1077
|
```ts
|
|
1074
1078
|
import { ai } from "@opencode/ai"
|
|
1075
1079
|
|
|
1076
|
-
const response = await ai.speech.generate({ model, text: "Hello from OpenCode.", voice: "coral" })
|
|
1080
|
+
const response = await ai.experimental.speech.generate({ model, text: "Hello from OpenCode.", voice: "coral" })
|
|
1077
1081
|
await ai.write(response.audio, "hello.mp3")
|
|
1078
1082
|
|
|
1079
|
-
for await (const event of ai.speech.stream({ model, text: "Hello from OpenCode.", voice: "coral" })) {
|
|
1083
|
+
for await (const event of ai.experimental.speech.stream({ model, text: "Hello from OpenCode.", voice: "coral" })) {
|
|
1080
1084
|
if (event.type === "audio-delta") player.write(event.chunk)
|
|
1081
1085
|
}
|
|
1082
1086
|
```
|
|
1083
1087
|
|
|
1084
|
-
|
|
1088
|
+
### Transcription
|
|
1085
1089
|
|
|
1086
1090
|
Transcription (speech-to-text) is the one modality whose providers use every route kind: OpenAI and Gemini stream,
|
|
1087
1091
|
Deepgram and ElevenLabs answer inline, and AssemblyAI is queued. `Transcription.generate` and `Transcription.stream`
|
|
@@ -1093,7 +1097,8 @@ any network call; a route may return more than asked.
|
|
|
1093
1097
|
|
|
1094
1098
|
```ts
|
|
1095
1099
|
import { Console, Effect, Stream } from "effect"
|
|
1096
|
-
import { Media
|
|
1100
|
+
import { Media } from "@opencode/ai/effect"
|
|
1101
|
+
import { Transcription, TranscriptionEvent } from "@opencode/ai/experimental"
|
|
1097
1102
|
import { AssemblyAI, Deepgram, OpenAI } from "@opencode/ai/providers"
|
|
1098
1103
|
|
|
1099
1104
|
const openai = OpenAI.configure({ apiKey: process.env.OPENAI_API_KEY })
|
|
@@ -1146,33 +1151,43 @@ The promise client mirrors the Effect API:
|
|
|
1146
1151
|
|
|
1147
1152
|
```ts
|
|
1148
1153
|
const audio = await ai.file("./call.mp3")
|
|
1149
|
-
const text = (await ai.transcription.generate({ model, audio })).text
|
|
1150
|
-
for await (const event of ai.transcription.stream({ model, audio }))
|
|
1151
|
-
|
|
1154
|
+
const text = (await ai.experimental.transcription.generate({ model, audio })).text
|
|
1155
|
+
for await (const event of ai.experimental.transcription.stream({ model, audio }))
|
|
1156
|
+
if (event.type === "text-delta") write(event.delta)
|
|
1157
|
+
const generation = await ai.experimental.transcription.start({ model: assemblyai, audio })
|
|
1152
1158
|
const transcript = await generation.await({ poll: { interval: 3_000 } })
|
|
1153
1159
|
```
|
|
1154
1160
|
|
|
1155
|
-
|
|
1161
|
+
### Extraction
|
|
1156
1162
|
|
|
1157
|
-
|
|
1163
|
+
Extraction models read typed values out of text instead of answering questions with probabilities. A field of type
|
|
1164
|
+
`text`, `number`, `date`, `time`, `datetime`, `duration`, `list`, `estimate` or `forecast` gets an answer typed to
|
|
1165
|
+
match; other types are sent and answered as-is. Only Cloudflare's Clairic serves it today.
|
|
1158
1166
|
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1167
|
+
```ts
|
|
1168
|
+
import { ai } from "@opencode/ai"
|
|
1169
|
+
import { Extraction } from "@opencode/ai/experimental"
|
|
1170
|
+
import { CloudflareWorkersAI } from "@opencode/ai/providers"
|
|
1171
|
+
|
|
1172
|
+
const response = await ai.run(
|
|
1173
|
+
Extraction.generate({
|
|
1174
|
+
model: CloudflareWorkersAI.configure({ accountId }).experimental.extraction("@cf/cloudflare/clairic"),
|
|
1175
|
+
input: "Invoice INV-2291, issued 2026-09-02, net 30. Total $1,080.00. Contact: Dana Ruiz, Priya Shah.",
|
|
1176
|
+
fields: {
|
|
1177
|
+
invoiceNumber: { type: "text" },
|
|
1178
|
+
dueDate: { type: "date", instructions: "Issue date plus the net payment days" },
|
|
1179
|
+
total: { type: "number", decimals: 2, unit: "USD" },
|
|
1180
|
+
contacts: { type: "list", items: "text" },
|
|
1181
|
+
},
|
|
1182
|
+
}),
|
|
1183
|
+
)
|
|
1184
|
+
response.answers.total.value // 1080, or null when the input does not say
|
|
1185
|
+
```
|
|
1186
|
+
|
|
1187
|
+
Value answers carry `guess`, `nullProbability` and `confidence`; text answers carry a `span` into `input`. Estimates and
|
|
1188
|
+
forecasts return `median`, `p10` and `p90`. Field options other than `type`, `instructions` and `nullThreshold` go to
|
|
1189
|
+
Clairic as written. Effect users provide `RequestExecutor.fetchLayer` (or `AIClient.layer`). Images are not supported
|
|
1190
|
+
yet.
|
|
1176
1191
|
|
|
1177
1192
|
## Testing
|
|
1178
1193
|
|
|
@@ -1218,7 +1233,7 @@ For explicit compaction, script a `CompactionResponse` through `push`, `always`,
|
|
|
1218
1233
|
|
|
1219
1234
|
For `compact(request, { mechanism: "trigger" })`, script a `CompactionCheckpointResponse` instead. It carries `checkpoint`, `responseID`, and optional `usage`. Endpoint and trigger calls reject each other's fixtures; both share the same queue, gates, lazy recording, and fallback controls.
|
|
1220
1235
|
|
|
1221
|
-
`TestImage
|
|
1236
|
+
`TestImage` and `TestDecision` (and `TestVideo`, `TestSpeech`, and `TestTranscription` from `@opencode/ai/experimental/testing`) follow the same pattern: `testLayer()` provides the modality's client and `Test`, with the same `push`, `always`, `serve`, `requests`, `wait`, and `gate` controls. Script an `ImageResponse` (or the modality's response) or an `AIError`. `stream` expands the response into its events, and `start` returns an already finished generation that `resume` accepts by token. Decision responses are returned as scripted, without checking the answers against the questions.
|
|
1222
1237
|
|
|
1223
1238
|
The Promise client accepts the same layers as `AI.make({ clients: TestImage.testLayer() })`; `ai.run(TestImage.Test.use(...))` reaches the controls.
|
|
1224
1239
|
|
|
@@ -1234,25 +1249,25 @@ This is different from prompt caching, server-side history storage, or truncatio
|
|
|
1234
1249
|
|
|
1235
1250
|
### Explicit compaction
|
|
1236
1251
|
|
|
1237
|
-
`
|
|
1252
|
+
`ai.compact(request)` (equivalently, `{ mechanism: "endpoint" }`) is the caller-controlled operation for OpenAI, Azure, and xAI Responses. It performs exactly one HTTP call to `/responses/compact`, using the selected route's endpoint, credentials, query, and HTTP middleware. It returns a `CompactionResponse` with `replacement: Message[]` and optional `usage`, not a normal generation response. This mechanism does not accept a WebSocket executor.
|
|
1238
1253
|
|
|
1239
1254
|
Prefer this operation, where supported, when the application owns compaction policy and durable context updates.
|
|
1240
1255
|
|
|
1241
1256
|
```ts
|
|
1242
1257
|
const compacted = Effect.gen(function* () {
|
|
1243
|
-
const result = yield*
|
|
1258
|
+
const result = yield* ai.compact(request)
|
|
1244
1259
|
const next = LLMRequest.update(request, {
|
|
1245
1260
|
messages: result.replacement,
|
|
1246
1261
|
})
|
|
1247
|
-
return yield*
|
|
1262
|
+
return yield* ai.generate(next)
|
|
1248
1263
|
})
|
|
1249
1264
|
```
|
|
1250
1265
|
|
|
1251
|
-
From the Promise API, `await ai.
|
|
1266
|
+
From the Promise API, `await ai.compact(request)` takes the same request and options (plus `signal`) and returns the same result.
|
|
1252
1267
|
|
|
1253
1268
|
`replacement` replaces the complete input window. Do not append it to the original transcript or extract only the encrypted item: the provider may retain additional messages in its output. Retained user and assistant messages remain ordinary messages with typed text, media, or reasoning parts, in their original order. Provider-specific message IDs, status, and phase use `providerMetadata`, not a raw output array hidden in an assistant message. Unsupported returned item types fail explicitly.
|
|
1254
1269
|
|
|
1255
|
-
The selected model carries explicit-compaction capability through request construction and updates. Calls using unsupported routes fail type checking. When the model is selected dynamically, narrow the request with `
|
|
1270
|
+
The selected model carries explicit-compaction capability through request construction and updates. Calls using unsupported routes fail type checking. When the model is selected dynamically, narrow the request with `ai.canCompact(request)` before calling `ai.compact`; a model or route switch does not inherit the old capability. Runtime validation still rejects unsupported calls from untyped consumers. Capability describes the route's API, not whether every model or custom deployment supports the operation.
|
|
1256
1271
|
|
|
1257
1272
|
Generation-only body overlays such as `stream` and `store` are not sent to the compact endpoint. Supported compact controls such as service tier and prompt-cache settings preserve request defaults and HTTP-overlay precedence. Retained image and file detail settings survive serialization and replay.
|
|
1258
1273
|
|
|
@@ -1264,7 +1279,7 @@ OpenAI Responses also exposes a separate, explicitly selected mechanism:
|
|
|
1264
1279
|
|
|
1265
1280
|
```ts
|
|
1266
1281
|
const checkpoint = Effect.gen(function* () {
|
|
1267
|
-
const result = yield*
|
|
1282
|
+
const result = yield* ai.compact(request, {
|
|
1268
1283
|
mechanism: "trigger",
|
|
1269
1284
|
webSocket, // Optional: without it, the request uses HTTP/SSE.
|
|
1270
1285
|
})
|
|
@@ -1287,8 +1302,8 @@ Trigger support is separate from endpoint support. Only the OpenAI Responses rou
|
|
|
1287
1302
|
|
|
1288
1303
|
```ts
|
|
1289
1304
|
const narrowed = Effect.gen(function* () {
|
|
1290
|
-
if (
|
|
1291
|
-
const result = yield*
|
|
1305
|
+
if (ai.canCompact(request, { mechanism: "trigger" })) {
|
|
1306
|
+
const result = yield* ai.compact(request, { mechanism: "trigger" })
|
|
1292
1307
|
}
|
|
1293
1308
|
})
|
|
1294
1309
|
```
|
|
@@ -1303,10 +1318,10 @@ Enable OpenAI compaction with typed provider options:
|
|
|
1303
1318
|
|
|
1304
1319
|
```ts
|
|
1305
1320
|
import { Effect } from "effect"
|
|
1306
|
-
import {
|
|
1321
|
+
import { ai, LLMClient, LLMRequest, Message } from "@opencode/ai/effect"
|
|
1307
1322
|
import { OpenAI } from "@opencode/ai/providers"
|
|
1308
1323
|
|
|
1309
|
-
const request =
|
|
1324
|
+
const request = ai.request({
|
|
1310
1325
|
model: OpenAI.configure({ apiKey }).responses("gpt-5.3-codex"),
|
|
1311
1326
|
messages,
|
|
1312
1327
|
providerOptions: {
|
|
@@ -1382,7 +1397,7 @@ Requests below a provider's minimum cacheable size simply do not produce a reusa
|
|
|
1382
1397
|
### Opting out
|
|
1383
1398
|
|
|
1384
1399
|
```ts
|
|
1385
|
-
|
|
1400
|
+
ai.request({
|
|
1386
1401
|
model,
|
|
1387
1402
|
system,
|
|
1388
1403
|
prompt: "one-off question",
|
|
@@ -1408,7 +1423,7 @@ An object with placement fields places exactly those breakpoints. An object with
|
|
|
1408
1423
|
`ttl` is a duration in models.dev's format (`<number>` followed by `ms`, `s`, `m`, `h` or `d`). It is sent to the provider as given, so use one the provider accepts. Leaving it unset keeps the provider default.
|
|
1409
1424
|
|
|
1410
1425
|
```ts
|
|
1411
|
-
|
|
1426
|
+
ai.request({ model, system, prompt, cache: { ttl: "1h" } })
|
|
1412
1427
|
```
|
|
1413
1428
|
|
|
1414
1429
|
| Protocol | How `ttl` is sent |
|
|
@@ -1426,7 +1441,7 @@ OpenAI's two fields cover different models: `prompt_cache_retention` (`"in_memor
|
|
|
1426
1441
|
Inline `CacheHint` (`{ type: "ephemeral", ttl? }`) on any text / system / tool / tool-result part overrides automatic placement. The auto policy preserves manual hints, counts them against Anthropic and Bedrock's four-breakpoint limit, and only fills the remaining slots.
|
|
1427
1442
|
|
|
1428
1443
|
```ts
|
|
1429
|
-
|
|
1444
|
+
ai.request({
|
|
1430
1445
|
model,
|
|
1431
1446
|
system: [
|
|
1432
1447
|
{ type: "text", text: "stable system prompt", cache: { type: "ephemeral" } },
|
|
@@ -1551,7 +1566,7 @@ Route/provider defaults are overridden by request-level values for each axis.
|
|
|
1551
1566
|
The selected model supplies the provider-specific option type, so per-request overrides stay flat while the canonical runtime request remains provider-neutral:
|
|
1552
1567
|
|
|
1553
1568
|
```ts
|
|
1554
|
-
|
|
1569
|
+
ai.request({
|
|
1555
1570
|
model,
|
|
1556
1571
|
prompt,
|
|
1557
1572
|
providerOptions: {
|