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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/ai/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,12 @@ const program = Effect.gen(function* () {
await Effect.runPromise(program.pipe(Effect.provide(AI.fetchLayer)))
```

Credentials belong to the provider: `openai({ apiKey })` makes one credential that every model from that provider
shares as `model.auth`, and the model's API decides how it is sent (header and prefix). Without `apiKey`, the
provider's environment variables (`OPENAI_API_KEY`) are read when each request is sent; `apiKey: false` sends none. A
request's own `apiKey` wins over the provider's. Keys are kept as a `Secret`, which prints as `"<redacted>"` from
`String`, `JSON.stringify` and `console.log`; `Secret.value(secret)` reads one.

Run `ai.stream(...)` instead of `generate` when you want incremental `StreamEvent`s. Both accept input or a prebuilt
`ai.request(...)`. Input takes either `prompt`, a single user message, or `messages`, the whole conversation, never
both; `system` goes with either. The event stream is provider-neutral — same shape across OpenAI Chat, OpenAI Responses,
Expand Down
34 changes: 34 additions & 0 deletions packages/ai/src/auth-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type { Auth } from "./route/auth.js"
import type { Secret } from "./secret.js"

// Package-private: a custom source keeps its signing, OAuth or bearer handler behind this key, out of public types.
const HANDLER = Symbol("opencode.ai.auth")

/**
* Where a provider's credential comes from, as plain data. A provider makes one when it is called and every model it
* builds shares it; the API decides how a key is sent. Environment variables are read when a request is sent.
* `custom` is a handler the provider owns: Bedrock SigV4, Vertex access tokens and OAuth, bearer tokens.
*/
export type AuthSource =
| { readonly type: "env"; readonly vars: ReadonlyArray<string> }
| { readonly type: "key"; readonly key: Secret }
| { readonly type: "none" }
| { readonly type: "custom" }

/** A source whose handler signs or authorizes each request itself. */
export const custom = (handler: Auth.Definition): AuthSource => {
const source = { type: "custom" as const, [HANDLER]: handler }
return source
}

/** The handler behind a custom source. */
export const handlerOf = (source: AuthSource): Auth.Definition | undefined =>
isCustom(source) ? source[HANDLER] : undefined

const isCustom = (source: object): source is { readonly [HANDLER]: Auth.Definition } => HANDLER in source

/** What an API's own auth implies without a key: its environment variables, or its handler. */
export const sourceOf = (auth: Auth.Authentication | undefined): AuthSource => {
if (auth === undefined) return { type: "none" }
return "type" in auth ? { type: "env", vars: auth.env } : custom(auth)
}
2 changes: 1 addition & 1 deletion packages/ai/src/decision-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export interface Interface {

export const make = (execute: Execute): Interface => ({
generate: Effect.fnUntraced(function* (request) {
const route = jsonRouteOf<DecisionRequest, DecisionResponse>(request.model, internal(request.model.api))
const route = jsonRouteOf<DecisionRequest, DecisionResponse>(request, internal(request.model.api))
const input = internal(request.model.api).protocol.inlineMedia
? yield* Effect.forEach(request.input, (part) =>
materialize(
Expand Down
2 changes: 1 addition & 1 deletion packages/ai/src/embedding-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export interface Interface {

export const make = (execute: Execute): Interface => ({
generate: Effect.fnUntraced(function* (request) {
const route = jsonRouteOf<EmbeddingRequest, EmbeddingResponse>(request.model, internal(request.model.api))
const route = jsonRouteOf<EmbeddingRequest, EmbeddingResponse>(request, internal(request.model.api))
const response = yield* split(Api.maxValues(internal(request.model.api).maxValues, request.model.id), (part) =>
route.generate(part, execute),
)(request)
Expand Down
6 changes: 6 additions & 0 deletions packages/ai/src/generation.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import { Clock, Duration, Effect, Schedule, Schema, Stream } from "effect"
import { AIError, TimeoutError } from "./schema/errors.js"
import type { Secret } from "./secret.js"

/** Options of a job call by ID (`status`, `result`, `cancel`): the call's own API key wins over the provider's. */
export interface JobOptions {
readonly apiKey?: string | Secret
}

/** Why a generation ended in `error`. */
export const Reason = Schema.Literals(["failed", "cancelled", "expired"])
Expand Down
24 changes: 15 additions & 9 deletions packages/ai/src/image.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Effect, Schema, Stream } from "effect"
import { ProgressEvent, type AwaitOptions, type Job, type Status } from "./generation.js"
import { ProgressEvent, type AwaitOptions, type Job, type JobOptions, type Status } from "./generation.js"
import { Media } from "./media.js"
import { requestParser } from "./media-model.js"
import { isModel, type Model } from "./model.js"
Expand Down Expand Up @@ -160,16 +160,22 @@ export function start(input: ImageRequestInput) {
}

/** One status read for a job ID. */
export const status = (model: ImageModel, id: string): Effect.Effect<ImageStatus, AIError, AI.Service> =>
AI.Service.use((ai) => ai.image.status(model, id))

/** The finished images; fails while the job is still running, or with the provider's reason when it failed. */
export const result = (model: ImageModel, id: string): Effect.Effect<ImageResponse, AIError, AI.Service> =>
AI.Service.use((ai) => ai.image.result(model, id))
export const status = (
model: ImageModel,
id: string,
options?: JobOptions,
): Effect.Effect<ImageStatus, AIError, AI.Service> => AI.Service.use((ai) => ai.image.status(model, id, options))

/** The finished result; fails while the job is still running, or with the provider's reason when it failed. */
export const result = (
model: ImageModel,
id: string,
options?: JobOptions,
): Effect.Effect<ImageResponse, AIError, AI.Service> => AI.Service.use((ai) => ai.image.result(model, id, options))

/** Ask the provider to stop the job; fails with `UnsupportedOperation` when the provider has no cancel call. */
export const cancel = (model: ImageModel, id: string): Effect.Effect<void, AIError, AI.Service> =>
AI.Service.use((ai) => ai.image.cancel(model, id))
export const cancel = (model: ImageModel, id: string, options?: JobOptions): Effect.Effect<void, AIError, AI.Service> =>
AI.Service.use((ai) => ai.image.cancel(model, id, options))

export const Image = {
request,
Expand Down
31 changes: 19 additions & 12 deletions packages/ai/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { layerWith, type Services } from "./ai.js"
import { Decision, type DecisionModel, type DecisionQuestions, type DecisionRequestInput } from "./decision.js"
import { Embedding, type EmbeddingModel, type EmbeddingRequestInput } from "./embedding.js"
import { type FetchMiddleware, fromFetch } from "./fetch-middleware.js"
import type { JobOptions } from "./generation.js"
import { Image, type ImageModel, type ImageRequest, type ImageRequestInput } from "./image.js"
import { Media } from "./promise-media.js"
import {
Expand Down Expand Up @@ -299,10 +300,13 @@ const make = (options: ClientOptions = {}) => {
start: <const Model extends ImageModel>(input: ImageRequestInput<Model> | ImageRequest, options?: RunOptions) =>
run(Image.start(input), options),
/** One status read for a job ID. */
status: (model: ImageModel, id: string, options?: RunOptions) => run(Image.status(model, id), options),
status: (model: ImageModel, id: string, options?: RunOptions & JobOptions) =>
run(Image.status(model, id, options), options),
/** The finished images; fails while the job is still running. */
result: (model: ImageModel, id: string, options?: RunOptions) => run(Image.result(model, id), options),
cancel: (model: ImageModel, id: string, options?: RunOptions) => run(Image.cancel(model, id), options),
result: (model: ImageModel, id: string, options?: RunOptions & JobOptions) =>
run(Image.result(model, id, options), options),
cancel: (model: ImageModel, id: string, options?: RunOptions & JobOptions) =>
run(Image.cancel(model, id, options), options),
},
decision: {
request: Decision.request,
Expand Down Expand Up @@ -332,10 +336,13 @@ const make = (options: ClientOptions = {}) => {
start: <const Model extends VideoModel>(input: VideoRequestInput<Model> | VideoRequest, options?: RunOptions) =>
run(Video.start(input), options),
/** One status read for a job ID. */
status: (model: VideoModel, id: string, options?: RunOptions) => run(Video.status(model, id), options),
status: (model: VideoModel, id: string, options?: RunOptions & JobOptions) =>
run(Video.status(model, id, options), options),
/** The finished videos; fails while the job is still running. */
result: (model: VideoModel, id: string, options?: RunOptions) => run(Video.result(model, id), options),
cancel: (model: VideoModel, id: string, options?: RunOptions) => run(Video.cancel(model, id), options),
result: (model: VideoModel, id: string, options?: RunOptions & JobOptions) =>
run(Video.result(model, id, options), options),
cancel: (model: VideoModel, id: string, options?: RunOptions & JobOptions) =>
run(Video.cancel(model, id, options), options),
},
speech: {
request: Speech.request,
Expand Down Expand Up @@ -364,13 +371,13 @@ const make = (options: ClientOptions = {}) => {
options?: RunOptions,
) => run(Transcription.start(input), options),
/** One status read for a job ID. */
status: (model: TranscriptionModel, id: string, options?: RunOptions) =>
run(Transcription.status(model, id), options),
status: (model: TranscriptionModel, id: string, options?: RunOptions & JobOptions) =>
run(Transcription.status(model, id, options), options),
/** The finished transcript; fails while the job is still running. */
result: (model: TranscriptionModel, id: string, options?: RunOptions) =>
run(Transcription.result(model, id), options),
cancel: (model: TranscriptionModel, id: string, options?: RunOptions) =>
run(Transcription.cancel(model, id), options),
result: (model: TranscriptionModel, id: string, options?: RunOptions & JobOptions) =>
run(Transcription.result(model, id, options), options),
cancel: (model: TranscriptionModel, id: string, options?: RunOptions & JobOptions) =>
run(Transcription.cancel(model, id, options), options),
},
dispose: () => runtime.dispose(),
}
Expand Down
37 changes: 23 additions & 14 deletions packages/ai/src/media-client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import { Effect, Stream } from "effect"
import { resultEvents, wait, type AwaitOptions, type Job, type Observation, type Status } from "./generation.js"
import {
resultEvents,
wait,
type AwaitOptions,
type Job,
type JobOptions,
type Observation,
type Status,
} from "./generation.js"
import type { Api } from "./api.js"
import { routeOf } from "./media-model.js"
import type { Model } from "./model.js"
Expand All @@ -16,9 +24,9 @@ export interface Interface<Req extends ModelRequest, Event, Response> {
readonly generate: (request: Req, options?: AwaitOptions) => Effect.Effect<Response, AIError>
readonly stream: (request: Req, options?: AwaitOptions) => Stream.Stream<Event | Observation, AIError>
readonly start: (request: Req) => Effect.Effect<Job, AIError>
readonly status: (model: Req["model"], id: string) => Effect.Effect<Status, AIError>
readonly result: (model: Req["model"], id: string) => Effect.Effect<Response, AIError>
readonly cancel: (model: Req["model"], id: string) => Effect.Effect<void, AIError>
readonly status: (model: Req["model"], id: string, options?: JobOptions) => Effect.Effect<Status, AIError>
readonly result: (model: Req["model"], id: string, options?: JobOptions) => Effect.Effect<Response, AIError>
readonly cancel: (model: Req["model"], id: string, options?: JobOptions) => Effect.Effect<void, AIError>
}

export interface Input<Event, Response> {
Expand Down Expand Up @@ -49,26 +57,27 @@ export const operations = <Req extends ModelRequest, Event, Response>(
execute: MediaRoute.Execute,
input: Input<Event, Response>,
): Interface<Req, Event, Response> => {
const routeFor = (model: Req["model"]) => routeOf<Req, Event, Response>(model, input.collect)
const routeFor = (model: Req["model"], apiKey?: Req["apiKey"]) =>
routeOf<Req, Event, Response>(model, input.collect, apiKey)
const start = (request: Req) => {
const route = routeFor(request.model)
const route = routeFor(request.model, request.apiKey)
if (route.kind !== "queued") return Effect.fail(notQueued(input.modality, route, "start"))
return route.start(request, execute)
}
const generation = `${/^[aeiou]/.test(input.modality) ? "an" : "a"} ${input.modality} generation`
const attach = (model: Req["model"], id: string, operation: string) => {
const route = routeFor(model)
const attach = (model: Req["model"], id: string, operation: string, options: JobOptions | undefined) => {
const route = routeFor(model, options?.apiKey)
if (route.kind !== "queued") return Effect.fail(notQueued(input.modality, route, operation))
return route.attach(model, id, execute)
}
return {
generate: (request, options) => {
const route = routeFor(request.model)
const route = routeFor(request.model, request.apiKey)
if (route.kind !== "queued") return route.generate(request, execute)
return start(request).pipe(Effect.flatMap((started) => wait(started, options)))
},
stream: (request, options) => {
const route = routeFor(request.model)
const route = routeFor(request.model, request.apiKey)
if (route.kind === "stream") return route.stream(request, execute)
if (route.kind === "queued")
return Stream.unwrap(
Expand All @@ -77,10 +86,10 @@ export const operations = <Req extends ModelRequest, Event, Response>(
return Stream.fromIterableEffect(Effect.map(route.generate(request, execute), input.responseEvents))
},
start: (request) => start(request).pipe(Effect.map((started) => ({ id: started.id }))),
status: (model, id) => attach(model, id, "status").pipe(Effect.flatMap((route) => route.status)),
result: (model, id) => attach(model, id, "result").pipe(Effect.flatMap((route) => route.result)),
cancel: (model, id) =>
attach(model, id, "cancel").pipe(
status: (model, id, options) => attach(model, id, "status", options).pipe(Effect.flatMap((route) => route.status)),
result: (model, id, options) => attach(model, id, "result", options).pipe(Effect.flatMap((route) => route.result)),
cancel: (model, id, options) =>
attach(model, id, "cancel", options).pipe(
Effect.flatMap(
(route) =>
route.cancel ??
Expand Down
25 changes: 18 additions & 7 deletions packages/ai/src/media-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ import { Effect, Schema } from "effect"
import type { HttpClientResponse } from "effect/http"
import { Api } from "./api.js"
import type { Model } from "./model.js"
import { Auth } from "./route/auth.js"
import { resolve } from "./route/credential.js"
import { Endpoint } from "./route/endpoint.js"
import { MediaProtocol } from "./route/media-protocol.js"
import { MediaRoute } from "./route/media.js"
import { AIError, InvalidRequestError, type RequestHttpOptions } from "./schema/index.js"
import { Secret } from "./secret.js"

/**
* The route a media model runs on: its API's protocol at the API's path and host, with its auth. The API's name and the
Expand All @@ -16,11 +17,12 @@ import { AIError, InvalidRequestError, type RequestHttpOptions } from "./schema/
export const routeOf = <Request extends MediaRoute.MediaRequest, Event, Response>(
model: Model<Api.MediaKind>,
collect: (events: ReadonlyArray<Event>) => Effect.Effect<Response, AIError>,
apiKey?: MediaRoute.MediaRequest["apiKey"],
): MediaRoute.AnyRoute<Request, Event, Response> => {
const api = internal(model.api)
const composition = {
endpoint: Endpoint.path(api.path, { baseURL: Api.baseURL(api.baseURL, model.id) }),
auth: Auth.fromAuthentication(api.auth),
auth: resolve(api.auth, model.auth, apiKey),
headers: api.headers,
query: api.query,
}
Expand All @@ -38,7 +40,7 @@ export const routeOf = <Request extends MediaRoute.MediaRequest, Event, Response
* with its auth. The HTTP plumbing (URL, query, auth, headers, `http` overlays, surrogate sanitizing) is the media one.
*/
export const jsonRouteOf = <Request extends MediaRoute.MediaRequest, Response>(
model: MediaRoute.MediaRequest["model"],
request: Pick<MediaRoute.MediaRequest, "apiKey"> & { readonly model: Model<"decision" | "embedding"> },
api: Api.Connection & {
readonly name: string
readonly path: Endpoint.EndpointPart<MediaProtocol.Body, Request>
Expand All @@ -54,8 +56,9 @@ export const jsonRouteOf = <Request extends MediaRoute.MediaRequest, Response>(
}
}
},
) =>
MediaRoute.inline({
) => {
const model = request.model
return MediaRoute.inline({
protocol: MediaProtocol.inline<Request, Response>(
MediaProtocol.identity({ id: api.name, name: api.protocol.name, provider: model.provider }),
{
Expand All @@ -72,9 +75,10 @@ export const jsonRouteOf = <Request extends MediaRoute.MediaRequest, Response>(
},
),
endpoint: Endpoint.path(api.path, { baseURL: Api.baseURL(api.baseURL, model.id), query: api.query }),
auth: Auth.fromAuthentication(api.auth),
auth: resolve(api.auth, model.auth, request.apiKey),
headers: api.headers,
})
}

/** Lift a synchronous Schema-class constructor into a typed `InvalidRequest` failure. */
export const tryRequest = <A>(make: () => A): Effect.Effect<A, AIError> =>
Expand All @@ -94,10 +98,17 @@ export const tryRequest = <A>(make: () => A): Effect.Effect<A, AIError> =>
// `http` can carry `fetch`, so it passes through unchecked.
const RequestHttp = Schema.declare((_: unknown): _ is RequestHttpOptions => true)

// A secret is kept as the instance it is, so its value stays hidden.
const RequestApiKey = Schema.declare(
(value: unknown): value is string | Secret => typeof value === "string" || value instanceof Secret,
)

/** Parse a normalized request on its schema's type side; models and assets are checked as instances and kept as is. */
export const requestParser = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) => {
const parse = Schema.decodeUnknownSync(
Schema.toType(Schema.Struct({ ...schema.fields, http: Schema.optional(RequestHttp) })),
Schema.toType(
Schema.Struct({ ...schema.fields, http: Schema.optional(RequestHttp), apiKey: Schema.optional(RequestApiKey) }),
),
)
return (normalize: () => unknown) => tryRequest(() => parse(normalize()))
}
3 changes: 3 additions & 0 deletions packages/ai/src/model.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Api } from "./api.js"
import type { AuthSource } from "./auth-source.js"
import type { DecisionModelCompatibility } from "./decision.js"
import type {
Capabilities,
Expand Down Expand Up @@ -26,6 +27,8 @@ export type Model<
readonly kind: K
readonly id: ModelID
readonly provider: ProviderID
/** The provider's credential, shared by every model it builds. A request's own `apiKey` wins. */
readonly auth: AuthSource
/** Type only: the provider options requests on this model take. */
readonly "~options"?: Options
} & Fields<Compact>[K]
Expand Down
4 changes: 2 additions & 2 deletions packages/ai/src/protocols/utils/responses-compaction.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { internal } from "../../api-internal.js"
import { resolve } from "../../route/credential.js"
import { Effect, Schema } from "effect"
import {
AIError,
Expand All @@ -12,7 +13,6 @@ import {
mergeJsonRecords,
} from "../../schema/index.js"
import { endpoint, type CompactOperation } from "../../route/client.js"
import { Auth } from "../../route/auth.js"
import { stripEffortUpdates } from "../../effort-updates.js"
import { foldToolUpdates } from "../../tool-updates.js"
import { Endpoint } from "../../route/endpoint.js"
Expand Down Expand Up @@ -125,7 +125,7 @@ export const make = (
},
body,
endpoint: Endpoint.path(url.toString()),
auth: Auth.fromAuthentication(api.auth),
auth: resolve(api.auth, request.model.auth, request.apiKey),
encodeBody: Schema.encodeSync(Schema.fromJsonString(Body)),
})
const post = yield* ProviderShared.jsonPostEffect({
Expand Down
Loading
Loading