refactor(ai): make Model one plain object for every model type

This commit is contained in:
Aiden Cline 2026-11-05 10:37:52 -06:00
parent 14f7cb9db9
commit a95c4fcd96
173 changed files with 1959 additions and 1595 deletions

View file

@ -949,7 +949,7 @@ Everything below is exported from `@opencode/ai/effect` unless noted.
- **`ai.loop`** — stream model calls, running `tool(...)` tools between them until the model stops calling tools.
- **`ai.collect`** — fold a stream from `ai.stream` or `ai.loop` into its final result (`text`, `steps`, `messages`, `usage`).
- **`Message.user(...)` / `Message.assistant(...)` / `Message.tool(...)`** — message constructors from the canonical schema model.
- **`LanguageModel.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
- **`Model.make(...)` / `ToolCallPart.make(...)` / `ToolResultPart.make(...)` / `ToolDefinition.make(...)`** — model and tool-related constructors from the canonical schema model.
- **`LLMEvent.is.*`** — typed guards (`is.textDelta`, `is.toolCall`, `is.finish`, …) for filtering streams.
- **`ai.image.request` / `generate` / `stream` / `start` / `resume`** — images over inline, streaming (partial previews), and queued routes through a provider-neutral request and response model.
- **`ImageClient`** — Effect service and layer for image execution, parallel to `LLMClient`.
@ -1553,6 +1553,38 @@ const fireworks = Fireworks.configure({ apiKey }).model("accounts/fireworks/mode
The former `OpenAICompatible.baseten`, `.cerebras`, `.deepinfra`, `.deepseek`, `.fireworks`, `.groq`, and `.togetherai` presets are replaced by the top-level `Baseten`, `Cerebras`, `DeepInfra`, `DeepSeek`, `Fireworks`, `Groq`, and `TogetherAI` exports. Use `CloudflareAIGateway` and `CloudflareWorkersAI` directly; each has its own module. `OpenAICompatible` configures generic endpoints with an explicit `baseURL`.
### Describing a model by hand
A model is a plain readonly object. `OpenAI.configure(...).chat(id)` returns one with its fields filled in; describe one yourself by naming the models.dev v2 API it speaks:
```ts
import { Model } from "@opencode/ai"
import { Auth } from "@opencode/ai/route"
const local = Model.make({
type: "chat",
id: "qwen3-coder",
provider: "lmstudio",
api: "chat-completions",
baseURL: "http://localhost:1234/v1",
auth: Auth.none,
capabilities: { tools: { strict: false } },
options: { temperature: 0.7 },
compatibility: { maxTokensField: "max_tokens" },
})
// Edit a model with a spread: requests go to the new host, with the same auth.
const proxied = { ...local, baseURL: "http://gpu-box:1234/v1" }
const precise = { ...local, options: { ...local.options, temperature: 0 } }
// `type` narrows a model of any kind.
const describe = (model: Model) => (model.type === "chat" ? model.baseURL : model.api)
```
`api` is one of `"chat-completions"`, `"responses"`, `"messages"`, `"converse"`, `"generate-content"`, `"interactions"` or `"cohere-chat"` for a hand-described text model; the package loads its standard implementation of that API on the first request. Provider models carry their provider's own implementation (a vendor dialect such as Z.ai's or OpenRouter's chat), and keep it through spreads as long as `api` is unchanged. Fields a hand-described model leaves out (`baseURL`, `auth`, options) fall back to the API's defaults when the request is sent.
`Model.make` fills OpenCode's defaults for an unknown model: `capabilities.tools.supported`, text and image input with text output, a 200k context and 32k output. It never sets flags such as `capabilities.store` or `capabilities.streamUsage`; unset flags keep each protocol's own detection. Media and decision models run only on a provider's implementation.
### Provider entrypoints
Provider modules are available through dedicated exports from `@opencode/ai`. Each LLM entrypoint exports `model(modelID, settings)`, where `settings` contains provider configuration plus common `headers` and `body` overlays.

View file

@ -178,9 +178,10 @@ const FakeBody = Schema.Struct({
type FakeBody = Schema.Schema.Type<typeof FakeBody>
const FakeProtocol = Protocol.make<FakeBody, string, string, void>({
// Protocol ids are open strings, so external packages can define their own
// Protocol ids and API names are open strings, so external packages can define their own
// protocols without changing this package.
id: "fake-echo",
api: "fake-echo",
body: {
schema: FakeBody,
from: (request) =>

View file

@ -23,6 +23,7 @@ import {
type ToolEntry,
} from "./schema/messages.js"
import { effortUpdate } from "./effort-updates.js"
import { routeOf } from "./schema/model.js"
const AUTO: CachePolicyObject = {
tools: true,
@ -235,7 +236,7 @@ export const placesMarkers = (request: LLMRequest) => {
// A declared cache format overrides the route allowlist and its model-ID heuristics.
const selectPolicy = (request: LLMRequest): CachePolicyObject => {
const format = request.model.compatibility?.cacheFormat
const route = request.model.route.id
const route = routeOf(request.model).id
const auto = isAuto(request.cache)
if (format === "alibaba") return auto ? QWEN : { ...resolve(request.cache), tools: false }
if (format === "anthropic") return resolve(request.cache)

View file

@ -1,7 +1,6 @@
import { Context, Effect, Layer } from "effect"
import type {
DecisionAnswer,
DecisionModel,
DecisionOptions,
DecisionQuestion,
DecisionQuestions,
@ -9,20 +8,20 @@ import type {
DecisionResponseFor,
} from "./decision.js"
import { RequestExecutor } from "./route/executor.js"
import { AIError, InvalidProviderOutputError } from "./schema/index.js"
import { AIError, InvalidProviderOutputError, type Model, routeOf } from "./schema/index.js"
export type Execute = RequestExecutor.Interface["execute"]
export interface Interface {
readonly generate: <Options extends DecisionOptions, const Questions extends DecisionQuestions>(
request: DecisionRequest<DecisionModel<Options>, Questions>,
request: DecisionRequest<Model<"decision", Options>, Questions>,
) => Effect.Effect<DecisionResponseFor<Questions>, AIError>
}
export class Service extends Context.Service<Service, Interface>()("@opencode/AI/DecisionClient") {}
export const generate = <Options extends DecisionOptions, const Questions extends DecisionQuestions>(
request: DecisionRequest<DecisionModel<Options>, Questions>,
request: DecisionRequest<Model<"decision", Options>, Questions>,
): Effect.Effect<DecisionResponseFor<Questions>, AIError, Service> =>
Effect.flatMap(Service, (client) => client.generate(request))
@ -32,7 +31,7 @@ export const layer: Layer.Layer<Service, never, RequestExecutor.Service> = Layer
const executor = yield* RequestExecutor.Service
return Service.of({
generate: Effect.fnUntraced(function* (request) {
const route = request.model.route
const route = routeOf(request.model)
const response = yield* route.generate(request, executor.execute)
if (answersMatch(request.questions, response.answers))
return response as DecisionResponseFor<typeof request.questions>

View file

@ -5,9 +5,9 @@ import { tryRequest } from "./media-model.js"
import {
AIError,
type BaseRequest,
type HttpOptions,
ModelID,
ProviderID,
Model,
modelSchema,
type ModelProviderOptions,
ProviderMetadata,
ProviderOptions,
type OpenString,
@ -161,7 +161,7 @@ export type AnswersFor<Questions extends DecisionQuestions> = {
}
// ---------------------------------------------------------------------------
// Model
// SelectedModel
// ---------------------------------------------------------------------------
export type DecisionOptions = Record<string, unknown>
@ -169,85 +169,18 @@ export type DecisionOptions = Record<string, unknown>
/** What a decision model's route does; `DecisionRoute.make(...).model(...)` builds one from a protocol. */
export interface DecisionModelRoute<Options extends DecisionOptions = DecisionOptions> {
readonly id: string
generate(request: DecisionRequest<DecisionModel<Options>>, execute: Execute): Effect.Effect<DecisionResponse, AIError>
generate(
request: DecisionRequest<Model<"decision", Options>>,
execute: Execute,
): Effect.Effect<DecisionResponse, AIError>
}
/** Host quirks a protocol adapts to, like `LanguageModelCompatibility` for language models. */
export class DecisionModelCompatibility extends Schema.Class<DecisionModelCompatibility>("Decision.ModelCompatibility")(
{
/**
* Where a System One host reads media, from models.dev `[api.systemone] compatibility.media_input`, named after
* where the media goes in the body: `assets` (TypeSafe's assets map, referenced from the state), `state` (items
* inside a state list) or `root` (one top-level list per kind: `images`, `audio`, `videos`).
*/
mediaInput: Schema.optional(Schema.Literals(["assets", "state", "root"])),
},
) {}
export namespace DecisionModelCompatibility {
export type Input = DecisionModelCompatibility | ConstructorParameters<typeof DecisionModelCompatibility>[0]
export const make = (input: Input) =>
input instanceof DecisionModelCompatibility ? input : new DecisionModelCompatibility(input)
}
export class DecisionModel<Options extends DecisionOptions = DecisionOptions> {
declare protected readonly _Options: Options
readonly id: ModelID
readonly provider: ProviderID
readonly route: DecisionModelRoute<Options>
readonly http?: HttpOptions
readonly compatibility?: DecisionModelCompatibility
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
readonly providerOptions?: ProviderOptions
constructor(input: DecisionModel.Input<Options>) {
this.id = input.id
this.provider = input.provider
this.route = input.route
this.http = input.http
this.compatibility = input.compatibility
this.providerOptions = input.providerOptions
}
static make<Options extends DecisionOptions = DecisionOptions>(input: DecisionModel.MakeInput<Options>) {
return new DecisionModel<Options>({
...input,
id: ModelID.make(input.id),
provider: ProviderID.make(input.provider),
})
}
}
export namespace DecisionModel {
export interface Input<Options extends DecisionOptions = DecisionOptions> {
readonly id: ModelID
readonly provider: ProviderID
readonly route: DecisionModelRoute<Options>
readonly http?: HttpOptions
readonly compatibility?: DecisionModelCompatibility
readonly providerOptions?: ProviderOptions
}
export interface MakeInput<Options extends DecisionOptions = DecisionOptions>
extends Omit<Input<Options>, "id" | "provider"> {
readonly id: string | ModelID
readonly provider: string | ProviderID
}
}
export const DecisionModelSchema = Schema.declare((value): value is DecisionModel => value instanceof DecisionModel, {
expected: "Decision.Model",
})
export type DecisionModelOptions<Model> = Model extends DecisionModel<infer Options> ? Options : never
// ---------------------------------------------------------------------------
// Request and response
// ---------------------------------------------------------------------------
const DecisionRequestSchema = Schema.Struct({
model: DecisionModelSchema,
model: modelSchema("decision"),
input: Schema.Array(DecisionPart),
questions: DecisionQuestionList,
providerOptions: Schema.optional(ProviderOptions),
@ -255,18 +188,18 @@ const DecisionRequestSchema = Schema.Struct({
/** A normalized decision request, the plain object `ai.decision.request(...)` returns. */
export interface DecisionRequest<
Model extends DecisionModel = DecisionModel,
SelectedModel extends Model<"decision"> = Model<"decision">,
Questions extends DecisionQuestions = DecisionQuestions,
> extends BaseRequest<Model, DecisionModelOptions<Model>> {
> extends BaseRequest<SelectedModel, ModelProviderOptions<SelectedModel>> {
readonly input: ReadonlyArray<DecisionPart>
readonly questions: Questions
}
/** Input accepted by `ai.decision.request` and `generate`. A `DecisionRequest` is also a valid input. */
export interface DecisionRequestInput<
Model extends DecisionModel = DecisionModel,
SelectedModel extends Model<"decision"> = Model<"decision">,
Questions extends DecisionQuestions = DecisionQuestions,
> extends BaseRequest<Model, NoInfer<DecisionModelOptions<Model>>> {
> extends BaseRequest<SelectedModel, NoInfer<ModelProviderOptions<SelectedModel>>> {
readonly input: DecisionInput
readonly questions: Questions
}
@ -295,9 +228,9 @@ export type DecisionResponseFor<Questions extends DecisionQuestions> = Omit<Deci
// ---------------------------------------------------------------------------
/** Normalize decision request input into a plain `DecisionRequest`; a plain object `input` becomes one `json` part. */
export const request = <const Model extends DecisionModel, const Questions extends DecisionQuestions>(
input: DecisionRequestInput<Model, Questions>,
): DecisionRequest<Model, Questions> => ({
export const request = <const SelectedModel extends Model<"decision">, const Questions extends DecisionQuestions>(
input: DecisionRequestInput<SelectedModel, Questions>,
): DecisionRequest<SelectedModel, Questions> => ({
...input,
input: isParts(input.input) ? input.input.map(decisionPart) : [{ type: "json", value: input.input }],
})
@ -313,8 +246,8 @@ const decisionPart = (part: DecisionPartInput): DecisionPart => {
return { ...rest, media: Media.make(part.media, mediaType) }
}
export function generate<const Model extends DecisionModel, const Questions extends DecisionQuestions>(
input: DecisionRequestInput<Model, Questions>,
export function generate<const SelectedModel extends Model<"decision">, const Questions extends DecisionQuestions>(
input: DecisionRequestInput<SelectedModel, Questions>,
): Effect.Effect<DecisionResponseFor<Questions>, AIError, Service>
export function generate(input: DecisionRequestInput) {
return tryRequest(() => {

View file

@ -1,6 +1,7 @@
// Changing the top-level reasoning effort invalidates the provider prompt cache. Protocols with a native
// per-message update keep it frozen and lower `Message.effort(...)` markers instead; other routes strip them.
import { type LLMRequest, type EffortPart, type Message } from "./schema/messages.js"
import { routeOf } from "./schema/model.js"
export const effortUpdate = (message: Message): EffortPart | undefined => {
if (message.role !== "system" || message.content.length !== 1) return undefined
@ -14,7 +15,7 @@ export const stripEffortUpdates = (request: LLMRequest) => {
}
export const applyEffortUpdates = (request: LLMRequest): LLMRequest =>
request.model.route.supportsEffortUpdates?.(request) ? request : stripEffortUpdates(request)
routeOf(request.model).supportsEffortUpdates?.(request) ? request : stripEffortUpdates(request)
// Reverted or forked history can leave the last marker disagreeing with the requested effort.
export const resolveEffortUpdates = (request: LLMRequest, current: string | undefined) => {

View file

@ -1,50 +1,32 @@
export { VideoClient } from "./video-client.js"
export { VideoAspectRatio, VideoEvent, VideoFrames, VideoModel, VideoModelSchema, VideoResponse } from "./video.js"
export type {
VideoModelOptions,
VideoOptions,
VideoRequest,
VideoRequestInput,
VideoResolution,
VideoRoute,
} from "./video.js"
export { VideoAspectRatio, VideoEvent, VideoFrames, VideoResponse } from "./video.js"
export type { VideoOptions, VideoRequest, VideoRequestInput, VideoResolution, VideoRoute } from "./video.js"
export { Video } from "./video.js"
export { SpeechClient } from "./speech-client.js"
export { SpeechEvent, SpeechModel, SpeechModelSchema, SpeechResponse, SpeechTimestamp, SpeechVoice } from "./speech.js"
export type {
SpeechFormat,
SpeechModelOptions,
SpeechOptions,
SpeechRequest,
SpeechRequestInput,
SpeechRoute,
} from "./speech.js"
export { SpeechEvent, SpeechResponse, SpeechTimestamp, SpeechVoice } from "./speech.js"
export type { SpeechFormat, SpeechOptions, SpeechRequest, SpeechRequestInput, SpeechRoute } from "./speech.js"
export { Speech } from "./speech.js"
export { TranscriptionClient } from "./transcription-client.js"
export {
TranscriptionEvent,
TranscriptionModel,
TranscriptionModelSchema,
TranscriptionResponse,
TranscriptionSegment,
TranscriptionTimestamps,
TranscriptionWord,
} from "./transcription.js"
export type {
TranscriptionModelOptions,
TranscriptionOptions,
TranscriptionRequest,
TranscriptionRequestInput,
TranscriptionRoute,
} from "./transcription.js"
export { Transcription } from "./transcription.js"
export { Extraction, ExtractionModel, ExtractionResponse } from "./experimental/extraction.js"
export { Extraction, ExtractionResponse } from "./experimental/extraction.js"
export type {
ExtractionAnswerFor,
ExtractionAnswersFor,
ExtractionField,
ExtractionFields,
ExtractionModelOptions,
ExtractionOptions,
ExtractionRequest,
ExtractionRequestInput,

View file

@ -1,10 +1,11 @@
import { Effect, Schema } from "effect"
import { ExtractionAnswers, ExtractionModel, ExtractionResponse, type ExtractionRequest } from "./extraction.js"
import { mediaOptions } from "../media-model.js"
import { ExtractionAnswers, ExtractionResponse, type ExtractionRequest } from "./extraction.js"
import { JsonObject, ProviderShared } from "../protocols/shared.js"
import { Endpoint } from "../route/endpoint.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { Usage, mergeJsonRecords } from "../schema/index.js"
import { mediaApi, implementation, Usage, mergeJsonRecords, Model } from "../schema/index.js"
const route = MediaProtocol.identity({
id: "cloudflare-run-extraction",
@ -96,11 +97,13 @@ export const protocol = MediaProtocol.inline<ExtractionRequest, ExtractionRespon
/** `baseURL` is the Run API base, `.../client/v4/accounts/{account}/ai/run`. */
export const model = (input: MediaRoute.ModelInput) =>
new ExtractionModel({
Model.make({
type: "extraction",
id: input.id,
provider: route.provider,
http: input.http,
route: MediaRoute.inline({
options: mediaOptions(input),
api: mediaApi(protocol.id),
[implementation]: MediaRoute.inline({
protocol,
endpoint: Endpoint.path<MediaProtocol.Body, ExtractionRequest>(({ request }) => `/${request.model.id}`, {
baseURL: input.baseURL,

View file

@ -1,5 +1,5 @@
import { Effect, Schema } from "effect"
import { MediaModel, tryRequest } from "../media-model.js"
import { type MediaModel, tryRequest } from "../media-model.js"
import { RequestExecutor } from "../route/executor.js"
import type { MediaRoute } from "../route/media.js"
import {
@ -9,6 +9,10 @@ import {
Usage,
type BaseRequest,
type OpenString,
Model,
routeOf,
modelSchema,
type ModelProviderOptions,
} from "../schema/index.js"
// ---------------------------------------------------------------------------
@ -96,30 +100,19 @@ export type ExtractionField = typeof ExtractionFieldSchema.Type & { readonly typ
export type ExtractionFields = Readonly<Record<string, ExtractionField>>
// ---------------------------------------------------------------------------
// Model
// SelectedModel
// ---------------------------------------------------------------------------
export type ExtractionOptions = MediaModel.Options
export type ExtractionRoute = MediaRoute.InlineRoute<ExtractionRequest, ExtractionResponse>
export class ExtractionModel<Options extends ExtractionOptions = ExtractionOptions> extends MediaModel<
ExtractionRoute,
Options
> {
declare protected readonly _ExtractionModel: void
}
export type ExtractionModelOptions<Model> = Model extends ExtractionModel<infer Options> ? Options : never
// ---------------------------------------------------------------------------
// Request and response
// ---------------------------------------------------------------------------
const ExtractionRequestSchema = Schema.Struct({
model: Schema.declare((value): value is ExtractionModel => value instanceof ExtractionModel, {
expected: "Extraction.Model",
}),
model: modelSchema("extraction"),
input: Schema.String,
fields: Schema.Record(Schema.String, ExtractionFieldSchema).pipe(
Schema.refine((x): x is typeof x => Object.keys(x).length > 0, { message: "Extraction fields must not be empty" }),
@ -130,9 +123,9 @@ const ExtractionRequestSchema = Schema.Struct({
/** A normalized extraction request, the plain object `Extraction.request(...)` returns. */
export interface ExtractionRequest<
Model extends ExtractionModel = ExtractionModel,
SelectedModel extends Model<"extraction"> = Model<"extraction">,
Fields extends ExtractionFields = ExtractionFields,
> extends BaseRequest<Model, ExtractionModelOptions<Model>> {
> extends BaseRequest<SelectedModel, ModelProviderOptions<SelectedModel>> {
/** The text to read; text answers carry spans into it. */
readonly input: string
readonly fields: Fields
@ -142,10 +135,10 @@ export interface ExtractionRequest<
/** Input accepted by `Extraction.request` and `generate`; an `ExtractionRequest` is also a valid input. */
export type ExtractionRequestInput<
Model extends ExtractionModel = ExtractionModel,
SelectedModel extends Model<"extraction"> = Model<"extraction">,
Fields extends ExtractionFields = ExtractionFields,
> = Omit<ExtractionRequest<Model, Fields>, "providerOptions"> & {
readonly providerOptions?: NoInfer<ExtractionModelOptions<Model>>
> = Omit<ExtractionRequest<SelectedModel, Fields>, "providerOptions"> & {
readonly providerOptions?: NoInfer<ModelProviderOptions<SelectedModel>>
}
export class ExtractionResponse extends Schema.Class<ExtractionResponse>("Extraction.Response")({
@ -163,14 +156,14 @@ export type ExtractionResponseFor<Fields extends ExtractionFields> = Omit<Extrac
// ---------------------------------------------------------------------------
/** Normalize extraction request input into a plain `ExtractionRequest`. */
export const request = <const Model extends ExtractionModel, const Fields extends ExtractionFields>(
input: ExtractionRequestInput<Model, Fields>,
): ExtractionRequest<Model, Fields> => ({ ...input })
export const request = <const SelectedModel extends Model<"extraction">, const Fields extends ExtractionFields>(
input: ExtractionRequestInput<SelectedModel, Fields>,
): ExtractionRequest<SelectedModel, Fields> => ({ ...input })
const validate = Schema.decodeUnknownSync(ExtractionRequestSchema)
export function generate<const Model extends ExtractionModel, const Fields extends ExtractionFields>(
input: ExtractionRequestInput<Model, Fields>,
export function generate<const SelectedModel extends Model<"extraction">, const Fields extends ExtractionFields>(
input: ExtractionRequestInput<SelectedModel, Fields>,
): Effect.Effect<ExtractionResponseFor<Fields>, AIError, RequestExecutor.Service>
export function generate(input: ExtractionRequestInput) {
return Effect.gen(function* () {
@ -180,7 +173,7 @@ export function generate(input: ExtractionRequestInput) {
validate(normalized)
return normalized
})
return yield* built.model.route.generate(built, executor.execute)
return yield* routeOf(built.model).generate(built, executor.execute)
})
}

View file

@ -1,7 +1,7 @@
import { Effect, Schema, Stream } from "effect"
import { Generation, ProgressEvent, QueuedEvent, type AwaitOptions } from "./generation.js"
import { Media } from "./media.js"
import { MediaModel, composeRoute, tryRequest } from "./media-model.js"
import { type MediaModel, composeRoute, mediaOptions, tryRequest } from "./media-model.js"
import { MediaRoute } from "./route/media.js"
import {
AIError,
@ -10,51 +10,56 @@ import {
ProviderOptions,
type OpenString,
type BaseRequest,
mediaApi,
implementation,
Model,
modelSchema,
type ModelProviderOptions,
} from "./schema/index.js"
import { ImageClient, Service } from "./image-client.js"
// ---------------------------------------------------------------------------
// Model
// SelectedModel
// ---------------------------------------------------------------------------
export type ImageOptions = MediaModel.Options
export type ImageRoute = MediaRoute.AnyRoute<ImageRequest, ImageEvent, ImageResponse>
export class ImageModel<Options extends ImageOptions = ImageOptions> extends MediaModel<ImageRoute, Options> {
declare protected readonly _ImageModel: void
/** The number of type arguments selects the kind: `<Options>`, `<Options, Frame, State>`, or `<Options, Token>`. */
static fromRoute<Options extends ImageOptions>(
route: MediaModel.InlineRouteInput<ImageRequest<ImageModel<Options>>, ImageResponse>,
input: MediaRoute.ModelInput,
): ImageModel<Options>
static fromRoute<Options extends ImageOptions, Frame, State>(
route: MediaModel.StreamRouteInput<ImageRequest<ImageModel<Options>>, ImageEvent, Frame, State>,
input: MediaRoute.ModelInput,
): ImageModel<Options>
static fromRoute<Options extends ImageOptions, Token>(
route: MediaModel.QueuedRouteInput<ImageRequest<ImageModel<Options>>, ImageResponse, Token>,
input: MediaRoute.ModelInput,
): ImageModel<Options>
static fromRoute<Options extends ImageOptions, Frame, State, Token>(
route: MediaModel.AnyRouteInput<ImageRequest<ImageModel<Options>>, ImageEvent, ImageResponse, Frame, State, Token>,
input: MediaRoute.ModelInput,
) {
return new ImageModel<Options>({
id: input.id,
provider: route.protocol.provider,
http: input.http,
providerOptions: input.providerOptions,
route: composeRoute(route, input, collectResponse) as ImageRoute,
})
}
/** The number of type arguments selects the kind: `<Options>`, `<Options, Frame, State>`, or `<Options, Token>`. */
export function imageModel<Options extends ImageOptions>(
route: MediaModel.InlineRouteInput<ImageRequest<Model<"image", Options>>, ImageResponse>,
input: MediaRoute.ModelInput,
): Model<"image", Options>
export function imageModel<Options extends ImageOptions, Frame, State>(
route: MediaModel.StreamRouteInput<ImageRequest<Model<"image", Options>>, ImageEvent, Frame, State>,
input: MediaRoute.ModelInput,
): Model<"image", Options>
export function imageModel<Options extends ImageOptions, Token>(
route: MediaModel.QueuedRouteInput<ImageRequest<Model<"image", Options>>, ImageResponse, Token>,
input: MediaRoute.ModelInput,
): Model<"image", Options>
export function imageModel<Options extends ImageOptions, Frame, State, Token>(
route: MediaModel.AnyRouteInput<
ImageRequest<Model<"image", Options>>,
ImageEvent,
ImageResponse,
Frame,
State,
Token
>,
input: MediaRoute.ModelInput,
) {
return Model.make<"image", Options>({
type: "image",
id: input.id,
provider: route.protocol.provider,
options: mediaOptions(input),
api: mediaApi(route.protocol.id),
[implementation]: composeRoute(route, input, collectResponse) as ImageRoute,
})
}
export const ImageModelSchema = Schema.declare((value): value is ImageModel => value instanceof ImageModel, {
expected: "Image.Model",
})
// ---------------------------------------------------------------------------
// Request
// ---------------------------------------------------------------------------
@ -66,7 +71,7 @@ export const ImageAspectRatio = Media.AspectRatio
export type ImageResolution = OpenString<"1K" | "2K" | "4K">
const ImageRequestSchema = Schema.Struct({
model: ImageModelSchema,
model: modelSchema("image"),
prompt: Schema.String,
images: Schema.optional(Schema.Array(Media.AssetSchema)),
n: Schema.optional(Schema.Int),
@ -76,8 +81,8 @@ const ImageRequestSchema = Schema.Struct({
})
/** A normalized image request, the plain object `ai.image.request(...)` returns. */
export interface ImageRequest<Model extends ImageModel = ImageModel>
extends BaseRequest<Model, ImageModelOptions<Model>> {
export interface ImageRequest<SelectedModel extends Model<"image"> = Model<"image">>
extends BaseRequest<SelectedModel, ModelProviderOptions<SelectedModel>> {
readonly prompt: string
/** Edit sources or style/subject references, in order. */
readonly images?: ReadonlyArray<Media.Asset>
@ -86,16 +91,14 @@ export interface ImageRequest<Model extends ImageModel = ImageModel>
readonly resolution?: ImageResolution
}
export type ImageModelOptions<Model> = Model extends ImageModel<infer Options> ? Options : never
/** Input accepted by `ai.image.request`, `generate`, `stream` and `start`. An `ImageRequest` is also a valid input. */
export type ImageRequestInput<Model extends ImageModel = ImageModel> = Omit<
ImageRequest<Model>,
export type ImageRequestInput<SelectedModel extends Model<"image"> = Model<"image">> = Omit<
ImageRequest<SelectedModel>,
"images" | "providerOptions"
> & {
/** Edit sources or style/subject references, in order: assets or plain data with a detectable type. */
readonly images?: ReadonlyArray<Media.Input>
readonly providerOptions?: NoInfer<ImageModelOptions<Model>>
readonly providerOptions?: NoInfer<ModelProviderOptions<SelectedModel>>
}
// ---------------------------------------------------------------------------
@ -167,7 +170,9 @@ const collectResponse = (events: ReadonlyArray<ImageEvent>): Effect.Effect<Image
// ---------------------------------------------------------------------------
/** Normalize image request input into a plain `ImageRequest`. */
export const request = <const Model extends ImageModel>(input: ImageRequestInput<Model>): ImageRequest<Model> => ({
export const request = <const SelectedModel extends Model<"image">>(
input: ImageRequestInput<SelectedModel>,
): ImageRequest<SelectedModel> => ({
...input,
images: input.images?.map((image) => Media.make(image)),
})
@ -181,16 +186,16 @@ const requestEffect = (input: ImageRequestInput) =>
return normalized
})
export function generate<const Model extends ImageModel>(
input: ImageRequestInput<Model>,
export function generate<const SelectedModel extends Model<"image">>(
input: ImageRequestInput<SelectedModel>,
options?: AwaitOptions,
): Effect.Effect<ImageResponse, AIError, Service>
export function generate(input: ImageRequestInput, options?: AwaitOptions) {
return requestEffect(input).pipe(Effect.flatMap((request) => ImageClient.generate(request, options)))
}
export function stream<const Model extends ImageModel>(
input: ImageRequestInput<Model>,
export function stream<const SelectedModel extends Model<"image">>(
input: ImageRequestInput<SelectedModel>,
options?: AwaitOptions,
): Stream.Stream<ImageEvent, AIError, Service>
export function stream(input: ImageRequestInput, options?: AwaitOptions) {
@ -198,15 +203,17 @@ export function stream(input: ImageRequestInput, options?: AwaitOptions) {
}
/** Inline and streaming routes fail with `UnsupportedOperation`. */
export function start<const Model extends ImageModel>(
input: ImageRequestInput<Model>,
export function start<const SelectedModel extends Model<"image">>(
input: ImageRequestInput<SelectedModel>,
): Effect.Effect<Generation<ImageResponse>, AIError, Service>
export function start(input: ImageRequestInput) {
return requestEffect(input).pipe(Effect.flatMap((request) => ImageClient.start(request)))
}
export const resume = (model: ImageModel, token: unknown): Effect.Effect<Generation<ImageResponse>, AIError, Service> =>
ImageClient.resume(model, token)
export const resume = (
model: Model<"image">,
token: unknown,
): Effect.Effect<Generation<ImageResponse>, AIError, Service> => ImageClient.resume(model, token)
export const Image = {
request,

View file

@ -1,8 +1,8 @@
import { Effect, Layer, ManagedRuntime, Schema, Stream } from "effect"
import { AIClient } from "./ai-client.js"
import { Decision, type DecisionModel, type DecisionQuestions, type DecisionRequestInput } from "./decision.js"
import { Decision, type DecisionQuestions, type DecisionRequestInput } from "./decision.js"
import type { AwaitOptions, Event, Generation, Snapshot } from "./generation.js"
import { Image, type ImageModel, type ImageRequest, type ImageRequestInput } from "./image.js"
import { Image, type ImageRequest, type ImageRequestInput } from "./image.js"
import { LLM } from "./llm.js"
import { Media } from "./media.js"
import {
@ -16,11 +16,11 @@ import { RequestExecutor } from "./route/executor.js"
import {
AIError,
InvalidRequestError,
LanguageModel,
type CompactionCheckpointResponse,
type CompactionResponse,
type LLMEvent,
type LLMResponse,
type Model,
} from "./schema/index.js"
import type {
LoopObjectEvent,
@ -31,17 +31,12 @@ import type {
LLMLoopInput,
LLMRequestInput,
} from "./llm.js"
import { Speech, type SpeechModel, type SpeechRequest, type SpeechRequestInput } from "./speech.js"
import {
Transcription,
type TranscriptionModel,
type TranscriptionRequest,
type TranscriptionRequestInput,
} from "./transcription.js"
import { Speech, type SpeechRequest, type SpeechRequestInput } from "./speech.js"
import { Transcription, type TranscriptionRequest, type TranscriptionRequestInput } from "./transcription.js"
import { ToolFailure, build } from "./tool.js"
import type { NoExecute, ToolExecuteContext, ToolInput, ToolInputType, ToolOptions, ToolSchema } from "./tool.js"
import { fileMediaType } from "./utils/media-type.js"
import { Video, type VideoModel, type VideoRequest, type VideoRequestInput } from "./video.js"
import { Video, type VideoRequest, type VideoRequestInput } from "./video.js"
/**
* Promise-first entrypoint for scripts and non-Effect callers. One `ManagedRuntime` hosts the LLM, image, video, speech,
@ -110,36 +105,36 @@ export const make = (options: Options = {}) => {
),
)
function generate<const Model extends LanguageModel, S extends OutputSchema>(
input: LLMRequestInput<Model> & { readonly schema: S },
function generate<const SelectedModel extends Model<"chat">, S extends OutputSchema>(
input: LLMRequestInput<SelectedModel> & { readonly schema: S },
options?: StreamOptions & RunOptions,
): Promise<ObjectResponse<OutputType<S>>>
function generate<const Model extends LanguageModel>(
input: LLMRequestInput<Model>,
function generate<const SelectedModel extends Model<"chat">>(
input: LLMRequestInput<SelectedModel>,
options?: StreamOptions & RunOptions,
): Promise<LLMResponse>
function generate(input: LLMRequestInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) {
return run(LLM.generate(input, options), options)
}
function stream<const Model extends LanguageModel, S extends OutputSchema>(
input: LLMRequestInput<Model> & { readonly schema: S },
function stream<const SelectedModel extends Model<"chat">, S extends OutputSchema>(
input: LLMRequestInput<SelectedModel> & { readonly schema: S },
options?: StreamOptions & RunOptions,
): AsyncIterable<ObjectEvent<OutputType<S>>>
function stream<const Model extends LanguageModel>(
input: LLMRequestInput<Model>,
function stream<const SelectedModel extends Model<"chat">>(
input: LLMRequestInput<SelectedModel>,
options?: StreamOptions & RunOptions,
): AsyncIterable<LLMEvent>
function stream(input: LLMRequestInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) {
return iterate(LLM.stream(input, options), options)
}
function loop<const Model extends LanguageModel, S extends OutputSchema>(
input: LLMLoopInput<Model> & { readonly schema: S },
function loop<const SelectedModel extends Model<"chat">, S extends OutputSchema>(
input: LLMLoopInput<SelectedModel> & { readonly schema: S },
options?: StreamOptions & RunOptions,
): AsyncIterable<LoopObjectEvent<OutputType<S>>>
function loop<const Model extends LanguageModel>(
input: LLMLoopInput<Model>,
function loop<const SelectedModel extends Model<"chat">>(
input: LLMLoopInput<SelectedModel>,
options?: StreamOptions & RunOptions,
): AsyncIterable<LLMEvent>
function loop(input: LLMLoopInput & { readonly schema?: OutputSchema }, options?: StreamOptions & RunOptions) {
@ -229,23 +224,25 @@ export const make = (options: Options = {}) => {
canCompact: LLM.canCompact,
image: {
request: Image.request,
generate: <const Model extends ImageModel>(
input: ImageRequestInput<Model> | ImageRequest,
generate: <const SelectedModel extends Model<"image">>(
input: ImageRequestInput<SelectedModel> | ImageRequest,
options?: AwaitOptions & RunOptions,
) => run(Image.generate(input, options), options),
stream: <const Model extends ImageModel>(
input: ImageRequestInput<Model> | ImageRequest,
stream: <const SelectedModel extends Model<"image">>(
input: ImageRequestInput<SelectedModel> | ImageRequest,
options?: AwaitOptions & RunOptions,
) => iterate(Image.stream(input, options), options),
start: <const Model extends ImageModel>(input: ImageRequestInput<Model> | ImageRequest, options?: RunOptions) =>
run(Image.start(input), options).then(handle),
resume: (model: ImageModel, token: unknown, options?: RunOptions) =>
start: <const SelectedModel extends Model<"image">>(
input: ImageRequestInput<SelectedModel> | ImageRequest,
options?: RunOptions,
) => run(Image.start(input), options).then(handle),
resume: (model: Model<"image">, token: unknown, options?: RunOptions) =>
run(Image.resume(model, token), options).then(handle),
},
decision: {
request: Decision.request,
generate: <const Model extends DecisionModel, const Questions extends DecisionQuestions>(
input: DecisionRequestInput<Model, Questions>,
generate: <const SelectedModel extends Model<"decision">, const Questions extends DecisionQuestions>(
input: DecisionRequestInput<SelectedModel, Questions>,
options?: RunOptions,
) => run(Decision.generate(input), options),
},
@ -253,44 +250,46 @@ export const make = (options: Options = {}) => {
experimental: {
speech: {
request: Speech.request,
generate: <const Model extends SpeechModel>(
input: SpeechRequestInput<Model> | SpeechRequest,
generate: <const SelectedModel extends Model<"speech">>(
input: SpeechRequestInput<SelectedModel> | SpeechRequest,
options?: RunOptions,
) => run(Speech.generate(input), options),
stream: <const Model extends SpeechModel>(
input: SpeechRequestInput<Model> | SpeechRequest,
stream: <const SelectedModel extends Model<"speech">>(
input: SpeechRequestInput<SelectedModel> | SpeechRequest,
options?: RunOptions,
) => iterate(Speech.stream(input), options),
},
transcription: {
request: Transcription.request,
generate: <const Model extends TranscriptionModel>(
input: TranscriptionRequestInput<Model> | TranscriptionRequest,
generate: <const SelectedModel extends Model<"transcription">>(
input: TranscriptionRequestInput<SelectedModel> | TranscriptionRequest,
options?: AwaitOptions & RunOptions,
) => run(Transcription.generate(input, { poll: options?.poll }), options),
stream: <const Model extends TranscriptionModel>(
input: TranscriptionRequestInput<Model> | TranscriptionRequest,
stream: <const SelectedModel extends Model<"transcription">>(
input: TranscriptionRequestInput<SelectedModel> | TranscriptionRequest,
options?: AwaitOptions & RunOptions,
) => iterate(Transcription.stream(input, { poll: options?.poll }), options),
start: <const Model extends TranscriptionModel>(
input: TranscriptionRequestInput<Model> | TranscriptionRequest,
start: <const SelectedModel extends Model<"transcription">>(
input: TranscriptionRequestInput<SelectedModel> | TranscriptionRequest,
options?: RunOptions,
) => run(Transcription.start(input), options).then(handle),
resume: (model: TranscriptionModel, token: unknown, options?: RunOptions) =>
resume: (model: Model<"transcription">, token: unknown, options?: RunOptions) =>
run(Transcription.resume(model, token), options).then(handle),
},
video: {
request: Video.request,
start: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: RunOptions) =>
run(Video.start(input), options).then(handle),
generate: <const Model extends VideoModel>(
input: VideoRequestInput<Model> | VideoRequest,
start: <const SelectedModel extends Model<"video">>(
input: VideoRequestInput<SelectedModel> | VideoRequest,
options?: RunOptions,
) => run(Video.start(input), options).then(handle),
generate: <const SelectedModel extends Model<"video">>(
input: VideoRequestInput<SelectedModel> | VideoRequest,
options?: AwaitOptions & RunOptions,
) => run(Video.generate(input, { poll: options?.poll }), options),
resume: (model: VideoModel, token: unknown, options?: RunOptions) =>
resume: (model: Model<"video">, token: unknown, options?: RunOptions) =>
run(Video.resume(model, token), options).then(handle),
stream: <const Model extends VideoModel>(
input: VideoRequestInput<Model> | VideoRequest,
stream: <const SelectedModel extends Model<"video">>(
input: VideoRequestInput<SelectedModel> | VideoRequest,
options?: AwaitOptions & RunOptions,
) => iterate(Video.stream(input, { poll: options?.poll }), options),
},

View file

@ -20,7 +20,6 @@ import {
LLMResponse,
ResponseFold,
Message,
LanguageModel,
SystemPart,
type BaseRequest,
type CachePolicy,
@ -30,26 +29,28 @@ import {
ToolChoice,
ToolEntry,
Usage,
type LanguageModelProviderOptions,
type ModelProviderOptions,
type GenerationOptionsFields,
type LLMRequest,
type ToolEntryInput,
withPartial,
type Model,
} from "./schema/index.js"
import { tool, type ExecutableTool, type Tool, type ToolSchema } from "./tool.js"
import { runTools } from "./tool-runtime.js"
import { addUsage, nextRequest, pendingCalls } from "./loop.js"
/** Input accepted by `ai.request`, `ai.generate`, `ai.stream` and `ai.compact`. An `LLMRequest` is also a valid input. */
export type LLMRequestInput<Model extends LanguageModel = LanguageModel> = TextRequestFields<Model> & PromptOrMessages
export type LLMRequestInput<SelectedModel extends Model<"chat"> = Model<"chat">> = TextRequestFields<SelectedModel> &
PromptOrMessages
/** Exactly one of `prompt`, a single user message, or `messages`, the full conversation. */
export type PromptOrMessages =
| { readonly prompt: Message.UserContentInput; readonly messages?: never }
| { readonly messages: ReadonlyArray<Message | Message.Input>; readonly prompt?: never }
interface TextRequestFields<Model extends LanguageModel>
extends BaseRequest<Model, NoInfer<LanguageModelProviderOptions<Model>>>,
interface TextRequestFields<SelectedModel extends Model<"chat">>
extends BaseRequest<SelectedModel, NoInfer<ModelProviderOptions<SelectedModel>>>,
GenerationOptionsFields {
readonly id?: string
readonly system?: string | SystemPart | ReadonlyArray<SystemPart>
@ -77,12 +78,12 @@ export type ObjectEvent<T> = Exclude<LLMEvent, Finish> | (Finish & { readonly ob
export type LoopObjectEvent<T> = Exclude<LLMEvent, Finish> | (Finish & { readonly object?: T })
/** Run one model call. With `schema`, the model must answer through a forced tool call decoded into `object`. */
export function generate<const Model extends LanguageModel, S extends OutputSchema>(
input: LLMRequestInput<Model> & { readonly schema: S },
export function generate<const SelectedModel extends Model<"chat">, S extends OutputSchema>(
input: LLMRequestInput<SelectedModel> & { readonly schema: S },
options?: StreamOptions,
): Effect.Effect<ObjectResponse<OutputType<S>>, AIError, Service>
export function generate<const Model extends LanguageModel>(
input: LLMRequestInput<Model>,
export function generate<const SelectedModel extends Model<"chat">>(
input: LLMRequestInput<SelectedModel>,
options?: StreamOptions,
): Effect.Effect<LLMResponse, AIError, Service>
export function generate(input: Input, options?: StreamOptions) {
@ -103,12 +104,12 @@ export function generate(input: Input, options?: StreamOptions) {
* Stream one model call. The `finish` event carries the assistant `message` and `usage`; with `schema`, also the
* decoded `object`.
*/
export function stream<const Model extends LanguageModel, S extends OutputSchema>(
input: LLMRequestInput<Model> & { readonly schema: S },
export function stream<const SelectedModel extends Model<"chat">, S extends OutputSchema>(
input: LLMRequestInput<SelectedModel> & { readonly schema: S },
options?: StreamOptions,
): Stream.Stream<ObjectEvent<OutputType<S>>, AIError, Service>
export function stream<const Model extends LanguageModel>(
input: LLMRequestInput<Model>,
export function stream<const SelectedModel extends Model<"chat">>(
input: LLMRequestInput<SelectedModel>,
options?: StreamOptions,
): Stream.Stream<LLMEvent, AIError, Service>
export function stream(input: Input, options?: StreamOptions) {
@ -123,7 +124,10 @@ export function stream(input: Input, options?: StreamOptions) {
)
}
export type LLMLoopInput<Model extends LanguageModel = LanguageModel> = Omit<TextRequestFields<Model>, "tools"> &
export type LLMLoopInput<SelectedModel extends Model<"chat"> = Model<"chat">> = Omit<
TextRequestFields<SelectedModel>,
"tools"
> &
PromptOrMessages & {
readonly tools: ReadonlyArray<ExecutableTool>
/** Called after each step that has tool calls; returning `true` ends the loop without running them. */
@ -137,12 +141,12 @@ export type LLMLoopInput<Model extends LanguageModel = LanguageModel> = Omit<Tex
* the loop with the final step's reason and `message` and the usage summed across steps. With `schema`, the model ends
* by calling the hidden answer tool, decoded into `object` on the `finish`.
*/
export function loop<const Model extends LanguageModel, S extends OutputSchema>(
input: LLMLoopInput<Model> & { readonly schema: S },
export function loop<const SelectedModel extends Model<"chat">, S extends OutputSchema>(
input: LLMLoopInput<SelectedModel> & { readonly schema: S },
options?: StreamOptions,
): Stream.Stream<LoopObjectEvent<OutputType<S>>, AIError, Service>
export function loop<const Model extends LanguageModel>(
input: LLMLoopInput<Model>,
export function loop<const SelectedModel extends Model<"chat">>(
input: LLMLoopInput<SelectedModel>,
options?: StreamOptions,
): Stream.Stream<LLMEvent, AIError, Service>
export function loop(input: LLMLoopInput & { readonly schema?: OutputSchema }, options?: StreamOptions) {
@ -289,7 +293,9 @@ const decodeObject = (output: Tool, response: LLMResponse) => {
}
/** Normalize text request input into a plain `LLMRequest`, with `prompt` turned into the one user message. */
export const request = <const Model extends LanguageModel>(input: LLMRequestInput<Model>): LLMRequest<Model> => {
export const request = <const SelectedModel extends Model<"chat">>(
input: LLMRequestInput<SelectedModel>,
): LLMRequest<SelectedModel> => {
if ((input.prompt === undefined) === (input.messages === undefined))
throw new AIError({
reason: new InvalidRequestError({ message: "Pass exactly one of `prompt` or `messages`, not both or neither" }),
@ -326,7 +332,7 @@ export function compact(
input: CheckpointRequest | CompactionRequest,
options?: EndpointCompactOptions | TriggerCompactOptions,
) {
return tryRequest(() => request<LanguageModel>(input)).pipe(
return tryRequest(() => request<Model<"chat">>(input)).pipe(
Effect.flatMap((normalized) => compactRequest(normalized, options)),
)
}

View file

@ -2,11 +2,14 @@ import { type Context, Effect, Layer, Stream } from "effect"
import { resultEvents, type AwaitOptions, type Generation, type Observation } from "./generation.js"
import { RequestExecutor } from "./route/executor.js"
import type { MediaRoute } from "./route/media.js"
import { AIError, UnsupportedOperationError } from "./schema/index.js"
import { AIError, implementation, UnsupportedOperationError } from "./schema/index.js"
/** A media request whose model carries the route that executes it. */
/** A media request whose model may carry the route that executes it; media models get theirs from a provider. */
export interface RoutedRequest<Self extends MediaRoute.MediaRequest, Event, Response> extends MediaRoute.MediaRequest {
readonly model: MediaRoute.MediaRequest["model"] & { readonly route: MediaRoute.AnyRoute<Self, Event, Response> }
readonly model: MediaRoute.MediaRequest["model"] & {
readonly api: string
readonly [implementation]?: MediaRoute.AnyRoute<Self, Event, Response>
}
}
/** `start` and `resume` fail with `UnsupportedOperation` on inline and stream routes. */
@ -40,31 +43,52 @@ export const make = <Self, Req extends RoutedRequest<Req, Event, Response>, Even
message: `${route.provider}/${route.id} is not a queued route; use generate or stream`,
}),
})
const start = (request: Req) => {
const route = request.model.route
if (route.kind !== "queued") return Effect.fail(notQueued(route, "start"))
return route.start(request, executor.execute)
const routeOf = (model: Req["model"]) => {
const route = model[implementation]
if (route !== undefined) return Effect.succeed(route)
return Effect.fail(
new AIError({
reason: new UnsupportedOperationError({
operation: input.modality,
provider: model.provider,
route: model.api,
message: `${model.provider}/${model.id}: media models run on their provider's implementation; build it with a provider`,
}),
}),
)
}
const start = (request: Req) =>
Effect.flatMap(routeOf(request.model), (route) => {
if (route.kind !== "queued") return Effect.fail(notQueued(route, "start"))
return route.start(request, executor.execute)
})
return service.of({
start,
resume: (model, token) => {
if (model.route.kind !== "queued") return Effect.fail(notQueued(model.route, "resume"))
return model.route.resume(model, token, executor.execute)
},
generate: (request, options) => {
const route = request.model.route
if (route.kind !== "queued") return route.generate(request, executor.execute)
return start(request).pipe(Effect.flatMap((generation) => generation.await(options)))
},
stream: (request, options) => {
const route = request.model.route
if (route.kind === "stream") return route.stream(request, executor.execute)
if (route.kind === "queued")
return Stream.unwrap(
start(request).pipe(Effect.map((generation) => resultEvents(generation, input.responseEvents, options))),
)
return Stream.fromIterableEffect(Effect.map(route.generate(request, executor.execute), input.responseEvents))
},
resume: (model, token) =>
Effect.flatMap(routeOf(model), (route) => {
if (route.kind !== "queued") return Effect.fail(notQueued(route, "resume"))
return route.resume(model, token, executor.execute)
}),
generate: (request, options) =>
Effect.flatMap(routeOf(request.model), (route) => {
if (route.kind !== "queued") return route.generate(request, executor.execute)
return start(request).pipe(Effect.flatMap((generation) => generation.await(options)))
}),
stream: (request, options) =>
Stream.unwrap(
Effect.map(routeOf(request.model), (route) => {
if (route.kind === "stream") return route.stream(request, executor.execute)
if (route.kind === "queued")
return Stream.unwrap(
start(request).pipe(
Effect.map((generation) => resultEvents(generation, input.responseEvents, options)),
),
)
return Stream.fromIterableEffect(
Effect.map(route.generate(request, executor.execute), input.responseEvents),
)
}),
),
})
}),
),

View file

@ -5,48 +5,14 @@ import type { MediaProtocol } from "./route/media-protocol.js"
import {
AIError,
InvalidRequestError,
ModelID,
ProviderID,
mergeRequestOptions,
type HttpOptions,
type ProviderOptions,
} from "./schema/index.js"
/**
* What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
* (`ImageModel`, `VideoModel`, `SpeechModel`, `TranscriptionModel`) extend it with their route type and a nominal
* marker so one cannot stand in for the other in requests.
*/
export class MediaModel<Route, Options> {
// As with `LanguageModel`, the route type is erased over `Options`; `fromRoute` and the constructor trust that the
// route accepts every request this model's `Options` admit.
declare protected readonly _Options: Options
readonly id: ModelID
readonly provider: ProviderID
readonly route: Route
readonly http?: HttpOptions
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
readonly providerOptions?: ProviderOptions
constructor(input: MediaModel.Input<Route>) {
this.id = ModelID.make(input.id)
this.provider = ProviderID.make(input.provider)
this.route = input.route
this.http = input.http
this.providerOptions = input.providerOptions
}
}
export namespace MediaModel {
export type Options = ProviderOptions
export interface Input<Route> {
readonly id: string | ModelID
readonly provider: string | ProviderID
readonly route: Route
readonly http?: HttpOptions
readonly providerOptions?: ProviderOptions
}
/** A protocol plus its canonical start path; `ModelInput.baseURL` overrides `baseURL` per deployment. */
export interface RouteInput<Request extends MediaRoute.MediaRequest, Protocol> {
readonly protocol: Protocol
@ -77,6 +43,10 @@ export namespace MediaModel {
| QueuedRouteInput<Request, Response, Token>
}
/** A media deployment's `http` overlays and `providerOptions` defaults as model options. */
export const mediaOptions = (input: { readonly http?: HttpOptions; readonly providerOptions?: ProviderOptions }) =>
mergeRequestOptions({ http: input.http, providerOptions: input.providerOptions })
/** Compose a protocol route input with one deployment through `MediaRoute.inline`, `queued`, or `stream`. */
export const composeRoute = <Request extends MediaRoute.MediaRequest, Event, Response, Frame, State, Token>(
route: MediaModel.AnyRouteInput<Request, Event, Response, Frame, State, Token>,

View file

@ -1,6 +1,6 @@
import { Effect, Schema } from "effect"
import { Protocol } from "../route/protocol.js"
import type { LanguageModelCompatibility, Capabilities } from "../schema/index.js"
import type { Compatibility, Capabilities } from "../schema/index.js"
import { OpenAIChat } from "./openai-chat.js"
import { JsonObject, ProviderShared } from "./shared.js"
import { cacheControl } from "./utils/cache.js"
@ -43,12 +43,13 @@ export const compatibility = {
maxTokensField: "max_completion_tokens",
reasoningField: "reasoning_content",
zaiToolStream: false,
} satisfies LanguageModelCompatibility
} satisfies Compatibility
export const capabilities = { tools: { strict: false } } satisfies Capabilities
export const protocol = Protocol.make({
id: "alibaba-chat",
api: "chat-completions",
body: {
schema: Schema.Struct({
...OpenAIChat.bodyFields,

View file

@ -1,9 +1,9 @@
import { Duration, Effect, Schema } from "effect"
import type { HttpClientResponse } from "effect/http"
import { ImageModel, ImageResponse, type ImageRequest } from "../image.js"
import { ImageResponse, type ImageRequest, imageModel } from "../image.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords } from "../schema/index.js"
import { mergeJsonRecords, type Model } from "../schema/index.js"
import { JsonObject, ProviderShared, lenient } from "./shared.js"
import { ImageSizing } from "./utils/image-sizing.js"
@ -27,7 +27,7 @@ export type AlibabaImageOptions = {
readonly enableSequential?: boolean
} & Record<string, unknown>
export type Request = ImageRequest<ImageModel<AlibabaImageOptions>>
export type Request = ImageRequest<Model<"image", AlibabaImageOptions>>
// ---------------------------------------------------------------------------
// 2. Response schema
@ -117,8 +117,7 @@ export const protocol = MediaProtocol.inline<Request, ImageResponse>(route, {
response: { decode: decodeResponse },
})
export const model = (input: MediaRoute.ModelInput) =>
ImageModel.fromRoute<AlibabaImageOptions>({ protocol, path: PATH }, input)
export const model = (input: MediaRoute.ModelInput) => imageModel<AlibabaImageOptions>({ protocol, path: PATH }, input)
export const AlibabaImages = {
protocol,

View file

@ -17,6 +17,7 @@ const Options = Schema.Struct({
export type OptionsInput = typeof Options.Type & Pick<AnthropicMessages.OptionsInput, "outputConfig">
export const protocol = Protocol.make({
id: "alibaba-messages",
api: "messages",
body: {
schema: Schema.Struct({
...AnthropicMessages.AnthropicMessagesBody.fields,

View file

@ -44,6 +44,7 @@ const tools = {
export const protocol = Protocol.make({
id: adapter.id,
api: "responses",
body: {
schema: Body,
from: Effect.fn("AlibabaResponses.fromRequest")(function* (req) {

View file

@ -32,6 +32,7 @@ import * as Cache from "./utils/cache.js"
import { claudeVersion, supportsThinkingBlockBinding, THINKING_BINDING_BETA } from "./utils/claude-model.js"
import { Lifecycle } from "./utils/lifecycle.js"
import { ToolStream } from "./utils/tool-stream.js"
import { routeOf } from "../schema/model.js"
const ADAPTER = "anthropic-messages"
export const DEFAULT_BASE_URL = "https://api.anthropic.com/v1"
@ -657,7 +658,7 @@ const lowerMedia = Effect.fnUntraced(function* (part: MediaPart, request: LLMReq
} satisfies AnthropicVideoBlock
}
const options = yield* decodeMediaOptions(
part.providerMetadata?.[request.model.route.providerMetadataKey ?? request.model.provider] ?? {},
part.providerMetadata?.[routeOf(request.model).providerMetadataKey ?? request.model.provider] ?? {},
)
const image = (source: AnthropicImageBlock["source"]): AnthropicImageBlock => ({
type: "image",
@ -727,7 +728,7 @@ const requireThinkingSignature = (request: LLMRequest) => {
if (request.model.compatibility?.requireSignature !== undefined) return request.model.compatibility.requireSignature
const provider = request.model.provider.toLowerCase()
const model = request.model.id.toLowerCase()
const baseURL = (request.model.route.endpoint.baseURL ?? "").toLowerCase()
const baseURL = (routeOf(request.model).endpoint.baseURL ?? "").toLowerCase()
if (
provider === "kimi-for-coding" ||
provider === "moonshotai" ||
@ -800,7 +801,7 @@ const appendToUserTurn = (messages: AnthropicMessage[], block: AnthropicUserBloc
const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoints: Cache.Breakpoints) {
const messages: AnthropicMessage[] = []
const providerMetadataKey = request.model.route.providerMetadataKey ?? request.model.provider
const providerMetadataKey = routeOf(request.model).providerMetadataKey ?? request.model.provider
// Text updates stay where they are unless a user turn follows them; then they move after the latest
// user turn, the nearest spot where Anthropic accepts a native system message.
const holdUpdates = supportsNativeSystemUpdates(request)
@ -916,7 +917,7 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoi
})
// The model-ID checks below are fallbacks for models that leave `capabilities.reasoning.updates`,
// `capabilities.systemUpdates` and `compatibility.supportsThinkingBlockBinding` unset.
// `capabilities.systemUpdates` and `compatibility.thinkingBlockBinding` unset.
const isThinkingOff = Schema.is(AnthropicThinkingDisabled)
// Per-turn effort started with Claude Opus 5 and every Claude 5.1 model; later versions of any family inherit it.
@ -1503,6 +1504,7 @@ const step = (state: ParserState, event: AnthropicEvent) => {
*/
export const protocol = Protocol.make({
id: ADAPTER,
api: "messages",
body: {
schema: AnthropicMessagesBody,
from: fromRequest,
@ -1512,7 +1514,7 @@ export const protocol = Protocol.make({
initial: (request) => ({
provider: request.model.provider,
compactions: {},
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
providerMetadataKey: routeOf(request.model).providerMetadataKey ?? request.model.provider,
tools: ToolStream.empty<number>(),
reasoningSignatures: {},
lifecycle: Lifecycle.initial(),

View file

@ -4,8 +4,8 @@ import type { Status } from "../generation.js"
import { Media } from "../media.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, type OpenString } from "../schema/index.js"
import { TranscriptionModel, TranscriptionResponse, type TranscriptionRequest } from "../transcription.js"
import { mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import { TranscriptionResponse, type TranscriptionRequest, transcriptionModel } from "../transcription.js"
import { ProviderShared, optionalNull } from "./shared.js"
import { MediaInput } from "./utils/media-input.js"
@ -34,7 +34,7 @@ export type AssemblyAITranscriptionOptions = {
readonly speech_models?: ReadonlyArray<OpenString<"universal-3-5-pro" | "universal-2">>
} & Record<string, unknown>
export type Request = TranscriptionRequest<TranscriptionModel<AssemblyAITranscriptionOptions>>
export type Request = TranscriptionRequest<Model<"transcription", AssemblyAITranscriptionOptions>>
// ---------------------------------------------------------------------------
// 2. Token and response schemas
@ -198,10 +198,7 @@ export const protocol = MediaProtocol.queued<Request, TranscriptionResponse, Tok
})
export const model = (input: MediaRoute.ModelInput) =>
TranscriptionModel.fromRoute<AssemblyAITranscriptionOptions, Token>(
{ protocol, baseURL: DEFAULT_BASE_URL, path: PATH },
input,
)
transcriptionModel<AssemblyAITranscriptionOptions, Token>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
export const AssemblyAITranscription = {
protocol,

View file

@ -11,13 +11,13 @@ import {
type FinishReason,
type FinishReasonDetails,
type LLMRequest,
type LanguageModel,
type ProviderMetadata,
type ProviderOptions,
type ReasoningPart,
type ToolCallPart,
type ToolDefinition,
type ToolResultPart,
type Model,
} from "../schema/index.js"
import { BedrockEventStream } from "./bedrock-event-stream.js"
import { classifyProviderFailure } from "../provider-error.js"
@ -31,6 +31,7 @@ import { Lifecycle } from "./utils/lifecycle.js"
import { MistralToolID } from "./utils/mistral-tool-id.js"
import { ToolStream } from "./utils/tool-stream.js"
import { concatBytes } from "../utils/bytes.js"
import { routeOf } from "../schema/model.js"
const ADAPTER = "bedrock-converse"
@ -357,7 +358,7 @@ const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest, breakpoi
const documentNames = new Set<string>()
// Mistral can reject replay IDs even when they satisfy Converse's broader ID syntax.
const normalizeID = request.model.id.includes("mistral.") ? MistralToolID.normalizer(request) : (id: string) => id
const providerMetadataKey = request.model.route.providerMetadataKey ?? request.model.provider
const providerMetadataKey = routeOf(request.model).providerMetadataKey ?? request.model.provider
const hoistImages = !keepToolImagesInline(request.model.id)
// Bedrock expects parallel tool results before any images hoisted beside them.
const pendingImages: BedrockMedia.ImageBlock[] = []
@ -475,7 +476,7 @@ const lowerSystem = (breakpoints: BedrockCache.Breakpoints, system: ReadonlyArra
// Nova 2 rejects `maxTokens` at high reasoning effort, where its output can exceed the field's maximum. Other models
// that take `reasoningConfig`, such as Grok on Bedrock, accept it.
const isNova2 = (model: LanguageModel) => /\bamazon\.nova-2-/.test(model.id)
const isNova2 = (model: Model<"chat">) => /\bamazon\.nova-2-/.test(model.id)
const isHighReasoningEffort = Schema.is(
Schema.Struct({
additionalModelRequestFields: Schema.Struct({
@ -485,12 +486,12 @@ const isHighReasoningEffort = Schema.is(
)
// Claude 4.6+ pairs effort with adaptive thinking; earlier Claude models take effort beside a manual budget.
const supportsAdaptiveThinking = (model: LanguageModel) => {
const supportsAdaptiveThinking = (model: Model<"chat">) => {
const version = claudeVersion(model.id)
return version !== undefined && (version.major > 4 || (version.major === 4 && version.minor >= 6))
}
const effortFields = (model: LanguageModel, effort: string) => {
const effortFields = (model: Model<"chat">, effort: string) => {
if (model.id.includes("anthropic")) return { output_config: { effort } }
// gpt-oss takes the flat chat-completions spelling; newer OpenAI and xAI models take the Responses one.
if (model.id.includes("openai.gpt-oss")) return { reasoning_effort: effort }
@ -945,6 +946,7 @@ const onHalt = (state: ParserState): ReadonlyArray<LLMEvent> => {
*/
export const protocol = Protocol.make({
id: ADAPTER,
api: "converse",
body: {
schema: BedrockConverseBody,
from: fromRequest,
@ -952,7 +954,7 @@ export const protocol = Protocol.make({
stream: {
event: BedrockEventStream.Frame.pipe(Schema.decodeTo(BedrockEvent)),
initial: (request) => ({
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
providerMetadataKey: routeOf(request.model).providerMetadataKey ?? request.model.provider,
tools: ToolStream.empty<number>(),
finishReason: undefined,
usage: undefined,

View file

@ -3,8 +3,8 @@ import { classifyProviderFailure } from "../provider-error.js"
import { Framing } from "../route/framing.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { AIError, mergeJsonRecords, type OpenString } from "../schema/index.js"
import { SpeechModel, type SpeechEvent, type SpeechRequest } from "../speech.js"
import { AIError, mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import { type SpeechEvent, type SpeechRequest, speechModel } from "../speech.js"
import { ProviderShared, optionalNull } from "./shared.js"
import { SpeechStream } from "./utils/speech-stream.js"
@ -33,7 +33,7 @@ export type CartesiaSpeechOptions = {
readonly pronunciation_dict_id?: string
} & Record<string, unknown>
export type Request = SpeechRequest<SpeechModel<CartesiaSpeechOptions>>
export type Request = SpeechRequest<Model<"speech", CartesiaSpeechOptions>>
// ---------------------------------------------------------------------------
// 3. Streaming event schema
@ -166,7 +166,7 @@ export const protocol = MediaProtocol.stream<Request, SpeechEvent, string | Uint
})
export const model = (input: MediaRoute.ModelInput) =>
SpeechModel.fromRoute<CartesiaSpeechOptions, string | Uint8Array, State>(
speechModel<CartesiaSpeechOptions, string | Uint8Array, State>(
{
protocol,
baseURL: DEFAULT_BASE_URL,

View file

@ -1,10 +1,10 @@
import { Effect, Schema } from "effect"
import type { HttpClientResponse } from "effect/http"
import { ImageModel, ImageResponse, type ImageRequest } from "../image.js"
import { ImageResponse, type ImageRequest, imageModel } from "../image.js"
import { Media } from "../media.js"
import { MediaProtocol } from "../route/media-protocol.js"
import type { MediaRoute } from "../route/media.js"
import { mergeJsonRecords } from "../schema/index.js"
import { mergeJsonRecords, type Model } from "../schema/index.js"
import { ProviderShared } from "./shared.js"
import { ImageSizing } from "./utils/image-sizing.js"
import { MediaInput } from "./utils/media-input.js"
@ -36,7 +36,7 @@ export type CloudflareWorkersAIImageOptions = {
readonly negative_prompt?: string
} & Record<string, unknown>
export type Request = ImageRequest<ImageModel<CloudflareWorkersAIImageOptions>>
export type Request = ImageRequest<Model<"image", CloudflareWorkersAIImageOptions>>
// ---------------------------------------------------------------------------
// 2. Response schema
@ -113,10 +113,7 @@ export const protocol = MediaProtocol.inline<Request, ImageResponse>(route, {
})
export const model = (input: MediaRoute.ModelInput) =>
ImageModel.fromRoute<CloudflareWorkersAIImageOptions>(
{ protocol, path: ({ request }) => `/${request.model.id}` },
input,
)
imageModel<CloudflareWorkersAIImageOptions>({ protocol, path: ({ request }) => `/${request.model.id}` }, input)
export const CloudflareWorkersAIImages = {
protocol,

View file

@ -334,6 +334,7 @@ const step = Effect.fnUntraced(function* (state: State, event: Event) {
export const protocol = Protocol.make({
id: ADAPTER,
api: "cohere-chat",
body: { schema: Body, from: fromRequest },
stream: {
event: Protocol.jsonEvent(Event),

View file

@ -1,8 +1,8 @@
import { Effect } from "effect"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, type OpenString } from "../schema/index.js"
import { SpeechModel, type SpeechEvent, type SpeechRequest } from "../speech.js"
import { mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import { type SpeechEvent, type SpeechRequest, speechModel } from "../speech.js"
import { MediaInput } from "./utils/media-input.js"
import { SpeechStream } from "./utils/speech-stream.js"
@ -25,7 +25,7 @@ export type DeepgramSpeechOptions = {
readonly tag?: string
} & Record<string, unknown>
export type Request = SpeechRequest<SpeechModel<DeepgramSpeechOptions>>
export type Request = SpeechRequest<Model<"speech", DeepgramSpeechOptions>>
// ---------------------------------------------------------------------------
// 4. Parser state
@ -137,10 +137,7 @@ export const protocol = MediaProtocol.stream<Request, SpeechEvent, Uint8Array, S
})
export const model = (input: MediaRoute.ModelInput) =>
SpeechModel.fromRoute<DeepgramSpeechOptions, Uint8Array, State>(
{ protocol, baseURL: DEFAULT_BASE_URL, path: PATH },
input,
)
speechModel<DeepgramSpeechOptions, Uint8Array, State>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
export const DeepgramSpeech = {
protocol,

View file

@ -2,8 +2,8 @@ import { Effect, Schema } from "effect"
import type { HttpClientResponse } from "effect/http"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, type OpenString } from "../schema/index.js"
import { TranscriptionModel, TranscriptionResponse, type TranscriptionRequest } from "../transcription.js"
import { mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import { TranscriptionResponse, type TranscriptionRequest, transcriptionModel } from "../transcription.js"
import { ProviderShared } from "./shared.js"
import { MediaInput } from "./utils/media-input.js"
import { SpeakerTurns } from "./utils/speaker-turns.js"
@ -30,7 +30,7 @@ export type DeepgramTranscriptionOptions = {
readonly tag?: string | ReadonlyArray<string>
} & Record<string, unknown>
export type Request = TranscriptionRequest<TranscriptionModel<DeepgramTranscriptionOptions>>
export type Request = TranscriptionRequest<Model<"transcription", DeepgramTranscriptionOptions>>
// ---------------------------------------------------------------------------
// 2. Response schema
@ -171,7 +171,7 @@ export const protocol = MediaProtocol.inline<Request, TranscriptionResponse>(rou
})
export const model = (input: MediaRoute.ModelInput) =>
TranscriptionModel.fromRoute<DeepgramTranscriptionOptions>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
transcriptionModel<DeepgramTranscriptionOptions>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
export const DeepgramTranscription = {
protocol,

View file

@ -2,8 +2,8 @@ import { Effect, Schema } from "effect"
import { Framing } from "../route/framing.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, type OpenString } from "../schema/index.js"
import { SpeechModel, type SpeechEvent, type SpeechRequest } from "../speech.js"
import { mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import { type SpeechEvent, type SpeechRequest, speechModel } from "../speech.js"
import { ProviderShared, optionalNull } from "./shared.js"
import { SpeechStream } from "./utils/speech-stream.js"
@ -58,7 +58,7 @@ export type ElevenLabsSpeechOptions = {
readonly apply_text_normalization?: OpenString<"auto" | "on" | "off">
} & Record<string, unknown>
export type Request = SpeechRequest<SpeechModel<ElevenLabsSpeechOptions>>
export type Request = SpeechRequest<Model<"speech", ElevenLabsSpeechOptions>>
// ---------------------------------------------------------------------------
// 3. Streaming event schema
@ -196,7 +196,7 @@ export const protocol = MediaProtocol.stream<Request, SpeechEvent, string | Uint
})
export const model = (input: MediaRoute.ModelInput) =>
SpeechModel.fromRoute<ElevenLabsSpeechOptions, string | Uint8Array, State>(
speechModel<ElevenLabsSpeechOptions, string | Uint8Array, State>(
{ protocol, baseURL: DEFAULT_BASE_URL, path: ({ request }) => path(request) },
input,
)

View file

@ -2,8 +2,8 @@ import { Effect, Schema } from "effect"
import type { HttpClientResponse } from "effect/http"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, type OpenString } from "../schema/index.js"
import { TranscriptionModel, TranscriptionResponse, type TranscriptionRequest } from "../transcription.js"
import { mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import { TranscriptionResponse, type TranscriptionRequest, transcriptionModel } from "../transcription.js"
import { mediaTypeExtension } from "../utils/media-type.js"
import { ProviderShared, optionalNull } from "./shared.js"
import { MediaInput } from "./utils/media-input.js"
@ -37,7 +37,7 @@ export type ElevenLabsTranscriptionOptions = {
readonly entity_redaction_mode?: OpenString<"redacted" | "entity_type" | "enumerated_entity_type">
} & Record<string, unknown>
export type Request = TranscriptionRequest<TranscriptionModel<ElevenLabsTranscriptionOptions>>
export type Request = TranscriptionRequest<Model<"transcription", ElevenLabsTranscriptionOptions>>
// ---------------------------------------------------------------------------
// 2. Response schema
@ -200,10 +200,7 @@ export const protocol = MediaProtocol.inline<Request, TranscriptionResponse>(rou
})
export const model = (input: MediaRoute.ModelInput) =>
TranscriptionModel.fromRoute<ElevenLabsTranscriptionOptions>(
{ protocol, baseURL: DEFAULT_BASE_URL, path: PATH },
input,
)
transcriptionModel<ElevenLabsTranscriptionOptions>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
export const ElevenLabsTranscription = {
protocol,

View file

@ -29,6 +29,7 @@ import { Media } from "../media.js"
import { JsonObject, knownString, lenient, optionalArray, optionalNull, ProviderShared } from "./shared.js"
import { GeminiGenerateContent } from "./utils/gemini-generate-content.js"
import { Lifecycle } from "./utils/lifecycle.js"
import { routeOf } from "../schema/model.js"
const ADAPTER = "gemini"
const CONTINUATION = "CONTINUATION"
@ -315,7 +316,7 @@ const lowerToolCall = (part: ToolCallPart, omitIds: boolean, metadataKey: string
const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest) {
const contents: GeminiContent[] = []
const metadataKey = request.model.route.providerMetadataKey ?? request.model.provider
const metadataKey = routeOf(request.model).providerMetadataKey ?? request.model.provider
const omitCallIds = omitsFunctionCallIds(request.model.id)
const legacyToolMedia = routesLegacyToolMedia(request.model.id)
let pendingMedia: Array<GeminiInlineDataPart | typeof GeminiFileDataPart.Type> | undefined
@ -823,7 +824,7 @@ export const transport: Transport<GeminiBody, Prepared, unknown> = {
prepare: (input) => sse.prepare(input).pipe(Effect.map((http) => ({ http, input }))),
execute: (prepared, request, runtime) =>
Effect.gen(function* () {
const route = request.model.route.id
const route = routeOf(request.model).id
const label = `${request.model.provider}/${route}`
// Frames are parsed once here, so errors recover each frame's raw text for their body.
const raw = new WeakMap<object, string>()
@ -890,6 +891,7 @@ export const transport: Transport<GeminiBody, Prepared, unknown> = {
*/
export const protocol = Protocol.make({
id: ADAPTER,
api: "generate-content",
body: {
schema: GeminiBody,
from: fromRequest,
@ -899,8 +901,8 @@ export const protocol = Protocol.make({
stream: {
event: Schema.Union([Schema.instanceOf(NextRequest), GeminiEvent]),
initial: (request): ParserState => ({
route: `${request.model.provider}/${request.model.route.id}`,
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
route: `${request.model.provider}/${routeOf(request.model).id}`,
providerMetadataKey: routeOf(request.model).providerMetadataKey ?? request.model.provider,
hasToolCalls: false,
lifecycle: Lifecycle.initial(),
nextReasoningId: 0,

View file

@ -1,9 +1,9 @@
import { Effect, Schema } from "effect"
import type { HttpClientResponse } from "effect/http"
import { ImageModel, ImageResponse, type ImageRequest } from "../image.js"
import { ImageResponse, type ImageRequest, imageModel } from "../image.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, tokenUsage, type OpenString } from "../schema/index.js"
import { mergeJsonRecords, tokenUsage, type OpenString, type Model } from "../schema/index.js"
import { ProviderShared } from "./shared.js"
import { GeminiGenerateContent } from "./utils/gemini-generate-content.js"
import { MediaInput } from "./utils/media-input.js"
@ -22,7 +22,7 @@ export type GoogleImageOptions = {
readonly includeThoughts?: boolean
} & Record<string, unknown>
export type Request = ImageRequest<ImageModel<GoogleImageOptions>>
export type Request = ImageRequest<Model<"image", GoogleImageOptions>>
// ---------------------------------------------------------------------------
// 2. Response schema
@ -240,7 +240,7 @@ export const protocol = MediaProtocol.inline<Request, ImageResponse>(route, {
})
export const model = (input: MediaRoute.ModelInput) =>
ImageModel.fromRoute<GoogleImageOptions>(
imageModel<GoogleImageOptions>(
{
protocol,
baseURL: DEFAULT_BASE_URL,

View file

@ -23,6 +23,7 @@ import { Lifecycle } from "./utils/lifecycle.js"
import { MediaInput } from "./utils/media-input.js"
import { GeminiGenerateContent } from "./utils/gemini-generate-content.js"
import { ToolStream } from "./utils/tool-stream.js"
import { routeOf } from "../schema/model.js"
const ADAPTER = "google-interactions"
const SKIP_THOUGHT_SIGNATURE_VALIDATOR = "skip_thought_signature_validator"
@ -253,7 +254,7 @@ const signature = (metadata: ProviderMetadata | undefined, key: string) => {
const lowerMessages = Effect.fnUntraced(function* (request: LLMRequest) {
const steps: InputStep[] = []
const key = request.model.route.providerMetadataKey ?? request.model.provider
const key = routeOf(request.model).providerMetadataKey ?? request.model.provider
for (const message of request.messages) {
if (message.role === "system") {
const part = yield* ProviderShared.wrappedSystemUpdate("Google Interactions", message)
@ -597,13 +598,14 @@ const step = Effect.fnUntraced(function* (state: ParserState, event: Event) {
// =============================================================================
export const protocol = Protocol.make({
id: ADAPTER,
api: "interactions",
sanitizer: "gemini",
body: { schema: Body, from: fromRequest },
stream: {
event: Protocol.jsonEvent(Event),
initial: (request): ParserState => ({
route: `${request.model.provider}/${request.model.route.id}`,
metadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
route: `${request.model.provider}/${routeOf(request.model).id}`,
metadataKey: routeOf(request.model).providerMetadataKey ?? request.model.provider,
lifecycle: Lifecycle.initial(),
steps: {},
tools: ToolStream.empty<number>(),

View file

@ -1,8 +1,8 @@
import { Effect, Schema } from "effect"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords } from "../schema/index.js"
import { SpeechModel, type SpeechEvent, type SpeechRequest } from "../speech.js"
import { mergeJsonRecords, type Model } from "../schema/index.js"
import { type SpeechEvent, type SpeechRequest, speechModel } from "../speech.js"
import { GeminiGenerateContent } from "./utils/gemini-generate-content.js"
import { SpeechStream } from "./utils/speech-stream.js"
@ -28,7 +28,7 @@ export type GoogleSpeechOptions = {
}
} & Record<string, unknown>
export type Request = SpeechRequest<SpeechModel<GoogleSpeechOptions>>
export type Request = SpeechRequest<Model<"speech", GoogleSpeechOptions>>
// ---------------------------------------------------------------------------
// 3. Streaming event schema
@ -141,7 +141,7 @@ export const protocol = MediaProtocol.stream<Request, SpeechEvent, string, State
})
export const model = (input: MediaRoute.ModelInput) =>
SpeechModel.fromRoute<GoogleSpeechOptions, string, State>(
speechModel<GoogleSpeechOptions, string, State>(
{
protocol,
baseURL: DEFAULT_BASE_URL,

View file

@ -1,16 +1,16 @@
import { Effect, Schema, SchemaGetter } from "effect"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, type OpenString } from "../schema/index.js"
import { mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import {
TranscriptionFinishEvent,
TranscriptionModel,
TranscriptionSegmentEvent,
TranscriptionTextDeltaEvent,
type TranscriptionRequest,
type TranscriptionSegment,
type TranscriptionWord,
type TranscriptionEvent,
transcriptionModel,
} from "../transcription.js"
import { GeminiGenerateContent } from "./utils/gemini-generate-content.js"
@ -33,7 +33,7 @@ export type GoogleTranscriptionOptions = {
}
} & Record<string, unknown>
export type Request = TranscriptionRequest<TranscriptionModel<GoogleTranscriptionOptions>>
export type Request = TranscriptionRequest<Model<"transcription", GoogleTranscriptionOptions>>
// ---------------------------------------------------------------------------
// 3. Streaming event schema
@ -191,7 +191,7 @@ export const protocol = MediaProtocol.stream<Request, TranscriptionEvent, string
})
export const model = (input: MediaRoute.ModelInput) =>
TranscriptionModel.fromRoute<GoogleTranscriptionOptions, string, State>(
transcriptionModel<GoogleTranscriptionOptions, string, State>(
{
protocol,
baseURL: DEFAULT_BASE_URL,

View file

@ -4,8 +4,8 @@ import type { Status } from "../generation.js"
import { Media } from "../media.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, type OpenString } from "../schema/index.js"
import { VideoModel, VideoResponse, type VideoRequest } from "../video.js"
import { mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import { VideoResponse, type VideoRequest, videoModel } from "../video.js"
import { ProviderShared, optionalArray } from "./shared.js"
const route = MediaProtocol.identity({ id: "google-video", name: "Google Veo", provider: "google" })
@ -22,7 +22,7 @@ export type GoogleVideoOptions = {
readonly personGeneration?: OpenString<"allow_all" | "allow_adult" | "dont_allow">
} & Record<string, unknown>
export type Request = VideoRequest<VideoModel<GoogleVideoOptions>>
export type Request = VideoRequest<Model<"video", GoogleVideoOptions>>
// ---------------------------------------------------------------------------
// 2. Token and response schemas
@ -213,7 +213,7 @@ export const protocol = MediaProtocol.queued<Request, VideoResponse, Token>(rout
})
export const model = (input: MediaRoute.ModelInput) =>
VideoModel.fromRoute<GoogleVideoOptions, Token>(
videoModel<GoogleVideoOptions, Token>(
{
protocol,
baseURL: DEFAULT_BASE_URL,

View file

@ -1,10 +1,10 @@
import { Effect, Schema } from "effect"
import type { HttpClientResponse } from "effect/http"
import { ImageModel, ImageResponse, type ImageRequest } from "../image.js"
import { ImageResponse, type ImageRequest, imageModel } from "../image.js"
import { Media } from "../media.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, tokenUsage, type OpenString } from "../schema/index.js"
import { mergeJsonRecords, tokenUsage, type OpenString, type Model } from "../schema/index.js"
import { JsonObject, ProviderShared, optionalNull } from "./shared.js"
import { ImageSizing } from "./utils/image-sizing.js"
import { MediaInput } from "./utils/media-input.js"
@ -34,7 +34,7 @@ export type ImageOptions = {
readonly [key: string]: unknown
}
export type Request = ImageRequest<ImageModel<ImageOptions>>
export type Request = ImageRequest<Model<"image", ImageOptions>>
// ---------------------------------------------------------------------------
// 2. Request body and response schemas
@ -150,7 +150,7 @@ export const protocol = MediaProtocol.inline<Request, ImageResponse>(route, {
})
export const model = (input: MediaRoute.ModelInput) =>
ImageModel.fromRoute<ImageOptions>(
imageModel<ImageOptions>(
{
protocol,
baseURL: DEFAULT_BASE_URL,

View file

@ -60,6 +60,7 @@ const fromRequest = Effect.fn("MetaMessages.fromRequest")(function* (request: LL
export const protocol = Protocol.make({
id: "meta-messages",
api: "messages",
body: { schema: Body, from: fromRequest },
stream: AnthropicMessages.protocol.stream,
})

View file

@ -6,6 +6,7 @@ import { OpenResponses } from "./open-responses.js"
import { JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js"
import { ResponsesHostedTools } from "./utils/responses-hosted-tools.js"
import { detectMediaType } from "../utils/media-type.js"
import { routeOf } from "../schema/model.js"
const ADAPTER = "meta-responses"
const NAME = "Meta Responses"
@ -60,7 +61,7 @@ const adapter = {
} satisfies OpenResponses.ProviderAdapter
const fromRequest = Effect.fn("MetaResponses.fromRequest")(function* (request: LLMRequest) {
const key = request.model.route.providerMetadataKey ?? String(request.model.provider)
const key = routeOf(request.model).providerMetadataKey ?? String(request.model.provider)
const body = yield* OpenResponses.fromRequestWithAdapter(
{
...request,
@ -235,6 +236,7 @@ const step = Effect.fnUntraced(function* (state: ParserState, input: OpenRespons
export const protocol = Protocol.make({
id: ADAPTER,
api: "responses",
body: { schema: OpenResponses.OpenResponsesBody, from: fromRequest },
stream: {
event: OpenResponses.protocol.stream.event,

View file

@ -1,10 +1,10 @@
import { Duration, Effect, Schema } from "effect"
import type { HttpClientResponse } from "effect/http"
import { ImageModel, ImageResponse, type ImageRequest } from "../image.js"
import { ImageResponse, type ImageRequest, imageModel } from "../image.js"
import { Media } from "../media.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { AIError, QuotaExceededError, mergeJsonRecords, type OpenString } from "../schema/index.js"
import { AIError, QuotaExceededError, mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import { ProviderShared, optionalNull } from "./shared.js"
import { ImageSizing } from "./utils/image-sizing.js"
import { MediaInput } from "./utils/media-input.js"
@ -31,7 +31,7 @@ export type MiniMaxImageOptions = {
readonly height?: number
} & Record<string, unknown>
export type Request = ImageRequest<ImageModel<MiniMaxImageOptions>>
export type Request = ImageRequest<Model<"image", MiniMaxImageOptions>>
// ---------------------------------------------------------------------------
// 2. Response schema
@ -207,7 +207,7 @@ export const protocol = MediaProtocol.inline<Request, ImageResponse>(route, {
})
export const model = (input: MediaRoute.ModelInput) =>
ImageModel.fromRoute<MiniMaxImageOptions>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
imageModel<MiniMaxImageOptions>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
export const MiniMaxImages = {
protocol,

View file

@ -733,6 +733,7 @@ const finishEvents = Effect.fnUntraced(function* (state: ParserState) {
export const protocol = Protocol.make({
id: ADAPTER,
api: "chat-completions",
body: { schema: MistralBody, from: fromRequest },
stream: {
event: MistralStreamEvent,

View file

@ -34,6 +34,7 @@ import { OpenResponsesOptions } from "./utils/open-responses-options.js"
import { Lifecycle } from "./utils/lifecycle.js"
import { ToolStream } from "./utils/tool-stream.js"
import { OpenAIFreeform } from "./openai-freeform.js"
import { routeOf } from "../schema/model.js"
const ADAPTER = "open-responses"
const NAME = "Open Responses"
@ -921,7 +922,7 @@ const mapFinishReason = (event: Event, hasFunctionCall: boolean): FinishReason =
return hasFunctionCall ? "tool-calls" : "unknown"
}
export const metadataKey = (model: LLMRequest["model"]) => model.route.providerMetadataKey ?? "openresponses"
export const metadataKey = (model: LLMRequest["model"]) => routeOf(model).providerMetadataKey ?? "openresponses"
export const providerMetadata = (state: ParserState, metadata: Record<string, unknown>): ProviderMetadata => ({
[state.providerMetadataKey]: metadata,
@ -1542,6 +1543,7 @@ export const initial = (request: LLMRequest, adapter: ProviderAdapter = BASE_ADA
export const protocol = Protocol.make({
id: ADAPTER,
api: "responses",
body: {
schema: OpenResponsesBody,
from: fromRequest,

View file

@ -34,6 +34,7 @@ import { OpenResponsesOptions } from "./utils/open-responses-options.js"
import { Lifecycle } from "./utils/lifecycle.js"
import { ToolStream } from "./utils/tool-stream.js"
import { OpenAIFreeform } from "./openai-freeform.js"
import { routeOf } from "../schema/model.js"
const ADAPTER = "openai-chat"
const RESERVED_REASONING_FIELDS = new Set(["role", "content", "refusal", "tool_calls"])
@ -643,13 +644,13 @@ const lowerMessages = Effect.fnUntraced(function* (
request.model.compatibility?.requireReasoning ??
(request.model.compatibility?.reasoningField !== undefined ||
request.model.provider === "deepseek" ||
request.model.route.endpoint.baseURL?.toLowerCase().includes("deepseek.com") ||
routeOf(request.model).endpoint.baseURL?.toLowerCase().includes("deepseek.com") ||
modelID.includes("deepseek"))
const reasoningField = request.model.compatibility?.reasoningField
const mistral = ["mistral", "devstral", "codestral", "pixtral", "mixtral"].some((family) => modelID.includes(family))
const lowering = {
...options,
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
providerMetadataKey: routeOf(request.model).providerMetadataKey ?? request.model.provider,
toolCallID: (id: string) => {
if (mistral)
return id
@ -858,7 +859,7 @@ export const fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (
)
const flattened = ProviderShared.flattenToolRequest(request)
const provider = request.model.provider
const baseURL = request.model.route.endpoint.baseURL
const baseURL = routeOf(request.model).endpoint.baseURL
const detectedMaxTokensField = detectMaxTokensField(provider, baseURL)
const maxTokensField = request.model.compatibility?.maxTokensField ?? detectedMaxTokensField
const supportsStore = request.model.capabilities?.store ?? detectSupportsStore(provider, baseURL)
@ -1334,6 +1335,7 @@ export const finishEvents = Effect.fnUntraced(function* (state: ParserState) {
*/
export const protocol = Protocol.make({
id: ADAPTER,
api: "chat-completions",
body: {
schema: OpenAIChatBody,
from: fromRequest,
@ -1341,7 +1343,7 @@ export const protocol = Protocol.make({
stream: {
event: OpenAIChatStreamEvent,
initial: (request) => ({
providerMetadataKey: request.model.route.providerMetadataKey ?? request.model.provider,
providerMetadataKey: routeOf(request.model).providerMetadataKey ?? request.model.provider,
tools: ToolStream.empty<number>(),
custom: OpenAIFreeform.tools(request),
customCalls: new Set<number>(),

View file

@ -13,6 +13,7 @@ import { AIError, UnsupportedOperationError, mergeJsonRecords, type ProviderOpti
import { encodeJson } from "../utils/json.js"
import { OpenResponses } from "./open-responses.js"
import { ProviderShared } from "./shared.js"
import { routeOf } from "../schema/model.js"
const ID = "openai-decisions"
const NAME = "OpenAI Decisions"
@ -91,7 +92,7 @@ const inputPart = (request: DecisionRequest, part: DecisionPart): Effect.Effect<
reason: new UnsupportedOperationError({
operation: "decision.media",
provider: request.model.provider,
route: request.model.route.id,
route: routeOf(request.model).id,
message: `${NAME} takes images only; got ${part.media.kind} media`,
}),
}),

View file

@ -1,18 +1,26 @@
import { Effect, Schema, SchemaGetter, Stream } from "effect"
import {
ImageFinishEvent,
ImageModel,
ImageOutputEvent,
ImagePartialEvent,
type ImageEvent,
type ImageRequest,
imageModel,
} from "../image.js"
import { Media } from "../media.js"
import { classifyProviderFailure } from "../provider-error.js"
import { Framing } from "../route/framing.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { AIError, mergeJsonRecords, ProviderID, tokenUsage, type MediaUsage, type OpenString } from "../schema/index.js"
import {
AIError,
mergeJsonRecords,
ProviderID,
tokenUsage,
type MediaUsage,
type OpenString,
type Model,
} from "../schema/index.js"
import { optionalNull, ProviderShared } from "./shared.js"
import { ImageSizing } from "./utils/image-sizing.js"
import { MediaInput } from "./utils/media-input.js"
@ -41,7 +49,7 @@ export type OpenAIImageOptions = {
readonly partialImages?: number
} & Record<string, unknown>
export type Request = ImageRequest<ImageModel<OpenAIImageOptions>>
export type Request = ImageRequest<Model<"image", OpenAIImageOptions>>
// ---------------------------------------------------------------------------
// 2. Response schema
@ -425,7 +433,7 @@ export const model = (
input.sizing === undefined && imageInput === "edits"
? protocol
: makeProtocol({ sizing: input.sizing ?? pixelSize, imageInput })
return ImageModel.fromRoute<OpenAIImageOptions, Frame, State>(
return imageModel<OpenAIImageOptions, Frame, State>(
{
protocol: input.provider === undefined ? base : { ...base, provider: ProviderID.make(input.provider) },
baseURL: DEFAULT_BASE_URL,

View file

@ -323,6 +323,7 @@ const HOSTED_TOOLS = {
export const protocol = Protocol.make({
id: ADAPTER,
api: "responses",
body: {
schema: OpenAIResponsesBody,
from: fromRequest,

View file

@ -2,8 +2,8 @@ import { Effect, Schema, SchemaGetter } from "effect"
import { Framing } from "../route/framing.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, tokenUsage, type MediaUsage } from "../schema/index.js"
import { SpeechModel, type SpeechEvent, type SpeechRequest } from "../speech.js"
import { mergeJsonRecords, tokenUsage, type MediaUsage, type Model } from "../schema/index.js"
import { type SpeechEvent, type SpeechRequest, speechModel } from "../speech.js"
import { SpeechStream } from "./utils/speech-stream.js"
const route = MediaProtocol.identity({ id: "openai-speech", name: "OpenAI Speech", provider: "openai" })
@ -22,7 +22,7 @@ export type OpenAISpeechOptions = {
readonly stream_format?: "sse" | "audio"
} & Record<string, unknown>
export type Request = SpeechRequest<SpeechModel<OpenAISpeechOptions>>
export type Request = SpeechRequest<Model<"speech", OpenAISpeechOptions>>
// ---------------------------------------------------------------------------
// 3. Streaming event schema
@ -153,7 +153,7 @@ export const protocol = MediaProtocol.stream<Request, SpeechEvent, string | Uint
})
export const model = (input: MediaRoute.ModelInput) =>
SpeechModel.fromRoute<OpenAISpeechOptions, string | Uint8Array, State>(
speechModel<OpenAISpeechOptions, string | Uint8Array, State>(
{ protocol, baseURL: DEFAULT_BASE_URL, path: PATH },
input,
)

View file

@ -3,15 +3,15 @@ import { classifyProviderFailure } from "../provider-error.js"
import { Framing } from "../route/framing.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { AIError, mergeJsonRecords, tokenUsage, type MediaUsage } from "../schema/index.js"
import { AIError, mergeJsonRecords, tokenUsage, type MediaUsage, type Model } from "../schema/index.js"
import {
TranscriptionFinishEvent,
TranscriptionModel,
TranscriptionSegmentEvent,
TranscriptionTextDeltaEvent,
type TranscriptionEvent,
type TranscriptionRequest,
type TranscriptionSegment,
transcriptionModel,
} from "../transcription.js"
import { mediaTypeExtension } from "../utils/media-type.js"
import { ProviderShared } from "./shared.js"
@ -41,7 +41,7 @@ export type OpenAITranscriptionOptions = {
readonly temperature?: number
} & Record<string, unknown>
export type Request = TranscriptionRequest<TranscriptionModel<OpenAITranscriptionOptions>>
export type Request = TranscriptionRequest<Model<"transcription", OpenAITranscriptionOptions>>
// ---------------------------------------------------------------------------
// 3. Streaming event schema
@ -284,7 +284,7 @@ export const protocol = MediaProtocol.stream<Request, TranscriptionEvent, Frame,
})
export const model = (input: MediaRoute.ModelInput) =>
TranscriptionModel.fromRoute<OpenAITranscriptionOptions, Frame, State>(
transcriptionModel<OpenAITranscriptionOptions, Frame, State>(
{ protocol, baseURL: DEFAULT_BASE_URL, path: PATH },
input,
)

View file

@ -4,8 +4,8 @@ import type { Status } from "../generation.js"
import { Media } from "../media.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, type OpenString } from "../schema/index.js"
import { VideoModel, VideoResponse, type VideoRequest } from "../video.js"
import { mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import { VideoResponse, type VideoRequest, videoModel } from "../video.js"
import { ProviderShared, optionalArray, optionalNull } from "./shared.js"
const route = MediaProtocol.identity({ id: "runway-video", name: "Runway", provider: "runway" })
@ -33,7 +33,7 @@ export type RunwayVideoOptions = {
readonly outputFormat?: OpenString<"mp4" | "prores" | "png_sequence">
} & Record<string, unknown>
export type Request = VideoRequest<VideoModel<RunwayVideoOptions>>
export type Request = VideoRequest<Model<"video", RunwayVideoOptions>>
// ---------------------------------------------------------------------------
// 2. Token and response schemas
@ -185,7 +185,7 @@ const startPath = (request: Request) => {
}
export const model = (input: MediaRoute.ModelInput) =>
VideoModel.fromRoute<RunwayVideoOptions, Token>(
videoModel<RunwayVideoOptions, Token>(
{
protocol,
baseURL: DEFAULT_BASE_URL,

View file

@ -3,7 +3,6 @@ import {
DecisionResponse,
DecisionUsage,
type DecisionAnswer,
type DecisionModelCompatibility,
type DecisionPart,
type DecisionQuestion,
type DecisionRequest,
@ -12,16 +11,17 @@ import type { Media } from "../media.js"
import { DecisionRoute } from "../route/decision.js"
import { Endpoint } from "../route/endpoint.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { AIError, UnsupportedOperationError, mergeJsonRecords } from "../schema/index.js"
import { AIError, UnsupportedOperationError, mergeJsonRecords, type Compatibility } from "../schema/index.js"
import { encodeJson } from "../utils/json.js"
import { JsonObject, ProviderShared } from "./shared.js"
import { routeOf } from "../schema/model.js"
export const DEFAULT_PATH = "/systemone"
export const DEFAULT_BASE_URL = "https://api.typesafe.ai/v1"
/** `state.messages` is Baseten's own placement (parts in a user message inside `state.messages`), set by its provider. */
type MediaInput = NonNullable<DecisionModelCompatibility["mediaInput"]> | "state.messages"
type MediaInput = NonNullable<Compatibility["mediaInput"]> | "state.messages"
const Probability = Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1 }))
const Answer = Schema.Union([
@ -109,7 +109,7 @@ const placeMedia = Effect.fnUntraced(function* (request: DecisionRequest, mediaI
reason: new UnsupportedOperationError({
operation: "decision.media",
provider: request.model.provider,
route: request.model.route.id,
route: routeOf(request.model).id,
message: `${NAME} takes ${accepted} here; got ${asset.mediaType}`,
}),
})

View file

@ -12,7 +12,7 @@ export const claudeVersion = (id: string) => {
}
export const supportsThinkingBlockBinding = (model: LLMRequest["model"]) => {
const override = model.compatibility?.supportsThinkingBlockBinding
const override = model.compatibility?.thinkingBlockBinding
if (override !== undefined) return override
const version = claudeVersion(model.id)
return version !== undefined && (version.major > 5 || (version.major === 5 && version.minor >= 1))

View file

@ -55,6 +55,7 @@ export function gatewayProtocol<Body, Event, State>(
return Protocol.make({
id: input.id,
api: protocol.api,
body: {
schema: JsonObject,
from: Effect.fnUntraced(function* (request: LLMRequest) {

View file

@ -2,6 +2,7 @@ import { Effect, Schema, Stream } from "effect"
import { Route, type RouteBody, type TriggerCompactOperation } from "../../route/client.js"
import { Protocol } from "../../route/protocol.js"
import { CompactionCheckpointResponse, LLMEvent, type LLMRequest } from "../../schema/index.js"
import { routeOf } from "../../schema/model.js"
import { OpenResponses } from "../open-responses.js"
import { ProviderShared } from "../shared.js"
@ -46,12 +47,13 @@ const onOutputItem = Effect.fnUntraced(function* (state: State, input: OpenRespo
/** Collect a trigger response before acknowledging transport completion. No generation output escapes. */
export const make = <Body>(body: RouteBody<Body>): TriggerCompactOperation =>
Effect.fn("ResponsesCheckpoint.execute")(function* (request, executor, options) {
const source = request.model.route
const source = routeOf(request.model)
let result: CompactionCheckpointResponse | undefined
// Route registries erase the frame type. The codec validates that boundary before parsing.
const event: Schema.Codec<OpenResponses.Event, unknown> = OpenResponses.protocol.stream.event
const protocol = Protocol.make({
id: source.protocol,
api: source.api ?? source.protocol,
body,
stream: {
event,

View file

@ -11,6 +11,7 @@ import {
mergeJsonRecords,
} from "../../schema/index.js"
import type { CompactOperation } from "../../route/client.js"
import { routeOf } from "../../schema/model.js"
import { stripEffortUpdates } from "../../effort-updates.js"
import { Endpoint } from "../../route/endpoint.js"
import { RequestExecutor } from "../../route/executor.js"
@ -85,7 +86,7 @@ export const make = (
lowerTools: (request: LLMRequest) => Effect.Effect<ReadonlyArray<Record<string, unknown>>, AIError>,
): CompactOperation =>
Effect.fn("ResponsesCompaction.execute")(function* (request, executor, options) {
const route = request.model.route
const route = routeOf(request.model)
// The standalone compaction endpoint rejects histories containing configuration updates.
const native = yield* OpenResponses.lowerConversation(stripEffortUpdates(request), adapter)
const generation = OpenResponses.lowerGeneration(request)

View file

@ -1,6 +1,7 @@
import { ToolDefinition, type JsonSchema, type LanguageModel, type LLMRequest } from "../../schema/index.js"
import { ToolDefinition, type JsonSchema, type LLMRequest, type Model } from "../../schema/index.js"
import { isRecord } from "../../utils/record.js"
import { GeminiJsonSchema } from "./gemini-json-schema.js"
import { routeOf } from "../../schema/model.js"
const { SCHEMA_MAPS, VALUES, mapValues } = GeminiJsonSchema
@ -83,11 +84,11 @@ const objectRoot = (schema: JsonSchema): JsonSchema => {
// Otherwise the protocol's own default applies (the Gemini API always uses Gemini's rules), then the
// model name selects the family's rules so models reached through gateways and OpenAI-compatible
// endpoints get the same handling.
const modelCompatibility = (schema: JsonSchema, model: LanguageModel): JsonSchema => {
const modelCompatibility = (schema: JsonSchema, model: Model<"chat">): JsonSchema => {
const root = objectRoot(schema)
switch (
model.compatibility?.sanitizer ??
model.route.sanitizer ??
routeOf(model).sanitizer ??
MODEL_NAMES.find(([name]) => name.test(model.id))?.[1]
) {
case "gemini":
@ -101,7 +102,7 @@ const modelCompatibility = (schema: JsonSchema, model: LanguageModel): JsonSchem
}
// Applied once to every request before any protocol builds its body, including tools in namespaces.
const tools = (entries: LLMRequest["tools"], model: LanguageModel): LLMRequest["tools"] =>
const tools = (entries: LLMRequest["tools"], model: Model<"chat">): LLMRequest["tools"] =>
entries.map((tool) =>
tool.type === "tool"
? new ToolDefinition({ ...tool, inputSchema: modelCompatibility(tool.inputSchema, model) })

View file

@ -1,12 +1,6 @@
import { Effect, Schema } from "effect"
import { Protocol } from "../route/protocol.js"
import {
AIError,
LLMEvent,
type LanguageModelCompatibility,
type LLMRequest,
type Capabilities,
} from "../schema/index.js"
import { AIError, LLMEvent, type Compatibility, type LLMRequest, type Capabilities } from "../schema/index.js"
import { classifyProviderFailure } from "../provider-error.js"
import { OpenAIChat } from "./openai-chat.js"
import { JsonObject, optionalArray, optionalNull, ProviderShared } from "./shared.js"
@ -331,12 +325,13 @@ const onHalt = Effect.fn("VeniceChat.onHalt")(function* (state: State) {
export const compatibility = {
maxTokensField: "max_completion_tokens",
} satisfies LanguageModelCompatibility
} satisfies Compatibility
export const capabilities = { promptCacheKey: true } satisfies Capabilities
export const protocol = Protocol.make({
id: "venice-chat",
api: "chat-completions",
body: { schema: Body, from: fromRequest },
stream: {
event: Schema.Union([Schema.Literal("[DONE]"), Protocol.jsonEvent(Event)]),

View file

@ -1,10 +1,10 @@
import { Effect, Schema } from "effect"
import type { HttpClientResponse } from "effect/http"
import { ImageModel, ImageResponse, type ImageRequest } from "../image.js"
import { ImageResponse, type ImageRequest, imageModel } from "../image.js"
import { Media } from "../media.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, type OpenString } from "../schema/index.js"
import { mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import { JsonObject, ProviderShared, lenient, optionalNull } from "./shared.js"
import { ImageSizing } from "./utils/image-sizing.js"
import { MediaInput } from "./utils/media-input.js"
@ -25,7 +25,7 @@ export type XAIImageOptions = {
readonly response_format?: OpenString<"url" | "b64_json">
} & Record<string, unknown>
export type Request = ImageRequest<ImageModel<XAIImageOptions>>
export type Request = ImageRequest<Model<"image", XAIImageOptions>>
// ---------------------------------------------------------------------------
// 2. Response schema
@ -125,7 +125,7 @@ export const protocol = MediaProtocol.inline<Request, ImageResponse>(route, {
})
export const model = (input: MediaRoute.ModelInput) =>
ImageModel.fromRoute<XAIImageOptions>(
imageModel<XAIImageOptions>(
{ protocol, baseURL: DEFAULT_BASE_URL, path: ({ request }) => (isEdit(request) ? EDIT_PATH : PATH) },
input,
)

View file

@ -6,6 +6,7 @@ import { JsonObject, optionalNull, ProviderShared } from "./shared.js"
import { ResponsesHostedTools } from "./utils/responses-hosted-tools.js"
import { ResponsesCompaction } from "./utils/responses-compaction.js"
import { OpenAIFreeform } from "./openai-freeform.js"
import { routeOf } from "../schema/model.js"
const ADAPTER = "xai-responses"
const NAME = "xAI Responses"
@ -61,7 +62,7 @@ const fromRequest = Effect.fn("XAIResponses.fromRequest")(function* (request: LL
return yield* ProviderShared.unsupportedOperation({
operation: "in-band-compaction",
provider: request.model.provider,
route: request.model.route.id,
route: routeOf(request.model).id,
message: "xAI requires explicit compaction through ai.compact; automatic context management is not supported",
})
const options = yield* ProviderShared.validateWith(Schema.decodeUnknownEffect(Options))(request.providerOptions ?? {})
@ -86,6 +87,7 @@ const HOSTED_TOOLS = {
export const protocol = Protocol.make({
id: ADAPTER,
api: "responses",
body: {
schema: Body,
from: fromRequest,

View file

@ -4,8 +4,8 @@ import type { Status } from "../generation.js"
import { Media } from "../media.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords } from "../schema/index.js"
import { VideoModel, VideoResponse, type VideoRequest } from "../video.js"
import { mergeJsonRecords, type Model } from "../schema/index.js"
import { VideoResponse, type VideoRequest, videoModel } from "../video.js"
import { ProviderShared, optionalNull } from "./shared.js"
const route = MediaProtocol.identity({ id: "xai-video", name: "xAI Video", provider: "xai" })
@ -28,7 +28,7 @@ export type XAIVideoOptions = {
readonly reference_audios?: ReadonlyArray<{ readonly voice_id: string }>
} & Record<string, unknown>
export type Request = VideoRequest<VideoModel<XAIVideoOptions>>
export type Request = VideoRequest<Model<"video", XAIVideoOptions>>
// ---------------------------------------------------------------------------
// 2. Token and response schemas
@ -200,7 +200,7 @@ const startPath = (request: Request) => {
}
export const model = (input: MediaRoute.ModelInput) =>
VideoModel.fromRoute<XAIVideoOptions, Token>(
videoModel<XAIVideoOptions, Token>(
{
protocol,
baseURL: DEFAULT_BASE_URL,

View file

@ -1,6 +1,6 @@
import { Effect, Schema } from "effect"
import { Protocol } from "../route/protocol.js"
import type { LanguageModelCompatibility, LLMRequest, Capabilities } from "../schema/index.js"
import type { Compatibility, LLMRequest, Capabilities } from "../schema/index.js"
import { OpenAIChat } from "./openai-chat.js"
import { ProviderShared } from "./shared.js"
import { OpenResponsesOptions } from "./utils/open-responses-options.js"
@ -58,12 +58,13 @@ export const compatibility = {
maxTokensField: "max_tokens",
reasoningField: "reasoning_content",
zaiToolStream: false,
} satisfies LanguageModelCompatibility
} satisfies Compatibility
export const capabilities = { tools: { strict: false } } satisfies Capabilities
export const protocol = Protocol.make({
id: "zai-chat",
api: "chat-completions",
body: { schema: Body, from: fromRequest },
stream: OpenAIChat.protocol.stream,
})

View file

@ -1,9 +1,9 @@
import { Duration, Effect, Schema } from "effect"
import type { HttpClientResponse } from "effect/http"
import { ImageModel, ImageResponse, type ImageRequest } from "../image.js"
import { ImageResponse, type ImageRequest, imageModel } from "../image.js"
import { MediaProtocol } from "../route/media-protocol.js"
import { MediaRoute } from "../route/media.js"
import { mergeJsonRecords, type OpenString } from "../schema/index.js"
import { mergeJsonRecords, type OpenString, type Model } from "../schema/index.js"
import { ImageSizing } from "./utils/image-sizing.js"
const route = MediaProtocol.identity({ id: "zai-images", name: "Z.ai Images", provider: "zai" })
@ -23,7 +23,7 @@ export type ZAIImageOptions = {
readonly userID?: string
} & Record<string, unknown>
export type Request = ImageRequest<ImageModel<ZAIImageOptions>>
export type Request = ImageRequest<Model<"image", ZAIImageOptions>>
// ---------------------------------------------------------------------------
// 2. Response schema
@ -112,7 +112,7 @@ export const protocol = MediaProtocol.inline<Request, ImageResponse>(route, {
})
export const model = (input: MediaRoute.ModelInput) =>
ImageModel.fromRoute<ZAIImageOptions>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
imageModel<ZAIImageOptions>({ protocol, baseURL: DEFAULT_BASE_URL, path: PATH }, input)
export const ZAIImages = {
protocol,

View file

@ -27,6 +27,7 @@ const fromRequest = Effect.fn("ZAIMessages.fromRequest")(function* (request: LLM
export const protocol = Protocol.make({
id: "zai-messages",
api: "messages",
body: { schema: Body, from: fromRequest },
stream: AnthropicMessages.protocol.stream,
})

View file

@ -1,4 +1,5 @@
import type { LanguageModel, ProviderOptions } from "./schema/index.js"
// `Model` below names the loader type, so the AI model type is imported under another name.
import type { Model as AIModel, ProviderOptions } from "./schema/index.js"
import type { CompactionOperations } from "./route/client.js"
/**
@ -16,7 +17,7 @@ export interface Definition<
Options extends ProviderOptions = ProviderOptions,
Compact extends CompactionOperations | undefined = CompactionOperations | undefined,
> {
readonly model: (modelID: string, settings: ProviderSettings) => LanguageModel<Options, Compact>
readonly model: (modelID: string, settings: ProviderSettings) => AIModel<"chat", Options, Compact>
}
/** A provider's `model` export. Settings are optional when every key is optional. */
@ -27,6 +28,6 @@ export type Model<
> = (
modelID: string,
...settings: {} extends ProviderSettings ? [settings?: ProviderSettings] : [settings: ProviderSettings]
) => LanguageModel<Options, Compact>
) => AIModel<"chat", Options, Compact>
export * as ProviderPackage from "./provider-package.js"

View file

@ -28,6 +28,7 @@ export type Settings<Options = OpenAIProviderOptionsInput> = ProviderPackage.Set
export const protocol = Protocol.make({
id: "digitalocean-chat",
api: "chat-completions",
body: {
schema: OpenAIChat.protocol.body.schema,
from: (request) => OpenAIChat.fromRequest(request, { cacheControl: cacheControl() }),

View file

@ -40,6 +40,7 @@ const route = Route.make({
providerMetadataKey: "vertex",
protocol: Protocol.make({
id: AnthropicMessages.protocol.id,
api: "messages",
body: {
schema: Schema.Struct({
...Struct.omit(AnthropicMessages.AnthropicMessagesBody.fields, ["model"]),

View file

@ -38,6 +38,7 @@ const route = Route.make({
providerMetadataKey: "vertex",
protocol: Protocol.make({
id: MistralChat.protocol.id,
api: "chat-completions",
body: {
schema: Schema.Struct(Struct.omit(MistralChat.MistralBody.fields, ["prompt_cache_key"])),
from: (request) =>

View file

@ -40,6 +40,7 @@ const Options = Schema.Struct({
export const protocol = Protocol.make({
id: "groq-chat",
api: "chat-completions",
body: {
schema: Schema.Struct({
...OpenAIChat.bodyFields,

View file

@ -64,6 +64,7 @@ const ChatOptions = Schema.Struct({
const chatProtocol = Protocol.make({
id: "minimax-chat",
api: "chat-completions",
body: {
schema: Schema.Struct({
...OpenAIChat.bodyFields,

View file

@ -58,6 +58,7 @@ const ChatOptions = Schema.Struct({
const chatProtocol = Protocol.make({
id: "moonshot-chat",
api: "chat-completions",
body: {
schema: Schema.Struct({ ...OpenAIChat.bodyFields, thinking: ChatOptions.fields.thinking }),
from: Effect.fn("Moonshot.chatFromRequest")(function* (request: LLMRequest) {

View file

@ -133,6 +133,7 @@ export type OpenRouterBody = Schema.Schema.Type<typeof OpenRouterBody>
export const protocol = Protocol.make({
id: "openrouter-chat",
api: "chat-completions",
body: {
schema: OpenRouterBody,
from: (request) =>
@ -218,6 +219,7 @@ type OpenRouterResponsesBody = Schema.Schema.Type<typeof OpenRouterResponsesBody
const responsesProtocol = Protocol.make({
id: "openrouter-responses",
api: "responses",
body: {
schema: OpenRouterResponsesBody,
from: (request) =>

View file

@ -2,6 +2,7 @@ export { isContextOverflow, isContextOverflowFailure, isRetryable } from "./prov
export {
ProtocolID,
RouteID,
Model,
ModelID,
ProviderID,
ResponseID,
@ -15,9 +16,6 @@ export {
GENERATION_KEYS,
ReasoningEfforts,
ReasoningEffort,
LanguageModelCompatibility,
LanguageModel,
LanguageModelSchema,
CacheTTL,
CacheHint,
CachePolicyObject,
@ -90,12 +88,19 @@ export {
} from "./schema/index.js"
export type {
BaseRequest,
Compatibility,
ContentPartInput,
GenerationOptionsFields,
HttpOptions,
Api,
ApiName,
Capabilities,
Limit,
Modalities,
Modality,
RequestOptions,
LanguageModelInput,
LanguageModelProviderOptions,
ModelProviderOptions,
ModelType,
LLMRequest,
MediaPartInput,
RequestTimeout,
@ -107,15 +112,8 @@ export type {
TransportOptions,
UsageInput,
} from "./schema/index.js"
export { ImageAspectRatio, ImageEvent, ImageModel, ImageModelSchema, ImageResponse } from "./image.js"
export type {
ImageModelOptions,
ImageOptions,
ImageRequest,
ImageRequestInput,
ImageResolution,
ImageRoute,
} from "./image.js"
export { ImageAspectRatio, ImageEvent, ImageResponse } from "./image.js"
export type { ImageOptions, ImageRequest, ImageRequestInput, ImageResolution, ImageRoute } from "./image.js"
export {
ChoiceAnswer,
ChoiceQuestion,
@ -123,9 +121,6 @@ export {
DecisionAnswer,
DecisionJsonPart,
DecisionMediaPart,
DecisionModel,
DecisionModelCompatibility,
DecisionModelSchema,
DecisionPart,
DecisionQuestion,
DecisionResponse,
@ -143,7 +138,6 @@ export type {
AnswersFor,
DecisionInput,
DecisionMediaPartInput,
DecisionModelOptions,
DecisionOptions,
DecisionPartInput,
DecisionQuestions,

View file

@ -12,7 +12,16 @@ import { normalizeToolHistory } from "../tool-history.js"
import { sanitizeSurrogates } from "../utils/sanitize.js"
import * as ProviderShared from "../protocols/shared.js"
import { ToolSchemaProjection } from "../protocols/utils/tool-schema.js"
import type { LanguageModelSanitizerCompatibility, ProtocolID, ProviderOptions } from "../schema/index.js"
import {
type Api,
attachedRoute,
implementation,
type LanguageModelSanitizerCompatibility,
type ProtocolID,
type ProviderOptions,
Model,
routeOf,
} from "../schema/index.js"
import type { LLMRequestInput } from "../llm.js"
import {
AIError,
@ -21,7 +30,6 @@ import {
AIErrorReason,
LLMResponse,
ResponseFold,
LanguageModel,
Message,
LLMEvent,
InvalidProviderOutputError,
@ -56,6 +64,8 @@ export interface Route<
/** ProviderMetadata namespace emitted and consumed by this route. */
readonly providerMetadataKey?: string
readonly protocol: ProtocolID
/** The models.dev v2 API the route speaks; the protocol id when unset. */
readonly api?: Api
readonly endpoint: Endpoint.Definition<Body>
readonly auth: Auth.Definition
/** Deployment headers resolved once for every operation, before transport authentication. */
@ -77,7 +87,7 @@ export interface Route<
}
readonly model: <Options extends ProviderOptions = ProviderOptions>(
input: RouteMappedLanguageModelInput,
) => LanguageModel<Options, Compact>
) => Model<"chat", Options, Compact>
readonly prepareTransport: (
body: Body,
request: LLMRequest,
@ -101,9 +111,15 @@ export type AnyRoute<Compact extends CompactionOperations | undefined = Compacti
Compact
>
export type RouteLanguageModelInput = Omit<LanguageModel.Input, "provider" | "route">
export type RouteLanguageModelInput = Omit<
Model.Input<"chat">,
"type" | "provider" | "api" | "baseURL" | "auth" | typeof implementation
>
export type RouteRoutedLanguageModelInput = Omit<LanguageModel.Input, "route">
export type RouteRoutedLanguageModelInput = Omit<
Model.Input<"chat">,
"type" | "api" | "baseURL" | "auth" | typeof implementation
>
export interface RoutePatch<Body, Prepared> extends RequestOptions {
readonly compact?: CompactionOperations
@ -128,13 +144,22 @@ const makeRouteLanguageModel = <Options extends ProviderOptions, Compact extends
provider: ProviderID.make(provider),
message: `Route.model(${route.id}) requires an endpoint baseURL — configure it on the route first`,
})
return LanguageModel.make<Options, Compact>({
...mapped,
provider,
route,
})
return model<Options, Compact>(route, { ...mapped, provider })
}
/**
* A text model that runs on `route`: its `api` is the protocol the route speaks, and `Model.make` takes the route's
* `baseURL`, `auth` and options where the input leaves them out.
*/
const model = <
Options extends ProviderOptions = ProviderOptions,
C extends CompactionOperations | undefined = CompactionOperations | undefined,
>(
route: AnyRoute<C>,
input: Omit<Model.Input<"chat", C>, "type" | "api" | typeof implementation>,
) =>
Model.make<"chat", Options, C>({ ...input, type: "chat", api: route.api ?? route.protocol, [implementation]: route })
export interface Interface {
readonly compact: CompactMethod
readonly stream: StreamMethod
@ -181,8 +206,10 @@ export interface TriggerCompactOptions extends StreamOptions {
readonly mechanism: "trigger"
}
type EndpointModel = LanguageModel<ProviderOptions, { readonly endpoint: CompactOperation }>
type TriggerModel = LanguageModel<ProviderOptions, { readonly trigger: TriggerCompactOperation }>
type EndpointModelCompact = { readonly endpoint: CompactOperation }
type TriggerModelCompact = { readonly trigger: TriggerCompactOperation }
type EndpointModel = Model<"chat", ProviderOptions, EndpointModelCompact>
type TriggerModel = Model<"chat", ProviderOptions, TriggerModelCompact>
/** A text request whose model supports explicit compaction. */
export type CompactionRequest = LLMRequestInput & { readonly model: EndpointModel }
@ -201,40 +228,104 @@ export interface CompactMethod<R = never> {
}
/** Whether a model, or a text request's model, supports compaction through the given mechanism. */
export function canCompact<Model extends LanguageModel>(
model: Model,
export function canCompact<SelectedModel extends Model<"chat">>(
model: SelectedModel,
options: { readonly mechanism: "trigger" },
): model is Model & TriggerModel
export function canCompact<Request extends { readonly model: LanguageModel }>(
): model is SelectedModel & TriggerModel
export function canCompact<Request extends { readonly model: Model<"chat"> }>(
request: Request,
options: { readonly mechanism: "trigger" },
): request is Request & { readonly model: TriggerModel }
export function canCompact<Model extends LanguageModel>(
model: Model,
export function canCompact<SelectedModel extends Model<"chat">>(
model: SelectedModel,
options?: { readonly mechanism?: "endpoint" },
): model is Model & EndpointModel
export function canCompact<Request extends { readonly model: LanguageModel }>(
): model is SelectedModel & EndpointModel
export function canCompact<Request extends { readonly model: Model<"chat"> }>(
request: Request,
options?: { readonly mechanism?: "endpoint" },
): request is Request & { readonly model: EndpointModel }
export function canCompact(
target: LanguageModel | { readonly model: LanguageModel },
target: Model<"chat"> | { readonly model: Model<"chat"> },
options?: { readonly mechanism?: string },
) {
const model = target instanceof LanguageModel ? target : target.model
if (options?.mechanism === "trigger") return model.route.compact?.trigger !== undefined
const route = attachedRoute("model" in target ? target.model : target)
if (options?.mechanism === "trigger") return route?.compact?.trigger !== undefined
if (options?.mechanism !== undefined && options.mechanism !== "endpoint") return false
return model.route.compact?.endpoint !== undefined
return route?.compact?.endpoint !== undefined
}
const unsupportedCompaction = (model: LanguageModel, mechanism: string | undefined) => {
/** `route` at the model's own `baseURL`, `path` and `auth`: what its requests are sent through. */
const deploy = <C extends CompactionOperations | undefined>(route: AnyRoute<C>, model: Model<"chat">): AnyRoute<C> => {
const baseURL = model.baseURL ?? route.endpoint.baseURL
const auth = model.auth ?? route.auth
if (baseURL === route.endpoint.baseURL && auth === route.auth && model.path === undefined) return route
return route.with({ endpoint: { baseURL, ...(model.path === undefined ? {} : { path: model.path }) }, auth })
}
// The package's own implementation of each text API, loaded on first use.
const standardRoutes: Partial<Record<Api, () => Promise<AnyRoute>>> = {
"chat-completions": async () => {
const { route } = await import("../protocols/openai-chat.js")
return route
},
responses: async () => {
const { route } = await import("../protocols/openai-responses.js")
return route
},
messages: async () => {
const { route } = await import("../protocols/anthropic-messages.js")
return route
},
converse: async () => {
const { route } = await import("../protocols/bedrock-converse.js")
return route
},
"generate-content": async () => {
const { route } = await import("../protocols/gemini.js")
return route
},
interactions: async () => {
const { route } = await import("../protocols/google-interactions.js")
return route
},
"cohere-chat": async () => {
const { route } = await import("../protocols/cohere-chat.js")
return route
},
}
/**
* The request with its model's implementation attached and deployed: the provider's own when it still implements
* the model's `api`, otherwise the package's standard one, whose options then start the model's.
*/
const resolveModel = Effect.fn("LLM.resolveModel")(function* (request: LLMRequest) {
const own = attachedRoute(request.model)
if (own !== undefined) return deployed(request, own)
const load = standardRoutes[request.model.api]
if (load === undefined)
return yield* ProviderShared.invalidRequest(
`${request.model.provider}/${request.model.id}: the package has no implementation of "${request.model.api}"`,
)
const route = yield* Effect.promise(load)
return deployed(
{ ...request, model: { ...request.model, options: mergeRequestOptions(route.options, request.model.options) } },
route,
)
})
const deployed = (request: LLMRequest, route: AnyRoute): LLMRequest => ({
...request,
model: { ...request.model, [implementation]: deploy(route, request.model) },
})
const unsupportedCompaction = (model: Model<"chat">, mechanism: string | undefined) => {
if (mechanism !== undefined && mechanism !== "endpoint" && mechanism !== "trigger")
return ProviderShared.invalidRequest(`Unknown compaction mechanism: ${mechanism}`)
return ProviderShared.unsupportedOperation({
operation: mechanism === "trigger" ? "compact.trigger" : "compact",
provider: model.provider,
route: model.route.id,
message: `${model.provider}/${model.route.id} does not support ${mechanism === "trigger" ? "trigger" : "explicit"} compaction`,
route: attachedRoute(model)?.id ?? model.api,
message: `${model.provider}/${attachedRoute(model)?.id ?? model.api} does not support ${mechanism === "trigger" ? "trigger" : "explicit"} compaction`,
})
}
@ -369,6 +460,7 @@ function makeFromTransport<Body, Prepared, Frame, Event, State>(
provider: routeInput.provider === undefined ? undefined : ProviderID.make(routeInput.provider),
providerMetadataKey: routeInput.providerMetadataKey,
protocol: protocol.id,
api: protocol.api,
endpoint: routeInput.endpoint,
auth: routeInput.auth ?? Auth.none,
headers: routeInput.headers,
@ -406,7 +498,7 @@ function makeFromTransport<Body, Prepared, Frame, Event, State>(
webSocket: options?.webSocket,
}),
streamPrepared: (prepared: Prepared, request: LLMRequest, runtime: TransportRuntime, options?: StreamOptions) => {
const route = `${request.model.provider}/${request.model.route.id}`
const route = `${request.model.provider}/${routeOf(request.model).id}`
return Stream.unwrap(
routeInput.transport.execute(prepared, request, runtime, options).pipe(
Effect.map((execution) => {
@ -550,7 +642,7 @@ const prepareRequest = (request: LLMRequest): LLMRequest => {
const resolved = applyCachePolicy(
applyEffortUpdates({ ...sanitized, tools: ToolSchemaProjection.tools(dedupe(sanitized.tools), sanitized.model) }),
)
const headers = resolved.model.route.headers?.({ request: resolved })
const headers = routeOf(resolved.model).headers?.({ request: resolved })
return headers === undefined ? resolved : { ...resolved, headers: { ...headers, ...resolved.headers } }
}
@ -577,8 +669,8 @@ const compile = Effect.fn("LLM.compile")(function* (request: LLMRequest, options
return yield* ProviderShared.invalidRequest(
"Local file references must be read with Media.file(path) before sending",
)
const resolved = prepareRequest(request)
const route = resolved.model.route
const resolved = prepareRequest(yield* resolveModel(request))
const route = routeOf(resolved.model)
const body = yield* route.body.from(resolved)
const prepared = yield* route.prepareTransport(body, resolved, options)
@ -622,7 +714,7 @@ export const generateWith = (stream: Interface["stream"]) =>
const response = ResponseFold.complete(state)
if (response) return response
return yield* withPartial(
incompleteStreamError(`${request.model.provider}/${request.model.route.id}`),
incompleteStreamError(`${request.model.provider}/${attachedRoute(request.model)?.id ?? request.model.api}`),
ResponseFold.partial(state),
)
})
@ -671,9 +763,17 @@ export const layer: Layer.Layer<Service, never, RequestExecutor.Service> = Layer
function compact(request: LLMRequest, options?: EndpointCompactOptions | TriggerCompactOptions) {
return Effect.suspend((): Effect.Effect<CompactionResponse | CompactionCheckpointResponse, AIError> => {
if (options?.mechanism === "trigger" && canCompact(request, options))
return request.model.route.compact.trigger(prepareRequest(request), executor, options)
return routeOf<"chat", TriggerModelCompact>(request.model).compact.trigger(
prepareRequest(deployed(request, routeOf(request.model))),
executor,
options,
)
if ((options?.mechanism === undefined || options.mechanism === "endpoint") && canCompact(request))
return request.model.route.compact.endpoint(prepareRequest(request), executor, options)
return routeOf<"chat", EndpointModelCompact>(request.model).compact.endpoint(
prepareRequest(deployed(request, routeOf(request.model))),
executor,
options,
)
return unsupportedCompaction(request.model, options?.mechanism)
})
}
@ -685,7 +785,10 @@ export const layer: Layer.Layer<Service, never, RequestExecutor.Service> = Layer
}),
)
export const Route = { make } as const
/** The implementation a provider attached to a model, when it still implements the model's `api`. */
const of = attachedRoute
export const Route = { make, model, of } as const
export const LLMClient = {
Service,

View file

@ -1,19 +1,22 @@
import { Effect } from "effect"
import type { HttpClientResponse } from "effect/http"
import { type DecisionOptions, type DecisionPart, type DecisionRequest, type DecisionResponse } from "../decision.js"
import {
DecisionModel,
DecisionModelCompatibility,
type DecisionOptions,
type DecisionPart,
type DecisionRequest,
type DecisionResponse,
} from "../decision.js"
import { ProviderID, type HttpOptions, type AIError, type ProviderOptions } from "../schema/index.js"
mediaApi,
implementation,
ProviderID,
type HttpOptions,
type AIError,
type ProviderOptions,
type Compatibility,
Model,
} from "../schema/index.js"
import { Auth } from "./auth.js"
import { Endpoint } from "./endpoint.js"
import { RequestExecutorService } from "./executor-service.js"
import { MediaProtocol } from "./media-protocol.js"
import { MediaRoute, type Execute } from "./media.js"
import { mediaOptions } from "../media-model.js"
/** One decision API: how a request becomes its JSON body and how its response becomes a `DecisionResponse`. */
export interface Protocol {
@ -55,9 +58,9 @@ export interface Route {
readonly with: (patch: Patch) => Route
readonly model: <Options extends DecisionOptions = DecisionOptions>(input: {
readonly id: string
readonly compatibility?: DecisionModelCompatibility.Input
readonly compatibility?: Compatibility
readonly providerOptions?: ProviderOptions
}) => DecisionModel<Options>
}) => Model<"decision", Options>
}
export interface MakeInput extends Omit<Patch, "endpoint"> {
@ -94,18 +97,18 @@ export const make = (input: MakeInput): Route => {
}),
model: <Options extends DecisionOptions>(model: {
readonly id: string
readonly compatibility?: DecisionModelCompatibility.Input
readonly compatibility?: Compatibility
readonly providerOptions?: ProviderOptions
}) => {
const send = transport(route)
return DecisionModel.make<Options>({
return Model.make<"decision", Options>({
id: model.id,
provider,
http: route.http,
providerOptions: model.providerOptions,
compatibility:
model.compatibility === undefined ? undefined : DecisionModelCompatibility.make(model.compatibility),
route: { id: route.id, generate: send },
type: "decision",
options: mediaOptions({ http: route.http, providerOptions: model.providerOptions }),
compatibility: model.compatibility,
api: mediaApi(route.protocol.id),
[implementation]: { id: route.id, generate: send },
})
},
}

View file

@ -28,8 +28,7 @@ export type Execute = Interface["execute"]
export type MediaRequest = BaseRequest<{
readonly id: string
readonly provider: ProviderID
readonly http?: HttpOptions
readonly providerOptions?: ProviderOptions
readonly options?: { readonly http?: HttpOptions; readonly providerOptions?: ProviderOptions }
}>
/** What every HTTP exchange of one generation shares. */
@ -345,7 +344,7 @@ const makeTransport = <Request extends MediaRequest>(
})
return {
/** Route and model overlays; `start` additionally merges the request's own. */
exchange: (model: MediaRequest["model"]): Exchange => mergeTransport({ headers: input.headers, http: model.http }),
exchange: (model: MediaRequest["model"]): Exchange => mergeTransport({ headers: input.headers, http: model.options?.http }),
/** POST the protocol body to the route endpoint. */
submit: Effect.fn("MediaRoute.submit")(function* (
request: Request,
@ -357,9 +356,9 @@ const makeTransport = <Request extends MediaRequest>(
execute: Execute,
) {
yield* rejectUnsupported(input.protocol.id, input.protocol.provider, request, protocol.unsupported)
const { headers: merged, http } = mergeTransport({ headers: input.headers, http: request.model.http }, request)
const { headers: merged, http } = mergeTransport({ headers: input.headers, http: request.model.options?.http }, request)
const exchange = { headers: merged, http, fetch: request.fetch }
const providerOptions = mergeProviderOptions(request.model.providerOptions, request.providerOptions)
const providerOptions = mergeProviderOptions(request.model.options?.providerOptions, request.providerOptions)
const headers = Headers.fromInput(merged)
const prepared =
protocol.prepare === undefined

View file

@ -1,5 +1,12 @@
import { Schema, type Effect } from "effect"
import type { AIError, LanguageModelSanitizerCompatibility, LLMEvent, LLMRequest, ProtocolID } from "../schema/index.js"
import type {
AIError,
Api,
LanguageModelSanitizerCompatibility,
LLMEvent,
LLMRequest,
ProtocolID,
} from "../schema/index.js"
/**
* The semantic API contract of one model server family.
@ -37,6 +44,8 @@ import type { AIError, LanguageModelSanitizerCompatibility, LLMEvent, LLMRequest
export interface Protocol<Body, Frame, Event, State> {
/** Stable id for the wire protocol implementation. */
readonly id: ProtocolID
/** The models.dev v2 API this protocol speaks, such as `"chat-completions"`; dialects name the API they extend. */
readonly api: Api
/** Request side: schema for the provider-native body and how to build it. */
readonly body: ProtocolBody<Body>
/** Response side: streaming state machine. */

View file

@ -0,0 +1,57 @@
import type { OpenString } from "./options.js"
/**
* The models.dev v2 API protocols the package implements. A model names the one it speaks; text models with one of
* the first seven run on the package's standard implementation unless their provider attached its own dialect.
*/
export type ApiName =
| "chat-completions"
| "responses"
| "messages"
| "converse"
| "generate-content"
| "interactions"
| "cohere-chat"
| "systemone"
| "decisions"
| "workers-ai-run"
| "images"
| "videos"
| "speech"
| "transcriptions"
/** A model's API: a models.dev v2 protocol name, or a custom route's protocol id. */
export type Api = OpenString<ApiName>
// Every media protocol id, by the models.dev v2 API it speaks. Text protocols name theirs in `Protocol.api`.
const media: Record<string, ApiName> = {
"google-images": "generate-content",
"google-speech": "generate-content",
"google-transcription": "generate-content",
"system-one": "systemone",
"baseten-system-one": "systemone",
"openai-decisions": "decisions",
"cloudflare-run-decisions": "workers-ai-run",
"cloudflare-run-extraction": "workers-ai-run",
"cloudflare-workers-ai-images": "workers-ai-run",
"openai-images": "images",
"xai-images": "images",
"zai-images": "images",
"alibaba-images": "images",
"minimax-images": "images",
"meta-images": "images",
"xai-video": "videos",
"runway-video": "videos",
"google-video": "videos",
"openai-speech": "speech",
"elevenlabs-speech": "speech",
"cartesia-speech": "speech",
"deepgram-speech": "speech",
"openai-transcription": "transcriptions",
"elevenlabs-transcription": "transcriptions",
"deepgram-transcription": "transcriptions",
"assemblyai-transcription": "transcriptions",
}
/** The API a media or decision protocol speaks; a protocol the package doesn't know keeps its own id. */
export const mediaApi = (protocol: string): Api => media[protocol] ?? protocol

View file

@ -8,10 +8,10 @@ export type ProtocolID = Schema.Schema.Type<typeof ProtocolID>
export const RouteID = Schema.String
export type RouteID = Schema.Schema.Type<typeof RouteID>
export const ModelID = Schema.String.pipe(Schema.brand("AI.ModelID"))
export const ModelID = Schema.String
export type ModelID = typeof ModelID.Type
export const ProviderID = Schema.String.pipe(Schema.brand("AI.ProviderID"))
export const ProviderID = Schema.String
export type ProviderID = typeof ProviderID.Type
export const ResponseID = Schema.String

View file

@ -1,5 +1,7 @@
export * from "./ids.js"
export * from "./options.js"
export * from "./api.js"
export * from "./model.js"
export * from "./messages.js"
export * from "./events.js"
export * from "./errors.js"

View file

@ -1,4 +1,5 @@
import { Option, Schema } from "effect"
import type { Model, ModelProviderOptions } from "./model.js"
import { withStatics } from "@opencode/schema/schema"
import { Tool } from "@opencode/schema/tool"
import {
@ -6,8 +7,6 @@ import {
CacheHint,
type CachePolicy,
JsonSchema,
type LanguageModel,
type LanguageModelProviderOptions,
ProviderMetadata,
ReasoningEffort,
type GenerationOptionsFields,
@ -486,8 +485,8 @@ export namespace ToolChoice {
* A normalized text request, the plain object `ai.request(...)` returns. Edit it with a spread, such as
* `{ ...request, messages: [...request.messages, next] }`, or pass the edited object back to `ai.request`.
*/
export interface LLMRequest<Model extends LanguageModel = LanguageModel>
extends BaseRequest<Model, LanguageModelProviderOptions<Model>>,
export interface LLMRequest<SelectedModel extends Model<"chat"> = Model<"chat">>
extends BaseRequest<SelectedModel, ModelProviderOptions<SelectedModel>>,
GenerationOptionsFields {
readonly id?: string
readonly system: ReadonlyArray<SystemPart>

View file

@ -0,0 +1,189 @@
import { Schema } from "effect"
import type { Api } from "./api.js"
import {
mergeRequestOptions,
type Capabilities,
type Compatibility,
type OpenString,
type RequestOptions,
type ProviderOptions,
} from "./options.js"
import type { Auth } from "../route/auth.js"
import { isRecord } from "../utils/record.js"
import type { AnyRoute, CompactionOperations } from "../route/client.js"
import type { DecisionModelRoute } from "../decision.js"
import type { ImageRoute } from "../image.js"
import type { SpeechRoute } from "../speech.js"
import type { TranscriptionRoute } from "../transcription.js"
import type { VideoRoute } from "../video.js"
import type { ExtractionRoute } from "../experimental/extraction.js"
/** The kind of model, named after models.dev model types. Each `ai.*` entry point takes one. */
export type ModelType = "chat" | "image" | "speech" | "transcription" | "video" | "extraction" | "decision"
/** Size limits, from models.dev v2 `limit` in camelCase. Carried for callers; requests don't read them yet. */
export interface Limit {
readonly context?: number
readonly input?: number
readonly output?: number
readonly requestBytes?: number
readonly image?: {
readonly maxPerMessage?: number
readonly maxPerRequest?: number
readonly maxBytes?: number
readonly minWidth?: number
readonly minHeight?: number
readonly maxWidth?: number
readonly maxHeight?: number
}
readonly pdf?: { readonly maxPerRequest?: number; readonly maxBytes?: number; readonly maxPages?: number }
}
/** A models.dev v2 modality: a broad kind or an exact MIME type. Outputs may also be `decision`, `embedding` or `reranking`. */
export type Modality = OpenString<
"text" | "image" | "audio" | "video" | "application/pdf" | "decision" | "embedding" | "reranking"
>
/** Input and output modalities, from models.dev v2 `modalities`. Carried for callers; requests don't read them yet. */
export interface Modalities {
readonly input: ReadonlyArray<Modality>
readonly output: ReadonlyArray<Modality>
}
type Compact = CompactionOperations | undefined
/** Where a model built by a provider keeps its implementation of `api`, outside the public shape. Spreads keep it. */
export const implementation: unique symbol = Symbol("@opencode/ai/implementation")
/**
* One model of any type, as a plain readonly object: who serves it, which API it speaks, what it accepts, and the
* options every request starts from. `type` selects the `ai.*` entry point that takes it and narrows the union.
* Edit a model with a spread, such as `{ ...model, baseURL }`.
*/
export type Model<
Type extends ModelType = ModelType,
Options extends ProviderOptions = ProviderOptions,
C extends Compact = Compact,
> = Type extends "chat" ? Model.Chat<Options, C> : Type extends ModelType ? Model.Fields<Type, Options, C> : never
export namespace Model {
interface Routes<C extends Compact> {
readonly chat: AnyRoute<C>
readonly image: ImageRoute
readonly speech: SpeechRoute
readonly transcription: TranscriptionRoute
readonly video: VideoRoute
readonly extraction: ExtractionRoute
readonly decision: DecisionModelRoute
}
/** The implementation behind a model of the given type. */
export type Route<Type extends ModelType, C extends Compact = Compact> = Routes<C>[Type]
export interface Fields<Type extends ModelType, Options extends ProviderOptions, C extends Compact> {
readonly id: string
readonly provider: string
readonly type: Type
/** The models.dev v2 API the model speaks, such as `"chat-completions"`, `"messages"` or `"images"`. */
readonly api: Api
/** Options every request starts from; the request's own win per key. */
readonly options?: Omit<RequestOptions, "providerOptions"> & { readonly providerOptions?: Options }
/** What the model accepts. Flags left unset keep the protocol's own detection. */
readonly capabilities: Capabilities
readonly limit: Limit
readonly modalities: Modalities
readonly compatibility?: Compatibility
/** The provider's implementation of `api`, such as a vendor dialect. Absent means the package's standard one. */
readonly [implementation]?: Route<Type, C>
}
export interface Chat<Options extends ProviderOptions = ProviderOptions, C extends Compact = Compact>
extends Fields<"chat", Options, C> {
/** Where requests go; the API's default host when unset. */
readonly baseURL?: string
/** The request path when the host departs from the API's usual one, as models.dev v2 `path`. */
readonly path?: string
/** How requests authenticate; the API's default when unset. */
readonly auth?: Auth.Definition
}
/** `Model.make` input: a model whose `capabilities`, `limit` and `modalities` may be left out. */
export interface Input<Type extends ModelType, C extends Compact = Compact> {
readonly id: string
readonly provider: string
readonly type: Type
readonly api: Api
/** Text models only. */
readonly baseURL?: Type extends "chat" ? string : never
/** Text models only. */
readonly path?: Type extends "chat" ? string : never
/** Text models only. */
readonly auth?: Type extends "chat" ? Auth.Definition : never
readonly options?: RequestOptions
readonly capabilities?: Capabilities
readonly limit?: Limit
readonly modalities?: Modalities
readonly compatibility?: Compatibility
readonly [implementation]?: Route<Type, C>
}
/**
* A model from its description, with OpenCode's defaults for an unknown model: tools supported, text and image in,
* text out, a 200k context and 32k output. A text model built on a provider's implementation also takes that
* implementation's `baseURL`, `auth` and options where it leaves them out.
*/
export const make = <
Type extends ModelType,
Options extends ProviderOptions = ProviderOptions,
C extends Compact = Compact,
>(
input: Input<Type, C>,
): Model<Type, Options, C> => {
const route = input.type === "chat" ? (input[implementation] as AnyRoute<C> | undefined) : undefined
// The model's `providerOptions` type is a promise the API's request typing keeps; nothing here can check it.
return {
...input,
capabilities: { ...input.capabilities, tools: { supported: true, ...input.capabilities?.tools } },
limit: input.limit ?? { context: 200_000, output: 32_000 },
modalities: input.modalities ?? { input: ["text", "image"], output: ["text"] },
...(route && {
baseURL: input.baseURL ?? route.endpoint.baseURL,
auth: input.auth ?? route.auth,
options: mergeRequestOptions(route.options, input.options),
}),
} as Model<Type, Options, C>
}
}
/**
* The implementation a provider attached to the model. A text model's counts only while it still implements the
* model's `api`, so a spread that changes `api` falls back to the package's standard implementation.
*/
export const attachedRoute = <Type extends ModelType, C extends Compact = Compact>(
model: Model.Fields<Type, ProviderOptions, C>,
): Model.Route<Type, C> | undefined => {
const route = model[implementation]
if (route === undefined || model.type !== "chat") return route
const chat = route as AnyRoute
return (chat.api ?? chat.protocol) === model.api ? route : undefined
}
/** The implementation a model's requests run on, once the client attached it. */
export const routeOf = <Type extends ModelType, C extends Compact = Compact>(
model: Model.Fields<Type, ProviderOptions, C>,
): Model.Route<Type, C> => {
const route = attachedRoute(model)
if (route === undefined) throw new Error(`${model.provider}/${model.id} has no implementation of "${model.api}"`)
return route
}
/** A Schema that accepts models of the given type, for request schemas. */
export const modelSchema = <Type extends ModelType>(type: Type) =>
Schema.declare(
(value): value is Model<Type> => isRecord(value) && value.type === type && typeof value.api === "string",
{ expected: `Model<"${type}">` },
)
/** The `providerOptions` type a model's requests accept. */
export type ModelProviderOptions<SelectedModel> =
SelectedModel extends Model<ModelType, infer Options> ? Options : never

View file

@ -1,6 +1,4 @@
import { Schema } from "effect"
import { ModelID, ProviderID } from "./ids.js"
import type { AnyRoute, CompactionOperations } from "../route/client.js"
import { isRecord } from "../utils/record.js"
export const JsonSchema = Schema.Record(Schema.String, Schema.Unknown)
@ -200,30 +198,29 @@ export type LanguageModelMaxTokensFieldCompatibility = Schema.Schema.Type<
export const LanguageModelCacheFormatCompatibility = Schema.Literals(["anthropic", "alibaba"])
export type LanguageModelCacheFormatCompatibility = Schema.Schema.Type<typeof LanguageModelCacheFormatCompatibility>
export class LanguageModelCompatibility extends Schema.Class<LanguageModelCompatibility>(
"LLM.LanguageModelCompatibility",
)({
sanitizer: Schema.optional(LanguageModelSanitizerCompatibility),
reasoningField: Schema.optional(Schema.String),
/**
* Wire quirks of the model's API: models.dev v2 `compatibility` in camelCase (`reasoningField`, `maxTokensField`,
* `mediaInput`) plus the package's own quirks. Unset fields keep the protocol default.
*/
export interface Compatibility {
readonly reasoningField?: string
/** Require every assistant message to include its reasoning field, even when empty. */
requireReasoning: Schema.optional(Schema.Boolean),
maxTokensField: Schema.optional(LanguageModelMaxTokensFieldCompatibility),
requireFinishReason: Schema.optional(Schema.Boolean),
requireAssistantAfterTool: Schema.optional(Schema.Boolean),
readonly requireReasoning?: boolean
readonly maxTokensField?: LanguageModelMaxTokensFieldCompatibility
/**
* System One: where the host reads media, named after where it goes in the body: `assets` (TypeSafe's assets map,
* referenced from the state), `state` (items inside a state list) or `root` (one top-level list per kind).
*/
readonly mediaInput?: "assets" | "state" | "root"
readonly sanitizer?: LanguageModelSanitizerCompatibility
readonly requireFinishReason?: boolean
readonly requireAssistantAfterTool?: boolean
/** Prompt-cache marker syntax the endpoint accepts. Overrides the route default; both send `cache_control`, and `alibaba` skips tool definitions. */
cacheFormat: Schema.optional(LanguageModelCacheFormatCompatibility),
zaiToolStream: Schema.optional(Schema.Boolean),
requireSignature: Schema.optional(Schema.Boolean),
/** Supports Anthropic's thinking-prefix mismatch controls. Overrides model-ID detection. */
supportsThinkingBlockBinding: Schema.optional(Schema.Boolean),
}) {}
export namespace LanguageModelCompatibility {
export type Input = LanguageModelCompatibility | ConstructorParameters<typeof LanguageModelCompatibility>[0]
/** Normalize model/upstream compatibility metadata without projecting requests. */
export const make = (input: Input) =>
input instanceof LanguageModelCompatibility ? input : new LanguageModelCompatibility(input)
readonly cacheFormat?: LanguageModelCacheFormatCompatibility
readonly zaiToolStream?: boolean
readonly requireSignature?: boolean
/** Anthropic Messages and Bedrock Converse: the host takes thinking-prefix mismatch controls. Overrides model-ID detection. */
readonly thinkingBlockBinding?: boolean
}
/**
@ -284,107 +281,6 @@ export interface Capabilities {
readonly serviceTier?: ReadonlyArray<OpenString<"flex" | "priority" | "fast" | "ultrafast" | "standby">>
}
export class LanguageModel<
Options extends ProviderOptions = ProviderOptions,
Compact extends CompactionOperations | undefined = CompactionOperations | undefined,
> {
declare protected readonly _ProviderOptions: Options
readonly id: ModelID
readonly provider: ProviderID
readonly route: AnyRoute<Compact>
readonly options?: RequestOptions
readonly capabilities?: Capabilities
readonly compatibility?: LanguageModelCompatibility
constructor(input: LanguageModel.ConstructorInput<Compact>) {
this.id = input.id
this.provider = input.provider
this.route = input.route
this.options = input.options
this.capabilities = input.capabilities
this.compatibility = input.compatibility
}
static make<
Options extends ProviderOptions = ProviderOptions,
Compact extends CompactionOperations | undefined = CompactionOperations | undefined,
>(input: LanguageModel.Input<Compact>) {
return new LanguageModel<Options, Compact>({
id: ModelID.make(input.id),
provider: ProviderID.make(input.provider),
route: input.route,
// The route's options are a preset under the model's own.
options: mergeRequestOptions(input.route.options, input.options),
capabilities: input.capabilities,
compatibility:
input.compatibility === undefined ? undefined : LanguageModelCompatibility.make(input.compatibility),
})
}
static input<Options extends ProviderOptions, Compact extends CompactionOperations | undefined>(
model: LanguageModel<Options, Compact>,
): LanguageModel.ConstructorInput<Compact> {
return {
id: model.id,
provider: model.provider,
route: model.route,
options: model.options,
capabilities: model.capabilities,
compatibility: model.compatibility,
}
}
static update<Options extends ProviderOptions, Compact extends CompactionOperations | undefined>(
model: LanguageModel<Options>,
patch: Partial<LanguageModel.Input<Compact>> & { readonly route: AnyRoute<Compact> },
): LanguageModel<Options, Compact>
static update<Options extends ProviderOptions, Compact extends CompactionOperations | undefined>(
model: LanguageModel<Options, Compact>,
patch: Partial<Omit<LanguageModel.Input, "route">> & { readonly route?: undefined },
): LanguageModel<Options, Compact>
static update<Options extends ProviderOptions>(
model: LanguageModel<Options>,
patch: Partial<LanguageModel.Input>,
): LanguageModel<Options>
static update<Options extends ProviderOptions>(model: LanguageModel<Options>, patch: Partial<LanguageModel.Input>) {
if (Object.keys(patch).length === 0) return model
return LanguageModel.make<Options>({
...LanguageModel.input(model),
...patch,
route: patch.route ?? model.route,
})
}
}
export namespace LanguageModel {
export type ConstructorInput<Compact extends CompactionOperations | undefined = CompactionOperations | undefined> = {
readonly id: ModelID
readonly provider: ProviderID
readonly route: AnyRoute<Compact>
readonly options?: RequestOptions
readonly capabilities?: Capabilities
readonly compatibility?: LanguageModelCompatibility
}
export type Input<Compact extends CompactionOperations | undefined = CompactionOperations | undefined> = Omit<
ConstructorInput<Compact>,
"id" | "provider" | "compatibility"
> & {
readonly id: string | ModelID
readonly provider: string | ProviderID
readonly compatibility?: LanguageModelCompatibility.Input
}
}
export type LanguageModelInput = LanguageModel.Input
export type LanguageModelProviderOptions<SelectedModel> =
SelectedModel extends LanguageModel<infer Options> ? Options : never
export const LanguageModelSchema = Schema.declare((value): value is LanguageModel => value instanceof LanguageModel, {
expected: "LLM.LanguageModel",
})
// Provider cache lifetime such as "5m", "30m", "1h" or "24h", in models.dev's duration format. It is sent as given;
// each provider accepts its own set, and omitting it keeps the provider default.
export const CacheTTL = Schema.TemplateLiteral([Schema.Number, Schema.Literals(["ms", "s", "m", "h", "d"])]).check(

View file

@ -1,7 +1,7 @@
import { Effect, Schema, Stream } from "effect"
import { ProgressEvent, QueuedEvent } from "./generation.js"
import { Media } from "./media.js"
import { MediaModel, composeRoute, tryRequest } from "./media-model.js"
import { type MediaModel, composeRoute, mediaOptions, tryRequest } from "./media-model.js"
import { MediaRoute } from "./route/media.js"
import {
AIError,
@ -10,58 +10,56 @@ import {
ProviderOptions,
type OpenString,
type BaseRequest,
mediaApi,
implementation,
Model,
modelSchema,
type ModelProviderOptions,
} from "./schema/index.js"
import { SpeechClient, Service } from "./speech-client.js"
// ---------------------------------------------------------------------------
// Model
// SelectedModel
// ---------------------------------------------------------------------------
export type SpeechOptions = MediaModel.Options
export type SpeechRoute = MediaRoute.AnyRoute<SpeechRequest, SpeechEvent, SpeechResponse>
export class SpeechModel<Options extends SpeechOptions = SpeechOptions> extends MediaModel<SpeechRoute, Options> {
declare protected readonly _SpeechModel: void
/** The number of type arguments selects the kind: `<Options>`, `<Options, Frame, State>`, or `<Options, Token>`. */
static fromRoute<Options extends SpeechOptions>(
route: MediaModel.InlineRouteInput<SpeechRequest<SpeechModel<Options>>, SpeechResponse>,
input: MediaRoute.ModelInput,
): SpeechModel<Options>
static fromRoute<Options extends SpeechOptions, Frame, State>(
route: MediaModel.StreamRouteInput<SpeechRequest<SpeechModel<Options>>, SpeechEvent, Frame, State>,
input: MediaRoute.ModelInput,
): SpeechModel<Options>
static fromRoute<Options extends SpeechOptions, Token>(
route: MediaModel.QueuedRouteInput<SpeechRequest<SpeechModel<Options>>, SpeechResponse, Token>,
input: MediaRoute.ModelInput,
): SpeechModel<Options>
static fromRoute<Options extends SpeechOptions, Frame, State, Token>(
route: MediaModel.AnyRouteInput<
SpeechRequest<SpeechModel<Options>>,
SpeechEvent,
SpeechResponse,
Frame,
State,
Token
>,
input: MediaRoute.ModelInput,
) {
return new SpeechModel<Options>({
id: input.id,
provider: route.protocol.provider,
http: input.http,
providerOptions: input.providerOptions,
route: composeRoute(route, input, collectResponse) as SpeechRoute,
})
}
/** The number of type arguments selects the kind: `<Options>`, `<Options, Frame, State>`, or `<Options, Token>`. */
export function speechModel<Options extends SpeechOptions>(
route: MediaModel.InlineRouteInput<SpeechRequest<Model<"speech", Options>>, SpeechResponse>,
input: MediaRoute.ModelInput,
): Model<"speech", Options>
export function speechModel<Options extends SpeechOptions, Frame, State>(
route: MediaModel.StreamRouteInput<SpeechRequest<Model<"speech", Options>>, SpeechEvent, Frame, State>,
input: MediaRoute.ModelInput,
): Model<"speech", Options>
export function speechModel<Options extends SpeechOptions, Token>(
route: MediaModel.QueuedRouteInput<SpeechRequest<Model<"speech", Options>>, SpeechResponse, Token>,
input: MediaRoute.ModelInput,
): Model<"speech", Options>
export function speechModel<Options extends SpeechOptions, Frame, State, Token>(
route: MediaModel.AnyRouteInput<
SpeechRequest<Model<"speech", Options>>,
SpeechEvent,
SpeechResponse,
Frame,
State,
Token
>,
input: MediaRoute.ModelInput,
) {
return Model.make<"speech", Options>({
type: "speech",
id: input.id,
provider: route.protocol.provider,
options: mediaOptions(input),
api: mediaApi(route.protocol.id),
[implementation]: composeRoute(route, input, collectResponse) as SpeechRoute,
})
}
export const SpeechModelSchema = Schema.declare((value): value is SpeechModel => value instanceof SpeechModel, {
expected: "Speech.Model",
})
// ---------------------------------------------------------------------------
// Request
// ---------------------------------------------------------------------------
@ -83,7 +81,7 @@ export const SpeechTimestamp = Schema.Struct({
export type SpeechTimestamp = Schema.Schema.Type<typeof SpeechTimestamp>
const SpeechRequestSchema = Schema.Struct({
model: SpeechModelSchema,
model: modelSchema("speech"),
text: Schema.String,
voice: Schema.optional(SpeechVoice),
format: Schema.optional(Schema.String),
@ -95,20 +93,18 @@ const SpeechRequestSchema = Schema.Struct({
})
/** A normalized speech request, the plain object `Speech.request(...)` returns. */
export type SpeechRequest<Model extends SpeechModel = SpeechModel> = Omit<
export type SpeechRequest<SelectedModel extends Model<"speech"> = Model<"speech">> = Omit<
typeof SpeechRequestSchema.Type,
"model" | "providerOptions" | "format"
> &
BaseRequest<Model, SpeechModelOptions<Model>> & { readonly format?: SpeechFormat }
export type SpeechModelOptions<Model> = Model extends SpeechModel<infer Options> ? Options : never
BaseRequest<SelectedModel, ModelProviderOptions<SelectedModel>> & { readonly format?: SpeechFormat }
/** Input accepted by `Speech.request` and the calls; a `SpeechRequest` is also a valid input. */
export type SpeechRequestInput<Model extends SpeechModel = SpeechModel> = Omit<
SpeechRequest<Model>,
export type SpeechRequestInput<SelectedModel extends Model<"speech"> = Model<"speech">> = Omit<
SpeechRequest<SelectedModel>,
"providerOptions"
> & {
readonly providerOptions?: NoInfer<SpeechModelOptions<Model>>
readonly providerOptions?: NoInfer<ModelProviderOptions<SelectedModel>>
}
// ---------------------------------------------------------------------------
@ -179,7 +175,9 @@ const collectResponse = (events: ReadonlyArray<SpeechEvent>): Effect.Effect<Spee
// ---------------------------------------------------------------------------
/** Normalize speech request input into a plain `SpeechRequest`. */
export const request = <const Model extends SpeechModel>(input: SpeechRequestInput<Model>): SpeechRequest<Model> => ({
export const request = <const SelectedModel extends Model<"speech">>(
input: SpeechRequestInput<SelectedModel>,
): SpeechRequest<SelectedModel> => ({
...input,
})
@ -192,15 +190,15 @@ const requestEffect = (input: SpeechRequestInput) =>
return normalized
})
export function generate<const Model extends SpeechModel>(
input: SpeechRequestInput<Model>,
export function generate<const SelectedModel extends Model<"speech">>(
input: SpeechRequestInput<SelectedModel>,
): Effect.Effect<SpeechResponse, AIError, Service>
export function generate(input: SpeechRequestInput) {
return requestEffect(input).pipe(Effect.flatMap((request) => SpeechClient.generate(request)))
}
export function stream<const Model extends SpeechModel>(
input: SpeechRequestInput<Model>,
export function stream<const SelectedModel extends Model<"speech">>(
input: SpeechRequestInput<SelectedModel>,
): Stream.Stream<SpeechEvent, AIError, Service>
export function stream(input: SpeechRequestInput) {
return Stream.unwrap(requestEffect(input).pipe(Effect.map((request) => SpeechClient.stream(request))))

View file

@ -1,69 +1,73 @@
import { Effect, Schema, Stream } from "effect"
import { Generation, ProgressEvent, QueuedEvent, type AwaitOptions } from "./generation.js"
import { Media } from "./media.js"
import { MediaModel, composeRoute, tryRequest } from "./media-model.js"
import { type MediaModel, composeRoute, mediaOptions, tryRequest } from "./media-model.js"
import { MediaRoute } from "./route/media.js"
import { AIError, MediaUsage, ProviderMetadata, ProviderOptions, type BaseRequest } from "./schema/index.js"
import {
AIError,
MediaUsage,
ProviderMetadata,
ProviderOptions,
type BaseRequest,
mediaApi,
implementation,
Model,
modelSchema,
type ModelProviderOptions,
} from "./schema/index.js"
import { TranscriptionClient, Service } from "./transcription-client.js"
// ---------------------------------------------------------------------------
// Model
// SelectedModel
// ---------------------------------------------------------------------------
export type TranscriptionOptions = MediaModel.Options
export type TranscriptionRoute = MediaRoute.AnyRoute<TranscriptionRequest, TranscriptionEvent, TranscriptionResponse>
export class TranscriptionModel<Options extends TranscriptionOptions = TranscriptionOptions> extends MediaModel<
TranscriptionRoute,
Options
> {
declare protected readonly _TranscriptionModel: void
/** The number of type arguments selects the kind: `<Options>`, `<Options, Frame, State>`, or `<Options, Token>`. */
static fromRoute<Options extends TranscriptionOptions>(
route: MediaModel.InlineRouteInput<TranscriptionRequest<TranscriptionModel<Options>>, TranscriptionResponse>,
input: MediaRoute.ModelInput,
): TranscriptionModel<Options>
static fromRoute<Options extends TranscriptionOptions, Frame, State>(
route: MediaModel.StreamRouteInput<
TranscriptionRequest<TranscriptionModel<Options>>,
TranscriptionEvent,
Frame,
State
>,
input: MediaRoute.ModelInput,
): TranscriptionModel<Options>
static fromRoute<Options extends TranscriptionOptions, Token>(
route: MediaModel.QueuedRouteInput<TranscriptionRequest<TranscriptionModel<Options>>, TranscriptionResponse, Token>,
input: MediaRoute.ModelInput,
): TranscriptionModel<Options>
static fromRoute<Options extends TranscriptionOptions, Frame, State, Token>(
route: MediaModel.AnyRouteInput<
TranscriptionRequest<TranscriptionModel<Options>>,
TranscriptionEvent,
TranscriptionResponse,
Frame,
State,
Token
>,
input: MediaRoute.ModelInput,
) {
return new TranscriptionModel<Options>({
id: input.id,
provider: route.protocol.provider,
http: input.http,
providerOptions: input.providerOptions,
route: composeRoute(route, input, collectResponse) as TranscriptionRoute,
})
}
/** The number of type arguments selects the kind: `<Options>`, `<Options, Frame, State>`, or `<Options, Token>`. */
export function transcriptionModel<Options extends TranscriptionOptions>(
route: MediaModel.InlineRouteInput<TranscriptionRequest<Model<"transcription", Options>>, TranscriptionResponse>,
input: MediaRoute.ModelInput,
): Model<"transcription", Options>
export function transcriptionModel<Options extends TranscriptionOptions, Frame, State>(
route: MediaModel.StreamRouteInput<
TranscriptionRequest<Model<"transcription", Options>>,
TranscriptionEvent,
Frame,
State
>,
input: MediaRoute.ModelInput,
): Model<"transcription", Options>
export function transcriptionModel<Options extends TranscriptionOptions, Token>(
route: MediaModel.QueuedRouteInput<
TranscriptionRequest<Model<"transcription", Options>>,
TranscriptionResponse,
Token
>,
input: MediaRoute.ModelInput,
): Model<"transcription", Options>
export function transcriptionModel<Options extends TranscriptionOptions, Frame, State, Token>(
route: MediaModel.AnyRouteInput<
TranscriptionRequest<Model<"transcription", Options>>,
TranscriptionEvent,
TranscriptionResponse,
Frame,
State,
Token
>,
input: MediaRoute.ModelInput,
) {
return Model.make<"transcription", Options>({
type: "transcription",
id: input.id,
provider: route.protocol.provider,
options: mediaOptions(input),
api: mediaApi(route.protocol.id),
[implementation]: composeRoute(route, input, collectResponse) as TranscriptionRoute,
})
}
export const TranscriptionModelSchema = Schema.declare(
(value): value is TranscriptionModel => value instanceof TranscriptionModel,
{ expected: "Transcription.Model" },
)
// ---------------------------------------------------------------------------
// Request
// ---------------------------------------------------------------------------
@ -72,7 +76,7 @@ export const TranscriptionTimestamps = Schema.Literals(["none", "segment", "word
export type TranscriptionTimestamps = Schema.Schema.Type<typeof TranscriptionTimestamps>
const TranscriptionRequestSchema = Schema.Struct({
model: TranscriptionModelSchema,
model: modelSchema("transcription"),
audio: Media.AssetSchema,
language: Schema.optional(Schema.String),
prompt: Schema.optional(Schema.String),
@ -84,20 +88,18 @@ const TranscriptionRequestSchema = Schema.Struct({
})
/** A normalized transcription request, the plain object `Transcription.request(...)` returns. */
export type TranscriptionRequest<Model extends TranscriptionModel = TranscriptionModel> = Omit<
export type TranscriptionRequest<SelectedModel extends Model<"transcription"> = Model<"transcription">> = Omit<
typeof TranscriptionRequestSchema.Type,
"model" | "providerOptions"
> &
BaseRequest<Model, TranscriptionModelOptions<Model>>
export type TranscriptionModelOptions<Model> = Model extends TranscriptionModel<infer Options> ? Options : never
BaseRequest<SelectedModel, ModelProviderOptions<SelectedModel>>
/** Input accepted by `Transcription.request` and the calls; a `TranscriptionRequest` is also a valid input. */
export type TranscriptionRequestInput<Model extends TranscriptionModel = TranscriptionModel> = Omit<
TranscriptionRequest<Model>,
export type TranscriptionRequestInput<SelectedModel extends Model<"transcription"> = Model<"transcription">> = Omit<
TranscriptionRequest<SelectedModel>,
"providerOptions"
> & {
readonly providerOptions?: NoInfer<TranscriptionModelOptions<Model>>
readonly providerOptions?: NoInfer<ModelProviderOptions<SelectedModel>>
}
// ---------------------------------------------------------------------------
@ -183,9 +185,9 @@ const collectResponse = (events: ReadonlyArray<TranscriptionEvent>): Effect.Effe
// ---------------------------------------------------------------------------
/** Normalize transcription request input into a plain `TranscriptionRequest`. */
export const request = <const Model extends TranscriptionModel>(
input: TranscriptionRequestInput<Model>,
): TranscriptionRequest<Model> => ({
export const request = <const SelectedModel extends Model<"transcription">>(
input: TranscriptionRequestInput<SelectedModel>,
): TranscriptionRequest<SelectedModel> => ({
...input,
})
@ -198,16 +200,16 @@ const requestEffect = (input: TranscriptionRequestInput) =>
return normalized
})
export function generate<const Model extends TranscriptionModel>(
input: TranscriptionRequestInput<Model>,
export function generate<const SelectedModel extends Model<"transcription">>(
input: TranscriptionRequestInput<SelectedModel>,
options?: AwaitOptions,
): Effect.Effect<TranscriptionResponse, AIError, Service>
export function generate(input: TranscriptionRequestInput, options?: AwaitOptions) {
return requestEffect(input).pipe(Effect.flatMap((request) => TranscriptionClient.generate(request, options)))
}
export function stream<const Model extends TranscriptionModel>(
input: TranscriptionRequestInput<Model>,
export function stream<const SelectedModel extends Model<"transcription">>(
input: TranscriptionRequestInput<SelectedModel>,
options?: AwaitOptions,
): Stream.Stream<TranscriptionEvent, AIError, Service>
export function stream(input: TranscriptionRequestInput, options?: AwaitOptions) {
@ -215,15 +217,15 @@ export function stream(input: TranscriptionRequestInput, options?: AwaitOptions)
}
/** Inline and streaming routes fail with `UnsupportedOperation`. */
export function start<const Model extends TranscriptionModel>(
input: TranscriptionRequestInput<Model>,
export function start<const SelectedModel extends Model<"transcription">>(
input: TranscriptionRequestInput<SelectedModel>,
): Effect.Effect<Generation<TranscriptionResponse>, AIError, Service>
export function start(input: TranscriptionRequestInput) {
return requestEffect(input).pipe(Effect.flatMap((request) => TranscriptionClient.start(request)))
}
export const resume = (
model: TranscriptionModel,
model: Model<"transcription">,
token: unknown,
): Effect.Effect<Generation<TranscriptionResponse>, AIError, Service> => TranscriptionClient.resume(model, token)

View file

@ -1,7 +1,7 @@
import { Effect, Schema, Stream } from "effect"
import { Generation, ProgressEvent, QueuedEvent, type AwaitOptions } from "./generation.js"
import { Media } from "./media.js"
import { MediaModel, composeRoute, tryRequest } from "./media-model.js"
import { type MediaModel, composeRoute, mediaOptions, tryRequest } from "./media-model.js"
import { MediaRoute } from "./route/media.js"
import {
AIError,
@ -10,51 +10,56 @@ import {
ProviderOptions,
type OpenString,
type BaseRequest,
mediaApi,
implementation,
Model,
modelSchema,
type ModelProviderOptions,
} from "./schema/index.js"
import { VideoClient, Service } from "./video-client.js"
// ---------------------------------------------------------------------------
// Model
// SelectedModel
// ---------------------------------------------------------------------------
export type VideoOptions = MediaModel.Options
export type VideoRoute = MediaRoute.AnyRoute<VideoRequest, VideoEvent, VideoResponse>
export class VideoModel<Options extends VideoOptions = VideoOptions> extends MediaModel<VideoRoute, Options> {
declare protected readonly _VideoModel: void
/** The number of type arguments selects the kind: `<Options>`, `<Options, Frame, State>`, or `<Options, Token>`. */
static fromRoute<Options extends VideoOptions>(
route: MediaModel.InlineRouteInput<VideoRequest<VideoModel<Options>>, VideoResponse>,
input: MediaRoute.ModelInput,
): VideoModel<Options>
static fromRoute<Options extends VideoOptions, Frame, State>(
route: MediaModel.StreamRouteInput<VideoRequest<VideoModel<Options>>, VideoEvent, Frame, State>,
input: MediaRoute.ModelInput,
): VideoModel<Options>
static fromRoute<Options extends VideoOptions, Token>(
route: MediaModel.QueuedRouteInput<VideoRequest<VideoModel<Options>>, VideoResponse, Token>,
input: MediaRoute.ModelInput,
): VideoModel<Options>
static fromRoute<Options extends VideoOptions, Frame, State, Token>(
route: MediaModel.AnyRouteInput<VideoRequest<VideoModel<Options>>, VideoEvent, VideoResponse, Frame, State, Token>,
input: MediaRoute.ModelInput,
) {
return new VideoModel<Options>({
id: input.id,
provider: route.protocol.provider,
http: input.http,
providerOptions: input.providerOptions,
route: composeRoute(route, input, collectResponse) as VideoRoute,
})
}
/** The number of type arguments selects the kind: `<Options>`, `<Options, Frame, State>`, or `<Options, Token>`. */
export function videoModel<Options extends VideoOptions>(
route: MediaModel.InlineRouteInput<VideoRequest<Model<"video", Options>>, VideoResponse>,
input: MediaRoute.ModelInput,
): Model<"video", Options>
export function videoModel<Options extends VideoOptions, Frame, State>(
route: MediaModel.StreamRouteInput<VideoRequest<Model<"video", Options>>, VideoEvent, Frame, State>,
input: MediaRoute.ModelInput,
): Model<"video", Options>
export function videoModel<Options extends VideoOptions, Token>(
route: MediaModel.QueuedRouteInput<VideoRequest<Model<"video", Options>>, VideoResponse, Token>,
input: MediaRoute.ModelInput,
): Model<"video", Options>
export function videoModel<Options extends VideoOptions, Frame, State, Token>(
route: MediaModel.AnyRouteInput<
VideoRequest<Model<"video", Options>>,
VideoEvent,
VideoResponse,
Frame,
State,
Token
>,
input: MediaRoute.ModelInput,
) {
return Model.make<"video", Options>({
type: "video",
id: input.id,
provider: route.protocol.provider,
options: mediaOptions(input),
api: mediaApi(route.protocol.id),
[implementation]: composeRoute(route, input, collectResponse) as VideoRoute,
})
}
export const VideoModelSchema = Schema.declare((value): value is VideoModel => value instanceof VideoModel, {
expected: "Video.Model",
})
// ---------------------------------------------------------------------------
// Request
// ---------------------------------------------------------------------------
@ -72,7 +77,7 @@ export const VideoFrames = Schema.Struct({
export type VideoFrames = Schema.Schema.Type<typeof VideoFrames>
const VideoRequestSchema = Schema.Struct({
model: VideoModelSchema,
model: modelSchema("video"),
prompt: Schema.String,
frames: Schema.optional(VideoFrames),
/** Style or subject references that guide the output without pinning a frame. */
@ -91,17 +96,18 @@ const VideoRequestSchema = Schema.Struct({
})
/** A normalized video request, the plain object `Video.request(...)` returns. */
export type VideoRequest<Model extends VideoModel = VideoModel> = Omit<
export type VideoRequest<SelectedModel extends Model<"video"> = Model<"video">> = Omit<
typeof VideoRequestSchema.Type,
"model" | "providerOptions" | "resolution"
> &
BaseRequest<Model, VideoModelOptions<Model>> & { readonly resolution?: VideoResolution }
export type VideoModelOptions<Model> = Model extends VideoModel<infer Options> ? Options : never
BaseRequest<SelectedModel, ModelProviderOptions<SelectedModel>> & { readonly resolution?: VideoResolution }
/** Input accepted by `Video.request` and the calls; a `VideoRequest` is also a valid input. */
export type VideoRequestInput<Model extends VideoModel = VideoModel> = Omit<VideoRequest<Model>, "providerOptions"> & {
readonly providerOptions?: NoInfer<VideoModelOptions<Model>>
export type VideoRequestInput<SelectedModel extends Model<"video"> = Model<"video">> = Omit<
VideoRequest<SelectedModel>,
"providerOptions"
> & {
readonly providerOptions?: NoInfer<ModelProviderOptions<SelectedModel>>
}
// ---------------------------------------------------------------------------
@ -161,7 +167,9 @@ const collectResponse = (events: ReadonlyArray<VideoEvent>): Effect.Effect<Video
// ---------------------------------------------------------------------------
/** Normalize video request input into a plain `VideoRequest`. */
export const request = <const Model extends VideoModel>(input: VideoRequestInput<Model>): VideoRequest<Model> => ({
export const request = <const SelectedModel extends Model<"video">>(
input: VideoRequestInput<SelectedModel>,
): VideoRequest<SelectedModel> => ({
...input,
})
@ -174,15 +182,15 @@ const requestEffect = (input: VideoRequestInput) =>
return normalized
})
export function start<const Model extends VideoModel>(
input: VideoRequestInput<Model>,
export function start<const SelectedModel extends Model<"video">>(
input: VideoRequestInput<SelectedModel>,
): Effect.Effect<Generation<VideoResponse>, AIError, Service>
export function start(input: VideoRequestInput) {
return requestEffect(input).pipe(Effect.flatMap((request) => VideoClient.start(request)))
}
export function generate<const Model extends VideoModel>(
input: VideoRequestInput<Model>,
export function generate<const SelectedModel extends Model<"video">>(
input: VideoRequestInput<SelectedModel>,
options?: AwaitOptions,
): Effect.Effect<VideoResponse, AIError, Service>
export function generate(input: VideoRequestInput, options?: AwaitOptions) {
@ -190,11 +198,13 @@ export function generate(input: VideoRequestInput, options?: AwaitOptions) {
}
/** Rebuild a generation handle from a persisted `Generation.token`, refreshing its status once. */
export const resume = (model: VideoModel, token: unknown): Effect.Effect<Generation<VideoResponse>, AIError, Service> =>
VideoClient.resume(model, token)
export const resume = (
model: Model<"video">,
token: unknown,
): Effect.Effect<Generation<VideoResponse>, AIError, Service> => VideoClient.resume(model, token)
export function stream<const Model extends VideoModel>(
input: VideoRequestInput<Model>,
export function stream<const SelectedModel extends Model<"video">>(
input: VideoRequestInput<SelectedModel>,
options?: AwaitOptions,
): Stream.Stream<VideoEvent, AIError, Service>
export function stream(input: VideoRequestInput, options?: AwaitOptions) {

View file

@ -3,12 +3,9 @@ import { Effect, Schema, Stream } from "effect"
import { ai, LLMResponse } from "../src/effect.js"
import { Route, Endpoint, LLMClient, Protocol, type Framing } from "../src/route.js"
import { compileRequest } from "../src/route/client.js"
import { LanguageModel } from "../src/schema/index.js"
import { testEffect } from "./lib/effect.js"
import { dynamicResponse } from "./lib/http.js"
const updateModel = (model: LanguageModel, patch: Partial<LanguageModel.Input>) => LanguageModel.update(model, patch)
const Json = Schema.fromJsonString(Schema.Unknown)
const encodeJson = Schema.encodeSync(Json)
@ -86,11 +83,7 @@ const configuredGemini = gemini.with({ endpoint: { baseURL: "https://fake.local"
const request = ai.request({
id: "req_1",
model: LanguageModel.make({
id: "fake-model",
provider: "fake-provider",
route: configuredFake,
}),
model: Route.model(configuredFake, { id: "fake-model", provider: "fake-provider" }),
prompt: "hello",
})
@ -142,7 +135,7 @@ describe("llm route", () => {
Effect.gen(function* () {
const prepared = yield* compileRequest({
...request,
model: updateModel(request.model, { route: configuredGemini }),
model: Route.model(configuredGemini, { id: request.model.id, provider: request.model.provider }),
})
expect(prepared.route).toBe("gemini-fake")
@ -172,7 +165,10 @@ describe("llm route", () => {
framing: fakeFraming,
})
const prepared = yield* compileRequest({ ...request, model: updateModel(request.model, { route: duplicate }) })
const prepared = yield* compileRequest({
...request,
model: Route.model(duplicate, { id: request.model.id, provider: request.model.provider }),
})
expect(prepared.body).toEqual({ body: "late-default" })
}),

View file

@ -4,12 +4,13 @@ import { Headers } from "effect/http"
import { ai } from "../src/effect.js"
import { Auth } from "../src/route/auth.js"
import * as OpenAIChat from "../src/protocols/openai-chat.js"
import { LanguageModel } from "../src/schema/index.js"
import { Model } from "../src/schema/index.js"
import { it } from "./lib/effect.js"
import { Route } from "../src/route.js"
const request = ai.request({
id: "req_auth",
model: LanguageModel.make({ id: "fake-model", provider: "fake", route: OpenAIChat.route }),
model: Route.model(OpenAIChat.route, { id: "fake-model", provider: "fake" }),
prompt: "hello",
})

View file

@ -1,7 +1,7 @@
import { expect, test } from "bun:test"
import { Effect, Schema } from "effect"
import { CompactionPart, CompactionResponse, LLMEvent, LLMResponse, Message, ProviderID } from "../src/schema/index.js"
import { ai, LanguageModel } from "../src/effect.js"
import { ai } from "../src/effect.js"
import { OpenAI, Anthropic } from "../src/providers.js"
import { testEffect } from "./lib/effect.js"
import { fixedResponse } from "./lib/http.js"
@ -13,14 +13,8 @@ test("runtime capability checks follow model and route updates", () => {
expect(ai.canCompact(request)).toBe(true)
expect(ai.canCompact({ ...request, messages: [] })).toBe(true)
expect(ai.canCompact({ ...request, model: unsupported })).toBe(false)
expect(
ai.canCompact(
ai.request({ model: LanguageModel.update(supported, { route: unsupported.route }), prompt: "Hello" }),
),
).toBe(false)
expect(
ai.canCompact(ai.request({ model: LanguageModel.update(supported, { route: undefined }), prompt: "Hello" })),
).toBe(true)
expect(ai.canCompact(ai.request({ model: { ...supported, api: unsupported.api }, prompt: "Hello" }))).toBe(false)
expect(ai.canCompact(ai.request({ model: { ...supported }, prompt: "Hello" }))).toBe(true)
expect(ai.canCompact(supported)).toBe(true)
expect(ai.canCompact(supported, { mechanism: "trigger" })).toBe(true)
expect(ai.canCompact(unsupported)).toBe(false)

View file

@ -1,13 +1,13 @@
import {
ai,
type AssistantMessage,
type LanguageModel,
Media,
Message,
ToolCallPart,
ToolDefinition,
ToolResultPart,
type UserMessage,
Model,
} from "../src/effect.js"
export const basicContinuation = ["system", "user-text", "assistant-text", "user-follow-up"] as const
@ -50,7 +50,7 @@ export const continuationTool = ToolDefinition.make({
export function continuationRequest(input: {
readonly id: string
readonly model: LanguageModel
readonly model: Model<"chat">
readonly features: ReadonlyArray<ContinuationFeature>
readonly image?: string
}) {

View file

@ -1,5 +1,5 @@
import { Effect } from "effect"
import { ai, DecisionClient, DecisionModel, type DecisionModelRoute, type DecisionRequestInput } from "../src/effect.js"
import { ai, DecisionClient, type DecisionRequestInput, Model } from "../src/effect.js"
import type { Service } from "../src/decision-client.js"
import { Baseten, OpenAI, OpenCode, OpenRouter, TypeSafeAI } from "../src/providers.js"
@ -55,8 +55,12 @@ Effect.gen(function* () {
questions: [{ name: "ok", type: "predicate", instructions: "OK?" }],
}) satisfies DecisionRequestInput
declare const route: DecisionModelRoute<{ readonly temperature?: number }>
const custom = DecisionModel.make({ id: "custom", provider: "custom", route })
const custom = Model.make<"decision", { readonly temperature?: number }>({
type: "decision",
id: "custom",
provider: "custom",
api: "decisions",
})
ai.decision.generate({
model: custom,
input: { text: "hello" },

View file

@ -1,16 +1,12 @@
import { describe, expect, test } from "bun:test"
import { ai } from "../src/effect.js"
import * as OpenAIChat from "../src/protocols/openai-chat.js"
import { Endpoint } from "../src/route.js"
import { LanguageModel } from "../src/schema/index.js"
import { Endpoint, Route } from "../src/route.js"
import { Model } from "../src/schema/index.js"
const request = () =>
ai.request({
model: LanguageModel.make({
id: "model-1",
provider: "test",
route: OpenAIChat.route,
}),
model: Route.model(OpenAIChat.route, { id: "model-1", provider: "test" }),
prompt: "hello",
})

View file

@ -1,16 +1,16 @@
import { describe, expect, test } from "bun:test"
import { Effect, Layer, Schema, Stream } from "effect"
import { ai, LanguageModel, LLMEvent, ProviderInternalError, tool } from "../src/effect.js"
import { ai, LLMEvent, ProviderInternalError, tool, Model } from "../src/effect.js"
import { AI, AIError } from "../src/index.js"
import { OpenAIChat } from "../src/protocols/openai-chat.js"
import { OpenAI } from "../src/providers.js"
import { RequestExecutor } from "../src/route.js"
import { RequestExecutor, Route } from "../src/route.js"
import { TestLLM } from "../src/testing.js"
import { testEffect } from "./lib/effect.js"
import { handlerLayer } from "./lib/http.js"
import { sseEvents } from "./lib/sse.js"
const model = LanguageModel.make({ id: "fictional-model", provider: "fixture", route: OpenAIChat.route })
const model = Route.model(OpenAIChat.route, { id: "fictional-model", provider: "fixture" })
const it = testEffect(TestLLM.testLayer())
const overloaded = new AIError({ reason: new ProviderInternalError({ message: "Overloaded" }) })

View file

@ -7,11 +7,11 @@ import {
DecisionClient,
Generation,
ImageClient,
LanguageModel,
LLMClient,
LLMEvent,
Media,
RawEvent,
Model,
} from "@opencode/ai/effect"
import { AI } from "@opencode/ai"
import { Speech, SpeechClient, SpeechEvent, TranscriptionClient, Video, VideoClient } from "@opencode/ai/experimental"
@ -71,7 +71,7 @@ describe("public exports", () => {
expect(LLMClient.Service).toBeFunction()
expect(LLMClient.layer).toBeDefined()
expect(AIError).toBeFunction()
expect(LanguageModel.make).toBeFunction()
expect(Model.make).toBeFunction()
expect(Media.bytes).toBeFunction()
expect(ai.image.generate).toBeFunction()
expect(Video.start).toBeFunction()
@ -138,7 +138,7 @@ describe("public exports", () => {
expect(OpenAICompatible).not.toHaveProperty(name)
}
expect(
OpenAICompatibleResponses.configure({ baseURL: "https://responses.test/v1" }).model("fixture").route.id,
Route.of(OpenAICompatibleResponses.configure({ baseURL: "https://responses.test/v1" }).model("fixture"))?.id,
).toBe("openai-compatible-responses")
expect(CloudflareAIGateway.configure).toBeFunction()
expect(CloudflareAIGateway.configure({ accountId: "fixture", gatewayApiKey: "fixture" }).model).toBeFunction()
@ -148,58 +148,68 @@ describe("public exports", () => {
expect(OpenRouter.decision).toBeFunction()
expect(TypeSafeAI.decision).toBeFunction()
expect(OpenCode.decision).toBeFunction()
expect(VercelAIGateway.decision("typesafe-ai/jev").route.id).toBe("openai-decisions")
expect(Route.of(VercelAIGateway.decision("typesafe-ai/jev"))?.id).toBe("openai-decisions")
expect(Baseten.decision).toBeFunction()
expect(DigitalOcean.decision).toBeFunction()
expect(OpenAI.decision("gpt-6-luna").route.id).toBe("openai-decisions")
expect(Route.of(OpenAI.decision("gpt-6-luna"))?.id).toBe("openai-decisions")
expect(XAI.model).toBeFunction()
expect(XAI.provider.responses).toBe(XAI.responses)
expect(XAI.provider.chat).toBe(XAI.chat)
expect(XAI.configure({ apiKey: "fixture" }).responses("grok-4.3").route.id).toBe("xai-responses")
expect(XAI.configure({ apiKey: "fixture" }).chat("grok-4.3").route.id).toBe("xai-chat")
expect(OpenAI.configure({ apiKey: "fixture" }).image("gpt-image-2").route.id).toBe("openai-images")
expect(Route.of(XAI.configure({ apiKey: "fixture" }).responses("grok-4.3"))?.id).toBe("xai-responses")
expect(Route.of(XAI.configure({ apiKey: "fixture" }).chat("grok-4.3"))?.id).toBe("xai-chat")
expect(Route.of(OpenAI.configure({ apiKey: "fixture" }).image("gpt-image-2"))?.id).toBe("openai-images")
expect(OpenAI.provider.image).toBe(OpenAI.image)
expect(Google.configure({ apiKey: "fixture" }).image("imagen-4.0-generate-001").route.id).toBe("google-images")
expect(Route.of(Google.configure({ apiKey: "fixture" }).image("imagen-4.0-generate-001"))?.id).toBe("google-images")
expect(Google.provider.image).toBe(Google.image)
expect(XAI.configure({ apiKey: "fixture" }).image("grok-imagine-image").route.id).toBe("xai-images")
expect(Route.of(XAI.configure({ apiKey: "fixture" }).image("grok-imagine-image"))?.id).toBe("xai-images")
expect(XAI.provider.image).toBe(XAI.image)
expect(Meta.configure({ apiKey: "fixture" }).image("muse-image").route.id).toBe("meta-images")
expect(Route.of(Meta.configure({ apiKey: "fixture" }).image("muse-image"))?.id).toBe("meta-images")
expect(Meta.provider.image).toBe(Meta.image)
expect(ZAI.configure({ apiKey: "fixture" }).image("glm-image").route.id).toBe("zai-images")
expect(Route.of(ZAI.configure({ apiKey: "fixture" }).image("glm-image"))?.id).toBe("zai-images")
expect(ZAI.provider.image).toBe(ZAI.image)
expect(MiniMax.configure({ apiKey: "fixture" }).image("image-01").route.id).toBe("minimax-images")
expect(Route.of(MiniMax.configure({ apiKey: "fixture" }).image("image-01"))?.id).toBe("minimax-images")
expect(MiniMax.provider.image).toBe(MiniMax.image)
expect(Alibaba.configure({ region: "ap-southeast-1", apiKey: "fixture" }).image("qwen-image-2.0").route.id).toBe(
"alibaba-images",
expect(
Route.of(Alibaba.configure({ region: "ap-southeast-1", apiKey: "fixture" }).image("qwen-image-2.0"))?.id,
).toBe("alibaba-images")
expect(Route.of(VercelAIGateway.configure({ apiKey: "fixture" }).image("meta/muse-image-1.0"))?.id).toBe(
"openai-images",
)
expect(VercelAIGateway.configure({ apiKey: "fixture" }).image("meta/muse-image-1.0").route.id).toBe("openai-images")
expect(VercelAIGateway.provider.image).toBe(VercelAIGateway.image)
expect(
CloudflareWorkersAI.configure({ accountId: "fixture", apiKey: "fixture" }).image(
"@cf/black-forest-labs/flux-1-schnell",
).route.id,
Route.of(
CloudflareWorkersAI.configure({ accountId: "fixture", apiKey: "fixture" }).image(
"@cf/black-forest-labs/flux-1-schnell",
),
)?.id,
).toBe("cloudflare-workers-ai-images")
expect(XAI.configure({ apiKey: "fixture" }).video("grok-imagine-video-1.5").route.id).toBe("xai-video")
expect(Route.of(XAI.configure({ apiKey: "fixture" }).video("grok-imagine-video-1.5"))?.id).toBe("xai-video")
expect(XAI.provider.video).toBe(XAI.video)
expect(Google.configure({ apiKey: "fixture" }).video("veo-3.1-generate-preview").route.id).toBe("google-video")
expect(Route.of(Google.configure({ apiKey: "fixture" }).video("veo-3.1-generate-preview"))?.id).toBe("google-video")
expect(Google.provider.video).toBe(Google.video)
expect(Runway.configure({ apiKey: "fixture" }).video("gen4.5").route.id).toBe("runway-video")
expect(Route.of(Runway.configure({ apiKey: "fixture" }).video("gen4.5"))?.id).toBe("runway-video")
expect(Runway.provider.video).toBe(Runway.video)
expect(OpenAI.configure({ apiKey: "fixture" }).speech("gpt-4o-mini-tts").route.id).toBe("openai-speech")
expect(Google.configure({ apiKey: "fixture" }).speech("gemini-2.5-flash-preview-tts").route.id).toBe(
expect(Route.of(OpenAI.configure({ apiKey: "fixture" }).speech("gpt-4o-mini-tts"))?.id).toBe("openai-speech")
expect(Route.of(Google.configure({ apiKey: "fixture" }).speech("gemini-2.5-flash-preview-tts"))?.id).toBe(
"google-speech",
)
expect(ElevenLabs.configure({ apiKey: "fixture" }).speech("eleven_flash_v2_5").route.id).toBe("elevenlabs-speech")
expect(Cartesia.configure({ apiKey: "fixture" }).speech("sonic-3").route.id).toBe("cartesia-speech")
expect(Deepgram.configure({ apiKey: "fixture" }).speech("aura-2-thalia-en").route.id).toBe("deepgram-speech")
expect(OpenAI.configure({ apiKey: "fixture" }).transcription("gpt-transcribe").route.kind).toBe("stream")
expect(Google.configure({ apiKey: "fixture" }).transcription("gemini-3.5-transcribe").route.kind).toBe("stream")
expect(Deepgram.configure({ apiKey: "fixture" }).transcription("nova-3").route.kind).toBe("inline")
expect(AssemblyAI.configure({ apiKey: "fixture" }).transcription("universal-3-5-pro").route.kind).toBe("queued")
expect(ElevenLabs.configure({ apiKey: "fixture" }).transcription("scribe_v2").route.id).toBe(
expect(Route.of(ElevenLabs.configure({ apiKey: "fixture" }).speech("eleven_flash_v2_5"))?.id).toBe(
"elevenlabs-speech",
)
expect(Route.of(Cartesia.configure({ apiKey: "fixture" }).speech("sonic-3"))?.id).toBe("cartesia-speech")
expect(Route.of(Deepgram.configure({ apiKey: "fixture" }).speech("aura-2-thalia-en"))?.id).toBe("deepgram-speech")
expect(Route.of(OpenAI.configure({ apiKey: "fixture" }).transcription("gpt-transcribe"))?.kind).toBe("stream")
expect(Route.of(Google.configure({ apiKey: "fixture" }).transcription("gemini-3.5-transcribe"))?.kind).toBe(
"stream",
)
expect(Route.of(Deepgram.configure({ apiKey: "fixture" }).transcription("nova-3"))?.kind).toBe("inline")
expect(Route.of(AssemblyAI.configure({ apiKey: "fixture" }).transcription("universal-3-5-pro"))?.kind).toBe(
"queued",
)
expect(Route.of(ElevenLabs.configure({ apiKey: "fixture" }).transcription("scribe_v2"))?.id).toBe(
"elevenlabs-transcription",
)
expect(ElevenLabs.configure({ apiKey: "fixture" }).transcription("scribe_v2").route.kind).toBe("inline")
expect(Route.of(ElevenLabs.configure({ apiKey: "fixture" }).transcription("scribe_v2"))?.kind).toBe("inline")
expect(ElevenLabs.provider.transcription).toBe(ElevenLabs.transcription)
})

View file

@ -5,6 +5,7 @@ import { ai, ImageClient, Media } from "../src/effect.js"
import { Google, OpenAI, OpenAICompatible, OpenRouter, VercelAIGateway, XAI, ZAI } from "../src/providers.js"
import { it } from "./lib/effect.js"
import { dynamicResponse, json } from "./lib/http.js"
import { Route } from "../src/route.js"
const layer = (handler: Parameters<typeof dynamicResponse>[0]) =>
ImageClient.layer.pipe(Layer.provideMerge(dynamicResponse(handler)))
@ -132,7 +133,7 @@ describe("Image", () => {
it.effect("sends only model and prompt by default and sniffs bytes when output_format is missing", () =>
Effect.gen(function* () {
const openai = OpenAI.configure({ apiKey: "test", baseURL: "https://openai.test/v1" })
expect(openai.image("gpt-image-2").route.id).toBe("openai-images")
expect(Route.of(openai.image("gpt-image-2"))?.id).toBe("openai-images")
const response = yield* ai.image.generate({ model: openai.image("gpt-image-2"), prompt: "A lighthouse" }).pipe(
Effect.provide(
ImageClient.layer.pipe(

View file

@ -2,11 +2,11 @@ import { Effect } from "effect"
import {
ai,
ImageClient,
ImageModel,
type ImageModelOptions,
type ModelProviderOptions,
type ImageOptions,
type ImageRequest,
Media,
Model,
} from "../src/effect.js"
import type { Service } from "../src/image-client.js"
import { Anthropic, Google, OpenAI, XAI, ZAI } from "../src/providers.js"
@ -20,9 +20,9 @@ type GoogleLikeOptions = {
readonly thinkingLevel?: "LOW" | "HIGH"
} & Record<string, unknown>
declare const google: ImageModel<GoogleLikeOptions>
declare const google: Model<"image", GoogleLikeOptions>
// @ts-expect-error Extracted model options retain known provider fields.
const invalidGoogleOptions: ImageModelOptions<typeof google> = { imageSize: "8K" }
const invalidGoogleOptions: ModelProviderOptions<typeof google> = { imageSize: "8K" }
void invalidGoogleOptions
ai.image.generate({
@ -71,7 +71,7 @@ ai.image.generate({ model: googleProvider, prompt: "A lighthouse", providerOptio
const openai = OpenAI.image("gpt-image-2")
// @ts-expect-error Image generation options are request-scoped, not provider configuration.
OpenAI.configure({ image: { providerOptions: { quality: "medium" } } })
const futureOpenAIOptions: ImageModelOptions<typeof openai> = { quality: "future-quality" }
const futureOpenAIOptions: ModelProviderOptions<typeof openai> = { quality: "future-quality" }
void futureOpenAIOptions
ai.image.generate({
model: openai,
@ -150,8 +150,8 @@ ai.image.generate({ model: zai, prompt: "A lighthouse", providerOptions: { quali
// @ts-expect-error Known Z.ai user IDs retain their value kind.
ai.image.generate({ model: zai, prompt: "A lighthouse", providerOptions: { userID: 1 } })
declare const generic: ImageModel<ImageOptions>
const widenImage = <Options extends ImageOptions>(model: ImageModel<Options>): ImageModel => model
declare const generic: Model<"image", ImageOptions>
const widenImage = <Options extends ImageOptions>(model: Model<"image", Options>): Model<"image"> => model
void widenImage
ai.image.generate({ model: generic, prompt: "A lighthouse", providerOptions: { arbitrary: true } })
const explicitAsset: Media.Asset = Media.url("https://example.com/image.png")
@ -172,7 +172,7 @@ const request = ai.image.request({
prompt: "A lighthouse",
providerOptions: { imageSize: "1K", futureOption: true },
})
const typedRequest: ImageRequest<ImageModel<GoogleLikeOptions>> = request
const typedRequest: ImageRequest<Model<"image", GoogleLikeOptions>> = request
void typedRequest
const generated = ImageClient.generate(request)
type GenerateRequirements = Assert<Equal<Requirements<typeof generated>, Service>>

View file

@ -2,10 +2,10 @@ import { Effect, Schema, Stream } from "effect"
import {
ai,
type Finish,
type LanguageModel,
type LanguageModelProviderOptions,
type ModelProviderOptions,
type LLMClientService,
type ProviderOptions,
Model,
} from "../src/effect.js"
import { AI } from "../src/index.js"
import { OpenAIChat } from "../src/protocols.js"
@ -87,11 +87,11 @@ type LoopObjectValue = Assert<
>
>
declare const generic: LanguageModel
declare const generic: Model<"chat">
ai.request({ model: generic, prompt: "Hello", providerOptions: { arbitrary: { option: true } } })
const options: LanguageModelProviderOptions<typeof model> = { mode: "fast" }
void (options satisfies LanguageModelProviderOptions<typeof model>)
const options: ModelProviderOptions<typeof model> = { mode: "fast" }
void (options satisfies ModelProviderOptions<typeof model>)
void (true satisfies GenerateRequirements)
void (true satisfies StreamClientRequirements)
void (true satisfies InputGenerateRequirements)

View file

@ -6,16 +6,17 @@ import * as OpenAIChat from "../src/protocols/openai-chat.js"
import * as OpenAIResponses from "../src/protocols/openai-responses.js"
import {
Message,
LanguageModel,
SystemMessage,
ToolCallPart,
ToolChoice,
ToolDefinition,
ToolResultPart,
UserMessage,
Model,
} from "../src/schema/index.js"
import { fixedResponse } from "./lib/http.js"
import { sseEvents } from "./lib/sse.js"
import { Route } from "../src/route.js"
const chatRoute = OpenAIChat.route
const responsesRoute = OpenAIResponses.route
@ -23,7 +24,7 @@ const responsesRoute = OpenAIResponses.route
describe("llm constructors", () => {
test("normalizes recursive tool namespaces", () => {
const request = ai.request({
model: LanguageModel.make({ id: "fake-model", provider: "fake", route: responsesRoute }),
model: Route.model(responsesRoute, { id: "fake-model", provider: "fake" }),
prompt: "Hello",
tools: [
{
@ -71,13 +72,13 @@ describe("llm constructors", () => {
test("normalizes ergonomic input into a plain request", () => {
const request = ai.request({
id: "req_1",
model: LanguageModel.make({ id: "fake-model", provider: "fake", route: chatRoute }),
model: Route.model(chatRoute, { id: "fake-model", provider: "fake" }),
system: "You are concise.",
prompt: "Say hello.",
})
expect(Object.getPrototypeOf(request)).toBe(Object.prototype)
expect(request.model).toBeInstanceOf(LanguageModel)
expect(request.model.type).toBe("chat")
expect(request.messages[0]).toBeInstanceOf(UserMessage)
expect(request.system).toEqual([{ type: "text", text: "You are concise." }])
expect(request.messages[0]?.content).toEqual([{ type: "text", text: "Say hello." }])
@ -88,7 +89,7 @@ describe("llm constructors", () => {
test("edits requests with a spread or by passing them back to ai.request", () => {
const base = ai.request({
id: "req_1",
model: LanguageModel.make({ id: "fake-model", provider: "fake", route: chatRoute }),
model: Route.model(chatRoute, { id: "fake-model", provider: "fake" }),
prompt: "Say hello.",
})
const updated = {
@ -128,16 +129,15 @@ describe("llm constructors", () => {
test("keeps request options separate from route defaults", () => {
const request = ai.request({
model: LanguageModel.make({
id: "fake-model",
provider: "fake",
route: chatRoute.with({
model: Route.model(
chatRoute.with({
maxTokens: 100,
temperature: 1,
providerOptions: { store: false, metadata: { model: true } },
http: { body: { metadata: { model: true } }, headers: { "x-shared": "model" }, query: { model: "1" } },
}),
}),
{ id: "fake-model", provider: "fake" },
),
prompt: "Say hello.",
temperature: 0,
providerOptions: { store: true, metadata: { request: true } },
@ -152,28 +152,20 @@ describe("llm constructors", () => {
expect(request.http).toEqual({ body: { metadata: { request: true } }, query: { request: "1" } })
})
test("updates canonical models from the model datatype", () => {
const base = LanguageModel.make({
id: "fake-model",
provider: "fake",
route: chatRoute,
})
const updated = LanguageModel.update(base, {
route: responsesRoute,
test("edits models with a spread", () => {
const base = Route.model(chatRoute, { id: "fake-model", provider: "fake" })
const updated = {
...base,
api: "responses",
options: { maxTokens: 20 },
compatibility: { sanitizer: "gemini", requireFinishReason: false },
})
const updatedInput = LanguageModel.input(updated)
} satisfies Model<"chat">
expect(updated).toBeInstanceOf(LanguageModel)
expect(String(updated.id)).toBe("fake-model")
expect(updated.route).toBe(responsesRoute)
expect(updated.api).toBe("responses")
expect(updated.options?.maxTokens).toBe(20)
expect(updated.compatibility).toEqual({ sanitizer: "gemini", requireFinishReason: false })
expect(updatedInput.options).toBe(updated.options)
expect(updatedInput.compatibility).toBe(updated.compatibility)
expect(String(updatedInput.provider)).toBe("fake")
expect(LanguageModel.update(updated, {})).toBe(updated)
expect(String(updated.provider)).toBe("fake")
})
test("carries model defaults and compatibility through route model selection", () => {
@ -213,11 +205,7 @@ describe("llm constructors", () => {
expect(ToolChoice.make("required")).toEqual(new ToolChoice({ type: "required" }))
expect(
ai.request({
model: LanguageModel.make({
id: "fake-model",
provider: "fake",
route: chatRoute,
}),
model: Route.model(chatRoute, { id: "fake-model", provider: "fake" }),
prompt: "Use tools if needed.",
toolChoice: "required",
}).toolChoice,
@ -239,7 +227,7 @@ describe("llm constructors", () => {
{ type: "text", text: "Use parameterized SQL.", cache: new CacheHint({ type: "ephemeral" }) },
])
const request = ai.request({
model: LanguageModel.make({ id: "fake-model", provider: "fake", route: chatRoute }),
model: Route.model(chatRoute, { id: "fake-model", provider: "fake" }),
system: "Initial operator prompt.",
messages: [Message.user("Review this."), update],
})

View file

@ -1,10 +1,11 @@
import { describe, expect, test } from "bun:test"
import { LanguageModel, LLMEvent, LLMResponse, Message, Usage } from "../src/effect.js"
import { LLMEvent, LLMResponse, Message, Usage, Model } from "../src/effect.js"
import { addUsage, nextRequest, pendingCalls } from "../src/loop.js"
import { OpenAIChat } from "../src/protocols/openai-chat.js"
import { LLM } from "../src/llm.js"
import { Route } from "../src/route.js"
const model = LanguageModel.make({ id: "fictional-model", provider: "fixture", route: OpenAIChat.route })
const model = Route.model(OpenAIChat.route, { id: "fictional-model", provider: "fixture" })
const step = (...events: ReadonlyArray<LLMEvent>) =>
LLMResponse.fromEvents([...events, LLMEvent.finish({ reason: { normalized: "tool-calls" } })])!

View file

@ -1,21 +1,13 @@
import { describe, expect } from "bun:test"
import { Effect, Schema, Stream } from "effect"
import {
ai,
AIError,
LanguageModel,
type LLM,
LLMEvent,
ProviderInternalError,
tool,
ToolFailure,
} from "../src/effect.js"
import { ai, AIError, type LLM, LLMEvent, ProviderInternalError, tool, ToolFailure } from "../src/effect.js"
import { AI } from "../src/index.js"
import { OpenAIChat } from "../src/protocols/openai-chat.js"
import { TestLLM } from "../src/testing.js"
import { testEffect } from "./lib/effect.js"
import { Route } from "../src/route.js"
const model = LanguageModel.make({ id: "fictional-model", provider: "fixture", route: OpenAIChat.route })
const model = Route.model(OpenAIChat.route, { id: "fictional-model", provider: "fixture" })
const it = testEffect(TestLLM.testLayer())
const read_file = tool({

View file

@ -0,0 +1,153 @@
import { describe, expect } from "bun:test"
import { Effect } from "effect"
import { ai, Model } from "../src/effect.js"
import { OpenAIChat } from "../src/protocols/openai-chat.js"
import { OpenAI, ZAI } from "../src/providers.js"
import { Auth, LLMClient, Route } from "../src/route.js"
import { compileRequest } from "../src/testing.js"
import { it } from "./lib/effect.js"
import { dynamicResponse, observe, type Call } from "./lib/http.js"
import { deltaChunk } from "./lib/openai-chunks.js"
import { sseEvents } from "./lib/sse.js"
const send = (model: Model<"chat">) =>
Effect.gen(function* () {
const calls: Array<Call> = []
yield* LLMClient.generate(ai.request({ model, prompt: "Hi" })).pipe(
Effect.provide(
dynamicResponse((input) =>
observe(calls, input).pipe(
Effect.as(
input.respond(sseEvents(deltaChunk({}, "stop")), { headers: { "content-type": "text/event-stream" } }),
),
),
),
),
// Only the outgoing request matters here.
Effect.exit,
)
return calls[0]!
})
describe("Model", () => {
it.effect("runs a hand-described model on the package's implementation of its API", () =>
Effect.gen(function* () {
const local = Model.make({
type: "chat",
id: "qwen3-coder",
provider: "lmstudio",
api: "chat-completions",
baseURL: "https://local.test/v1",
auth: Auth.bearer("fixture"),
})
const call = yield* send(local)
expect(call.url).toBe("https://local.test/v1/chat/completions")
expect(call.headers.get("authorization")).toBe("Bearer fixture")
expect((yield* compileRequest(ai.request({ model: local, prompt: "Hi" }))).body).toEqual(
(yield* compileRequest(
ai.request({
model: Route.model(
OpenAIChat.route.with({ endpoint: { baseURL: "https://local.test/v1" }, auth: Auth.bearer("fixture") }),
{ id: "qwen3-coder", provider: "lmstudio" },
),
prompt: "Hi",
}),
)).body,
)
}),
)
it.effect("starts a hand-described model's options from its API's defaults", () =>
Effect.gen(function* () {
const model = Model.make({ type: "chat", id: "gpt-5.5", provider: "proxy", api: "responses" })
const call = yield* send({ ...model, baseURL: "https://proxy.test/v1", auth: Auth.bearer("fixture") })
expect(call.url).toBe("https://proxy.test/v1/responses")
expect(JSON.parse(call.body).store).toBe(false)
}),
)
it.effect("fills OpenCode's defaults and leaves host capability flags unset", () =>
Effect.gen(function* () {
const model = Model.make({
type: "chat",
id: "custom",
provider: "custom",
api: "chat-completions",
capabilities: { tools: { strict: false } },
})
expect(model.capabilities).toEqual({ tools: { supported: true, strict: false } })
expect(model.modalities).toEqual({ input: ["text", "image"], output: ["text"] })
expect(model.limit).toEqual({ context: 200_000, output: 32_000 })
expect(model.baseURL).toBeUndefined()
}),
)
it.effect("fills baseURL and auth from a provider's implementation", () =>
Effect.gen(function* () {
const model = OpenAI.configure({ apiKey: "fixture" }).chat("gpt-5.5")
expect(model.api).toBe("chat-completions")
expect(model.baseURL).toBe("https://api.openai.com/v1")
expect(model.auth).toBe(Route.of(model)?.auth)
}),
)
it.effect("sends a spread-edited baseURL to the new host and keeps auth", () =>
Effect.gen(function* () {
const model = OpenAI.configure({ apiKey: "fixture" }).chat("gpt-5.5")
const call = yield* send({ ...model, baseURL: "https://proxy.test/v1" })
expect(call.url).toBe("https://proxy.test/v1/chat/completions")
expect(call.headers.get("authorization")).toBe("Bearer fixture")
}),
)
it.effect("sends a spread-edited path and auth", () =>
Effect.gen(function* () {
const model = OpenAI.configure({ apiKey: "fixture" }).chat("gpt-5.5")
const call = yield* send({ ...model, path: "/v2/chat", auth: Auth.bearer("other") })
expect(call.url).toBe("https://api.openai.com/v1/v2/chat")
expect(call.headers.get("authorization")).toBe("Bearer other")
}),
)
it.effect("applies spread-edited options and keeps the API's preset", () =>
Effect.gen(function* () {
const model = OpenAI.configure({ apiKey: "fixture" }).responses("gpt-5.5")
const call = yield* send({ ...model, options: { ...model.options, temperature: 0, maxTokens: 64 } })
const body = JSON.parse(call.body)
expect(body.temperature).toBe(0)
expect(body.max_output_tokens).toBe(64)
expect(body.store).toBe(false)
}),
)
it.effect("keeps a provider's dialect through spreads until api changes", () =>
Effect.gen(function* () {
const zai = ZAI.configure({ apiKey: "fixture" }).chat("glm-5.2")
const edited = { ...zai, options: { ...zai.options, temperature: 0 } }
const switched = { ...zai, api: "messages" }
expect(zai.api).toBe("chat-completions")
expect(Route.of(edited)?.id).toBe(Route.of(zai)?.id)
expect((yield* compileRequest(ai.request({ model: edited, prompt: "Hi" }))).protocol).toBe("zai-chat")
expect(Route.of(switched)).toBeUndefined()
expect((yield* compileRequest(ai.request({ model: switched, prompt: "Hi" }))).protocol).toBe("anthropic-messages")
}),
)
it.effect("fails a request for an API the package doesn't implement", () =>
Effect.gen(function* () {
const model = Model.make({ type: "chat", id: "custom", provider: "custom", api: "realtime" })
const error = yield* compileRequest(ai.request({ model, prompt: "Hi" })).pipe(Effect.flip)
expect(error.reason._tag).toBe("InvalidRequest")
expect(error.message).toContain('"realtime"')
}),
)
})

View file

@ -0,0 +1,17 @@
import type { Model } from "../src/effect.js"
import { OpenAI } from "../src/providers.js"
declare const model: Model
if (model.type === "chat") model.baseURL satisfies string | undefined
if (model.type === "image") {
// @ts-expect-error Only text models carry a baseURL.
void model.baseURL
}
const chat = OpenAI.configure({ apiKey: "fixture" }).chat("gpt-5.5")
;({ ...chat, baseURL: "https://proxy.test/v1" }) satisfies Model<"chat">
;({ ...chat, options: { ...chat.options, temperature: 0 } }) satisfies Model<"chat">
const image = OpenAI.configure({ apiKey: "fixture" }).image("gpt-image-2")
// @ts-expect-error Image models have no baseURL to edit.
;({ ...image, baseURL: "https://proxy.test/v1" }) satisfies Model<"image">

View file

@ -3,9 +3,9 @@ import {
ai,
CompactionCheckpointResponse,
CompactionResponse,
LanguageModel,
LLMClient,
type LLMRequest,
Model,
} from "../../src/effect.js"
import {
Anthropic,
@ -19,7 +19,7 @@ import {
import { AI } from "../../src/index.js"
import type { WebSocketChannelExecutor } from "../../src/route.js"
import type { RoutePatch } from "../../src/route/client.js"
import type { OpenAIResponsesBody } from "../../src/protocols/openai-responses.js"
import { OpenAIResponses, type OpenAIResponsesBody } from "../../src/protocols/openai-responses.js"
import type { Prepared } from "../../src/protocols/open-responses-channel.js"
declare const webSocket: WebSocketChannelExecutor
@ -45,9 +45,9 @@ ai.compact(request, { mechanism: "other" })
for (const selected of [
model,
OpenAI.model("fixture", {}),
model.route.with({ headers: { fixture: "test" } }).model({ id: "fixture" }),
LanguageModel.make(LanguageModel.input(model)),
LanguageModel.update(model, { options: { maxTokens: 100 } }),
OpenAIResponses.route.with({ headers: { fixture: "test" } }).model({ id: "fixture" }),
Model.make(model),
{ ...model, options: { maxTokens: 100 } },
]) {
ai.compact(ai.request({ model: selected, prompt: "Hello" }), { mechanism: "trigger" })
}
@ -95,13 +95,11 @@ ai.compact(unsupported.xai, { mechanism: "trigger" })
ai.compact(unsupported.compatible, { mechanism: "trigger" })
// @ts-expect-error Changing the model replaces its capability.
ai.compact({ ...request, model: azure }, { mechanism: "trigger" })
ai.compact(ai.request({ model: LanguageModel.update(model, { route: azure.route }), prompt: "Hello" }), {
// @ts-expect-error Changing the route replaces its capability.
mechanism: "trigger",
})
ai.compact(
ai.request({
model: model.route.with({ compact: { endpoint: model.route.compact.endpoint } }).model({ id: "fixture" }),
model: OpenAIResponses.route
.with({ compact: { endpoint: OpenAIResponses.route.compact.endpoint } })
.model({ id: "fixture" }),
prompt: "Hello",
}),
// @ts-expect-error Replacing route operations does not retain the old trigger capability.
@ -112,13 +110,12 @@ declare const dynamic: LLMRequest
declare const patch: Partial<LLMRequest>
declare const routePatch: RoutePatch<OpenAIResponsesBody, Prepared>
// @ts-expect-error A dynamic operation override cannot preserve trigger support.
ai.compact(ai.request({ model: model.route.with(routePatch).model({ id: "fixture" }), prompt: "Hello" }), {
ai.compact(ai.request({ model: OpenAIResponses.route.with(routePatch).model({ id: "fixture" }), prompt: "Hello" }), {
mechanism: "trigger",
})
const removed = OpenAIResponses.route.with({ compact: undefined }).model({ id: "fixture" })
// @ts-expect-error Explicitly removing operations removes trigger support.
ai.compact(ai.request({ model: model.route.with({ compact: undefined }).model({ id: "fixture" }), prompt: "Hello" }), {
mechanism: "trigger",
})
ai.compact(ai.request({ model: removed, prompt: "Hello" }), { mechanism: "trigger" })
// @ts-expect-error Dynamic models must be narrowed.
ai.compact(dynamic, { mechanism: "trigger" })
if (ai.canCompact(dynamic, { mechanism: "trigger" })) {

View file

@ -2,14 +2,15 @@ import { Effect } from "effect"
import {
ai,
CompactionPart,
LanguageModel,
LLMClient,
LLMEvent,
type LLMRequest,
Message,
ProviderID,
Model,
} from "../../src/effect.js"
import { OpenAI, Azure, XAI, Anthropic, OpenAICompatibleResponses } from "../../src/providers.js"
import { OpenAIResponses } from "../../src/protocols/openai-responses.js"
const openai = OpenAI.configure({
apiKey: "test",
@ -24,9 +25,9 @@ for (const model of [
OpenAI.model("fixture", {}),
Azure.responsesModel("fixture", { resourceName: "test" }),
XAI.model("fixture", {}),
openai.route.with({ headers: { "x-test": "test" } }).model({ id: "fixture" }),
LanguageModel.update(openai, { options: { maxTokens: 100 } }),
LanguageModel.make(LanguageModel.input(openai)),
OpenAIResponses.route.with({ headers: { "x-test": "test" } }).model({ id: "fixture" }),
{ ...openai, options: { maxTokens: 100 } },
Model.make(openai),
]) {
ai.compact(ai.request({ model, prompt: "hello" }))
}
@ -63,15 +64,8 @@ const switched = { ...request, model: Anthropic.configure().model("fixture") }
// @ts-expect-error Switching models replaces, rather than inherits, the capability.
ai.compact(switched)
ai.compact({ ...switched, model: openai })
ai.compact(
// @ts-expect-error Replacing the route also replaces compaction capability.
ai.request({
model: LanguageModel.update(openai, { route: Anthropic.configure().model("fixture").route }),
prompt: "Hello",
}),
)
declare const dynamicModel: LanguageModel
declare const dynamicModel: Model<"chat">
declare const dynamicPatch: Partial<LLMRequest>
const dynamicRequest = ai.request({ model: dynamicModel, prompt: "hello" })
// @ts-expect-error A dynamically selected model must be narrowed first.

Some files were not shown because too many files have changed in this diff Show more