@opencode/ai 2.2.5 → 2.2.7
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 +228 -72
- package/dist/ai-client.d.ts +2 -2
- package/dist/ai-client.js +2 -1
- package/dist/cache-policy.d.ts +1 -1
- package/dist/cache-policy.js +16 -4
- package/dist/decision-client.d.ts +3 -3
- package/dist/decision.d.ts +30 -125
- package/dist/decision.js +27 -15
- package/dist/effect.d.ts +10 -15
- package/dist/effect.js +6 -6
- package/dist/effort-updates.d.ts +3 -3
- package/dist/effort-updates.js +2 -2
- package/dist/embedding-client.d.ts +21 -0
- package/dist/embedding-client.js +30 -0
- package/dist/embedding.d.ts +111 -0
- package/dist/embedding.js +75 -0
- package/dist/experimental/cloudflare-run-extraction.d.ts +7 -3
- package/dist/experimental/cloudflare-run-extraction.js +4 -1
- package/dist/experimental/extraction.d.ts +10 -40
- package/dist/experimental/extraction.js +14 -13
- package/dist/experimental.d.ts +8 -8
- package/dist/experimental.js +4 -4
- package/dist/generation.d.ts +0 -2
- package/dist/generation.js +2 -2
- package/dist/image-client.d.ts +13 -7
- package/dist/image-client.js +1 -1
- package/dist/image.d.ts +357 -465
- package/dist/image.js +17 -18
- package/dist/index.d.ts +35 -467
- package/dist/index.js +23 -17
- package/dist/llm.d.ts +65 -266
- package/dist/llm.js +101 -92
- package/dist/loop.d.ts +38 -0
- package/dist/loop.js +136 -0
- package/dist/media-model.d.ts +1 -1
- package/dist/media-model.js +8 -6
- package/dist/media.d.ts +9 -0
- package/dist/media.js +37 -2
- package/dist/protocols/alibaba-chat.d.ts +9 -1
- package/dist/protocols/alibaba-chat.js +3 -3
- package/dist/protocols/alibaba-images.d.ts +2 -2
- package/dist/protocols/alibaba-messages.js +3 -3
- package/dist/protocols/alibaba-responses.js +8 -20
- package/dist/protocols/anthropic-messages.d.ts +1 -1
- package/dist/protocols/anthropic-messages.js +57 -176
- package/dist/protocols/assemblyai-transcription.d.ts +2 -2
- package/dist/protocols/bedrock-converse.js +10 -16
- package/dist/protocols/cartesia-speech.d.ts +2 -2
- package/dist/protocols/cloudflare-workers-ai-images.d.ts +2 -2
- package/dist/protocols/cohere-chat.js +9 -12
- package/dist/protocols/deepgram-speech.d.ts +2 -2
- package/dist/protocols/deepgram-transcription.d.ts +2 -2
- package/dist/protocols/elevenlabs-speech.d.ts +2 -2
- package/dist/protocols/elevenlabs-transcription.d.ts +2 -2
- package/dist/protocols/gemini.d.ts +3 -0
- package/dist/protocols/gemini.js +54 -72
- package/dist/protocols/google-embed-content.d.ts +34 -0
- package/dist/protocols/google-embed-content.js +110 -0
- package/dist/protocols/google-images.d.ts +2 -2
- package/dist/protocols/google-interactions.d.ts +3 -4
- package/dist/protocols/google-interactions.js +44 -30
- package/dist/protocols/google-speech.d.ts +2 -2
- package/dist/protocols/google-transcription.d.ts +2 -2
- package/dist/protocols/google-vertex-predict-embeddings.d.ts +18 -0
- package/dist/protocols/google-vertex-predict-embeddings.js +74 -0
- package/dist/protocols/google-video.d.ts +2 -2
- package/dist/protocols/index.d.ts +3 -0
- package/dist/protocols/index.js +3 -0
- package/dist/protocols/meta-images.d.ts +2 -2
- package/dist/protocols/meta-responses.js +26 -23
- package/dist/protocols/minimax-images.d.ts +2 -2
- package/dist/protocols/mistral-chat.js +7 -10
- package/dist/protocols/open-responses-channel.js +6 -19
- package/dist/protocols/open-responses-continuation.d.ts +1 -5
- package/dist/protocols/open-responses-continuation.js +1 -3
- package/dist/protocols/open-responses.d.ts +2 -22
- package/dist/protocols/open-responses.js +41 -23
- package/dist/protocols/openai-chat.d.ts +27 -23
- package/dist/protocols/openai-chat.js +62 -57
- package/dist/protocols/openai-compatible-chat.d.ts +2 -1
- package/dist/protocols/openai-compatible-responses.d.ts +2 -2
- package/dist/protocols/openai-compatible-responses.js +1 -1
- package/dist/protocols/openai-decisions.js +15 -2
- package/dist/protocols/openai-embeddings.d.ts +16 -0
- package/dist/protocols/openai-embeddings.js +76 -0
- package/dist/protocols/openai-images.d.ts +2 -2
- package/dist/protocols/openai-responses.js +10 -29
- package/dist/protocols/openai-speech.d.ts +2 -2
- package/dist/protocols/openai-transcription.d.ts +2 -2
- package/dist/protocols/runway-video.d.ts +2 -2
- package/dist/protocols/shared.d.ts +14 -7
- package/dist/protocols/shared.js +40 -15
- package/dist/protocols/system-one.d.ts +4 -4
- package/dist/protocols/system-one.js +8 -1
- package/dist/protocols/utils/bedrock-cache.js +2 -5
- package/dist/protocols/utils/bedrock-media.d.ts +0 -3
- package/dist/protocols/utils/cache.d.ts +3 -0
- package/dist/protocols/utils/cache.js +15 -2
- package/dist/protocols/utils/image-sizing.d.ts +1 -1
- package/dist/protocols/utils/responses-checkpoint.js +1 -1
- package/dist/protocols/utils/responses-compaction.d.ts +1 -1
- package/dist/protocols/utils/responses-compaction.js +6 -5
- package/dist/protocols/utils/responses-hosted-tools.d.ts +97 -1
- package/dist/protocols/utils/responses-hosted-tools.js +31 -0
- package/dist/protocols/utils/tool-stream.d.ts +5 -271
- package/dist/protocols/utils/tool-stream.js +3 -13
- package/dist/protocols/venice-chat.d.ts +7 -1
- package/dist/protocols/venice-chat.js +4 -4
- package/dist/protocols/xai-images.d.ts +2 -2
- package/dist/protocols/xai-responses.js +5 -25
- package/dist/protocols/xai-video.d.ts +2 -2
- package/dist/protocols/zai-chat.d.ts +9 -1
- package/dist/protocols/zai-chat.js +1 -1
- package/dist/protocols/zai-images.d.ts +2 -2
- package/dist/protocols/zai-messages.js +3 -3
- package/dist/provider-error.d.ts +0 -1
- package/dist/provider-error.js +7 -80
- package/dist/providers/alibaba/embeddings.d.ts +2 -0
- package/dist/providers/alibaba/embeddings.js +1 -0
- package/dist/providers/alibaba.d.ts +70 -4
- package/dist/providers/alibaba.js +20 -2
- package/dist/providers/amazon-bedrock-mantle.d.ts +7 -3
- package/dist/providers/amazon-bedrock-mantle.js +6 -3
- package/dist/providers/amazon-bedrock.d.ts +6 -7
- package/dist/providers/amazon-bedrock.js +1 -1
- package/dist/providers/anthropic-compatible.d.ts +7 -8
- package/dist/providers/anthropic-compatible.js +2 -5
- package/dist/providers/anthropic.d.ts +8 -9
- package/dist/providers/anthropic.js +2 -7
- package/dist/providers/assemblyai.d.ts +2 -2
- package/dist/providers/assemblyai.js +2 -7
- package/dist/providers/azure/embeddings.d.ts +2 -0
- package/dist/providers/azure/embeddings.js +1 -0
- package/dist/providers/azure/messages.d.ts +2 -0
- package/dist/providers/azure/messages.js +1 -0
- package/dist/providers/azure.d.ts +325 -7
- package/dist/providers/azure.js +40 -9
- package/dist/providers/baseten.d.ts +7 -5
- package/dist/providers/baseten.js +7 -21
- package/dist/providers/cartesia.d.ts +1 -1
- package/dist/providers/cerebras.d.ts +7 -5
- package/dist/providers/cerebras.js +4 -15
- package/dist/providers/cloudflare-ai-gateway.d.ts +23 -13
- package/dist/providers/cloudflare-ai-gateway.js +28 -40
- package/dist/providers/cloudflare-shared.d.ts +9 -0
- package/dist/providers/cloudflare-shared.js +25 -0
- package/dist/providers/cloudflare-workers-ai.d.ts +6 -4
- package/dist/providers/cloudflare-workers-ai.js +4 -20
- package/dist/providers/cohere/chat.js +2 -7
- package/dist/providers/cohere/embeddings.d.ts +2 -0
- package/dist/providers/cohere/embeddings.js +1 -0
- package/dist/providers/cohere.d.ts +14 -5
- package/dist/providers/cohere.js +23 -13
- package/dist/providers/deepgram.d.ts +2 -2
- package/dist/providers/deepgram.js +2 -7
- package/dist/providers/deepinfra/embeddings.d.ts +2 -0
- package/dist/providers/deepinfra/embeddings.js +1 -0
- package/dist/providers/deepinfra.d.ts +10 -5
- package/dist/providers/deepinfra.js +20 -14
- package/dist/providers/deepseek.d.ts +7 -5
- package/dist/providers/deepseek.js +3 -14
- package/dist/providers/digitalocean/embeddings.d.ts +2 -0
- package/dist/providers/digitalocean/embeddings.js +1 -0
- package/dist/providers/digitalocean.d.ts +18 -5
- package/dist/providers/digitalocean.js +28 -14
- package/dist/providers/elevenlabs.d.ts +2 -2
- package/dist/providers/elevenlabs.js +2 -7
- package/dist/providers/fireworks/embeddings.d.ts +2 -0
- package/dist/providers/fireworks/embeddings.js +1 -0
- package/dist/providers/fireworks.d.ts +10 -5
- package/dist/providers/fireworks.js +17 -14
- package/dist/providers/google/embeddings.d.ts +2 -0
- package/dist/providers/google/embeddings.js +1 -0
- package/dist/providers/google/interactions.d.ts +1 -1
- package/dist/providers/google/interactions.js +2 -7
- package/dist/providers/google-vertex/embeddings.d.ts +2 -0
- package/dist/providers/google-vertex/embeddings.js +1 -0
- package/dist/providers/google-vertex-chat.d.ts +4 -3
- package/dist/providers/google-vertex-chat.js +3 -29
- package/dist/providers/google-vertex-interactions.d.ts +3 -3
- package/dist/providers/google-vertex-messages.d.ts +3 -3
- package/dist/providers/google-vertex-messages.js +3 -29
- package/dist/providers/google-vertex-mistral.d.ts +3 -3
- package/dist/providers/google-vertex-mistral.js +3 -29
- package/dist/providers/google-vertex-responses.d.ts +3 -3
- package/dist/providers/google-vertex-responses.js +4 -30
- package/dist/providers/google-vertex-shared.d.ts +31 -0
- package/dist/providers/google-vertex-shared.js +25 -0
- package/dist/providers/google-vertex.d.ts +10 -3
- package/dist/providers/google-vertex.js +52 -0
- package/dist/providers/google.d.ts +21 -13
- package/dist/providers/google.js +23 -19
- package/dist/providers/groq.d.ts +10 -5
- package/dist/providers/groq.js +4 -15
- package/dist/providers/meta.d.ts +6 -5
- package/dist/providers/meta.js +10 -23
- package/dist/providers/minimax/chat.js +2 -7
- package/dist/providers/minimax/responses.js +2 -7
- package/dist/providers/minimax.d.ts +6 -5
- package/dist/providers/minimax.js +7 -22
- package/dist/providers/mistral.d.ts +10 -11
- package/dist/providers/mistral.js +3 -14
- package/dist/providers/moonshot/messages.js +2 -7
- package/dist/providers/moonshot/responses.js +2 -7
- package/dist/providers/moonshot.d.ts +6 -5
- package/dist/providers/moonshot.js +4 -16
- package/dist/providers/openai/embeddings.d.ts +2 -0
- package/dist/providers/openai/embeddings.js +1 -0
- package/dist/providers/openai-compatible/embeddings.d.ts +2 -0
- package/dist/providers/openai-compatible/embeddings.js +1 -0
- package/dist/providers/openai-compatible-responses.d.ts +6 -7
- package/dist/providers/openai-compatible-responses.js +2 -8
- package/dist/providers/openai-compatible.d.ts +10 -7
- package/dist/providers/openai-compatible.js +17 -10
- package/dist/providers/openai.d.ts +11 -4
- package/dist/providers/openai.js +17 -3
- package/dist/providers/opencode.d.ts +4 -4
- package/dist/providers/opencode.js +6 -2
- package/dist/providers/openrouter/embeddings.d.ts +2 -0
- package/dist/providers/openrouter/embeddings.js +1 -0
- package/dist/providers/openrouter.d.ts +24 -5
- package/dist/providers/openrouter.js +31 -24
- package/dist/providers/runway.d.ts +1 -1
- package/dist/providers/settings.d.ts +40 -0
- package/dist/providers/settings.js +19 -0
- package/dist/providers/togetherai.d.ts +7 -5
- package/dist/providers/togetherai.js +5 -15
- package/dist/providers/typesafe-ai.d.ts +4 -4
- package/dist/providers/typesafe-ai.js +6 -2
- package/dist/providers/venice.d.ts +5 -4
- package/dist/providers/venice.js +6 -2
- package/dist/providers/vercel-ai-gateway/embeddings.d.ts +2 -0
- package/dist/providers/vercel-ai-gateway/embeddings.js +1 -0
- package/dist/providers/vercel-ai-gateway.d.ts +9 -5
- package/dist/providers/vercel-ai-gateway.js +30 -29
- package/dist/providers/xai.d.ts +5 -4
- package/dist/providers/xai.js +4 -12
- package/dist/providers/zai-coding-plan/messages.js +2 -7
- package/dist/providers/zai-coding-plan/responses.js +2 -7
- package/dist/providers/zai-coding-plan.d.ts +6 -5
- package/dist/providers/zai-coding-plan.js +8 -15
- package/dist/providers/zai.d.ts +6 -5
- package/dist/providers/zai.js +10 -22
- package/dist/public.d.ts +14 -0
- package/dist/public.js +6 -0
- package/dist/route/auth-options.d.ts +9 -5
- package/dist/route/auth-options.js +10 -7
- package/dist/route/client.d.ts +50 -37
- package/dist/route/client.js +42 -53
- package/dist/route/decision.d.ts +8 -8
- package/dist/route/decision.js +3 -3
- package/dist/route/embedding.d.ts +61 -0
- package/dist/route/embedding.js +88 -0
- package/dist/route/executor.d.ts +5 -0
- package/dist/route/executor.js +10 -0
- package/dist/route/index.d.ts +5 -7
- package/dist/route/index.js +1 -1
- package/dist/route/media.d.ts +7 -11
- package/dist/route/media.js +22 -26
- package/dist/route/transport/http.js +6 -5
- package/dist/route/transport/websocket.js +7 -1
- package/dist/schema/errors.d.ts +16 -17
- package/dist/schema/errors.js +63 -12
- package/dist/schema/events.d.ts +2563 -2954
- package/dist/schema/events.js +54 -109
- package/dist/schema/messages.d.ts +194 -137
- package/dist/schema/messages.js +66 -83
- package/dist/schema/options.d.ts +112 -65
- package/dist/schema/options.js +52 -101
- package/dist/speech-client.d.ts +7 -7
- package/dist/speech.d.ts +306 -316
- package/dist/speech.js +16 -14
- package/dist/testing.d.ts +31 -175
- package/dist/testing.js +60 -5
- package/dist/tool-history.d.ts +1 -1
- package/dist/tool-history.js +3 -10
- package/dist/tool-runtime.d.ts +9 -2
- package/dist/tool-runtime.js +17 -31
- package/dist/tool.d.ts +39 -43
- package/dist/tool.js +16 -26
- package/dist/transcription-client.d.ts +7 -7
- package/dist/transcription.d.ts +314 -265
- package/dist/transcription.js +16 -14
- package/dist/utils/provider-codes.d.ts +3 -0
- package/dist/utils/provider-codes.js +41 -0
- package/dist/video-client.d.ts +7 -7
- package/dist/video-client.js +1 -1
- package/dist/video.d.ts +269 -287
- package/dist/video.js +16 -14
- package/package.json +309 -257
- package/dist/experimental/testing.d.ts +0 -3
- package/dist/experimental/testing.js +0 -3
- package/dist/testing/decision.d.ts +0 -16
- package/dist/testing/decision.js +0 -20
- package/dist/testing/image.d.ts +0 -14
- package/dist/testing/image.js +0 -12
- package/dist/testing/media.d.ts +0 -18
- package/dist/testing/media.js +0 -36
- package/dist/testing/script.d.ts +0 -28
- package/dist/testing/script.js +0 -60
- package/dist/testing/speech.d.ts +0 -14
- package/dist/testing/speech.js +0 -12
- package/dist/testing/transcription.d.ts +0 -14
- package/dist/testing/transcription.js +0 -12
- package/dist/testing/video.d.ts +0 -14
- package/dist/testing/video.js +0 -12
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @opencode/ai
|
|
2
2
|
|
|
3
|
-
Schema-first APIs for text, images, and
|
|
3
|
+
Schema-first APIs for text, images, decisions, and embeddings, built with Effect. Video, speech, transcription, extraction, and
|
|
4
4
|
realtime voice are [experimental](#experimental).
|
|
5
5
|
|
|
6
6
|
`@opencode/ai` is the Promise API: one managed runtime behind the LLM and media methods, plus asset helpers. `ai.file`
|
|
@@ -16,7 +16,7 @@ const input = { model: openai.responses("gpt-4o-mini"), prompt: "Say hello." }
|
|
|
16
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
|
-
await ai.write(generated.
|
|
19
|
+
await ai.write(generated.images[0], "./lighthouse.png") // also ai.file(path), ai.bytes(asset), ai.base64(asset), ai.materialize(asset)
|
|
20
20
|
for await (const event of ai.stream(ai.request(input))) {
|
|
21
21
|
// LLMEvent
|
|
22
22
|
}
|
|
@@ -37,7 +37,7 @@ const program = Effect.gen(function* () {
|
|
|
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.",
|
|
40
|
-
|
|
40
|
+
maxTokens: 40,
|
|
41
41
|
})
|
|
42
42
|
console.log(response.text)
|
|
43
43
|
})
|
|
@@ -47,17 +47,26 @@ await Effect.runPromise(program.pipe(Effect.provide(AIClient.layer)))
|
|
|
47
47
|
```
|
|
48
48
|
|
|
49
49
|
Run `ai.stream(...)` instead of `generate` when you want incremental `LLMEvent`s. Both accept input or a prebuilt
|
|
50
|
-
`ai.request(...)`.
|
|
50
|
+
`ai.request(...)`. Input takes either `prompt`, a single user message, or `messages`, the whole conversation, never
|
|
51
|
+
both; `system` goes with either. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses,
|
|
51
52
|
Anthropic Messages, Gemini, Bedrock Converse, and any OpenAI-compatible deployment.
|
|
52
53
|
|
|
53
54
|
### Tool loop
|
|
54
55
|
|
|
55
56
|
`stream` runs one model call; `loop` runs the model's tool calls and calls the model again until it stops calling
|
|
56
|
-
tools. Events from every step arrive on one stream, with a `tool-result` after each tool runs
|
|
57
|
+
tools. Events from every step arrive on one stream, with a `tool-result` after each tool runs (an error result when
|
|
58
|
+
it fails). Each step ends with its own `step-finish`; one `finish` ends the loop, carrying the final step's reason
|
|
59
|
+
and the usage summed across steps. `until` is checked
|
|
57
60
|
after each step that has tool calls, with every step's `LLMResponse`; returning `true` ends the loop without running
|
|
58
|
-
them.
|
|
59
|
-
`
|
|
60
|
-
|
|
61
|
+
them. Tools are an array, sent in the order given so the provider can reuse its cached prompt prefix. Each tool has a
|
|
62
|
+
`name`, and two tools with the same name fail the request. Tool arguments that are not valid JSON go back to the model
|
|
63
|
+
as an error result so it can retry. A step that hits the output token limit ends the loop without running its tool
|
|
64
|
+
calls, which may be cut off. A forced `toolChoice` applies to the first step only; later steps use `auto`. `tool` takes
|
|
65
|
+
a plain `async` execute; a throw or rejection goes back to the model as an error result, and `signal` aborts when the
|
|
66
|
+
loop is interrupted.
|
|
67
|
+
`input` is an Effect Schema that decodes and types the arguments, or a raw JSON Schema object, such as an MCP tool's,
|
|
68
|
+
whose arguments arrive as `unknown` (pair it with an optional JSON Schema `outputSchema`). `tool` from
|
|
69
|
+
`@opencode/ai/effect` takes the same options (including an optional `success` schema) with an Effect execute:
|
|
61
70
|
|
|
62
71
|
```ts
|
|
63
72
|
import { readFile } from "node:fs/promises"
|
|
@@ -65,15 +74,16 @@ import { Schema } from "effect"
|
|
|
65
74
|
import { ai, tool } from "@opencode/ai"
|
|
66
75
|
|
|
67
76
|
const read_file = tool({
|
|
77
|
+
name: "read_file",
|
|
68
78
|
description: "Read a UTF-8 file.",
|
|
69
|
-
|
|
79
|
+
input: Schema.Struct({ path: Schema.String }),
|
|
70
80
|
execute: ({ path }, { signal }) => readFile(path, { encoding: "utf8", signal }),
|
|
71
81
|
})
|
|
72
82
|
|
|
73
83
|
const events = ai.loop({
|
|
74
84
|
model,
|
|
75
85
|
prompt: "Summarize package.json.",
|
|
76
|
-
tools:
|
|
86
|
+
tools: [read_file],
|
|
77
87
|
until: ({ steps }) => steps.length >= 8,
|
|
78
88
|
})
|
|
79
89
|
for await (const event of events) {
|
|
@@ -81,6 +91,17 @@ for await (const event of events) {
|
|
|
81
91
|
}
|
|
82
92
|
```
|
|
83
93
|
|
|
94
|
+
The terminal `finish` carries the final assistant `message` and `usage`. To skip the events, `ai.collect` folds a
|
|
95
|
+
stream from `stream` or `loop` into one result: `text` of the final step, `steps` (one `LLMResponse` per call),
|
|
96
|
+
`messages` (each step's assistant message and its tool results, ready to append to the next request), the total
|
|
97
|
+
`usage`, `finishReason`, and `object` with `schema`.
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
const result = await ai.collect(ai.loop({ model, prompt: "Summarize package.json.", tools: { read_file } }))
|
|
101
|
+
// Effect: const result = yield* ai.collect(ai.loop({ ... }))
|
|
102
|
+
console.log(result.text, result.usage?.totalTokens)
|
|
103
|
+
```
|
|
104
|
+
|
|
84
105
|
### Freeform tools
|
|
85
106
|
|
|
86
107
|
A tool with exactly one required string parameter can set `freeform`, so the model writes that parameter as raw text
|
|
@@ -88,8 +109,9 @@ instead of JSON arguments: unconstrained `text`, or text matching a `regex` or `
|
|
|
88
109
|
|
|
89
110
|
```ts
|
|
90
111
|
const run_code = tool({
|
|
112
|
+
name: "run_code",
|
|
91
113
|
description: "Run JavaScript",
|
|
92
|
-
|
|
114
|
+
input: Schema.Struct({ code: Schema.String }),
|
|
93
115
|
freeform: { type: "lark", grammar: JS_GRAMMAR },
|
|
94
116
|
execute: ({ code }) => runCode(code),
|
|
95
117
|
})
|
|
@@ -104,35 +126,57 @@ history works with or without `freeform`.
|
|
|
104
126
|
|
|
105
127
|
### Structured output
|
|
106
128
|
|
|
107
|
-
`
|
|
108
|
-
unvalidated `unknown` object:
|
|
129
|
+
Pass `schema` to `generate`, `stream` or `loop`. The model must answer through a hidden tool call, decoded into
|
|
130
|
+
`object` (typed from an Effect Schema, or an unvalidated `unknown` for a raw JSON Schema object):
|
|
109
131
|
|
|
110
132
|
```ts
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
133
|
+
const res = await ai.generate({ model, prompt: "Pick a city.", schema: Schema.Struct({ city: Schema.String }) })
|
|
134
|
+
res.object.city
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`stream` puts `object` on its `finish` event; `loop` runs tools first and puts it on the loop's `finish`. A
|
|
138
|
+
decode failure is an `AIError` whose `partial` holds the response.
|
|
139
|
+
|
|
140
|
+
### Errors
|
|
141
|
+
|
|
142
|
+
Every failure is an `AIError`. `reason._tag` names the kind (`RateLimit`, `InvalidRequest`, `Transport`, ...), and
|
|
143
|
+
getters read the common fields without digging into `reason` or the raw body:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
try {
|
|
147
|
+
await ai.generate({ model, prompt: "Hi" })
|
|
148
|
+
} catch (error) {
|
|
149
|
+
if (!(error instanceof AIError)) throw error
|
|
150
|
+
error.status // HTTP status, when the failure came from a response
|
|
151
|
+
error.code // provider error code such as "model_not_found", when known
|
|
152
|
+
error.isRetryable // whether sending the same request again may succeed
|
|
153
|
+
error.retryAfterMs // delay the provider asked for, when known
|
|
154
|
+
}
|
|
116
155
|
```
|
|
117
156
|
|
|
118
157
|
### Raw provider events
|
|
119
158
|
|
|
120
159
|
Set `includeRaw: true` on a request to also receive every provider frame as `{ type: "raw", data }`, in order and
|
|
121
160
|
before the events parsed from that frame. `data` is the parsed JSON frame, so frames this package doesn't handle yet
|
|
122
|
-
are visible too. Raw events are off by default, and `generate` ignores them.
|
|
161
|
+
are visible too. Raw events are off by default, and `generate` ignores them. `RawEvent` is the event's type. Act on a
|
|
162
|
+
frame with a stream map:
|
|
123
163
|
|
|
124
164
|
```ts
|
|
125
|
-
import { Stream } from "effect"
|
|
126
|
-
import { ai,
|
|
165
|
+
import { Effect, Stream } from "effect"
|
|
166
|
+
import { ai, AIError, ContentPolicyError } from "@opencode/ai/effect"
|
|
127
167
|
|
|
128
168
|
const flagged = (data: unknown) =>
|
|
129
169
|
typeof data === "object" && data !== null && "type" in data && data.type === "moderation.flagged"
|
|
130
170
|
|
|
131
|
-
const events = ai
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
)
|
|
171
|
+
const events = ai
|
|
172
|
+
.stream({ model, prompt: "Say hello.", includeRaw: true })
|
|
173
|
+
.pipe(
|
|
174
|
+
Stream.mapEffect((event) =>
|
|
175
|
+
event.type === "raw" && flagged(event.data)
|
|
176
|
+
? Effect.fail(new AIError({ reason: new ContentPolicyError({ message: "Flagged by moderation" }) }))
|
|
177
|
+
: Effect.succeed(event),
|
|
178
|
+
),
|
|
179
|
+
)
|
|
136
180
|
```
|
|
137
181
|
|
|
138
182
|
### Google Interactions
|
|
@@ -147,11 +191,13 @@ live under `providerMetadata.vertex`. The default is still full-history replay w
|
|
|
147
191
|
|
|
148
192
|
```ts
|
|
149
193
|
const model = Google.configure({ apiKey }).interactions("gemini-3.8-flash")
|
|
150
|
-
const response =
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
194
|
+
const response =
|
|
195
|
+
yield *
|
|
196
|
+
ai.generate({
|
|
197
|
+
model,
|
|
198
|
+
prompt: "Say hello.",
|
|
199
|
+
providerOptions: { thinkingLevel: "low", thinkingSummaries: "auto", store: true },
|
|
200
|
+
})
|
|
155
201
|
```
|
|
156
202
|
|
|
157
203
|
Interactions supports text output, streamed function calls, native tool results, thought signatures, and multimodal
|
|
@@ -180,7 +226,7 @@ const image = Effect.gen(function* () {
|
|
|
180
226
|
resolution: "1K",
|
|
181
227
|
providerOptions: { quality: "high" }, // typed per image model
|
|
182
228
|
})
|
|
183
|
-
yield* Media.write(response.
|
|
229
|
+
yield* Media.write(response.images[0], "./garden.png")
|
|
184
230
|
})
|
|
185
231
|
|
|
186
232
|
// `Media.file` / `Media.write` use the Effect `FileSystem` service; provide your platform's layer.
|
|
@@ -276,6 +322,8 @@ const [refund, department] = response.answers
|
|
|
276
322
|
```
|
|
277
323
|
|
|
278
324
|
`input` is a JSON object or an ordered list of `text`, `json` and `media` parts. Answers come back in question order.
|
|
325
|
+
A `predicate` can say what counts as true and as false with `criteria: { true, false }`; hosts without a criteria field
|
|
326
|
+
read them appended to the instructions.
|
|
279
327
|
A question the host declines is `{ name, type: "error", reason, message? }`, with `reason` such as `"refusal"`; the
|
|
280
328
|
other answers still come back.
|
|
281
329
|
`response.usage` has `inputTokens`, `outputTokens`, `totalTokens` and the host's reported `cost` when it sends one;
|
|
@@ -309,6 +357,95 @@ CloudflareAIGateway.configure({ accountId }).decision("typesafe/jev")
|
|
|
309
357
|
OpenAI and Vercel AI Gateway use OpenAI's `/v1/decisions` API. TypeSafe, OpenCode, OpenRouter, Baseten and
|
|
310
358
|
DigitalOcean use System One (`/systemone`), and Cloudflare sends the System One body through `/ai/run`.
|
|
311
359
|
|
|
360
|
+
## Embeddings
|
|
361
|
+
|
|
362
|
+
Embedding models turn each value into a vector, returned in value order.
|
|
363
|
+
|
|
364
|
+
```ts
|
|
365
|
+
import { ai } from "@opencode/ai"
|
|
366
|
+
import { OpenAI } from "@opencode/ai/providers"
|
|
367
|
+
|
|
368
|
+
const response = await ai.embedding.generate({
|
|
369
|
+
model: OpenAI.configure().embedding("text-embedding-3-small"),
|
|
370
|
+
values: ["I was charged twice.", "How do I reset my password?"],
|
|
371
|
+
dimensions: 256,
|
|
372
|
+
inputType: "document",
|
|
373
|
+
})
|
|
374
|
+
const [charge, password] = response.embeddings
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
A string value is text; media values are an `Asset` (or bytes or a URL) for hosts that embed images or documents.
|
|
378
|
+
`dimensions` asks models that can shorten their vectors for that length. `inputType` says whether the values are
|
|
379
|
+
search queries or stored documents; hosts with no such field (OpenAI's `/embeddings` API) ignore it, and host-specific
|
|
380
|
+
task types go in `providerOptions` (NVIDIA's `input_type: "passage"`). `response.usage.inputTokens` is the host's
|
|
381
|
+
token count, and its raw usage stays in `providerMetadata`. Media values fail the call on hosts that only embed text.
|
|
382
|
+
|
|
383
|
+
```ts
|
|
384
|
+
import {
|
|
385
|
+
Alibaba,
|
|
386
|
+
Azure,
|
|
387
|
+
Cohere,
|
|
388
|
+
DeepInfra,
|
|
389
|
+
DigitalOcean,
|
|
390
|
+
Fireworks,
|
|
391
|
+
OpenAICompatible,
|
|
392
|
+
OpenRouter,
|
|
393
|
+
VercelAIGateway,
|
|
394
|
+
} from "@opencode/ai/providers"
|
|
395
|
+
|
|
396
|
+
OpenRouter.configure().embedding("openai/text-embedding-3-small")
|
|
397
|
+
VercelAIGateway.configure().embedding("openai/text-embedding-3-small")
|
|
398
|
+
Cohere.configure().embedding("embed-v4.0")
|
|
399
|
+
DeepInfra.configure().embedding("BAAI/bge-m3")
|
|
400
|
+
Fireworks.configure().embedding("nomic-ai/nomic-embed-text-v1.5")
|
|
401
|
+
DigitalOcean.configure().embedding("bge-m3")
|
|
402
|
+
Alibaba.configure({ region: "ap-southeast-1" }).embedding("text-embedding-v4")
|
|
403
|
+
Azure.configure({ resourceName }).embedding("text-embedding-3-small")
|
|
404
|
+
OpenAICompatible.configure({ provider: "nvidia", baseURL: "https://integrate.api.nvidia.com/v1" }).embedding(
|
|
405
|
+
"nvidia/nemotron-3.5-embed-1b",
|
|
406
|
+
)
|
|
407
|
+
```
|
|
408
|
+
|
|
409
|
+
Every host here uses OpenAI's `/embeddings` API; Cohere through its compatibility API
|
|
410
|
+
(`https://api.cohere.ai/compatibility/v1`). Package entry points are `@opencode/ai/providers/<provider>/embeddings`.
|
|
411
|
+
|
|
412
|
+
Google embeds through `embedContent`, which also takes images, audio, video and PDFs on `gemini-embedding-2`. Each
|
|
413
|
+
value is its own content and gets its own vector (several parts in one content would be averaged into one). `dimensions`
|
|
414
|
+
is `outputDimensionality`, `inputType` becomes `taskType` `RETRIEVAL_QUERY` or `RETRIEVAL_DOCUMENT`, and `taskType` or
|
|
415
|
+
`title` in `providerOptions` replace or add to it. `gemini-embedding-2` ignores task types; Google recommends writing the
|
|
416
|
+
task into the text instead (`task: search result | query: …`, `title: none | text: …`).
|
|
417
|
+
|
|
418
|
+
```ts
|
|
419
|
+
import { Google, GoogleVertex } from "@opencode/ai/providers"
|
|
420
|
+
|
|
421
|
+
const response = await ai.embedding.generate({
|
|
422
|
+
model: Google.configure().embedding("gemini-embedding-2"),
|
|
423
|
+
values: [await ai.file("./receipt.png"), "A receipt for two coffees."],
|
|
424
|
+
dimensions: 768,
|
|
425
|
+
})
|
|
426
|
+
|
|
427
|
+
GoogleVertex.configure({ project, location: "global" }).embedding("gemini-embedding-2")
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
`GoogleVertex.configure().embedding(id)` picks the API from the model id: `gemini-embedding-2*` uses `embedContent`,
|
|
431
|
+
and every other model (`gemini-embedding-001`, `text-embedding-005`, `text-multilingual-embedding-002`) uses the
|
|
432
|
+
text-only `:predict` API, which also works with Express Mode keys. On `:predict`, `inputType` and the `taskType` and
|
|
433
|
+
`title` options go on each instance (`task_type`, `title`), and `dimensions`, `autoTruncate` and other options go under
|
|
434
|
+
`parameters`.
|
|
435
|
+
|
|
436
|
+
```ts
|
|
437
|
+
GoogleVertex.configure({ apiKey }).embedding("text-embedding-005")
|
|
438
|
+
GoogleVertex.configure({ apiKey }).embedding("gemini-embedding-001")
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
The Gemini API sends up to 100 values per `batchEmbedContents` request, and Vertex `:predict` up to 250 per request
|
|
442
|
+
(one for `gemini-embedding-001`, as Google documents). Vertex `embedContent` takes one value per request, so a call
|
|
443
|
+
sends one request per value, four at a time, and needs project credentials: Vertex Express Mode API keys can't call
|
|
444
|
+
`embedContent`. `gemini-embedding-2` runs in the `global`, `us` and `eu` Vertex locations. When a call
|
|
445
|
+
is split into several requests, the vectors stay in value order, `usage.inputTokens` is their sum, and each request's
|
|
446
|
+
metadata is listed in order under `providerMetadata.<provider>.responses`. The package entry points are
|
|
447
|
+
`@opencode/ai/providers/google/embeddings` and `@opencode/ai/providers/google-vertex/embeddings`.
|
|
448
|
+
|
|
312
449
|
## Alibaba Cloud Model Studio
|
|
313
450
|
|
|
314
451
|
`Alibaba` provides standard Model Studio inference. Configure a region explicitly, then select
|
|
@@ -363,7 +500,7 @@ shared host; the entry above follows the base URL table. Dedicated hosts can be
|
|
|
363
500
|
Replay complete `response.message` values to retain `reasoning_content` separately from answer text.
|
|
364
501
|
Qwen 3.8 defaults to preserving thinking; older models have different defaults.
|
|
365
502
|
Additional options include `toolStream`, `parallelToolCalls`, `repetitionPenalty`, `responseFormat`,
|
|
366
|
-
`enableSearch`, and native `searchOptions`. `
|
|
503
|
+
`enableSearch`, and native `searchOptions`. `topK` lowers to `top_k`.
|
|
367
504
|
`clearThinking` is a hosted GLM control, and `thinking.type` is available for hosted MiniMax models.
|
|
368
505
|
- **Messages:** `effort` → `output_config.effort`. `thinking.type` accepts enabled/disabled with an
|
|
369
506
|
optional `budgetTokens` (or native `budget_tokens`). `outputConfig.format` accepts a JSON schema.
|
|
@@ -532,7 +669,7 @@ const request = ai.request({
|
|
|
532
669
|
model: minimax.model("MiniMax-M3"), // also minimax.messages("MiniMax-M3")
|
|
533
670
|
prompt: "What is 173 multiplied by 219?",
|
|
534
671
|
providerOptions: { thinking: { type: "adaptive" } },
|
|
535
|
-
|
|
672
|
+
maxTokens: 1536,
|
|
536
673
|
})
|
|
537
674
|
|
|
538
675
|
const response = await Effect.runPromise(ai.generate(request).pipe(Effect.provide(AIClient.layer)))
|
|
@@ -570,7 +707,7 @@ const request = ai.request({
|
|
|
570
707
|
model: meta.responses("muse-spark-1.3"), // meta.model(...) also selects Responses
|
|
571
708
|
prompt: "What is 173 multiplied by 219? Reply with the integer.",
|
|
572
709
|
providerOptions: { reasoningEffort: "low" },
|
|
573
|
-
|
|
710
|
+
maxTokens: 1024,
|
|
574
711
|
})
|
|
575
712
|
```
|
|
576
713
|
|
|
@@ -592,7 +729,7 @@ Responses and Chat support only `toolChoice: "auto"` (the default). Messages als
|
|
|
592
729
|
its documented forced `"any"` choice currently returns HTTP 400. Messages defaults to adaptive thinking
|
|
593
730
|
with `display: "omitted"`, preserving encrypted `redacted_thinking` in `response.message`. Use
|
|
594
731
|
`providerOptions: { effort: "low" }` for depth or `thinking: { type: "enabled", budgetTokens: 1024 }`
|
|
595
|
-
for budget compatibility (with `
|
|
732
|
+
for budget compatibility (with `maxTokens > 1024`).
|
|
596
733
|
|
|
597
734
|
Add `tools: [Meta.webSearch()]` to a Spark Responses or Messages request for hosted web search.
|
|
598
735
|
Responses exposes hosted results and URL citations in text-part `providerMetadata.meta.annotations`.
|
|
@@ -666,18 +803,18 @@ Common fields are portable in shape, not in support. Some routes approximate `as
|
|
|
666
803
|
size they offer; others fail with a typed `AIError` before any network call rather than dropping them, so check this
|
|
667
804
|
table before swapping only the `model`:
|
|
668
805
|
|
|
669
|
-
| Provider | `n` | `aspect`
|
|
670
|
-
| --------------------- | --- |
|
|
671
|
-
| OpenAI | ✓¹ | nearest size
|
|
672
|
-
| Google (Gemini) | 1 | ✓
|
|
673
|
-
| xAI | ✓ | ✓
|
|
674
|
-
| Meta | ✓ | ✓ (hint)
|
|
675
|
-
| Z.ai | ✗ | width × height
|
|
676
|
-
| Alibaba | ✓ | width × height
|
|
677
|
-
| MiniMax | ✓ | preset or w × h⁴
|
|
678
|
-
| Vercel AI Gateway | ✓ | as OpenAI³
|
|
679
|
-
| OpenRouter | ✓ | ✓ (`aspect_ratio`)
|
|
680
|
-
| Cloudflare Workers AI | 1 | width × height²
|
|
806
|
+
| Provider | `n` | `aspect` | `resolution` | `images` | Moved to `providerOptions` |
|
|
807
|
+
| --------------------- | --- | ------------------ | ------------------- | -------------------- | ----------------------------------------- |
|
|
808
|
+
| OpenAI | ✓¹ | nearest size | nearest size | ✓ | `size`, `outputFormat`, `mask` |
|
|
809
|
+
| Google (Gemini) | 1 | ✓ | ✓ (`0.5K` as `512`) | ✓ (no public URLs) | `seed` |
|
|
810
|
+
| xAI | ✓ | ✓ | `1k`/`2k` | ✓ | none |
|
|
811
|
+
| Meta | ✓ | ✓ (hint) | ignored | ✓ | `size`, `outputFormat` |
|
|
812
|
+
| Z.ai | ✗ | width × height | width × height | ✗ | `size` |
|
|
813
|
+
| Alibaba | ✓ | width × height | width × height | ✓ | `size`, `seed` |
|
|
814
|
+
| MiniMax | ✓ | preset or w × h⁴ | preset or w × h⁴ | 1 (portrait subject) | `aspect_ratio`, `width`, `height`, `seed` |
|
|
815
|
+
| Vercel AI Gateway | ✓ | as OpenAI³ | as OpenAI³ | per model | as OpenAI |
|
|
816
|
+
| OpenRouter | ✓ | ✓ (`aspect_ratio`) | tier⁵ | per model⁵ | `size`, `outputFormat` (no `mask`) |
|
|
817
|
+
| Cloudflare Workers AI | 1 | width × height² | width × height² | ✗ | `width`, `height`, `seed` |
|
|
681
818
|
|
|
682
819
|
✓ lowers natively; ✗ fails whenever the field is set (including `n: 1`); `1` means `n > 1` fails. "width × height"
|
|
683
820
|
computes a size the provider accepts and fails when the request falls outside its limits. ¹ `ai.image.stream` on OpenAI
|
|
@@ -698,6 +835,20 @@ edits endpoint, so input images go to `/images/generations` as `input_references
|
|
|
698
835
|
asset into owned bytes before the provider URL expires. Construct assets with `Media.bytes`, `Media.base64`,
|
|
699
836
|
`Media.url`, `Media.ref(provider, id)`, `Media.fromDataUrl`, or `Media.file(path)`.
|
|
700
837
|
|
|
838
|
+
File inputs (message `media` parts, image `images`, decision `media` parts) also take plain data: a `Uint8Array`,
|
|
839
|
+
`ArrayBuffer`, `URL`, or a string holding a data URL, an http(s) URL or base64. Bytes and base64 are sniffed from
|
|
840
|
+
magic bytes; pass `mediaType` when that fails:
|
|
841
|
+
|
|
842
|
+
```ts
|
|
843
|
+
ai.request({
|
|
844
|
+
model,
|
|
845
|
+
prompt: [
|
|
846
|
+
{ type: "text", text: "Summarize this report" },
|
|
847
|
+
{ type: "media", media: pdfBase64, mediaType: "application/pdf" },
|
|
848
|
+
],
|
|
849
|
+
})
|
|
850
|
+
```
|
|
851
|
+
|
|
701
852
|
Pass ordered image inputs to the same method for editing, composition, or image-conditioned generation:
|
|
702
853
|
|
|
703
854
|
```ts
|
|
@@ -719,8 +870,8 @@ const composed = Effect.gen(function* () {
|
|
|
719
870
|
|
|
720
871
|
`Media.ref(provider, id)` represents provider file handles such as OpenAI file IDs or Gemini Files URIs; routes
|
|
721
872
|
only forward refs that belong to their own provider (OpenAI, xAI, and Gemini images accept them). No shipped route
|
|
722
|
-
returns a ref yet, and `asset.bytes()` / `materialize()` on a ref fail by design.
|
|
723
|
-
|
|
873
|
+
returns a ref yet, and `asset.bytes()` / `materialize()` on a ref fail by design. Empty or omitted `images` uses
|
|
874
|
+
text-to-image generation; a
|
|
724
875
|
non-empty array selects the provider's edit behavior (see the table above for routes that limit the count). OpenAI
|
|
725
876
|
uses multipart for byte/data-URL edits and its JSON reference body for URL or file-ID edits. Inpainting is a
|
|
726
877
|
provider option on the routes that support it (OpenAI):
|
|
@@ -848,11 +999,13 @@ and emits `image-partial` events before each final `image`; `ai.image.generate`
|
|
|
848
999
|
import { Stream } from "effect"
|
|
849
1000
|
import { ImageEvent } from "@opencode/ai/effect"
|
|
850
1001
|
|
|
851
|
-
const previews = ai.image
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
1002
|
+
const previews = ai.image
|
|
1003
|
+
.stream({
|
|
1004
|
+
model: openai.image("gpt-image-2"),
|
|
1005
|
+
prompt: "A lighthouse at dusk",
|
|
1006
|
+
providerOptions: { partialImages: 2 },
|
|
1007
|
+
})
|
|
1008
|
+
.pipe(Stream.runForEach((event) => (ImageEvent.is.imagePartial(event) ? showPreview(event.image) : Effect.void)))
|
|
856
1009
|
```
|
|
857
1010
|
|
|
858
1011
|
The provider may send fewer previews than requested when the final image is ready first.
|
|
@@ -882,9 +1035,10 @@ The hosted result is represented as a provider-executed tool call and a tool res
|
|
|
882
1035
|
|
|
883
1036
|
Everything below is exported from `@opencode/ai/effect` unless noted.
|
|
884
1037
|
|
|
885
|
-
- **`ai.request({...})`** — build a provider-neutral `LLMRequest
|
|
1038
|
+
- **`ai.request({...})`** — build a provider-neutral `LLMRequest`, a plain object. Accepts ergonomic inputs (`system: string`, `prompt: string`) and normalizes them into `system`, `messages` and `tools` arrays. Edit it with a spread, or pass the edited object back to `ai.request`.
|
|
886
1039
|
- **`ai.generate` / `ai.stream`** — run direct input or an `LLMRequest` through `LLMClient` for one-import use.
|
|
887
1040
|
- **`ai.loop`** — stream model calls, running `tool(...)` tools between them until the model stops calling tools.
|
|
1041
|
+
- **`ai.collect`** — fold a stream from `ai.stream` or `ai.loop` into its final result (`text`, `steps`, `messages`, `usage`).
|
|
888
1042
|
- **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
|
|
889
1043
|
- **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
|
|
890
1044
|
- **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
|
|
@@ -893,18 +1047,19 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
|
|
|
893
1047
|
- **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
|
|
894
1048
|
- **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
|
|
895
1049
|
- **`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.
|
|
1050
|
+
- **`ai.embedding.request` / `ai.embedding.generate`** — one vector per text or media value, with optional `dimensions` and `inputType`; `EmbeddingClient` is its Effect service and layer.
|
|
896
1051
|
- **`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`, `
|
|
1052
|
+
- **`@opencode/ai`** (Promise root) — a default `ai` with the text calls (`request`, `generate`, `stream`, `loop`, `compact`, `canCompact`) at the top level plus `image`, `decision` and `embedding` (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? })` builds a client over a custom executor. The same `ai` from `@opencode/ai/effect` returns `Effect` and `Stream`.
|
|
898
1053
|
- **`@opencode/ai/experimental`** — APIs that may change without compatibility guarantees: `Video`, `Speech`, `Transcription`, `Extraction`, and `Realtime`. See [Experimental](#experimental).
|
|
899
1054
|
|
|
900
1055
|
## Experimental
|
|
901
1056
|
|
|
902
1057
|
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
|
|
1058
|
+
and the Promise client exposes it under `ai.experimental`.
|
|
904
1059
|
|
|
905
1060
|
- **`Video`**, **`Speech`**, and **`Transcription`** — media generation and speech-to-text, with `VideoClient`,
|
|
906
1061
|
`SpeechClient`, and `TranscriptionClient` as their Effect services. Promise: `ai.experimental.video`, `.speech`, and
|
|
907
|
-
`.transcription`.
|
|
1062
|
+
`.transcription`.
|
|
908
1063
|
- **`Extraction`** — typed values read out of text.
|
|
909
1064
|
- **`Realtime`** — `Realtime.connect` starts an OpenAI, xAI, or Gemini voice session and returns a WebRTC answer SDP or
|
|
910
1065
|
a short-lived WebSocket URL and token.
|
|
@@ -1233,13 +1388,16 @@ For explicit compaction, script a `CompactionResponse` through `push`, `always`,
|
|
|
1233
1388
|
|
|
1234
1389
|
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.
|
|
1235
1390
|
|
|
1236
|
-
|
|
1391
|
+
Response helpers build common event arrays: `TestLLM.text(value, id)`, `textWithUsage(value, id, inputTokens)`,
|
|
1392
|
+
`toolCall(id, name, input)`, `stop(...events)`, `toolCalls(...events)`, and
|
|
1393
|
+
`complete({ reason, usage?, providerMetadata? }, ...events)`. `failAfter(error, ...events)` and `hangAfter(...events)`
|
|
1394
|
+
return streams that fail or never finish after the given events.
|
|
1237
1395
|
|
|
1238
|
-
|
|
1396
|
+
`compileRequest`, also from `@opencode/ai/testing`, compiles an `LLMRequest` through its route without sending it, so
|
|
1397
|
+
tests can assert the provider payload.
|
|
1239
1398
|
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
`testLayer`.
|
|
1399
|
+
Other modalities and the Promise client have no test double. Test them over a custom executor layer, such as
|
|
1400
|
+
`AI.make({ layer })`, that answers the HTTP requests.
|
|
1243
1401
|
|
|
1244
1402
|
## Provider compaction
|
|
1245
1403
|
|
|
@@ -1256,9 +1414,7 @@ Prefer this operation, where supported, when the application owns compaction pol
|
|
|
1256
1414
|
```ts
|
|
1257
1415
|
const compacted = Effect.gen(function* () {
|
|
1258
1416
|
const result = yield* ai.compact(request)
|
|
1259
|
-
const next =
|
|
1260
|
-
messages: result.replacement,
|
|
1261
|
-
})
|
|
1417
|
+
const next = { ...request, messages: result.replacement }
|
|
1262
1418
|
return yield* ai.generate(next)
|
|
1263
1419
|
})
|
|
1264
1420
|
```
|
|
@@ -1318,7 +1474,7 @@ Enable OpenAI compaction with typed provider options:
|
|
|
1318
1474
|
|
|
1319
1475
|
```ts
|
|
1320
1476
|
import { Effect } from "effect"
|
|
1321
|
-
import { ai, LLMClient,
|
|
1477
|
+
import { ai, LLMClient, Message } from "@opencode/ai/effect"
|
|
1322
1478
|
import { OpenAI } from "@opencode/ai/providers"
|
|
1323
1479
|
|
|
1324
1480
|
const request = ai.request({
|
|
@@ -1330,9 +1486,7 @@ const request = ai.request({
|
|
|
1330
1486
|
})
|
|
1331
1487
|
const continued = Effect.gen(function* () {
|
|
1332
1488
|
const response = yield* LLMClient.generate(request)
|
|
1333
|
-
return
|
|
1334
|
-
messages: [...request.messages, response.message, Message.user("Continue")],
|
|
1335
|
-
})
|
|
1489
|
+
return { ...request, messages: [...request.messages, response.message, Message.user("Continue")] }
|
|
1336
1490
|
})
|
|
1337
1491
|
```
|
|
1338
1492
|
|
|
@@ -1476,6 +1630,8 @@ const gateway = CloudflareAIGateway.configure({
|
|
|
1476
1630
|
}).model("workers-ai/@cf/meta/llama-3.1-8b-instruct")
|
|
1477
1631
|
```
|
|
1478
1632
|
|
|
1633
|
+
For a provider that needs no key, such as a local server, pass `apiKey: false`: the package skips the environment lookup and sends no auth header (Amazon Bedrock and Google Vertex keep their own auth).
|
|
1634
|
+
|
|
1479
1635
|
Included LLM providers: OpenAI, Anthropic, Google (Gemini), Google Vertex, Amazon Bedrock (Converse and Mantle), Azure OpenAI, Alibaba, Baseten, Cerebras, Cohere, Cloudflare AI Gateway, Cloudflare Workers AI, DeepInfra, DeepSeek, DigitalOcean, Fireworks, Groq, Meta, MiniMax, Mistral, Moonshot, OpenRouter, TogetherAI, Venice, Vercel AI Gateway, xAI, Z.ai, and Z.ai Coding Plan. TypeSafe AI and OpenCode expose decision models only. Generic Chat Completions, Responses, and Anthropic Messages-compatible entrypoints support custom endpoints.
|
|
1480
1636
|
|
|
1481
1637
|
Each named provider owns its module, endpoint, authentication, and route setup. Providers with the same wire format compose the shared protocol directly:
|
|
@@ -1556,7 +1712,7 @@ Additional provider entrypoints include:
|
|
|
1556
1712
|
|
|
1557
1713
|
Request options in order of stability:
|
|
1558
1714
|
|
|
1559
|
-
1.
|
|
1715
|
+
1. **Portable knobs** — `maxTokens`, `temperature`, `topP`, `topK`, `frequencyPenalty`, `presencePenalty`, `seed` and `stop`, at the top level of a text request. `GENERATION_KEYS` lists them.
|
|
1560
1716
|
2. **`promptCacheKey`** — stable cache affinity lowered by every protocol that supports it.
|
|
1561
1717
|
3. **`providerOptions: { ... }`** — flat options inferred from the selected model (OpenAI `store`, Anthropic `thinking`, Gemini `thinkingConfig`, OpenRouter routing).
|
|
1562
1718
|
4. **`http: { body, headers, query }`** — last-resort serializable overlays merged into the final HTTP request. Reach for this only when a stable typed path doesn't yet exist.
|
package/dist/ai-client.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { Layer } from "effect";
|
|
2
2
|
import { RequestExecutor } from "./route/executor.js";
|
|
3
3
|
/** Every modality client over `executor`, which stays in the output so `asset.bytes()` and `Media.write` resolve. */
|
|
4
|
-
export declare const layerWith: <E, R>(executor: Layer.Layer<RequestExecutor.Service, E, R>) => Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, E, R>;
|
|
4
|
+
export declare const layerWith: <E, R>(executor: Layer.Layer<RequestExecutor.Service, E, R>) => Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./embedding-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, E, R>;
|
|
5
5
|
/** Every modality client plus the executor over `RequestExecutor.fetchLayer`: the one layer most programs need. */
|
|
6
|
-
export declare const layer: Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, never, never>;
|
|
6
|
+
export declare const layer: Layer.Layer<import("./image-client.js").ImageClientService | import("./route/client.js").LLMClientService | RequestExecutor.RequestExecutorService | import("./decision-client.js").Service | import("./embedding-client.js").Service | import("./speech-client.js").SpeechClientService | import("./transcription-client.js").TranscriptionClientService | import("./video-client.js").VideoClientService, never, never>;
|
|
7
7
|
export type Services = Layer.Success<typeof layer>;
|
|
8
8
|
export * as AIClient from "./ai-client.js";
|
package/dist/ai-client.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Layer } from "effect";
|
|
2
2
|
import { DecisionClient } from "./decision-client.js";
|
|
3
|
+
import { EmbeddingClient } from "./embedding-client.js";
|
|
3
4
|
import { ImageClient } from "./image-client.js";
|
|
4
5
|
import { LLMClient } from "./route/client.js";
|
|
5
6
|
import { RequestExecutor } from "./route/executor.js";
|
|
@@ -7,7 +8,7 @@ import { SpeechClient } from "./speech-client.js";
|
|
|
7
8
|
import { TranscriptionClient } from "./transcription-client.js";
|
|
8
9
|
import { VideoClient } from "./video-client.js";
|
|
9
10
|
/** Every modality client over `executor`, which stays in the output so `asset.bytes()` and `Media.write` resolve. */
|
|
10
|
-
export const layerWith = (executor) => Layer.mergeAll(LLMClient.layer, ImageClient.layer, VideoClient.layer, SpeechClient.layer, TranscriptionClient.layer, DecisionClient.layer).pipe(Layer.provideMerge(executor));
|
|
11
|
+
export const layerWith = (executor) => Layer.mergeAll(LLMClient.layer, ImageClient.layer, VideoClient.layer, SpeechClient.layer, TranscriptionClient.layer, DecisionClient.layer, EmbeddingClient.layer).pipe(Layer.provideMerge(executor));
|
|
11
12
|
/** Every modality client plus the executor over `RequestExecutor.fetchLayer`: the one layer most programs need. */
|
|
12
13
|
export const layer = layerWith(RequestExecutor.fetchLayer);
|
|
13
14
|
export * as AIClient from "./ai-client.js";
|
package/dist/cache-policy.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { LLMRequest } from "./schema/messages.js";
|
|
1
|
+
import { type LLMRequest } from "./schema/messages.js";
|
|
2
2
|
/** The requested cache lifetime, for routes that send it as a request-level option instead of on markers. */
|
|
3
3
|
export declare const requestTTL: (request: LLMRequest) => `${number}d` | `${number}h` | `${number}m` | `${number}ms` | `${number}s` | undefined;
|
|
4
4
|
export declare const applyCachePolicy: (request: LLMRequest) => LLMRequest;
|
package/dist/cache-policy.js
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
// Manual `cache: CacheHint` placements on individual parts are preserved and
|
|
12
12
|
// count against the four-breakpoint budget; auto only fills remaining slots.
|
|
13
13
|
import { CacheHint } from "./schema/options.js";
|
|
14
|
-
import {
|
|
14
|
+
import { AssistantMessage, SystemMessage, ToolDefinition, ToolMessage, UserMessage, } from "./schema/messages.js";
|
|
15
15
|
import { effortUpdate } from "./effort-updates.js";
|
|
16
16
|
const AUTO = {
|
|
17
17
|
tools: true,
|
|
@@ -119,8 +119,7 @@ const markMessageAt = (messages, index, hint, budget) => {
|
|
|
119
119
|
if (!existing || !isCacheablePart(existing) || existing.cache || budget.remaining === 0)
|
|
120
120
|
return messages;
|
|
121
121
|
budget.remaining -= 1;
|
|
122
|
-
const
|
|
123
|
-
const next = new Message({ ...target, content: nextContent });
|
|
122
|
+
const next = cachePartAt(target, markAt, hint);
|
|
124
123
|
// Single pass over `messages`, substituting the one updated entry. Long
|
|
125
124
|
// conversations call this on every request, so avoid `.map()` here — its
|
|
126
125
|
// closure dispatch and identity copies show up in profiling.
|
|
@@ -128,6 +127,19 @@ const markMessageAt = (messages, index, hint, budget) => {
|
|
|
128
127
|
result[index] = next;
|
|
129
128
|
return result;
|
|
130
129
|
};
|
|
130
|
+
const cachePartAt = (message, index, hint) => {
|
|
131
|
+
switch (message.role) {
|
|
132
|
+
case "system":
|
|
133
|
+
return new SystemMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
|
|
134
|
+
case "user":
|
|
135
|
+
return new UserMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
|
|
136
|
+
case "assistant":
|
|
137
|
+
return new AssistantMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
|
|
138
|
+
case "tool":
|
|
139
|
+
return new ToolMessage({ ...message, content: cacheContentAt(message.content, index, hint) });
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
const cacheContentAt = (content, index, hint) => content.map((part, i) => (i === index ? { ...part, cache: hint } : part));
|
|
131
143
|
const markMessages = (messages, strategy, hint, budget) => {
|
|
132
144
|
if (messages.length === 0)
|
|
133
145
|
return messages;
|
|
@@ -163,7 +175,7 @@ export const applyCachePolicy = (request) => {
|
|
|
163
175
|
const messages = policy.messages ? markMessages(request.messages, policy.messages, hint, budget) : request.messages;
|
|
164
176
|
if (tools === request.tools && system === request.system && messages === request.messages)
|
|
165
177
|
return request;
|
|
166
|
-
return
|
|
178
|
+
return { ...request, tools, system, messages };
|
|
167
179
|
};
|
|
168
180
|
/** Whether the cache policy places inline markers, which then carry the requested lifetime. */
|
|
169
181
|
export const placesMarkers = (request) => {
|