Skip to content

Commit 7321660

Browse files
authored
fix(ai): only expose model() on providers with a language API (#68545)
1 parent 3bf3459 commit 7321660

67 files changed

Lines changed: 400 additions & 306 deletions

File tree

Some content is hidden

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

‎packages/ai/README.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -303,8 +303,8 @@ continuation. Explicit caches, hosted tools, and generated media are not support
303303

304304
A provider also builds a model for each other kind it serves: `provider.image(id)`, `video`, `speech`,
305305
`transcription`, `decision` and `embedding`, each on that kind's first API, with `{ api }` naming another when it has
306-
several. A provider without a kind has no accessor for it (`anthropic().video` is a type error), and
307-
`provider.model(id, { api })` still builds any of them. `ai.image.generate` resolves the provider's image route from the
306+
several. A provider without a kind has no accessor for it (`anthropic().video` is a type error), and `provider.model`
307+
is the language accessor, so a provider with no language API has none. `ai.image.generate` resolves the provider's image route from the
308308
model and returns `Media.Asset`s with lazily decoded bytes:
309309

310310
```ts
@@ -1863,7 +1863,7 @@ Normalized cache usage is read back into `response.usage.cacheReadInputTokens` a
18631863

18641864
## Providers
18651865

1866-
A provider is a function from settings to a provider value. Settings are the connection keys (`apiKey`, `baseURL`, `headers`, `body`), the provider's own settings and its default API's provider options; any other key is a type error, and other provider options go in `native` (`openai({ native: { custom: true } })`). `Provider.SettingsOf<typeof openai>` is that type, derived from the provider. A package path's `model(modelID, settings)` takes settings as config files write them: every key it doesn't read is sent as a provider option. `provider.model(id)` returns a model on the provider's first language API, and `provider.model(id, { api })` picks another API by name. `provider.image(id)`, `video`, `speech`, `transcription`, `decision` and `embedding` return a model on that kind's first API (or the one `{ api }` names), and exist only for the kinds the provider serves. The model holds its API with the host's base URL, auth and the key its `native` metadata goes under. Making a provider reads nothing: API keys and other environment fallbacks (`AWS_REGION`, Google Vertex's project and location) are read when a request is sent, and bad settings fail that request with a typed error.
1866+
A provider is a function from settings to a provider value. Settings are the connection keys (`apiKey`, `baseURL`, `headers`, `body`), the provider's own settings and its default API's provider options; any other key is a type error, and other provider options go in `native` (`openai({ native: { custom: true } })`). `Provider.SettingsOf<typeof openai>` is that type, derived from the provider. A package path's `model(modelID, settings)` takes settings as config files write them: every key it doesn't read is sent as a provider option. `provider.model(id)` returns a model on the provider's first language API, and `provider.model(id, { api })` picks another language API by name. `provider.image(id)`, `video`, `speech`, `transcription`, `decision` and `embedding` return a model on that kind's first API (or the one `{ api }` names). Each accessor, `model` included, exists only for the kinds the provider serves, and naming an API of another kind is a type error (an `AIError` with an `UnsupportedOperation` reason for untyped callers). The model holds its API with the host's base URL, auth and the key its `native` metadata goes under. Making a provider reads nothing: API keys and other environment fallbacks (`AWS_REGION`, Google Vertex's project and location) are read when a request is sent, and bad settings fail that request with a typed error.
18671867

18681868
```ts
18691869
import { openai, cloudflareAIGateway } from "@opencode/ai/providers"

‎packages/ai/example/tutorial.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -239,7 +239,7 @@ const generateFake = Effect.gen(function* () {
239239
// `Media.write` persists them through the Effect `FileSystem`.
240240
const generateImage = Effect.gen(function* () {
241241
const response = yield* ai.image.generate({
242-
model: provider.model("gpt-image-1-mini", { api: "openai-images" }),
242+
model: provider.image("gpt-image-1-mini", { api: "openai-images" }),
243243
prompt: "A flat black circle centered on a plain white background.",
244244
aspect: "1:1",
245245
// Exact pixel sizes and output formats are provider options.

‎packages/ai/src/provider.ts‎

Lines changed: 88 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type { EmbeddingModel } from "./embedding.js"
55
import type { ProviderPackage } from "./provider-package.js"
66
import { Auth } from "./route/auth.js"
77
import {
8+
AIError,
89
type Capabilities,
910
type Cost,
1011
LanguageModel,
@@ -16,6 +17,7 @@ import {
1617
ProviderConfigurationError,
1718
ProviderID,
1819
type NativeOptions,
20+
UnsupportedOperationError,
1921
} from "./schema/index.js"
2022

2123
/** An API key read from `env` when none is passed, sent as `Authorization: Bearer` unless the options say otherwise. */
@@ -47,15 +49,15 @@ export type ApiName<A extends Apis> = ApiOf<A> extends { readonly name: infer Na
4749

4850
type First<L> = L extends readonly [infer Head, ...ReadonlyArray<unknown>] ? Head : Listed<L>
4951

50-
/** The API a model gets when none is named: the first language API, else any of them. */
52+
/** The API a package path uses when it names none: the first language API, else any of them. */
5153
type DefaultApi<A extends Apis> = [NonNullable<A["language"]>] extends [never]
5254
? ApiOf<A>
5355
: First<NonNullable<A["language"]>>
5456

5557
type Named<A extends Apis, Name> = [Name] extends [never] ? DefaultApi<A> : Extract<ApiOf<A>, { readonly name: Name }>
5658

5759
/**
58-
* A language model in full: the API it is reached through (the provider's default when omitted) and what is known
60+
* A language model in full: the language API it is reached through (the provider's first when omitted) and what is known
5961
* about it. Passed to `model`, it is used as given, and the provider's bundled entry for the ID is not read.
6062
*/
6163
export interface Definition<Name extends string = string> {
@@ -80,15 +82,25 @@ type BundleOf<C extends Catalog> = {
8082
}[keyof C]
8183
}
8284

83-
// The API a bundled model defaults to; the provider's default API for any other ID.
85+
// The API a bundled model defaults to; the provider's first language API for any other ID.
8486
type Bundled<A extends Apis, B extends Bundle, ID> = ID extends keyof B
85-
? Extract<ApiOf<A>, { readonly name: B[ID] }>
86-
: DefaultApi<A>
87+
? Extract<KindApi<A, "language">, { readonly name: B[ID] }>
88+
: First<NonNullable<A["language"]>>
89+
90+
/** The accessor each kind's models are built with: `model` for language, the kind's name for every other. */
91+
export type AccessorName<K extends Api.Kind> = K extends "language" ? "model" : K
8792

88-
/** The kinds a provider has an accessor for: every kind but language, which `model` serves. */
89-
export type ModelKind = Exclude<Api.Kind, "language">
93+
const KINDS: ReadonlyArray<Api.Kind> = [
94+
"image",
95+
"video",
96+
"embedding",
97+
"decision",
98+
"speech",
99+
"transcription",
100+
"language",
101+
]
90102

91-
const KINDS: ReadonlyArray<ModelKind> = ["image", "video", "embedding", "decision", "speech", "transcription"]
103+
const accessorName = <K extends Api.Kind>(kind: K) => (kind === "language" ? "model" : kind) as AccessorName<K>
92104

93105
type KindApi<A extends Apis, K extends Api.Kind> = Listed<NonNullable<A[K]>>
94106

@@ -100,19 +112,39 @@ type NamedOfKind<A extends Apis, K extends Api.Kind, Name> = [Name] extends [nev
100112
: Extract<KindApi<A, K>, { readonly name: Name }>
101113

102114
/**
103-
* One accessor per kind the provider serves: a model on that kind's first API unless `api` names another of it. A kind
104-
* `A` may leave out (as in the plain `Apis`) gets an optional accessor, so `Provider` stays a supertype of every
105-
* provider.
115+
* One accessor per kind the provider serves, `model` for language: a model on that kind's first API unless `api` names
116+
* another of it. A kind `A` may leave out (as in the plain `Apis`) gets an optional accessor, so `Provider` stays a
117+
* supertype of every provider.
106118
*/
107-
export type Accessors<A extends Apis> = {
108-
readonly [K in ServedKind<A> as {} extends Pick<A, K> ? never : K]: Accessor<A, K>
119+
export type Accessors<A extends Apis, B extends Bundle = Bundle> = {
120+
readonly [K in ServedKind<A> as {} extends Pick<A, K> ? never : AccessorName<K>]: KindAccessor<A, B, K>
109121
} & {
110-
readonly [K in ServedKind<A> as {} extends Pick<A, K> ? K : never]?: Accessor<A, K>
122+
readonly [K in ServedKind<A> as {} extends Pick<A, K> ? AccessorName<K> : never]?: KindAccessor<A, B, K>
111123
}
112124

113125
type ServedKind<A extends Apis> = {
114-
[K in ModelKind]: K extends keyof A ? ([NonNullable<A[K]>] extends [never] ? never : K) : never
115-
}[ModelKind]
126+
[K in Api.Kind]: K extends keyof A ? ([NonNullable<A[K]>] extends [never] ? never : K) : never
127+
}[Api.Kind]
128+
129+
type KindAccessor<A extends Apis, B extends Bundle, K extends Api.Kind> = K extends "language"
130+
? {
131+
/** A bundled model as models.dev defines it, on the API it recommends; any other ID on the first language API. */
132+
<
133+
const ID extends (keyof B & string) | (string & {}),
134+
Options extends NativeOptions = OptionsOf<Bundled<A, B, ID>>,
135+
>(
136+
modelID: ID,
137+
): ModelOf<Bundled<A, B, ID>, Options>
138+
/** A model as `definition` defines it, on its `api` or the first language API. Nothing bundled is read. */
139+
<
140+
const Name extends KindName<A, "language"> = never,
141+
Options extends NativeOptions = OptionsOf<NamedOfKind<A, "language", Name>>,
142+
>(
143+
modelID: string,
144+
definition: Definition<Name>,
145+
): ModelOf<NamedOfKind<A, "language", Name>, Options>
146+
}
147+
: Accessor<A, K>
116148

117149
type Accessor<A extends Apis, K extends Api.Kind> = <const Name extends KindName<A, K> = never>(
118150
modelID: string,
@@ -184,23 +216,15 @@ export interface Input<A extends Apis, C extends Catalog = Catalog> {
184216
readonly catalog?: C
185217
}
186218

187-
/** `image`, `video`, `embedding`, `decision`, `speech` and `transcription` exist for the kinds it serves. */
188-
export type Provider<A extends Apis = Apis, B extends Bundle = Bundle> = Accessors<A> & {
219+
/**
220+
* `model` (language), `image`, `video`, `embedding`, `decision`, `speech` and `transcription` exist for the kinds
221+
* it serves.
222+
*/
223+
export type Provider<A extends Apis = Apis, B extends Bundle = Bundle> = Accessors<A, B> & {
189224
readonly id: ProviderID
190225
readonly apis: Shown<A>
191226
/** The IDs of the models the provider bundles. */
192227
readonly models: ReadonlyArray<keyof B & string>
193-
readonly model: {
194-
/** A bundled model as models.dev defines it, on the API it recommends; any other ID on the default API. */
195-
<const ID extends (keyof B & string) | (string & {}), Options extends NativeOptions = OptionsOf<Bundled<A, B, ID>>>(
196-
modelID: ID,
197-
): ModelOf<Bundled<A, B, ID>, Options>
198-
/** A model as `definition` defines it, on its `api` or the default API. Nothing bundled is read. */
199-
<const Name extends ApiName<A> = never, Options extends NativeOptions = OptionsOf<Named<A, Name>>>(
200-
modelID: string,
201-
definition: Definition<Name>,
202-
): ModelOf<Named<A, Name>, Options>
203-
}
204228
}
205229

206230
/**
@@ -226,18 +250,19 @@ type Without<T, K> = { [P in keyof T as P extends K ? never : P]: T[P] }
226250
export const make =
227251
<const A extends Apis, const C extends Catalog = {}>(input: Input<A, C>) =>
228252
(settings?: Settings<OptionsOf<DefaultApi<A>>>): Provider<A, BundleOf<C>> => {
229-
const model = (kind: ModelKind | undefined) => (modelID: string, definition?: Definition) => {
253+
const model = (kind: Api.Kind) => (modelID: string, definition?: Definition) => {
230254
const resolved =
231-
kind === undefined && definition === undefined ? bundled(input.catalog ?? {}, modelID) : definition
255+
kind === "language" && definition === undefined ? bundled(input.catalog ?? {}, modelID) : definition
232256
return bind(input, settings ?? {}, select(input, kind, resolved?.api), modelID, resolved)
233257
}
234258
// Each accessor's types narrow `api` to its kind's names and the model to its API's; the runtime is one `bind`.
235259
return {
236-
...Object.fromEntries(KINDS.filter((kind) => input.apis[kind] !== undefined).map((kind) => [kind, model(kind)])),
260+
...Object.fromEntries(
261+
KINDS.filter((kind) => input.apis[kind] !== undefined).map((kind) => [accessorName(kind), model(kind)]),
262+
),
237263
id: ProviderID.make(input.id),
238264
apis: input.apis as Shown<A>,
239265
models: Object.values(input.catalog ?? {}).flatMap((models) => Object.keys(models)),
240-
model: model(undefined),
241266
} as Provider<A, BundleOf<C>>
242267
}
243268

@@ -260,27 +285,46 @@ export const entrypoint =
260285
<Options extends NativeOptions = OptionsOf<Named<A, Name>>>(
261286
modelID: string,
262287
...settings: ProviderPackage.Arguments<ApiSettings<S, A, Name>>
263-
): ModelOf<Named<A, Name>, Options> =>
264-
// Optional exactly when the provider's settings are. Hosts that load package paths bring their own catalog, so the
265-
// definition is always explicit and the bundled one is never read.
266-
provider(settings[0] as S).model<Name, Options>(modelID, options ?? {})
288+
): ModelOf<Named<A, Name>, Options> => {
289+
// Optional exactly when the provider's settings are.
290+
const built = provider(settings[0] as S)
291+
const apis = listed(built.apis as Apis)
292+
const api =
293+
options?.api === undefined
294+
? (apis.find((item) => item.kind === "language") ?? apis[0])
295+
: apis.find((item) => item.name === options.api)
296+
// A name outside the provider's APIs is a type error; only untyped callers reach this.
297+
if (api === undefined) throw unsupported(built.id, "model", `${built.id} serves no API named ${options?.api}`)
298+
const accessors = built as Record<string, (modelID: string, definition: Definition) => unknown>
299+
// Hosts that load package paths bring their own catalog, so the definition is always explicit and the bundled one
300+
// is never read.
301+
return accessors[accessorName(api.kind)](modelID, { api: api.name }) as ModelOf<Named<A, Name>, Options>
302+
}
267303

268304
const listed = (apis: Apis): ReadonlyArray<Api.AnyApi> =>
269305
Object.values(apis).flatMap((value: Apis[Api.Kind]) =>
270306
value === undefined ? [] : Array.isArray(value) ? value : [value as Api.AnyApi],
271307
)
272308

273-
// `model` picks from every API, defaulting to the first language one; an accessor picks from its kind's.
274-
const select = <A extends Apis>(input: Input<A>, kind: ModelKind | undefined, name: string | undefined): Api.AnyApi => {
275-
const apis = listed(kind === undefined ? input.apis : { [kind]: input.apis[kind] })
276-
const first = kind === undefined ? listed({ language: input.apis.language })[0] : undefined
277-
const selected = name === undefined ? (first ?? apis[0]) : apis.find((api) => api.name === name)
278-
// A name outside the provider's APIs is a type error; only untyped callers reach this.
309+
// Every accessor picks from its own kind's APIs only, so a model is never built on an API of another kind.
310+
const select = <A extends Apis>(input: Input<A>, kind: Api.Kind, name: string | undefined): Api.AnyApi => {
311+
const apis = listed({ [kind]: input.apis[kind] })
312+
const selected = name === undefined ? apis[0] : apis.find((api) => api.name === name)
313+
// A name outside the kind's APIs is a type error; only untyped callers reach this.
279314
if (selected === undefined)
280-
throw new Error(`${input.id} serves no ${kind === undefined ? "" : `${kind} `}API named ${name}`)
315+
throw unsupported(
316+
input.id,
317+
kind,
318+
`${input.name ?? input.id} serves no ${kind} API${name === undefined ? "" : ` named ${name}`}`,
319+
)
281320
return selected
282321
}
283322

323+
const unsupported = (provider: string, operation: string, message: string) =>
324+
new AIError({
325+
reason: new UnsupportedOperationError({ message, operation, provider: ProviderID.make(provider) }),
326+
})
327+
284328
// Package paths pass provider options flat, so every key that isn't a connection setting is one.
285329
const bind = <A extends Apis>(
286330
input: Input<A>,

‎packages/ai/src/providers/google-vertex/embeddings.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@ export type { Settings } from "../google-vertex.js"
55

66
/** `gemini-embedding-2*` models use `embedContent`, which takes media; every other model the text-only `:predict`. */
77
export const model = (modelID: string, settings?: Settings & ProviderPackage.Settings) =>
8-
googleVertex(settings).model(modelID, {
8+
googleVertex(settings).embedding(modelID, {
99
api: modelID.startsWith("gemini-embedding-2") ? "google-vertex-embed-content" : "google-vertex-predict-embeddings",
1010
})

‎packages/ai/src/providers/meta/images.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@ export type { Settings } from "../meta.js"
55

66
// Muse Image takes no provider options from settings; only the connection settings apply.
77
export const model = (modelID: string, { apiKey, baseURL, headers, body }: Settings & ProviderPackage.Settings = {}) =>
8-
meta({ apiKey, baseURL, headers, body }).model(modelID, { api: "meta-images" })
8+
meta({ apiKey, baseURL, headers, body }).image(modelID, { api: "meta-images" })

‎packages/ai/src/providers/openai-compatible/images.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@ const defaults: ProviderPackage.Settings = { response_format: "b64_json" }
88
// Many compatible hosts default to hosted URLs. GPT Image models always return bytes and reject the field; a proxy
99
// serving one under another name can drop the default with `response_format: null`.
1010
export const model = (modelID: string, settings: Settings & ProviderPackage.Settings) =>
11-
openaiCompatible(/gpt-image|chatgpt-image/.test(modelID) ? settings : { ...defaults, ...settings }).model(modelID, {
11+
openaiCompatible(/gpt-image|chatgpt-image/.test(modelID) ? settings : { ...defaults, ...settings }).image(modelID, {
1212
api: "openai-images",
1313
})

‎packages/ai/test/api.types.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,9 @@ const provider = Provider.make({
4848
},
4949
})()
5050
const chat: LanguageModel = provider.model("m")
51-
const providerImage: ImageModel<OpenAIImageOptions> = provider.model("m", { api: "openai-images" })
52-
const decision: DecisionModel = provider.model("m", { api: "openai-decisions" })
53-
const embedding: EmbeddingModel = provider.model("m", { api: "openai-embeddings" })
51+
const providerImage: ImageModel<OpenAIImageOptions> = provider.image("m", { api: "openai-images" })
52+
const decision: DecisionModel = provider.decision("m", { api: "openai-decisions" })
53+
const embedding: EmbeddingModel = provider.embedding("m", { api: "openai-embeddings" })
5454

5555
// @ts-expect-error an image protocol is not a speech API
5656
Api.http({ name: "bad", kind: "speech", protocol: OpenAIImages.protocol, path: "/" })

0 commit comments

Comments
 (0)