Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/ai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1989,7 +1989,7 @@ ai.request({

## Providers and APIs

`Provider.make({ id, baseURL, auth, metadataKey, apis })` from `@opencode/ai` (or `@opencode/ai/effect`) builds a provider from plain data, with its APIs grouped by kind (`language`, `image`, `speech`, `transcription`, `video`, `embedding`, `decision`); the first API of each kind is that kind's default. `requireBaseURL: true` makes every model fail without a `baseURL` setting, and `name` is how such errors name the provider. `Provider.apiKey(env, { header, prefix, authToken })` is API key auth as data; with `authToken: true` a bearer `authToken` setting replaces the key. `@opencode/ai/apis` exports the built-in wire APIs by name: `ChatCompletions`, `Responses`, `OpenResponses`, `Messages`, `Gemini`, `Interactions`, `Converse`, `CohereChat`, `MistralChat`, `OpenAIImages`, `OpenAIEmbeddings` and `SystemOne`. `api.with({ baseURL, metadataKey, query, auth, options, compatibility, capabilities })` returns a copy with what one host changes. A model's `api` and a provider's `apis` show each API's `name`, `kind` and `with`; how an API encodes requests and reaches its host is internal. Unsupported request shapes fail during protocol lowering.
`Provider.make({ id, baseURL, auth, metadataKey, apis })` from `@opencode/ai` (or `@opencode/ai/effect`) builds a provider from plain data, with its APIs grouped by kind (`language`, `image`, `speech`, `transcription`, `video`, `embedding`, `decision`); the first API of each kind is that kind's default. `requireBaseURL: true` makes every model fail without a `baseURL` setting, and `name` is how such errors name the provider. `Provider.apiKey(env, { header, prefix, authToken })` is API key auth as data; with `authToken: true` a bearer `authToken` setting replaces the key. `@opencode/ai/apis` exports the built-in wire APIs by name: `ChatCompletions`, `Responses`, `OpenResponses`, `Messages`, `Gemini`, `Interactions`, `Converse`, `CohereChat`, `MistralChat`, `OpenAIImages`, `OpenAIEmbeddings` and `SystemOne`. `api.with({ baseURL, metadataKey, query, auth, options, compatibility, capabilities })` returns a copy with what one host changes. A provider's `apis` show each API's `name`, `kind` and `with`; how an API encodes requests and reaches its host is internal. Every model is a plain record: its `kind` (`language`, `image`, …), `id`, `provider` and the `api` it is reached through, so a spread copies one. Unsupported request shapes fail during protocol lowering.

```ts
import { ai, Provider } from "@opencode/ai"
Expand Down
16 changes: 13 additions & 3 deletions packages/ai/src/ai.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { Context, Effect, Layer } from "effect"
import { DecisionClient } from "./decision-client.js"
import { EmbeddingClient } from "./embedding-client.js"
import type { ImageEvent, ImageRequest, ImageResponse } from "./image.js"
import { collectImageResponse, type ImageEvent, type ImageRequest, type ImageResponse } from "./image.js"
import { MediaClient } from "./media-client.js"
import { textOperations, type TextOperations } from "./route/client.js"
import { RequestExecutor } from "./route/executor.js"
import type { SpeechEvent, SpeechRequest, SpeechResponse } from "./speech.js"
import type { TranscriptionEvent, TranscriptionRequest, TranscriptionResponse } from "./transcription.js"
import { collectSpeechResponse, type SpeechEvent, type SpeechRequest, type SpeechResponse } from "./speech.js"
import {
collectTranscriptionResponse,
type TranscriptionEvent,
type TranscriptionRequest,
type TranscriptionResponse,
} from "./transcription.js"
import type { VideoEvent, VideoRequest, VideoResponse } from "./video.js"

/** Every operation: text (`stream`, `generate`, `compact`) at the top, media grouped by modality. */
Expand All @@ -31,20 +36,24 @@ export const layer: Layer.Layer<Service, never, RequestExecutor.Service> = Layer
...textOperations(executor),
image: MediaClient.operations<ImageRequest, ImageEvent, ImageResponse>(executor.execute, {
modality: "image",
collect: collectImageResponse,
responseEvents: (response) => [
...response.images.map((image, index) => ({ type: "image" as const, index, image })),
{ type: "finish" as const, usage: response.usage, native: response.native },
],
}),
video: MediaClient.operations<VideoRequest, VideoEvent, VideoResponse>(executor.execute, {
modality: "video",
// Every video API is queued, so no stream is ever collected.
collect: () => Effect.die(new Error("Video APIs do not stream")),
responseEvents: (response) => [
...response.videos.map((video, index) => ({ type: "video" as const, index, video })),
{ type: "finish" as const, usage: response.usage, native: response.native },
],
}),
speech: MediaClient.operations<SpeechRequest, SpeechEvent, SpeechResponse>(executor.execute, {
modality: "speech",
collect: collectSpeechResponse,
responseEvents: (response) => [
...(response.timestamps === undefined ? [] : [{ type: "timestamps" as const, items: response.timestamps }]),
{
Expand All @@ -59,6 +68,7 @@ export const layer: Layer.Layer<Service, never, RequestExecutor.Service> = Layer
executor.execute,
{
modality: "transcription",
collect: collectTranscriptionResponse,
responseEvents: (response) => [{ type: "finish" as const, ...response }],
},
),
Expand Down
47 changes: 47 additions & 0 deletions packages/ai/src/api-internal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import type { Api } from "./api.js"
import type { CompactionOperations } from "./route/client.js"
import type { NativeOptions } from "./schema/index.js"

// Package-private: models carry an API as its view, with the record behind this key. Nothing outside the package can
// reach it, so the public types never show a codec, transport, auth handler or deferred base URL.
const API_INTERNAL = Symbol("opencode.ai.api")

type Shown = { readonly [API_INTERNAL]: Api.Any }

/**
* The API as a model shows it: its name and kind, the base URL once known and the metadata key, and `with`, which
* changes the record behind it. Plain to print and spread.
*/
export const view = <View extends Api.AnyApi>(api: Api.Any, modelID: string): View & Api.Host => {
const record: Api.Any & { readonly with: (patch: never) => Api.Any } = api
const baseURL = typeof api.baseURL === "function" ? api.baseURL(modelID) : api.baseURL
const shown = {
name: api.name,
kind: api.kind,
baseURL: typeof baseURL === "string" ? baseURL : undefined,
metadataKey: api.metadataKey,
with: (patch: never) => view(record.with(patch), modelID),
[API_INTERNAL]: api,
}
// A view shows what its record's type shows, and `with` takes the patch the record's own `with` takes.
return shown as unknown as View & Api.Host
}

/** The record behind a model's API, or the record itself for an API used as built. */
export function internal(
api: Api.LanguageApi<string, NativeOptions, Api.CompactionCapability | undefined>,
// The body type is internal to the codec.
// oxlint-disable-next-line typescript-eslint/no-explicit-any
): Api.Http<string, CompactionOperations | undefined, any, any>
export function internal<K extends Api.Kind>(api: Api.KindMap[K]["view"] & { readonly kind: K }): Api.KindMap[K]["api"]
export function internal<K extends Api.Kind>(api: Api.KindMap[K]["view"]): Api.KindMap[K]["api"]
export function internal(api: Api.AnyApi): Api.Any {
if (isShown(api)) return api[API_INTERNAL]
if (isRecord(api)) return api
throw new Error(`The ${api.name} API was not built by Api.http or Api.make`)
}

const isShown = (api: object): api is Shown => API_INTERNAL in api

// Every built API has a protocol; views from `@opencode/ai/apis` and providers are the records themselves.
const isRecord = (api: object): api is Api.Any => "protocol" in api
Loading
Loading