Skip to content

Commit 416916e

Browse files
authored
feat(ai): one job shape for image, video and transcription (#68209)
1 parent c7f831b commit 416916e

44 files changed

Lines changed: 633 additions & 740 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/ai/README.md‎

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1180,17 +1180,21 @@ every image model today all four fail with an `UnsupportedOperation` reason befo
11801180
```ts
11811181
const program = Effect.gen(function* () {
11821182
const job = yield* ai.image.start({ model, prompt: "A lighthouse" })
1183-
const status = yield* ai.image.status(model, job.id) // { status, progress? }
1183+
const status = yield* ai.image.status(model, job.id) // { status: "running", progress? } | { status: "completed" } | ...
11841184
if (status.status === "completed") return yield* ai.image.result(model, job.id)
11851185
})
11861186
```
11871187

11881188
## Video generation
11891189

1190-
Video generation is a job: `start` submits it and returns at once, and the caller decides when to read its `status`,
1191-
fetch its `result`, or `cancel` it. Nothing polls for you. Every call after `start` takes the model and the job's
1192-
`id`, the provider's job ID as a string you can store and read back from another process, so recovering after a restart
1193-
is the same call as a normal status read. Models come from the video APIs of the `XAI`, `OpenRouter`, `Volcengine`,
1190+
Video generation is a job. `generate` submits it, polls it until it finishes and returns the videos; `stream` does the
1191+
same and emits `generation-progress` events, then one `video` event per video and `finish`. Both poll like images: every
1192+
5 seconds by default, for up to 10 minutes (`{ poll: { interval, timeout } }`), failing with a `Timeout` reason past it.
1193+
1194+
To manage the job yourself, `start` submits it and returns `{ id }` at once, and the caller decides when to read its
1195+
`status`, fetch its `result`, or `cancel` it. Every call after `start` takes the model and the job's `id`, the
1196+
provider's job ID as a string you can store and read back from another process, so recovering after a restart is the
1197+
same call as a normal status read. Models come from the video APIs of the `XAI`, `OpenRouter`, `Volcengine`,
11941198
`BytePlus`, `MiniMax` and `Google` providers (`provider.model(id, { api: "xai-video" })` and so on).
11951199

11961200
```ts
@@ -1201,12 +1205,15 @@ import { xai } from "@opencode/ai/providers"
12011205
const model = xai({ apiKey: process.env.XAI_API_KEY }).model("grok-imagine-video-1.5", { api: "xai-video" })
12021206

12031207
const program = Effect.gen(function* () {
1208+
const { videos } = yield* ai.video.generate({ model, prompt: "A red balloon floats up", duration: 5 })
1209+
yield* Media.write(videos[0], "./balloon.mp4")
1210+
12041211
const job = yield* ai.video.start({
12051212
model,
12061213
prompt: "Panning wide shot of a calico kitten sleeping in the sunshine",
12071214
start: "https://example.com/first-frame.png", // exact first frame; `end` pins the last one
12081215
references: [], // images, videos or audio that guide subject or style
1209-
duration: "8 seconds",
1216+
duration: 8, // seconds
12101217
aspect: "16:9", // or "auto" to follow the start image
12111218
resolution: "720p", // 480p | 720p | 1080p | 4k, or any provider value
12121219
sound: false,
@@ -1215,8 +1222,8 @@ const program = Effect.gen(function* () {
12151222

12161223
const status = yield* ai.video.status(model, job.id)
12171224
status.status // "running" | "completed" | "error"
1218-
status.reason // "failed" | "cancelled" | "expired", only when status is "error"
1219-
status.progress // 0..1, only when the provider reports it
1225+
if (status.status === "error") status.reason // "failed" | "cancelled" | "expired"
1226+
if (status.status === "running") status.progress // 0..1, only when the provider reports it
12201227

12211228
const response = yield* ai.video.result(model, job.id)
12221229
yield* Media.write(response.videos[0], "./kitten.mp4") // streams the download to disk
@@ -1288,6 +1295,7 @@ The promise client has the same calls, each accepting `{ signal }`:
12881295
```ts
12891296
import { ai } from "@opencode/ai"
12901297

1298+
const { videos } = await ai.video.generate({ model, prompt }, { poll: { interval: 5_000 } })
12911299
const job = await ai.video.start({ model, prompt })
12921300
const status = await ai.video.status(model, job.id)
12931301
if (status.status === "completed") await ai.write((await ai.video.result(model, job.id)).videos[0], "./kite.mp4")
@@ -1305,9 +1313,8 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
13051313
- **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
13061314
- **`StreamEvent`** — the discriminated union of stream events; narrow with `event.type === "text-delta"` or a `switch` on `type`.
13071315
- **`ai.image.request` / `generate` / `stream` / `start` / `status` / `result` / `cancel`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model. `start`, `status`, `result` and `cancel` address a queued job by the provider's job ID, like video; see [Image jobs](#image-jobs).
1308-
- **`ai.video.request` / `start` / `status` / `result` / `cancel`** — video generation as a job addressed by the provider's job ID; see [Video generation](#video-generation).
1316+
- **`ai.video.request` / `generate` / `stream` / `start` / `status` / `result` / `cancel`** — video generation: polled for you, or as a job addressed by the provider's job ID; see [Video generation](#video-generation).
13091317
- **`Media`** — the shared asset type (`Media.Asset`, `Media.Source`) and constructors used by messages, tool results, and media requests.
1310-
- **`Generation`** — provider-neutral handle for an in-flight media generation (`await`, `refresh`, `cancel`, `events`) used by queued media routes.
13111318
- **`ai.decision.request` / `ai.decision.generate`** — typed predicate, choice, and score questions over text, JSON, and media input.
13121319
- **`ai.embedding.request` / `ai.embedding.generate`** — one vector per text or media value, with optional `dimensions` and `inputType`.
13131320
- **`AI`** — one Effect service for every operation: text as `stream`, `generate` and `compact`, and media grouped as `image`, `video`, `speech`, `transcription`, `decision` and `embedding`. `ai.*` from `@opencode/ai/effect` runs through it. `AI.layer` requires `RequestExecutor.Service`; `AI.layerWith(executor)` and `AI.fetchLayer` provide `AI` and the executor in one layer.
@@ -1417,8 +1424,9 @@ for await (const event of ai.experimental.speech.stream({ model, text: "Hello fr
14171424

14181425
Transcription (speech-to-text) is the one modality whose providers use every route kind: OpenAI and Gemini stream,
14191426
Deepgram and ElevenLabs answer inline, and AssemblyAI is queued. `Transcription.generate` and `Transcription.stream`
1420-
work on all of them; `Transcription.start` / `resume` return a `Generation` on queued routes and fail with
1421-
`UnsupportedOperation` elsewhere. Models come from the transcription APIs of the `OpenAI`, `Google`,
1427+
work on all of them, polling queued routes like images and video. `Transcription.start`, `status`, `result` and `cancel`
1428+
address a queued job by the provider's job ID, like video, and fail with `UnsupportedOperation` elsewhere; `cancel`
1429+
also fails with it on AssemblyAI, which has no cancel endpoint. Models come from the transcription APIs of the `OpenAI`, `Google`,
14221430
`Deepgram`, `ElevenLabs`, and `AssemblyAI` facades. Common fields (`language`, `prompt`,
14231431
`timestamps: "none" | "segment" | "word"`, `diarize`, `speakers`) lower natively or fail with a typed `AIError` before
14241432
any network call; a route may return more than asked.
@@ -1455,11 +1463,11 @@ const program = Effect.gen(function* () {
14551463
Stream.runDrain,
14561464
)
14571465

1458-
// Queued: persist the token with the provider and model ID (the token alone cannot pick the model), resume, and await.
1466+
// Queued: persist the job ID with the provider and model ID (the ID alone cannot pick the model), then read it back.
14591467
const model = assemblyai({ apiKey }).model("universal-3-5-pro")
1460-
const generation = yield* Transcription.start({ model, audio })
1461-
const resumed = yield* Transcription.resume(model, JSON.parse(JSON.stringify(generation.token)))
1462-
const transcript = yield* resumed.await({ poll: { interval: "3 seconds" } })
1468+
const job = yield* Transcription.start({ model, audio })
1469+
const status = yield* Transcription.status(model, job.id)
1470+
if (status.status === "completed") return yield* Transcription.result(model, job.id)
14631471
})
14641472
```
14651473

@@ -1485,8 +1493,8 @@ const audio = await ai.file("./call.mp3")
14851493
const text = (await ai.experimental.transcription.generate({ model, audio })).text
14861494
for await (const event of ai.experimental.transcription.stream({ model, audio }))
14871495
if (event.type === "text-delta") write(event.delta)
1488-
const generation = await ai.experimental.transcription.start({ model: assemblyai, audio })
1489-
const transcript = await generation.await({ poll: { interval: 3_000 } })
1496+
const job = await ai.experimental.transcription.start({ model: assemblyai, audio })
1497+
const status = await ai.experimental.transcription.status(assemblyai, job.id)
14901498
```
14911499

14921500
### Extraction

‎packages/ai/src/ai.ts‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,18 @@
11
import { Context, Effect, Layer } from "effect"
22
import { DecisionClient } from "./decision-client.js"
33
import { EmbeddingClient } from "./embedding-client.js"
4-
import { ImageClient } from "./image-client.js"
4+
import type { ImageEvent, ImageRequest, ImageResponse } from "./image.js"
55
import { MediaClient } from "./media-client.js"
66
import { textOperations, type TextOperations } from "./route/client.js"
77
import { RequestExecutor } from "./route/executor.js"
88
import type { SpeechEvent, SpeechRequest, SpeechResponse } from "./speech.js"
99
import type { TranscriptionEvent, TranscriptionRequest, TranscriptionResponse } from "./transcription.js"
10-
import { VideoClient } from "./video-client.js"
10+
import type { VideoEvent, VideoRequest, VideoResponse } from "./video.js"
1111

1212
/** Every operation: text (`stream`, `generate`, `compact`) at the top, media grouped by modality. */
1313
export interface Interface extends TextOperations {
14-
readonly image: ImageClient.Interface
15-
readonly video: VideoClient.Interface
14+
readonly image: MediaClient.Interface<ImageRequest, ImageEvent, ImageResponse>
15+
readonly video: MediaClient.Interface<VideoRequest, VideoEvent, VideoResponse>
1616
readonly speech: MediaClient.Interface<SpeechRequest, SpeechEvent, SpeechResponse>
1717
readonly transcription: MediaClient.Interface<TranscriptionRequest, TranscriptionEvent, TranscriptionResponse>
1818
readonly decision: DecisionClient.Interface
@@ -29,8 +29,20 @@ export const layer: Layer.Layer<Service, never, RequestExecutor.Service> = Layer
2929
const executor = yield* RequestExecutor.Service
3030
return Service.of({
3131
...textOperations(executor),
32-
image: ImageClient.make(executor.execute),
33-
video: VideoClient.make(executor.execute),
32+
image: MediaClient.operations<ImageRequest, ImageEvent, ImageResponse>(executor.execute, {
33+
modality: "image",
34+
responseEvents: (response) => [
35+
...response.images.map((image, index) => ({ type: "image" as const, index, image })),
36+
{ type: "finish" as const, usage: response.usage, providerMetadata: response.providerMetadata },
37+
],
38+
}),
39+
video: MediaClient.operations<VideoRequest, VideoEvent, VideoResponse>(executor.execute, {
40+
modality: "video",
41+
responseEvents: (response) => [
42+
...response.videos.map((video, index) => ({ type: "video" as const, index, video })),
43+
{ type: "finish" as const, usage: response.usage, providerMetadata: response.providerMetadata },
44+
],
45+
}),
3446
speech: MediaClient.operations<SpeechRequest, SpeechEvent, SpeechResponse>(executor.execute, {
3547
modality: "speech",
3648
responseEvents: (response) => [

‎packages/ai/src/effect.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ export { AI } from "./ai.js"
3232
export { Api } from "./effect-api.js"
3333
export { Provider } from "./provider.js"
3434
export type { AIService } from "./ai.js"
35-
export { Generation } from "./generation.js"
3635
export type { AwaitOptions as GenerationAwaitOptions, Poll } from "./generation.js"
3736
export { ToolFailure, tool } from "./tool.js"
3837
export type { ToolExecute } from "./tool.js"

‎packages/ai/src/experimental.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@ export {
1111
TranscriptionWord,
1212
} from "./transcription.js"
1313
export type {
14+
TranscriptionJob,
1415
TranscriptionModelOptions,
1516
TranscriptionOptions,
1617
TranscriptionRequest,
1718
TranscriptionRequestInput,
19+
TranscriptionStatus,
1820
} from "./transcription.js"
1921
export { Transcription } from "./transcription.js"
2022
export { Extraction, ExtractionModel, ExtractionResponse } from "./experimental/extraction.js"

0 commit comments

Comments
 (0)