mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
fix(ai): apply HTTP timeouts to all requests (#64692)
This commit is contained in:
parent
102efff30e
commit
73215c55eb
51 changed files with 746 additions and 450 deletions
|
|
@ -5,7 +5,7 @@ import { tryRequest } from "./media-model.js"
|
|||
import {
|
||||
AIError,
|
||||
type BaseRequest,
|
||||
type HttpOptions,
|
||||
type TransportOptions,
|
||||
ModelID,
|
||||
ProviderID,
|
||||
ProviderMetadata,
|
||||
|
|
@ -200,7 +200,8 @@ export class DecisionModel<Options extends DecisionOptions = DecisionOptions> {
|
|||
readonly id: ModelID
|
||||
readonly provider: ProviderID
|
||||
readonly route: DecisionModelRoute<Options>
|
||||
readonly http?: HttpOptions
|
||||
/** Deployment headers, timeouts and `http` overlays, below each request's own. */
|
||||
readonly transport?: TransportOptions
|
||||
readonly compatibility?: DecisionModelCompatibility
|
||||
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
|
||||
readonly providerOptions?: ProviderOptions
|
||||
|
|
@ -209,7 +210,7 @@ export class DecisionModel<Options extends DecisionOptions = DecisionOptions> {
|
|||
this.id = input.id
|
||||
this.provider = input.provider
|
||||
this.route = input.route
|
||||
this.http = input.http
|
||||
this.transport = input.transport
|
||||
this.compatibility = input.compatibility
|
||||
this.providerOptions = input.providerOptions
|
||||
}
|
||||
|
|
@ -228,7 +229,7 @@ export namespace DecisionModel {
|
|||
readonly id: ModelID
|
||||
readonly provider: ProviderID
|
||||
readonly route: DecisionModelRoute<Options>
|
||||
readonly http?: HttpOptions
|
||||
readonly transport?: TransportOptions
|
||||
readonly compatibility?: DecisionModelCompatibility
|
||||
readonly providerOptions?: ProviderOptions
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { tryRequest } from "./media-model.js"
|
|||
import {
|
||||
type AIError,
|
||||
type BaseRequest,
|
||||
type HttpOptions,
|
||||
type TransportOptions,
|
||||
ModelID,
|
||||
ProviderID,
|
||||
ProviderMetadata,
|
||||
|
|
@ -38,7 +38,10 @@ export type EmbeddingOptions = Record<string, unknown>
|
|||
/** What an embedding model's route does; `EmbeddingRoute.make(...).model(...)` builds one from a protocol. */
|
||||
export interface EmbeddingModelRoute<Options extends EmbeddingOptions = EmbeddingOptions> {
|
||||
readonly id: string
|
||||
generate(request: EmbeddingRequest<EmbeddingModel<Options>>, execute: Execute): Effect.Effect<EmbeddingResponse, AIError>
|
||||
generate(
|
||||
request: EmbeddingRequest<EmbeddingModel<Options>>,
|
||||
execute: Execute,
|
||||
): Effect.Effect<EmbeddingResponse, AIError>
|
||||
}
|
||||
|
||||
export class EmbeddingModel<Options extends EmbeddingOptions = EmbeddingOptions> {
|
||||
|
|
@ -46,7 +49,8 @@ export class EmbeddingModel<Options extends EmbeddingOptions = EmbeddingOptions>
|
|||
readonly id: ModelID
|
||||
readonly provider: ProviderID
|
||||
readonly route: EmbeddingModelRoute<Options>
|
||||
readonly http?: HttpOptions
|
||||
/** Deployment headers, timeouts and `http` overlays, below each request's own. */
|
||||
readonly transport?: TransportOptions
|
||||
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
|
||||
readonly providerOptions?: ProviderOptions
|
||||
|
||||
|
|
@ -54,7 +58,7 @@ export class EmbeddingModel<Options extends EmbeddingOptions = EmbeddingOptions>
|
|||
this.id = input.id
|
||||
this.provider = input.provider
|
||||
this.route = input.route
|
||||
this.http = input.http
|
||||
this.transport = input.transport
|
||||
this.providerOptions = input.providerOptions
|
||||
}
|
||||
|
||||
|
|
@ -72,7 +76,7 @@ export namespace EmbeddingModel {
|
|||
readonly id: ModelID
|
||||
readonly provider: ProviderID
|
||||
readonly route: EmbeddingModelRoute<Options>
|
||||
readonly http?: HttpOptions
|
||||
readonly transport?: TransportOptions
|
||||
readonly providerOptions?: ProviderOptions
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -99,14 +99,13 @@ export const model = (input: MediaRoute.ModelInput) =>
|
|||
new ExtractionModel({
|
||||
id: input.id,
|
||||
provider: route.provider,
|
||||
http: input.http,
|
||||
transport: input.transport,
|
||||
route: MediaRoute.inline({
|
||||
protocol,
|
||||
endpoint: Endpoint.path<MediaProtocol.Body, ExtractionRequest>(({ request }) => `/${request.model.id}`, {
|
||||
baseURL: input.baseURL,
|
||||
}),
|
||||
auth: input.auth,
|
||||
headers: input.headers,
|
||||
}),
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { Clock, Effect, Redacted, Schema } from "effect"
|
||||
import { HttpClientRequest } from "effect/http"
|
||||
import { RequestExecutor } from "../route/executor.js"
|
||||
import { AIError, InvalidProviderOutputError, InvalidRequestError } from "../schema/index.js"
|
||||
import { AIError, InvalidProviderOutputError, InvalidRequestError, type RequestTimeout } from "../schema/index.js"
|
||||
import { encodeJson } from "../utils/json.js"
|
||||
|
||||
const OPENAI_BASE_URL = "https://api.openai.com/v1"
|
||||
|
|
@ -27,6 +27,7 @@ export interface RealtimeConnectInput {
|
|||
readonly baseURL?: string
|
||||
/** Headers that host needs besides the API key, such as OpenCode's workspace. */
|
||||
readonly headers?: Readonly<Record<string, string>>
|
||||
readonly timeout?: RequestTimeout
|
||||
readonly session?: RealtimeSession
|
||||
readonly transport: RealtimeTransportInput
|
||||
}
|
||||
|
|
@ -69,16 +70,23 @@ export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeC
|
|||
input.apiKey,
|
||||
{ session, transport: input.transport },
|
||||
LiveSessionResponse,
|
||||
{ headers: input.headers },
|
||||
{ headers: input.headers, timeout: input.timeout },
|
||||
)
|
||||
return { type: "webrtc" as const, sdp: data.transport.sdp }
|
||||
}
|
||||
case "openai-realtime": {
|
||||
if (input.transport.type === "websocket")
|
||||
return yield* clientSecret(resolved.id, OPENAI_BASE_URL, input.model, input.apiKey, {
|
||||
expires_after: { anchor: "created_at", seconds: 60 },
|
||||
session,
|
||||
})
|
||||
return yield* clientSecret(
|
||||
resolved.id,
|
||||
OPENAI_BASE_URL,
|
||||
input.model,
|
||||
input.apiKey,
|
||||
{
|
||||
expires_after: { anchor: "created_at", seconds: 60 },
|
||||
session,
|
||||
},
|
||||
input.timeout,
|
||||
)
|
||||
const form = new FormData()
|
||||
form.append("sdp", input.transport.sdp)
|
||||
form.append("session", encodeJson(session))
|
||||
|
|
@ -89,13 +97,21 @@ export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeC
|
|||
input.apiKey,
|
||||
form,
|
||||
Schema.String,
|
||||
{ timeout: input.timeout },
|
||||
)
|
||||
return { type: "webrtc" as const, sdp }
|
||||
}
|
||||
case "xai-realtime":
|
||||
return yield* clientSecret(resolved.id, XAI_BASE_URL, input.model, input.apiKey, {
|
||||
expires_after: { seconds: 60 },
|
||||
})
|
||||
return yield* clientSecret(
|
||||
resolved.id,
|
||||
XAI_BASE_URL,
|
||||
input.model,
|
||||
input.apiKey,
|
||||
{
|
||||
expires_after: { seconds: 60 },
|
||||
},
|
||||
input.timeout,
|
||||
)
|
||||
case "gemini-live": {
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
const expiresAt = now + 60_000
|
||||
|
|
@ -110,7 +126,7 @@ export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeC
|
|||
bidiGenerateContentSetup: { ...input.session, model: `models/${input.model}` },
|
||||
},
|
||||
AuthTokenResponse,
|
||||
{ authHeader: "x-goog-api-key" },
|
||||
{ authHeader: "x-goog-api-key", timeout: input.timeout },
|
||||
)
|
||||
return {
|
||||
type: "websocket" as const,
|
||||
|
|
@ -158,11 +174,18 @@ const post = <A>(
|
|||
apiKey: Redacted.Redacted,
|
||||
body: Record<string, unknown> | FormData,
|
||||
response: Schema.Codec<A, string>,
|
||||
options: { readonly authHeader?: string; readonly headers?: Readonly<Record<string, string>> } = {},
|
||||
options: {
|
||||
readonly authHeader?: string
|
||||
readonly headers?: Readonly<Record<string, string>>
|
||||
readonly timeout?: RequestTimeout
|
||||
} = {},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const executor = yield* RequestExecutor.Service
|
||||
const res = yield* executor.execute(
|
||||
const res = yield* RequestExecutor.withTimeout(
|
||||
executor.execute,
|
||||
options.timeout,
|
||||
)(
|
||||
HttpClientRequest.post(url).pipe(
|
||||
HttpClientRequest.setHeaders(options.headers ?? {}),
|
||||
options.authHeader
|
||||
|
|
@ -176,7 +199,7 @@ const post = <A>(
|
|||
const http = RequestExecutor.responseHttp(res)
|
||||
const fail = (message: string, cause?: unknown, raw?: string) =>
|
||||
new AIError({ reason: new InvalidProviderOutputError({ route, message, body: raw, http, cause }) })
|
||||
const text = yield* res.text.pipe(Effect.mapError((cause) => fail(`Failed to read ${route} response`, cause)))
|
||||
const text = yield* RequestExecutor.responseText(res)
|
||||
return yield* Schema.decodeEffect(response)(text).pipe(
|
||||
Effect.mapError((cause) => fail(`${route} returned an invalid response`, cause, text)),
|
||||
)
|
||||
|
|
@ -188,8 +211,9 @@ const clientSecret = (
|
|||
model: string,
|
||||
apiKey: Redacted.Redacted,
|
||||
body: Record<string, unknown>,
|
||||
timeout?: RequestTimeout,
|
||||
) =>
|
||||
post(route, `${baseURL}/realtime/client_secrets`, apiKey, body, ClientSecretResponse).pipe(
|
||||
post(route, `${baseURL}/realtime/client_secrets`, apiKey, body, ClientSecretResponse, { timeout }).pipe(
|
||||
Effect.map(
|
||||
(data): RealtimeTransport => ({
|
||||
type: "websocket",
|
||||
|
|
|
|||
|
|
@ -47,7 +47,7 @@ export class ImageModel<Options extends ImageOptions = ImageOptions> extends Med
|
|||
return new ImageModel<Options>({
|
||||
id: input.id,
|
||||
provider: route.protocol.provider,
|
||||
http: input.http,
|
||||
transport: input.transport,
|
||||
providerOptions: input.providerOptions,
|
||||
route: composeRoute(route, input, collectResponse) as ImageRoute,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -7,12 +7,12 @@ import {
|
|||
InvalidRequestError,
|
||||
ModelID,
|
||||
ProviderID,
|
||||
type HttpOptions,
|
||||
type ProviderOptions,
|
||||
type TransportOptions,
|
||||
} from "./schema/index.js"
|
||||
|
||||
/**
|
||||
* What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
|
||||
* What every media model carries: ids, the configured route, and deployment transport 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.
|
||||
*/
|
||||
|
|
@ -23,7 +23,8 @@ export class MediaModel<Route, Options> {
|
|||
readonly id: ModelID
|
||||
readonly provider: ProviderID
|
||||
readonly route: Route
|
||||
readonly http?: HttpOptions
|
||||
/** Deployment headers, timeouts and `http` overlays, below each request's own. */
|
||||
readonly transport?: TransportOptions
|
||||
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
|
||||
readonly providerOptions?: ProviderOptions
|
||||
|
||||
|
|
@ -31,7 +32,7 @@ export class MediaModel<Route, Options> {
|
|||
this.id = ModelID.make(input.id)
|
||||
this.provider = ProviderID.make(input.provider)
|
||||
this.route = input.route
|
||||
this.http = input.http
|
||||
this.transport = input.transport
|
||||
this.providerOptions = input.providerOptions
|
||||
}
|
||||
}
|
||||
|
|
@ -43,7 +44,7 @@ export namespace MediaModel {
|
|||
readonly id: string | ModelID
|
||||
readonly provider: string | ProviderID
|
||||
readonly route: Route
|
||||
readonly http?: HttpOptions
|
||||
readonly transport?: TransportOptions
|
||||
readonly providerOptions?: ProviderOptions
|
||||
}
|
||||
|
||||
|
|
@ -101,8 +102,7 @@ const composition = <Request extends MediaRoute.MediaRequest, Protocol>(
|
|||
protocol: route.protocol,
|
||||
endpoint: Endpoint.path(route.path, { baseURL: input.baseURL ?? route.baseURL }),
|
||||
auth: input.auth,
|
||||
headers:
|
||||
route.headers === undefined && input.headers === undefined ? undefined : { ...route.headers, ...input.headers },
|
||||
headers: route.headers,
|
||||
})
|
||||
|
||||
const isStreamInput = <Request extends MediaRoute.MediaRequest, Event, Response, Frame, State, Token>(
|
||||
|
|
|
|||
|
|
@ -4,9 +4,15 @@ import { Effect, FileSystem, Result, Schema, SchemaGetter, Stream } from "effect
|
|||
import { Base64 } from "effect/encoding"
|
||||
import { HttpClientRequest } from "effect/http"
|
||||
import { ProviderID } from "./schema/ids.js"
|
||||
import { AIError, InvalidProviderOutputError, InvalidRequestError } from "./schema/errors.js"
|
||||
import { AIError, InvalidRequestError } from "./schema/errors.js"
|
||||
import { ProviderMetadata } from "./schema/options.js"
|
||||
import { CurrentMiddleware, type HttpMiddleware, responseHttp, Service } from "./route/executor-service.js"
|
||||
import {
|
||||
CurrentMiddleware,
|
||||
type HttpMiddleware,
|
||||
responseBytes,
|
||||
responseStream,
|
||||
Service,
|
||||
} from "./route/executor-service.js"
|
||||
import { detectMediaType, fileMediaType } from "./utils/media-type.js"
|
||||
|
||||
export { detectMediaType } from "./utils/media-type.js"
|
||||
|
|
@ -271,19 +277,7 @@ const download = Effect.fn("Media.download")(function* (
|
|||
const response = yield* executor
|
||||
.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})))
|
||||
.pipe(Effect.provideService(CurrentMiddleware, middleware))
|
||||
const buffer = yield* response.arrayBuffer.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AIError({
|
||||
reason: new InvalidProviderOutputError({
|
||||
message: `Failed to read media from ${source.url}`,
|
||||
http: responseHttp(response),
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
)
|
||||
return new Uint8Array(buffer)
|
||||
return yield* responseBytes(response)
|
||||
})
|
||||
|
||||
const downloadStream = Effect.fn("Media.downloadStream")(function* (
|
||||
|
|
@ -295,18 +289,7 @@ const downloadStream = Effect.fn("Media.downloadStream")(function* (
|
|||
const response = yield* executor
|
||||
.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})))
|
||||
.pipe(Effect.provideService(CurrentMiddleware, middleware))
|
||||
return response.stream.pipe(
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
new AIError({
|
||||
reason: new InvalidProviderOutputError({
|
||||
message: `Failed to read media from ${source.url}`,
|
||||
http: responseHttp(response),
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
)
|
||||
return responseStream(response)
|
||||
})
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { Effect, Schema, Stream } from "effect"
|
||||
import { Effect, Schema } from "effect"
|
||||
import {
|
||||
AIError,
|
||||
InvalidProviderOutputError,
|
||||
|
|
@ -125,7 +125,10 @@ export const make = (
|
|||
auth: route.auth,
|
||||
encodeBody: Schema.encodeSync(Schema.fromJsonString(Body)),
|
||||
})
|
||||
const response = yield* RequestExecutor.withTls(executor.execute, request.http?.tls)(
|
||||
const response = yield* RequestExecutor.withTimeout(
|
||||
RequestExecutor.withTls(executor.execute, request.http?.tls),
|
||||
request.timeout,
|
||||
)(
|
||||
ProviderShared.jsonPost({
|
||||
url: parts.url,
|
||||
body: parts.bodyText,
|
||||
|
|
@ -134,13 +137,7 @@ export const make = (
|
|||
}),
|
||||
RequestExecutor.withFetch(request.fetch, options?.http),
|
||||
)
|
||||
const text = yield* RequestExecutor.responseStream(response).pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => "",
|
||||
(text, chunk) => text + chunk,
|
||||
),
|
||||
)
|
||||
const text = yield* RequestExecutor.responseText(response)
|
||||
const invalid = (message: string, cause?: unknown) =>
|
||||
new AIError({
|
||||
reason: new InvalidProviderOutputError({
|
||||
|
|
|
|||
|
|
@ -72,35 +72,33 @@ export const onDone: (
|
|||
state: OpenResponses.ParserState,
|
||||
item: Item,
|
||||
tools: Definitions,
|
||||
) => Effect.Effect<OpenResponses.StepResult, AIError> = Effect.fnUntraced(
|
||||
function* (state, item, tools) {
|
||||
const tool = tools[item.type]
|
||||
if (!tool) return [state, []] satisfies OpenResponses.StepResult
|
||||
const providerMetadata = OpenResponses.providerMetadata(state, { itemId: item.id })
|
||||
const events: LLMEvent[] = []
|
||||
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
||||
events.push(
|
||||
LLMEvent.toolCall({
|
||||
id: item.id,
|
||||
name: tool.name,
|
||||
input: tool.input(item),
|
||||
providerExecuted: true,
|
||||
providerMetadata,
|
||||
}),
|
||||
LLMEvent.toolResult({
|
||||
id: item.id,
|
||||
name: tool.name,
|
||||
result: tool.result
|
||||
? yield* tool.result(item)
|
||||
: item.error !== undefined && item.error !== null
|
||||
? { type: "error", value: item.error }
|
||||
: { type: "json", value: item },
|
||||
providerExecuted: true,
|
||||
providerMetadata,
|
||||
}),
|
||||
)
|
||||
return [{ ...state, lifecycle }, events] satisfies OpenResponses.StepResult
|
||||
},
|
||||
)
|
||||
) => Effect.Effect<OpenResponses.StepResult, AIError> = Effect.fnUntraced(function* (state, item, tools) {
|
||||
const tool = tools[item.type]
|
||||
if (!tool) return [state, []] satisfies OpenResponses.StepResult
|
||||
const providerMetadata = OpenResponses.providerMetadata(state, { itemId: item.id })
|
||||
const events: LLMEvent[] = []
|
||||
const lifecycle = Lifecycle.stepStart(state.lifecycle, events)
|
||||
events.push(
|
||||
LLMEvent.toolCall({
|
||||
id: item.id,
|
||||
name: tool.name,
|
||||
input: tool.input(item),
|
||||
providerExecuted: true,
|
||||
providerMetadata,
|
||||
}),
|
||||
LLMEvent.toolResult({
|
||||
id: item.id,
|
||||
name: tool.name,
|
||||
result: tool.result
|
||||
? yield* tool.result(item)
|
||||
: item.error !== undefined && item.error !== null
|
||||
? { type: "error", value: item.error }
|
||||
: { type: "json", value: item },
|
||||
providerExecuted: true,
|
||||
providerMetadata,
|
||||
}),
|
||||
)
|
||||
return [{ ...state, lifecycle }, events] satisfies OpenResponses.StepResult
|
||||
})
|
||||
|
||||
export * as ResponsesHostedTools from "./responses-hosted-tools.js"
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import { Endpoint } from "../route/endpoint.js"
|
|||
import { Framing } from "../route/framing.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import {
|
||||
mergeTransport,
|
||||
ProviderConfigurationError,
|
||||
ProviderID,
|
||||
ToolDefinition,
|
||||
|
|
@ -123,8 +124,7 @@ export const configure = (input: Config) => {
|
|||
provider: id,
|
||||
endpoint: common.endpoint,
|
||||
auth: opts.auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
const embedding = (id: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
embeddingRoute.model({ id, providerOptions })
|
||||
|
|
|
|||
|
|
@ -1,19 +1,18 @@
|
|||
import { Auth } from "../route/auth.js"
|
||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import { type HttpOptions, ProviderID, type ModelID } from "../schema/index.js"
|
||||
import { ProviderID, type ModelID, type TransportOptions } from "../schema/index.js"
|
||||
import { AssemblyAITranscription } from "../protocols/assemblyai-transcription.js"
|
||||
|
||||
export type { AssemblyAITranscriptionOptions } from "../protocols/assemblyai-transcription.js"
|
||||
|
||||
export const id = ProviderID.make("assemblyai")
|
||||
|
||||
export type Config = ProviderAuthOption<"optional"> & {
|
||||
/** `https://api.eu.assemblyai.com` for the EU region. */
|
||||
readonly baseURL?: string
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
}
|
||||
export type Config = TransportOptions &
|
||||
ProviderAuthOption<"optional"> & {
|
||||
/** `https://api.eu.assemblyai.com` for the EU region. */
|
||||
readonly baseURL?: string
|
||||
}
|
||||
|
||||
// The key is the whole `authorization` value, without a scheme.
|
||||
const auth = (options: ProviderAuthOption<"optional">) =>
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { Endpoint } from "../route/endpoint.js"
|
|||
import type { ProviderPackage } from "../provider-package.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import {
|
||||
mergeTransport,
|
||||
ProviderConfigurationError,
|
||||
ProviderID,
|
||||
type ModelID,
|
||||
|
|
@ -158,14 +159,9 @@ export const configure = (input: Config) => {
|
|||
|
||||
const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) => {
|
||||
const target = endpoint(input, modelID)
|
||||
const media = MediaRoute.deployment({ ...input, baseURL: target.baseURL }, auth(input))
|
||||
return OpenAIImages.model({
|
||||
...media,
|
||||
id: modelID,
|
||||
provider: id,
|
||||
providerOptions,
|
||||
http: { ...media.http, query: { ...media.http?.query, ...target.query } },
|
||||
})
|
||||
const transport = mergeTransport(input, { http: { query: target.query } })
|
||||
const media = MediaRoute.deployment({ ...transport, baseURL: target.baseURL }, auth(input))
|
||||
return OpenAIImages.model({ ...media, id: modelID, provider: id, providerOptions })
|
||||
}
|
||||
|
||||
const embedding = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
|
|
@ -174,8 +170,7 @@ export const configure = (input: Config) => {
|
|||
provider: id,
|
||||
endpoint: endpoint(input, modelID),
|
||||
auth: auth(input),
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
.model({ id: modelID, providerOptions })
|
||||
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import type { ProviderAuthOption } from "../route/auth-options.js"
|
|||
import { Route } from "../route/client.js"
|
||||
import { DecisionRoute } from "../route/decision.js"
|
||||
import { Endpoint } from "../route/endpoint.js"
|
||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
||||
|
||||
|
|
@ -63,8 +63,7 @@ export const configure = (input: Config = {}) => {
|
|||
protocol: decisionProtocol,
|
||||
endpoint: Endpoint.path("/systemone", { baseURL: options.endpoint.baseURL }),
|
||||
auth: options.auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
decisionRoute.model<BasetenDecisionOptions>({ id: modelID, providerOptions })
|
||||
|
|
|
|||
|
|
@ -2,16 +2,15 @@ import type { ProviderPackage } from "../provider-package.js"
|
|||
import { SeedanceVideo } from "../protocols/seedance-video.js"
|
||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import { type HttpOptions, ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js"
|
||||
import { ProviderID, type ModelID, type ProviderOptions, type TransportOptions } from "../schema/index.js"
|
||||
import { toConfig } from "./settings.js"
|
||||
|
||||
export const id = ProviderID.make("byteplus")
|
||||
|
||||
export type Config = ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
}
|
||||
export type Config = TransportOptions &
|
||||
ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
}
|
||||
|
||||
export type Settings = ProviderPackage.Settings & {
|
||||
readonly apiKey?: string | false
|
||||
|
|
|
|||
|
|
@ -1,17 +1,16 @@
|
|||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import { type HttpOptions, ProviderID, type ModelID } from "../schema/index.js"
|
||||
import { ProviderID, type ModelID, type TransportOptions } from "../schema/index.js"
|
||||
import { CartesiaSpeech } from "../protocols/cartesia-speech.js"
|
||||
|
||||
export type { CartesiaEncoding, CartesiaSpeechOptions } from "../protocols/cartesia-speech.js"
|
||||
|
||||
export const id = ProviderID.make("cartesia")
|
||||
|
||||
export type Config = ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
}
|
||||
export type Config = TransportOptions &
|
||||
ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
}
|
||||
|
||||
const auth = (options: ProviderAuthOption<"optional">) => AuthOptions.bearer(options, "CARTESIA_API_KEY")
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { CloudflareRunDecisions } from "../protocols/cloudflare-run-decisions.js
|
|||
import { AnthropicMessages, OpenAIChat, OpenAIResponses } from "../protocols/index.js"
|
||||
import { Auth } from "../route/auth.js"
|
||||
import { AuthOptions, type AtLeastOne, type ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import { encodeJson } from "../utils/json.js"
|
||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||
import { CloudflareShared } from "./cloudflare-shared.js"
|
||||
|
|
@ -96,6 +96,7 @@ export const configure = (input: Config) => {
|
|||
endpoint: { baseURL: baseURL(input) },
|
||||
auth: custom ?? credential(input, (credential) => credential.bearer()),
|
||||
headers: { "cf-aig-gateway-id": gatewayId(input), ...headers(input) },
|
||||
timeout: input.timeout,
|
||||
http: input.http,
|
||||
providerOptions: input.providerOptions,
|
||||
}
|
||||
|
|
@ -130,8 +131,7 @@ export const configure = (input: Config) => {
|
|||
provider: id,
|
||||
endpoint: { baseURL: runBaseURL(input) },
|
||||
auth: rest.auth,
|
||||
headers: rest.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input, { headers: rest.headers }),
|
||||
})
|
||||
.model({ id: value, providerOptions })
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import { AuthOptions, type AtLeastOne, type ProviderAuthOption } from "../route/
|
|||
import { Route } from "../route/client.js"
|
||||
import { Endpoint } from "../route/endpoint.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||
import { CloudflareShared } from "./cloudflare-shared.js"
|
||||
|
||||
|
|
@ -61,8 +61,7 @@ export const configure = (input: Config) => {
|
|||
provider: id,
|
||||
endpoint: { baseURL: runBaseURL(input) },
|
||||
auth: auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
.model({ id: modelID, providerOptions })
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { OpenAIEmbeddings } from "../protocols/openai-embeddings.js"
|
|||
import { Route } from "../route/client.js"
|
||||
import { Endpoint } from "../route/endpoint.js"
|
||||
import type { ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { ProviderID, type ModelID, type OpenString, type RequestOptions } from "../schema/index.js"
|
||||
import { mergeTransport, ProviderID, type ModelID, type OpenString, type RequestOptions } from "../schema/index.js"
|
||||
import type { ProviderPackage } from "../provider-package.js"
|
||||
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
||||
|
||||
|
|
@ -40,8 +40,7 @@ export const configure = (input: Config = {}) => {
|
|||
provider: id,
|
||||
endpoint: compatibility.endpoint,
|
||||
auth: options.auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
return {
|
||||
id,
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { Auth } from "../route/auth.js"
|
||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import { type HttpOptions, ProviderID, type ModelID } from "../schema/index.js"
|
||||
import { ProviderID, type ModelID, type TransportOptions } from "../schema/index.js"
|
||||
import { DeepgramSpeech } from "../protocols/deepgram-speech.js"
|
||||
import { DeepgramTranscription } from "../protocols/deepgram-transcription.js"
|
||||
|
||||
|
|
@ -10,11 +10,10 @@ export type { DeepgramTranscriptionOptions } from "../protocols/deepgram-transcr
|
|||
|
||||
export const id = ProviderID.make("deepgram")
|
||||
|
||||
export type Config = ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
}
|
||||
export type Config = TransportOptions &
|
||||
ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
}
|
||||
|
||||
const auth = (options: ProviderAuthOption<"optional">) =>
|
||||
AuthOptions.apiKey(options, "DEEPGRAM_API_KEY", Auth.scheme("Token"))
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { OpenAIEmbeddings } from "../protocols/openai-embeddings.js"
|
|||
import type { ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { Route } from "../route/client.js"
|
||||
import { Endpoint } from "../route/endpoint.js"
|
||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
||||
|
||||
|
|
@ -47,8 +47,7 @@ export const configure = (input: Config = {}) => {
|
|||
provider: id,
|
||||
endpoint: options.endpoint,
|
||||
auth: options.auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
return {
|
||||
id,
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ import { Route } from "../route/client.js"
|
|||
import { Endpoint } from "../route/endpoint.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import { Protocol } from "../route/protocol.js"
|
||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||
import type { OpenResponsesProviderOptionsInput } from "./open-responses-options.js"
|
||||
import { bearerRouteDefaults } from "./settings.js"
|
||||
|
|
@ -71,8 +71,7 @@ export const configure = (input: Config = {}) => {
|
|||
endpoint: options.endpoint,
|
||||
auth: options.auth,
|
||||
// DigitalOcean serves TypeSafe's Jev, which needs this header for images.
|
||||
headers: { "TypeSafe-Danger-Zone-Images": "true", ...input.headers },
|
||||
http: input.http,
|
||||
...mergeTransport({ headers: { "TypeSafe-Danger-Zone-Images": "true" } }, input),
|
||||
})
|
||||
const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
decisionRoute.model({ id: modelID, providerOptions })
|
||||
|
|
@ -83,8 +82,7 @@ export const configure = (input: Config = {}) => {
|
|||
provider: id,
|
||||
endpoint: options.endpoint,
|
||||
auth: options.auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
const embedding = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
embeddingRoute.model({ id: modelID, providerOptions })
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { Auth } from "../route/auth.js"
|
||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import { type HttpOptions, ProviderID, type ModelID } from "../schema/index.js"
|
||||
import { ProviderID, type ModelID, type TransportOptions } from "../schema/index.js"
|
||||
import { ElevenLabsSpeech } from "../protocols/elevenlabs-speech.js"
|
||||
import { ElevenLabsTranscription } from "../protocols/elevenlabs-transcription.js"
|
||||
|
||||
|
|
@ -10,11 +10,10 @@ export type { ElevenLabsTranscriptionOptions } from "../protocols/elevenlabs-tra
|
|||
|
||||
export const id = ProviderID.make("elevenlabs")
|
||||
|
||||
export type Config = ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
}
|
||||
export type Config = TransportOptions &
|
||||
ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
}
|
||||
|
||||
const auth = (options: ProviderAuthOption<"optional">) =>
|
||||
AuthOptions.apiKey(options, "ELEVENLABS_API_KEY", Auth.header("xi-api-key"))
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { OpenAIEmbeddings } from "../protocols/openai-embeddings.js"
|
|||
import type { ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { Route } from "../route/client.js"
|
||||
import { Endpoint } from "../route/endpoint.js"
|
||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import type { OpenAIProviderOptionsInput } from "./openai-options.js"
|
||||
import { bearerRouteDefaults, toConfig } from "./settings.js"
|
||||
|
||||
|
|
@ -41,8 +41,7 @@ export const configure = (input: Config = {}) => {
|
|||
provider: id,
|
||||
endpoint: options.endpoint,
|
||||
auth: options.auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
return {
|
||||
id,
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { EmbeddingRoute } from "../route/embedding.js"
|
|||
import { Endpoint } from "../route/endpoint.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import {
|
||||
mergeTransport,
|
||||
ProviderConfigurationError,
|
||||
ProviderID,
|
||||
type LLMRequest,
|
||||
|
|
@ -183,7 +184,11 @@ export const configure = (input: Config = {}) => {
|
|||
message: "Google Vertex embedContent does not support Express Mode API keys; use project credentials",
|
||||
})
|
||||
return selected.route
|
||||
.with({ endpoint: target.endpoint, auth: target.auth, headers: input.headers, http: input.http })
|
||||
.with({
|
||||
endpoint: target.endpoint,
|
||||
auth: target.auth,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
.model<VertexOptionsInput & PredictOptionsInput>({ id: modelID, providerOptions })
|
||||
},
|
||||
configure,
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { Auth } from "../route/auth.js"
|
|||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import type { ProviderPackage } from "../provider-package.js"
|
||||
import { ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import { mergeTransport, ProviderID, type ModelID, type ProviderOptions, type RequestOptions } from "../schema/index.js"
|
||||
import { Gemini } from "../protocols/gemini.js"
|
||||
import {
|
||||
GoogleEmbedContent,
|
||||
|
|
@ -63,8 +63,7 @@ export const configure = (input: Config = {}) => {
|
|||
provider: id,
|
||||
endpoint: { baseURL: input.baseURL },
|
||||
auth: auth(input),
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
return {
|
||||
id,
|
||||
|
|
@ -82,7 +81,11 @@ export const configure = (input: Config = {}) => {
|
|||
embeddingRoute.model<GoogleEmbeddingOptionsInput>({ id: modelID, providerOptions }),
|
||||
decision: (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
GoogleDecisions.route
|
||||
.with({ endpoint: { baseURL: media.baseURL }, auth: media.auth, headers: media.headers, http: media.http })
|
||||
.with({
|
||||
endpoint: { baseURL: media.baseURL },
|
||||
auth: media.auth,
|
||||
...media.transport,
|
||||
})
|
||||
.model<GoogleDecisions.OptionsInput>({ id: modelID, providerOptions }),
|
||||
configure,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import {
|
||||
mergeTransport,
|
||||
mergeProviderOptions,
|
||||
ProviderID,
|
||||
type ModelID,
|
||||
|
|
@ -48,15 +49,13 @@ export const configure = (input: Config) => {
|
|||
provider,
|
||||
endpoint: { baseURL },
|
||||
auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
const decisionRoute = SystemOne.route.with({
|
||||
provider,
|
||||
endpoint: { baseURL },
|
||||
auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
return {
|
||||
id: ProviderID.make(provider),
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import type { Route, CompactionOperations } from "../route/client.js"
|
|||
import { MediaRoute } from "../route/media.js"
|
||||
import type { ProviderPackage } from "../provider-package.js"
|
||||
import {
|
||||
mergeTransport,
|
||||
ProviderID,
|
||||
ToolDefinition,
|
||||
type ModelID,
|
||||
|
|
@ -109,11 +110,10 @@ export const configure = (input: Config = {}) => {
|
|||
id,
|
||||
capabilities: { promptCacheKey: true },
|
||||
})
|
||||
const deployment = MediaRoute.deployment(input, auth(input))
|
||||
const media = {
|
||||
...deployment,
|
||||
http: { ...deployment.http, query: { ...deployment.http?.query, ...input.queryParams } },
|
||||
}
|
||||
const media = MediaRoute.deployment(
|
||||
{ ...mergeTransport(input, { http: { query: input.queryParams } }), baseURL: input.baseURL },
|
||||
auth(input),
|
||||
)
|
||||
// The ChatGPT backend (ChatGPT sign-in) rejects multipart image edits with "Unsupported content type".
|
||||
const imageInput = media.baseURL?.startsWith("https://chatgpt.com/") ? "json-edits" : undefined
|
||||
const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
|
|
@ -123,16 +123,14 @@ export const configure = (input: Config = {}) => {
|
|||
const decisionRoute = OpenAIDecisions.route.with({
|
||||
endpoint: { baseURL: media.baseURL },
|
||||
auth: media.auth,
|
||||
headers: media.headers,
|
||||
http: media.http,
|
||||
...media.transport,
|
||||
})
|
||||
const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
decisionRoute.model<OpenAIDecisionOptionsInput>({ id: modelID, providerOptions })
|
||||
const embeddingRoute = OpenAIEmbeddings.route.with({
|
||||
endpoint: { baseURL: media.baseURL },
|
||||
auth: media.auth,
|
||||
headers: media.headers,
|
||||
http: media.http,
|
||||
...media.transport,
|
||||
})
|
||||
const embedding = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
embeddingRoute.model<OpenAIEmbeddingOptionsInput>({ id: modelID, providerOptions })
|
||||
|
|
|
|||
|
|
@ -1,4 +1,10 @@
|
|||
import { type HttpOptions, ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js"
|
||||
import {
|
||||
mergeTransport,
|
||||
ProviderID,
|
||||
type ModelID,
|
||||
type ProviderOptions,
|
||||
type TransportOptions,
|
||||
} from "../schema/index.js"
|
||||
import type { ProviderPackage } from "../provider-package.js"
|
||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { SystemOne } from "../protocols/system-one.js"
|
||||
|
|
@ -7,11 +13,10 @@ import { toConfig } from "./settings.js"
|
|||
export const id = ProviderID.make("opencode")
|
||||
const baseURL = "https://opencode.ai/inference/systemone/v1"
|
||||
|
||||
export type Config = ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
}
|
||||
export type Config = TransportOptions &
|
||||
ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
}
|
||||
|
||||
export type Settings = ProviderPackage.Settings & { readonly apiKey?: string | false }
|
||||
|
||||
|
|
@ -22,8 +27,7 @@ export const configure = (input: Config = {}) => {
|
|||
endpoint: { baseURL: input.baseURL ?? baseURL },
|
||||
auth: AuthOptions.bearer(input, "OPENCODE_API_KEY"),
|
||||
// Zen forwards TypeSafe's image opt-in header; text-only requests are unchanged with it.
|
||||
headers: { "TypeSafe-Danger-Zone-Images": "true", ...input.headers },
|
||||
http: input.http,
|
||||
...mergeTransport({ headers: { "TypeSafe-Danger-Zone-Images": "true" } }, input),
|
||||
})
|
||||
const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
route.model({ id: modelID, providerOptions })
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { Endpoint } from "../route/endpoint.js"
|
|||
import { Protocol } from "../route/protocol.js"
|
||||
import type { ProviderAuthOption } from "../route/auth-options.js"
|
||||
import {
|
||||
mergeTransport,
|
||||
ProviderID,
|
||||
type ModelID,
|
||||
type OpenString,
|
||||
|
|
@ -268,8 +269,7 @@ export const configure = (input: Config = {}) => {
|
|||
providerMetadataKey: "openrouter",
|
||||
endpoint: options.endpoint,
|
||||
auth: options.auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
const media = MediaRoute.deployment({ ...input, baseURL: options.endpoint.baseURL }, options.auth)
|
||||
const image = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
|
|
@ -293,8 +293,7 @@ export const configure = (input: Config = {}) => {
|
|||
provider: id,
|
||||
endpoint: options.endpoint,
|
||||
auth: options.auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
const embedding = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
embeddingRoute.model<OpenRouterEmbeddingOptions>({ id: modelID, providerOptions })
|
||||
|
|
|
|||
|
|
@ -1,4 +1,10 @@
|
|||
import { type HttpOptions, ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js"
|
||||
import {
|
||||
mergeTransport,
|
||||
ProviderID,
|
||||
type ModelID,
|
||||
type ProviderOptions,
|
||||
type TransportOptions,
|
||||
} from "../schema/index.js"
|
||||
import type { ProviderPackage } from "../provider-package.js"
|
||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { SystemOne } from "../protocols/system-one.js"
|
||||
|
|
@ -7,11 +13,10 @@ import { toConfig } from "./settings.js"
|
|||
export const id = ProviderID.make("typesafe-ai")
|
||||
const baseURL = "https://api.typesafe.ai/v1"
|
||||
|
||||
export type Config = ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
}
|
||||
export type Config = TransportOptions &
|
||||
ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
}
|
||||
|
||||
export type Settings = ProviderPackage.Settings & { readonly apiKey?: string | false }
|
||||
|
||||
|
|
@ -22,8 +27,7 @@ export const configure = (input: Config = {}) => {
|
|||
endpoint: { baseURL: input.baseURL ?? baseURL },
|
||||
auth: AuthOptions.bearer(input, "TYPESAFE_API_KEY"),
|
||||
// Required for images; text-only requests are unchanged with it.
|
||||
headers: { "TypeSafe-Danger-Zone-Images": "true", ...input.headers },
|
||||
http: input.http,
|
||||
...mergeTransport({ headers: { "TypeSafe-Danger-Zone-Images": "true" } }, input),
|
||||
})
|
||||
const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
route.model({ id: modelID, providerOptions })
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ import { Framing } from "../route/framing.js"
|
|||
import { MediaRoute } from "../route/media.js"
|
||||
import type { Protocol } from "../route/protocol.js"
|
||||
import {
|
||||
mergeTransport,
|
||||
type LLMRequest,
|
||||
ModelID,
|
||||
ProviderID,
|
||||
|
|
@ -251,8 +252,7 @@ export const configure = (input: Config = {}) => {
|
|||
provider: id,
|
||||
endpoint: { baseURL: configured.endpoint.baseURL },
|
||||
auth: configured.auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
const decision = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
decisionRoute.model({ id: modelID, providerOptions })
|
||||
|
|
@ -260,8 +260,7 @@ export const configure = (input: Config = {}) => {
|
|||
provider: id,
|
||||
endpoint: { baseURL: configured.endpoint.baseURL },
|
||||
auth: configured.auth,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
})
|
||||
const embedding = (modelID: string | ModelID, providerOptions?: ProviderOptions) =>
|
||||
embeddingRoute.model({ id: modelID, providerOptions })
|
||||
|
|
|
|||
|
|
@ -2,16 +2,15 @@ import type { ProviderPackage } from "../provider-package.js"
|
|||
import { SeedanceVideo } from "../protocols/seedance-video.js"
|
||||
import { AuthOptions, type ProviderAuthOption } from "../route/auth-options.js"
|
||||
import { MediaRoute } from "../route/media.js"
|
||||
import { type HttpOptions, ProviderID, type ModelID, type ProviderOptions } from "../schema/index.js"
|
||||
import { ProviderID, type ModelID, type ProviderOptions, type TransportOptions } from "../schema/index.js"
|
||||
import { toConfig } from "./settings.js"
|
||||
|
||||
export const id = ProviderID.make("volcengine")
|
||||
|
||||
export type Config = ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
}
|
||||
export type Config = TransportOptions &
|
||||
ProviderAuthOption<"optional"> & {
|
||||
readonly baseURL?: string
|
||||
}
|
||||
|
||||
export type Settings = ProviderPackage.Settings & {
|
||||
readonly apiKey?: string | false
|
||||
|
|
|
|||
|
|
@ -8,10 +8,16 @@ import {
|
|||
type DecisionRequest,
|
||||
type DecisionResponse,
|
||||
} from "../decision.js"
|
||||
import { ProviderID, type HttpOptions, type AIError, type ProviderOptions } from "../schema/index.js"
|
||||
import {
|
||||
mergeTransport,
|
||||
ProviderID,
|
||||
type AIError,
|
||||
type ProviderOptions,
|
||||
type TransportOptions,
|
||||
} from "../schema/index.js"
|
||||
import { Auth } from "./auth.js"
|
||||
import { Endpoint } from "./endpoint.js"
|
||||
import { RequestExecutorService } from "./executor-service.js"
|
||||
import { RequestExecutor } from "./executor.js"
|
||||
import { MediaProtocol } from "./media-protocol.js"
|
||||
import { MediaRoute, type Execute } from "./media.js"
|
||||
|
||||
|
|
@ -32,26 +38,23 @@ export interface Protocol {
|
|||
|
||||
export const protocol = (input: Protocol) => input
|
||||
|
||||
export interface Patch {
|
||||
/** Headers, timeouts and `http` overlays merge into the route's; every model of the route starts from them. */
|
||||
export interface Patch extends TransportOptions {
|
||||
readonly id?: string
|
||||
readonly provider?: string | ProviderID
|
||||
/** ProviderMetadata namespace for responses; defaults to the provider. */
|
||||
readonly providerMetadataKey?: string
|
||||
readonly endpoint?: Endpoint.EndpointPatch<MediaProtocol.Body, DecisionRequest>
|
||||
readonly auth?: Auth.Definition
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
}
|
||||
|
||||
export interface Route {
|
||||
export interface Route extends TransportOptions {
|
||||
readonly id: string
|
||||
readonly provider: ProviderID
|
||||
readonly providerMetadataKey: string
|
||||
readonly protocol: Protocol
|
||||
readonly endpoint: Endpoint.Definition<MediaProtocol.Body, DecisionRequest>
|
||||
readonly auth: Auth.Definition
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
readonly with: (patch: Patch) => Route
|
||||
readonly model: <Options extends DecisionOptions = DecisionOptions>(input: {
|
||||
readonly id: string
|
||||
|
|
@ -76,8 +79,7 @@ export const make = (input: MakeInput): Route => {
|
|||
protocol: input.protocol,
|
||||
endpoint: input.endpoint,
|
||||
auth: input.auth ?? Auth.none,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
}
|
||||
return {
|
||||
...route,
|
||||
|
|
@ -89,8 +91,7 @@ export const make = (input: MakeInput): Route => {
|
|||
providerMetadataKey:
|
||||
patch.providerMetadataKey ?? (patch.provider === undefined ? route.providerMetadataKey : undefined),
|
||||
endpoint: patch.endpoint === undefined ? route.endpoint : Endpoint.merge(route.endpoint, patch.endpoint),
|
||||
headers: patch.headers === undefined ? route.headers : { ...route.headers, ...patch.headers },
|
||||
http: patch.http ?? route.http,
|
||||
...mergeTransport(route, patch),
|
||||
}),
|
||||
model: <Options extends DecisionOptions>(model: {
|
||||
readonly id: string
|
||||
|
|
@ -101,7 +102,7 @@ export const make = (input: MakeInput): Route => {
|
|||
return DecisionModel.make<Options>({
|
||||
id: model.id,
|
||||
provider,
|
||||
http: route.http,
|
||||
transport: mergeTransport(route),
|
||||
providerOptions: model.providerOptions,
|
||||
compatibility:
|
||||
model.compatibility === undefined ? undefined : DecisionModelCompatibility.make(model.compatibility),
|
||||
|
|
@ -129,11 +130,11 @@ const transport = (route: Omit<Route, "with" | "model">) => {
|
|||
}),
|
||||
endpoint: route.endpoint,
|
||||
auth: route.auth,
|
||||
headers: route.headers,
|
||||
})
|
||||
return Effect.fnUntraced(function* (request: DecisionRequest, execute: Execute) {
|
||||
if (!route.protocol.inlineMedia) return yield* composed.generate(request, execute)
|
||||
const input = yield* Effect.forEach(request.input, (part) => materialize(part, execute))
|
||||
const timed = RequestExecutor.withTimeout(execute, mergeTransport(request.model.transport, request).timeout)
|
||||
const input = yield* Effect.forEach(request.input, (part) => materialize(part, timed))
|
||||
return yield* composed.generate({ ...request, input }, execute)
|
||||
})
|
||||
}
|
||||
|
|
@ -141,7 +142,7 @@ const transport = (route: Omit<Route, "with" | "model">) => {
|
|||
const materialize = (part: DecisionPart, execute: Execute) =>
|
||||
part.type === "media" && part.media.source.type === "url"
|
||||
? part.media.materialize().pipe(
|
||||
Effect.provideService(RequestExecutorService, { execute }),
|
||||
Effect.provideService(RequestExecutor.Service, { execute }),
|
||||
Effect.map((media) => ({ ...part, media })),
|
||||
)
|
||||
: Effect.succeed(part)
|
||||
|
|
|
|||
|
|
@ -7,7 +7,13 @@ import {
|
|||
type EmbeddingOptions,
|
||||
type EmbeddingRequest,
|
||||
} from "../embedding.js"
|
||||
import { ProviderID, type HttpOptions, type AIError, type ProviderOptions } from "../schema/index.js"
|
||||
import {
|
||||
mergeTransport,
|
||||
ProviderID,
|
||||
type AIError,
|
||||
type ProviderOptions,
|
||||
type TransportOptions,
|
||||
} from "../schema/index.js"
|
||||
import { Auth } from "./auth.js"
|
||||
import { Endpoint } from "./endpoint.js"
|
||||
import { MediaProtocol } from "./media-protocol.js"
|
||||
|
|
@ -28,15 +34,14 @@ export interface Protocol {
|
|||
|
||||
export const protocol = (input: Protocol) => input
|
||||
|
||||
export interface Patch {
|
||||
/** Headers, timeouts and `http` overlays merge into the route's; every model of the route starts from them. */
|
||||
export interface Patch extends TransportOptions {
|
||||
readonly id?: string
|
||||
readonly provider?: string | ProviderID
|
||||
/** ProviderMetadata namespace for responses; defaults to the provider. */
|
||||
readonly providerMetadataKey?: string
|
||||
readonly endpoint?: Endpoint.EndpointPatch<MediaProtocol.Body, EmbeddingRequest>
|
||||
readonly auth?: Auth.Definition
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
/**
|
||||
* Most values one HTTP request may carry. Longer requests are split into requests of this size, sent a few at a
|
||||
* time, and joined back in value order.
|
||||
|
|
@ -44,15 +49,13 @@ export interface Patch {
|
|||
readonly maxValues?: number
|
||||
}
|
||||
|
||||
export interface Route {
|
||||
export interface Route extends TransportOptions {
|
||||
readonly id: string
|
||||
readonly provider: ProviderID
|
||||
readonly providerMetadataKey: string
|
||||
readonly protocol: Protocol
|
||||
readonly endpoint: Endpoint.Definition<MediaProtocol.Body, EmbeddingRequest>
|
||||
readonly auth: Auth.Definition
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
readonly maxValues?: number
|
||||
readonly with: (patch: Patch) => Route
|
||||
readonly model: <Options extends EmbeddingOptions = EmbeddingOptions>(input: {
|
||||
|
|
@ -77,8 +80,7 @@ export const make = (input: MakeInput): Route => {
|
|||
protocol: input.protocol,
|
||||
endpoint: input.endpoint,
|
||||
auth: input.auth ?? Auth.none,
|
||||
headers: input.headers,
|
||||
http: input.http,
|
||||
...mergeTransport(input),
|
||||
maxValues: input.maxValues,
|
||||
}
|
||||
return {
|
||||
|
|
@ -91,8 +93,7 @@ export const make = (input: MakeInput): Route => {
|
|||
providerMetadataKey:
|
||||
patch.providerMetadataKey ?? (patch.provider === undefined ? route.providerMetadataKey : undefined),
|
||||
endpoint: patch.endpoint === undefined ? route.endpoint : Endpoint.merge(route.endpoint, patch.endpoint),
|
||||
headers: patch.headers === undefined ? route.headers : { ...route.headers, ...patch.headers },
|
||||
http: patch.http ?? route.http,
|
||||
...mergeTransport(route, patch),
|
||||
maxValues: patch.maxValues ?? route.maxValues,
|
||||
}),
|
||||
model: <Options extends EmbeddingOptions>(model: {
|
||||
|
|
@ -102,7 +103,7 @@ export const make = (input: MakeInput): Route => {
|
|||
EmbeddingModel.make<Options>({
|
||||
id: model.id,
|
||||
provider,
|
||||
http: route.http,
|
||||
transport: mergeTransport(route),
|
||||
providerOptions: model.providerOptions,
|
||||
route: { id: route.id, generate: split(route.maxValues, transport(route).generate) },
|
||||
}),
|
||||
|
|
@ -169,7 +170,6 @@ const transport = (route: Omit<Route, "with" | "model">) =>
|
|||
),
|
||||
endpoint: route.endpoint,
|
||||
auth: route.auth,
|
||||
headers: route.headers,
|
||||
})
|
||||
|
||||
export * as EmbeddingRoute from "./embedding.js"
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { Context, Effect, Stream } from "effect"
|
||||
import type { Headers, HttpClientRequest, HttpClientResponse } from "effect/http"
|
||||
import { HttpContext, type AIError } from "../schema/errors.js"
|
||||
import type { ClientTls } from "../schema/options.js"
|
||||
import { Cause, Context, Effect, Option, Schema, Stream } from "effect"
|
||||
import { HttpClientError, type Headers, type HttpClientRequest, type HttpClientResponse } from "effect/http"
|
||||
import { AIError, HttpContext, TransportError } from "../schema/errors.js"
|
||||
import type { ClientTls, RequestTimeout } from "../schema/options.js"
|
||||
|
||||
// The service tag lives in its own leaf module so `Media.Asset` (imported by the schema layer) can require the
|
||||
// executor without pulling the full executor implementation, and therefore the schema barrel, into a cycle.
|
||||
|
|
@ -32,6 +32,16 @@ export const Service = RequestExecutorService
|
|||
export const CurrentTls = Context.Reference<ClientTls | undefined>("@opencode/AI/RequestExecutor/CurrentTls", {
|
||||
defaultValue: () => undefined,
|
||||
})
|
||||
|
||||
/**
|
||||
* Per-phase HTTP timeouts for requests executed while it is set. Transports set it from `request.timeout`;
|
||||
* `RequestExecutor` applies defaults (`DEFAULT_HTTP_TIMEOUT_MS` for headers, `DEFAULT_CHUNK_TIMEOUT_MS` between
|
||||
* response chunks) whenever a phase is left unset.
|
||||
*/
|
||||
export const CurrentTimeout = Context.Reference<RequestTimeout | undefined>(
|
||||
"@opencode/AI/RequestExecutor/CurrentTimeout",
|
||||
{ defaultValue: () => undefined },
|
||||
)
|
||||
export type Service = RequestExecutorService
|
||||
|
||||
/**
|
||||
|
|
@ -83,3 +93,99 @@ export const responseHttp = (response: HttpClientResponse.HttpClientResponse) =>
|
|||
status: response.status,
|
||||
headers: headerDetails(response.headers),
|
||||
})
|
||||
|
||||
export type HttpOperation = "request" | "read"
|
||||
|
||||
const NativeTransportFailure = Schema.Struct({
|
||||
message: Schema.String,
|
||||
code: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.optionalKey(Schema.Unknown),
|
||||
})
|
||||
const decodeNativeTransportFailure = Schema.decodeUnknownOption(NativeTransportFailure)
|
||||
|
||||
const nativeTransportFailure = (error: unknown) => {
|
||||
const failure = Option.getOrUndefined(decodeNativeTransportFailure(error))
|
||||
if (!failure) return undefined
|
||||
if (failure.code !== undefined) return failure
|
||||
const cause = Option.getOrUndefined(decodeNativeTransportFailure(failure.cause))
|
||||
if (cause?.code !== undefined) return cause
|
||||
return failure
|
||||
}
|
||||
|
||||
// HTTP hooks re-wrap response bodies, so a read failure can arrive as an HttpClientError caused by
|
||||
// another HttpClientError. The innermost cause carries the native failure.
|
||||
export const rootCause = (error: unknown): unknown =>
|
||||
HttpClientError.isHttpClientError(error) && "cause" in error.reason && error.reason.cause !== undefined
|
||||
? rootCause(error.reason.cause)
|
||||
: error
|
||||
|
||||
const CONNECTION_LOST = "Connection lost while reading the response"
|
||||
|
||||
export const httpError = (input: {
|
||||
readonly error: unknown
|
||||
readonly request: HttpClientRequest.HttpClientRequest
|
||||
readonly operation: HttpOperation
|
||||
readonly http?: HttpContext
|
||||
}) => {
|
||||
const request = HttpClientError.isHttpClientError(input.error) ? input.error.request : input.request
|
||||
const transportError = (failure: { readonly message: string; readonly code?: string | undefined }) =>
|
||||
new AIError({
|
||||
reason: new TransportError({
|
||||
message: failure.message,
|
||||
cause: source,
|
||||
http: input.http,
|
||||
transport: "http",
|
||||
operation: input.operation,
|
||||
code: failure.code,
|
||||
url: request.url,
|
||||
}),
|
||||
})
|
||||
|
||||
const source = rootCause(input.error)
|
||||
const native = nativeTransportFailure(source)
|
||||
const code = native?.code
|
||||
const detail =
|
||||
code && native?.message && !native.message.includes(code) ? `${code}: ${native.message}` : native?.message
|
||||
const message = detail ?? (input.error instanceof Error ? input.error.message : undefined)
|
||||
|
||||
if (Cause.isTimeoutError(input.error) || Cause.isTimeoutError(source))
|
||||
return transportError({ message: message ?? "HTTP transport timed out", code: code ?? "Timeout" })
|
||||
if (!HttpClientError.isHttpClientError(input.error))
|
||||
return transportError({ message: message ?? "HTTP transport failed", code })
|
||||
// Effect reports every response body read failure as a DecodeError, but the raw byte stream decodes
|
||||
// nothing: provider output parsing happens later and fails as InvalidProviderOutput.
|
||||
if (input.operation === "read" && input.error.reason._tag === "DecodeError")
|
||||
return transportError({ message: detail ? `${CONNECTION_LOST}: ${detail}` : CONNECTION_LOST, code })
|
||||
if (input.error.reason._tag === "TransportError") {
|
||||
return transportError({
|
||||
message: message ?? input.error.reason.description ?? "HTTP transport failed",
|
||||
code: code ?? input.error.reason._tag,
|
||||
})
|
||||
}
|
||||
return transportError({
|
||||
message: message ?? `HTTP transport failed: ${input.error.reason._tag}`,
|
||||
code: code ?? input.error.reason._tag,
|
||||
})
|
||||
}
|
||||
|
||||
export const responseStream = (response: HttpClientResponse.HttpClientResponse): Stream.Stream<Uint8Array, AIError> =>
|
||||
response.stream.pipe(
|
||||
Stream.mapError((error) =>
|
||||
httpError({ error, request: response.request, operation: "read", http: responseHttp(response) }),
|
||||
),
|
||||
)
|
||||
|
||||
export const responseBytes = (response: HttpClientResponse.HttpClientResponse): Effect.Effect<Uint8Array, AIError> =>
|
||||
response.arrayBuffer.pipe(
|
||||
Effect.map((buffer) => new Uint8Array(buffer)),
|
||||
Effect.mapError((error) =>
|
||||
httpError({ error, request: response.request, operation: "read", http: responseHttp(response) }),
|
||||
),
|
||||
)
|
||||
|
||||
export const responseText = (response: HttpClientResponse.HttpClientResponse): Effect.Effect<string, AIError> =>
|
||||
response.text.pipe(
|
||||
Effect.mapError((error) =>
|
||||
httpError({ error, request: response.request, operation: "read", http: responseHttp(response) }),
|
||||
),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { Cause, Effect, Layer, Option, Schema, Stream } from "effect"
|
||||
import { Cause, Clock, Duration, Effect, Layer, Stream } from "effect"
|
||||
import {
|
||||
FetchHttpClient,
|
||||
Headers,
|
||||
|
|
@ -7,25 +7,43 @@ import {
|
|||
HttpClientRequest,
|
||||
HttpClientResponse,
|
||||
} from "effect/http"
|
||||
import { HttpContext, HttpRateLimitDetails, AIError, TransportError } from "../schema/index.js"
|
||||
import {
|
||||
AIError,
|
||||
DEFAULT_CHUNK_TIMEOUT_MS,
|
||||
DEFAULT_HTTP_TIMEOUT_MS,
|
||||
HttpContext,
|
||||
HttpRateLimitDetails,
|
||||
timeoutConfig,
|
||||
TransportError,
|
||||
type ClientTls,
|
||||
type HttpTimeout,
|
||||
type RequestTimeout,
|
||||
} from "../schema/index.js"
|
||||
import { classifyProviderFailure, providerErrorMessage } from "../provider-error.js"
|
||||
import {
|
||||
composeMiddleware,
|
||||
CurrentMiddleware,
|
||||
CurrentTimeout,
|
||||
CurrentTls,
|
||||
headerDetails,
|
||||
responseHttp,
|
||||
httpError,
|
||||
responseStream,
|
||||
rootCause,
|
||||
Service,
|
||||
type HttpMiddleware,
|
||||
type HttpOperation,
|
||||
type Interface,
|
||||
} from "./executor-service.js"
|
||||
import type { ClientTls } from "../schema/options.js"
|
||||
|
||||
export {
|
||||
composeMiddleware,
|
||||
CurrentMiddleware,
|
||||
CurrentTimeout,
|
||||
CurrentTls,
|
||||
responseBytes,
|
||||
responseHttp,
|
||||
responseStream,
|
||||
responseText,
|
||||
Service,
|
||||
withMiddleware,
|
||||
} from "./executor-service.js"
|
||||
|
|
@ -116,7 +134,7 @@ const statusError = (response: HttpClientResponse.HttpClientResponse) =>
|
|||
status: response.status,
|
||||
responseHeaders: headerDetails(response.headers),
|
||||
responseBody: result._tag === "Success" ? result.success : undefined,
|
||||
cause: result._tag === "Failure" ? (result.failure.cause ?? result.failure) : undefined,
|
||||
cause: result._tag === "Failure" ? rootCause(result.failure) : undefined,
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -150,86 +168,74 @@ export const httpFailure = (input: {
|
|||
})
|
||||
}
|
||||
|
||||
type HttpOperation = "request" | "read"
|
||||
const timeoutDuration = (value: HttpTimeout | undefined, fallback = DEFAULT_HTTP_TIMEOUT_MS) =>
|
||||
value === false ? Duration.infinity : Duration.millis(value ?? fallback)
|
||||
|
||||
const NativeTransportFailure = Schema.Struct({
|
||||
message: Schema.String,
|
||||
code: Schema.optionalKey(Schema.String),
|
||||
cause: Schema.optionalKey(Schema.Unknown),
|
||||
})
|
||||
const decodeNativeTransportFailure = Schema.decodeUnknownOption(NativeTransportFailure)
|
||||
|
||||
const nativeTransportFailure = (error: unknown) => {
|
||||
const failure = Option.getOrUndefined(decodeNativeTransportFailure(error))
|
||||
if (!failure) return undefined
|
||||
if (failure.code !== undefined) return failure
|
||||
const cause = Option.getOrUndefined(decodeNativeTransportFailure(failure.cause))
|
||||
if (cause?.code !== undefined) return cause
|
||||
return failure
|
||||
}
|
||||
|
||||
// HTTP hooks re-wrap response bodies, so a read failure can arrive as an HttpClientError caused by
|
||||
// another HttpClientError. The innermost cause carries the native failure.
|
||||
const rootCause = (error: unknown): unknown =>
|
||||
HttpClientError.isHttpClientError(error) && "cause" in error.reason && error.reason.cause !== undefined
|
||||
? rootCause(error.reason.cause)
|
||||
: error
|
||||
|
||||
const CONNECTION_LOST = "Connection lost while reading the response"
|
||||
|
||||
const httpError = (input: {
|
||||
readonly error: unknown
|
||||
readonly request: HttpClientRequest.HttpClientRequest
|
||||
readonly operation: HttpOperation
|
||||
readonly http?: HttpContext
|
||||
}) => {
|
||||
const request = HttpClientError.isHttpClientError(input.error) ? input.error.request : input.request
|
||||
const transportError = (failure: { readonly message: string; readonly code?: string | undefined }) =>
|
||||
new AIError({
|
||||
reason: new TransportError({
|
||||
message: failure.message,
|
||||
cause: source,
|
||||
http: input.http,
|
||||
transport: "http",
|
||||
operation: input.operation,
|
||||
code: failure.code,
|
||||
url: request.url,
|
||||
}),
|
||||
})
|
||||
|
||||
const source = rootCause(input.error)
|
||||
const native = nativeTransportFailure(source)
|
||||
const code = native?.code
|
||||
const detail =
|
||||
code && native?.message && !native.message.includes(code) ? `${code}: ${native.message}` : native?.message
|
||||
const message = detail ?? (input.error instanceof Error ? input.error.message : undefined)
|
||||
|
||||
if (Cause.isTimeoutError(input.error) || Cause.isTimeoutError(source))
|
||||
return transportError({ message: message ?? "HTTP transport timed out", code: code ?? "Timeout" })
|
||||
if (!HttpClientError.isHttpClientError(input.error))
|
||||
return transportError({ message: message ?? "HTTP transport failed", code })
|
||||
// Effect reports every response body read failure as a DecodeError, but the raw byte stream decodes
|
||||
// nothing: provider output parsing happens later and fails as InvalidProviderOutput.
|
||||
if (input.operation === "read" && input.error.reason._tag === "DecodeError")
|
||||
return transportError({ message: detail ? `${CONNECTION_LOST}: ${detail}` : CONNECTION_LOST, code })
|
||||
if (input.error.reason._tag === "TransportError") {
|
||||
return transportError({
|
||||
message: message ?? input.error.reason.description ?? "HTTP transport failed",
|
||||
code: code ?? input.error.reason._tag,
|
||||
})
|
||||
}
|
||||
return transportError({
|
||||
message: message ?? `HTTP transport failed: ${input.error.reason._tag}`,
|
||||
code: code ?? input.error.reason._tag,
|
||||
const timeoutError = (url: string, operation: HttpOperation, message: string, http?: HttpContext) =>
|
||||
new AIError({
|
||||
reason: new TransportError({
|
||||
message,
|
||||
transport: "http",
|
||||
operation,
|
||||
code: "Timeout",
|
||||
url,
|
||||
http,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
export const responseStream = (response: HttpClientResponse.HttpClientResponse): Stream.Stream<Uint8Array, AIError> =>
|
||||
response.stream.pipe(
|
||||
Stream.mapError((error) =>
|
||||
httpError({ error, request: response.request, operation: "read", http: responseHttp(response) }),
|
||||
const bodyTimeoutError = (response: HttpClientResponse.HttpClientResponse, message: string) =>
|
||||
new HttpClientError.HttpClientError({
|
||||
reason: new HttpClientError.DecodeError({
|
||||
request: response.request,
|
||||
response,
|
||||
cause: new Cause.TimeoutError(message),
|
||||
}),
|
||||
})
|
||||
|
||||
// A response with one of these statuses has no body to re-wrap.
|
||||
const NO_BODY = new Set([101, 204, 205, 304])
|
||||
|
||||
/**
|
||||
* Re-wraps the body behind the chunk and whole-request limits, so every way of reading it (`stream`, `text`, `json`,
|
||||
* `formData`, ...) fails cleanly once it stalls.
|
||||
*/
|
||||
const withBodyTimeouts = (
|
||||
raw: HttpClientResponse.HttpClientResponse,
|
||||
limits: { readonly chunk: Duration.Duration; readonly deadline: number | undefined },
|
||||
): Effect.Effect<HttpClientResponse.HttpClientResponse> => {
|
||||
if (NO_BODY.has(raw.status) || (!Duration.isFinite(limits.chunk) && limits.deadline === undefined))
|
||||
return Effect.succeed(raw)
|
||||
const chunked = raw.stream.pipe(
|
||||
Stream.catchIf(
|
||||
(error) => error.reason._tag === "EmptyBodyError",
|
||||
() => Stream.empty,
|
||||
),
|
||||
Stream.timeoutOrElse({
|
||||
duration: limits.chunk,
|
||||
orElse: () => Stream.fail(bodyTimeoutError(raw, "Timed out waiting for response data")),
|
||||
}),
|
||||
)
|
||||
const deadline = limits.deadline
|
||||
const body =
|
||||
deadline === undefined
|
||||
? chunked
|
||||
: Stream.unwrap(
|
||||
Effect.map(Clock.currentTimeMillis, (now) =>
|
||||
chunked.pipe(
|
||||
Stream.interruptWhen(
|
||||
Effect.sleep(Duration.millis(Math.max(0, deadline - now))).pipe(
|
||||
Effect.andThen(Effect.fail(bodyTimeoutError(raw, "Timed out waiting for the response to complete"))),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
return Stream.toReadableStreamEffect(body).pipe(
|
||||
Effect.map((readable) =>
|
||||
HttpClientResponse.fromWeb(raw.request, new Response(readable, { status: raw.status, headers: raw.headers })),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
export const stream = (
|
||||
executor: Interface,
|
||||
|
|
@ -247,28 +253,48 @@ export const layer: Layer.Layer<Service, never, HttpClient.HttpClient> = Layer.e
|
|||
Service,
|
||||
Effect.gen(function* () {
|
||||
const http = yield* HttpClient.HttpClient
|
||||
const executeOnce = (request: HttpClientRequest.HttpClientRequest, middleware?: HttpMiddleware) =>
|
||||
const executeOnce = (
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
middleware: HttpMiddleware | undefined,
|
||||
timeout: RequestTimeout | undefined,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
if (!middleware)
|
||||
return yield* http.execute(request).pipe(
|
||||
Effect.mapError((error) => httpError({ error, request, operation: "request" })),
|
||||
Effect.flatMap(statusError),
|
||||
)
|
||||
|
||||
const response = yield* middleware(request, (input) =>
|
||||
http
|
||||
.execute(input)
|
||||
.pipe(Effect.mapError((cause) => (cause instanceof Error ? cause : new Error(String(cause))))),
|
||||
).pipe(Effect.mapError((error) => httpError({ error, request, operation: "request" })))
|
||||
const started = yield* Clock.currentTimeMillis
|
||||
const limits = timeoutConfig(timeout)
|
||||
// Unlike the header and chunk limits, the whole-request budget has no default.
|
||||
const total = limits.total ? Duration.millis(limits.total) : Duration.infinity
|
||||
const headersLimit = Duration.min(timeoutDuration(limits.headers), total)
|
||||
const send = !middleware
|
||||
? http.execute(request).pipe(Effect.mapError((error) => httpError({ error, request, operation: "request" })))
|
||||
: middleware(request, (input) =>
|
||||
http
|
||||
.execute(input)
|
||||
.pipe(Effect.mapError((cause) => (cause instanceof Error ? cause : new Error(String(cause))))),
|
||||
).pipe(Effect.mapError((error) => httpError({ error, request, operation: "request" })))
|
||||
const raw = yield* send.pipe(
|
||||
Effect.timeoutOrElse({
|
||||
duration: headersLimit,
|
||||
orElse: () => Effect.fail(timeoutError(request.url, "request", "Timed out waiting for response headers")),
|
||||
}),
|
||||
)
|
||||
const deadline = Duration.isFinite(total) ? started + Duration.toMillis(total) : undefined
|
||||
const response = yield* withBodyTimeouts(raw, {
|
||||
chunk: timeoutDuration(limits.chunk, DEFAULT_CHUNK_TIMEOUT_MS),
|
||||
deadline,
|
||||
})
|
||||
return yield* statusError(response)
|
||||
})
|
||||
return Service.of({
|
||||
// Scoped middleware runs outside per-call middleware. It is cleared while the request runs, so a request a
|
||||
// middleware makes itself isn't wrapped again.
|
||||
// Scoped middleware and timeouts are cleared while the request runs, so a request a middleware makes itself
|
||||
// isn't wrapped again and starts with default timeouts.
|
||||
execute: (request, next) =>
|
||||
Effect.gen(function* () {
|
||||
const middleware = composeMiddleware(yield* CurrentMiddleware, next)
|
||||
return yield* executeOnce(request, middleware).pipe(Effect.provideService(CurrentMiddleware, undefined))
|
||||
const timeout = yield* CurrentTimeout
|
||||
return yield* executeOnce(request, middleware, timeout).pipe(
|
||||
Effect.provideService(CurrentMiddleware, undefined),
|
||||
Effect.provideService(CurrentTimeout, undefined),
|
||||
)
|
||||
}),
|
||||
})
|
||||
}),
|
||||
|
|
@ -283,6 +309,15 @@ export const fetchLayer = layer.pipe(Layer.provide(FetchHttpClient.layer))
|
|||
export const withTls = (execute: Interface["execute"], tls: ClientTls | undefined): Interface["execute"] =>
|
||||
tls ? (request, middleware) => execute(request, middleware).pipe(Effect.provideService(CurrentTls, tls)) : execute
|
||||
|
||||
/** Sends through `execute` with `timeout` applied to the request and its response body. */
|
||||
export const withTimeout = (
|
||||
execute: Interface["execute"],
|
||||
timeout: RequestTimeout | undefined,
|
||||
): Interface["execute"] =>
|
||||
timeout === undefined
|
||||
? execute
|
||||
: (request, middleware) => execute(request, middleware).pipe(Effect.provideService(CurrentTimeout, timeout))
|
||||
|
||||
/**
|
||||
* Per-call middleware that sends through `fetch` instead of the executor's HTTP client. Executor middleware and
|
||||
* `middleware` still wrap the call, and status classification still applies.
|
||||
|
|
|
|||
|
|
@ -206,15 +206,6 @@ export const identity = (input: { readonly id: string; readonly name: string; re
|
|||
const provider = ProviderID.make(input.provider)
|
||||
const frameError = (message: string, body?: string, cause?: unknown) =>
|
||||
new AIError({ reason: new InvalidProviderOutputError({ route: input.id, message, body, cause }) })
|
||||
const readError = (http: HttpContext) => (cause: unknown) =>
|
||||
new AIError({
|
||||
reason: new InvalidProviderOutputError({
|
||||
route: input.id,
|
||||
message: `Failed to read the ${input.name} response`,
|
||||
http,
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
|
||||
/**
|
||||
* Read a text body while retaining the original payload and HTTP context on every downstream error. `invalid` is a
|
||||
|
|
@ -225,7 +216,7 @@ export const identity = (input: { readonly id: string; readonly name: string; re
|
|||
*/
|
||||
const text = Effect.fn("MediaProtocol.text")(function* (response: HttpClientResponse.HttpClientResponse) {
|
||||
const http = RequestExecutor.responseHttp(response)
|
||||
const body = yield* response.text.pipe(Effect.mapError(readError(http)))
|
||||
const body = yield* RequestExecutor.responseText(response)
|
||||
return {
|
||||
body,
|
||||
http,
|
||||
|
|
@ -263,11 +254,7 @@ export const identity = (input: { readonly id: string; readonly name: string; re
|
|||
}
|
||||
|
||||
/** Read a raw binary body, for providers that answer with the media bytes themselves. */
|
||||
const bytes = (response: HttpClientResponse.HttpClientResponse) =>
|
||||
response.arrayBuffer.pipe(
|
||||
Effect.map((buffer) => new Uint8Array(buffer)),
|
||||
Effect.mapError(readError(RequestExecutor.responseHttp(response))),
|
||||
)
|
||||
const bytes = RequestExecutor.responseBytes
|
||||
|
||||
return {
|
||||
id: input.id,
|
||||
|
|
|
|||
|
|
@ -16,8 +16,9 @@ import {
|
|||
mergeProviderOptions,
|
||||
mergeTransport,
|
||||
type BaseRequest,
|
||||
type HttpOptions,
|
||||
type ProviderOptions,
|
||||
type RequestTimeout,
|
||||
type TransportOptions,
|
||||
} from "../schema/index.js"
|
||||
import { encodeJson } from "../utils/json.js"
|
||||
import { sanitizeSurrogates } from "../utils/sanitize.js"
|
||||
|
|
@ -28,29 +29,29 @@ export type Execute = Interface["execute"]
|
|||
export type MediaRequest = BaseRequest<{
|
||||
readonly id: string
|
||||
readonly provider: ProviderID
|
||||
readonly http?: HttpOptions
|
||||
readonly transport?: TransportOptions
|
||||
readonly providerOptions?: ProviderOptions
|
||||
}>
|
||||
|
||||
/** What every HTTP exchange of one generation shares. */
|
||||
type Exchange = Pick<MediaRequest, "headers" | "http" | "fetch">
|
||||
type Exchange = Pick<MediaRequest, "headers" | "timeout" | "http" | "fetch">
|
||||
|
||||
/** Deployment inputs every media model factory accepts; provider facades fill these from `configure(...)`. */
|
||||
export interface ModelInput {
|
||||
readonly id: string
|
||||
readonly auth: Auth.Definition
|
||||
readonly baseURL?: string
|
||||
readonly headers?: Record<string, string>
|
||||
readonly http?: HttpOptions
|
||||
/** Deployment headers, timeouts and `http` overlays every request of the model starts from. */
|
||||
readonly transport?: TransportOptions
|
||||
/** Defaults under each request's `providerOptions`. */
|
||||
readonly providerOptions?: ProviderOptions
|
||||
}
|
||||
|
||||
/** A provider facade's `configure(...)` input as the `ModelInput` every media selector shares, minus the model id. */
|
||||
export const deployment = (
|
||||
input: { readonly baseURL?: string; readonly headers?: Record<string, string>; readonly http?: HttpOptions },
|
||||
input: TransportOptions & { readonly baseURL?: string },
|
||||
auth: Auth.Definition,
|
||||
): Omit<ModelInput, "id"> => ({ auth, baseURL: input.baseURL, headers: input.headers, http: input.http })
|
||||
): Omit<ModelInput, "id"> => ({ auth, baseURL: input.baseURL, transport: mergeTransport(input) })
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Routes
|
||||
|
|
@ -104,7 +105,7 @@ export type AnyRoute<Request extends MediaRequest, Event, Response> =
|
|||
export interface Composition<Request extends MediaRequest> {
|
||||
readonly endpoint: Endpoint.Definition<MediaProtocol.Body, Request>
|
||||
readonly auth: Auth.Definition
|
||||
/** Deployment headers applied before transport authentication. */
|
||||
/** Headers the protocol requires on every call; the model's transport headers win. */
|
||||
readonly headers?: Record<string, string>
|
||||
}
|
||||
|
||||
|
|
@ -343,6 +344,7 @@ const makeTransport = <Request extends MediaRequest>(
|
|||
readonly headers: Headers.Headers
|
||||
readonly request: AuthInput["request"]
|
||||
readonly body?: MediaProtocol.Body
|
||||
readonly timeout?: RequestTimeout
|
||||
},
|
||||
fetch: typeof globalThis.fetch | undefined,
|
||||
execute: Execute,
|
||||
|
|
@ -356,7 +358,10 @@ const makeTransport = <Request extends MediaRequest>(
|
|||
body: encoded.text,
|
||||
headers: encoded.headers,
|
||||
})
|
||||
const response = yield* RequestExecutor.withTls(execute, call.request.http?.tls)(
|
||||
const response = yield* RequestExecutor.withTimeout(
|
||||
RequestExecutor.withTls(execute, call.request.http?.tls),
|
||||
call.timeout,
|
||||
)(
|
||||
encoded.apply(HttpClientRequest.make(call.method)(url).pipe(HttpClientRequest.setHeaders(headers))),
|
||||
RequestExecutor.withFetch(fetch),
|
||||
)
|
||||
|
|
@ -364,7 +369,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 }, model.transport),
|
||||
/** POST the protocol body to the route endpoint. */
|
||||
submit: Effect.fn("MediaRoute.submit")(function* (
|
||||
request: Request,
|
||||
|
|
@ -376,8 +381,12 @@ 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 exchange = { headers: merged, http, fetch: request.fetch }
|
||||
const {
|
||||
headers: merged,
|
||||
timeout,
|
||||
http,
|
||||
} = mergeTransport({ headers: input.headers }, request.model.transport, request)
|
||||
const exchange = { headers: merged, timeout, http, fetch: request.fetch }
|
||||
const providerOptions = mergeProviderOptions(request.model.providerOptions, request.providerOptions)
|
||||
const headers = Headers.fromInput(merged)
|
||||
const prepared =
|
||||
|
|
@ -385,7 +394,7 @@ const makeTransport = <Request extends MediaRequest>(
|
|||
? request
|
||||
: yield* protocol.prepare(request, (path, body) =>
|
||||
send(
|
||||
{ method: "POST", url: baseURL(path), headers, request: { ...request, http }, body },
|
||||
{ method: "POST", url: baseURL(path), headers, request: { ...request, http }, body, timeout },
|
||||
request.fetch,
|
||||
execute,
|
||||
).pipe(Effect.map((sent) => sent.response)),
|
||||
|
|
@ -403,7 +412,11 @@ const makeTransport = <Request extends MediaRequest>(
|
|||
),
|
||||
http?.query,
|
||||
)
|
||||
const sent = yield* send({ method: "POST", url, headers, request: resolved, body }, request.fetch, execute)
|
||||
const sent = yield* send(
|
||||
{ method: "POST", url, headers, request: resolved, body, timeout },
|
||||
request.fetch,
|
||||
execute,
|
||||
)
|
||||
return { response: sent.response, context: { request: resolved, body }, exchange }
|
||||
}),
|
||||
/**
|
||||
|
|
@ -426,7 +439,11 @@ const makeTransport = <Request extends MediaRequest>(
|
|||
const url = withQuery(/^https?:\/\//.test(path) ? new URL(path) : baseURL(path), exchange.http?.query)
|
||||
for (const [key, value] of Object.entries(input.endpoint.query ?? {})) url.searchParams.set(key, value)
|
||||
const headers = Headers.fromInput(exchange.headers)
|
||||
return send({ method, url, headers, request: { http: exchange.http } }, exchange.fetch, execute)
|
||||
return send(
|
||||
{ method, url, headers, request: { http: exchange.http }, timeout: exchange.timeout },
|
||||
exchange.fetch,
|
||||
execute,
|
||||
)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,21 +1,11 @@
|
|||
import { Clock, Duration, Effect, Stream } from "effect"
|
||||
import { Effect } from "effect"
|
||||
import { Headers, HttpClientRequest } from "effect/http"
|
||||
import { Auth } from "../auth.js"
|
||||
import { render as renderEndpoint } from "../endpoint.js"
|
||||
import { Framing } from "../framing.js"
|
||||
import type { HttpMiddleware, Transport, TransportPrepareInput } from "./index.js"
|
||||
import * as ProviderShared from "../../protocols/shared.js"
|
||||
import {
|
||||
AIError,
|
||||
DEFAULT_CHUNK_TIMEOUT_MS,
|
||||
DEFAULT_HTTP_TIMEOUT_MS,
|
||||
mergeJsonRecords,
|
||||
timeoutConfig,
|
||||
TransportError,
|
||||
type HttpContext,
|
||||
type HttpTimeout,
|
||||
type LLMRequest,
|
||||
} from "../../schema/index.js"
|
||||
import { mergeJsonRecords, type LLMRequest } from "../../schema/index.js"
|
||||
import { RequestExecutor } from "../executor.js"
|
||||
|
||||
export type JsonRequestInput<Body> = TransportPrepareInput<Body>
|
||||
|
|
@ -94,56 +84,19 @@ export const httpJson = <Body, Frame>(input: HttpJsonInput<Body, Frame>): HttpJs
|
|||
}),
|
||||
execute: (prepared, request, runtime) =>
|
||||
Effect.gen(function* () {
|
||||
const timeout = (operation: "request" | "read", message: string, http?: HttpContext) =>
|
||||
new AIError({
|
||||
reason: new TransportError({
|
||||
message,
|
||||
transport: "http",
|
||||
operation,
|
||||
code: "Timeout",
|
||||
url: prepared.request.url,
|
||||
http,
|
||||
}),
|
||||
})
|
||||
const started = yield* Clock.currentTimeMillis
|
||||
const limits = timeoutConfig(request.timeout)
|
||||
// Unlike the header and chunk limits, the whole-request budget has no default.
|
||||
const total = limits.total ? Duration.millis(limits.total) : Duration.infinity
|
||||
const response = yield* RequestExecutor.withTls(runtime.http.execute, request.http?.tls)(
|
||||
prepared.request,
|
||||
prepared.middleware,
|
||||
).pipe(
|
||||
Effect.timeoutOrElse({
|
||||
duration: Duration.min(timeoutDuration(limits.headers), total),
|
||||
orElse: () => timeout("request", "Timed out waiting for response headers"),
|
||||
}),
|
||||
)
|
||||
const http = RequestExecutor.responseHttp(response)
|
||||
const remaining = Duration.subtract(total, Duration.millis((yield* Clock.currentTimeMillis) - started))
|
||||
const response = yield* RequestExecutor.withTimeout(
|
||||
RequestExecutor.withTls(runtime.http.execute, request.http?.tls),
|
||||
request.timeout,
|
||||
)(prepared.request, prepared.middleware)
|
||||
return {
|
||||
frames: prepared.framing.frame(
|
||||
RequestExecutor.responseStream(response).pipe(
|
||||
Stream.timeoutOrElse({
|
||||
duration: timeoutDuration(limits.chunk, DEFAULT_CHUNK_TIMEOUT_MS),
|
||||
orElse: () => Stream.fail(timeout("read", "Timed out waiting for response data", http)),
|
||||
}),
|
||||
Stream.interruptWhen(
|
||||
Effect.sleep(remaining).pipe(
|
||||
Effect.andThen(Effect.fail(timeout("read", "Timed out waiting for the response to complete", http))),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
http,
|
||||
frames: prepared.framing.frame(RequestExecutor.responseStream(response)),
|
||||
http: RequestExecutor.responseHttp(response),
|
||||
body: prepared.framing.body,
|
||||
raw: prepared.framing.raw,
|
||||
}
|
||||
}),
|
||||
})
|
||||
|
||||
const timeoutDuration = (value: HttpTimeout | undefined, fallback = DEFAULT_HTTP_TIMEOUT_MS) =>
|
||||
value === false ? Duration.infinity : Duration.millis(value ?? fallback)
|
||||
|
||||
export const sseJson = {
|
||||
id: "http-json/sse",
|
||||
with: <Body>() => httpJson<Body, string>({ framing: Framing.sse }),
|
||||
|
|
|
|||
|
|
@ -206,7 +206,8 @@ export class AIError extends Schema.TaggedError<AIError>()("AI.Error", {
|
|||
// Read failures can still recover; the caller chooses retry versus continuation from durable output.
|
||||
case "Transport":
|
||||
return (
|
||||
this.reason.delivery !== "rejected" && (this.reason.delivery !== "accepted" || this.reason.operation === "read")
|
||||
this.reason.delivery !== "rejected" &&
|
||||
(this.reason.delivery !== "accepted" || this.reason.operation === "read")
|
||||
)
|
||||
case "InvalidProviderOutput":
|
||||
return this.reason.classification === "incomplete-stream"
|
||||
|
|
|
|||
|
|
@ -100,7 +100,7 @@ export type RequestTimeout = HttpTimeout | TimeoutConfig
|
|||
export interface TransportOptions {
|
||||
/** Merged over the provider's headers; these win. */
|
||||
readonly headers?: Record<string, string>
|
||||
/** Applied to text requests; media requests do not apply it yet. */
|
||||
/** Applied to every HTTP request. */
|
||||
readonly timeout?: RequestTimeout
|
||||
readonly http?: HttpOptions
|
||||
}
|
||||
|
|
|
|||
|
|
@ -51,7 +51,7 @@ export class SpeechModel<Options extends SpeechOptions = SpeechOptions> extends
|
|||
return new SpeechModel<Options>({
|
||||
id: input.id,
|
||||
provider: route.protocol.provider,
|
||||
http: input.http,
|
||||
transport: input.transport,
|
||||
providerOptions: input.providerOptions,
|
||||
route: composeRoute(route, input, collectResponse) as SpeechRoute,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -35,9 +35,7 @@ export const dispatch = (tools: ReadonlyArray<Tool>, call: ToolCallPart): Effect
|
|||
|
||||
return decodeAndExecute(tool, call).pipe(
|
||||
Effect.map((value) => result(call, value)),
|
||||
Effect.catchTag("Tool.Error", (failure) =>
|
||||
Effect.succeed(result(call, { type: "error", value: failure.message })),
|
||||
),
|
||||
Effect.catchTag("Tool.Error", (failure) => Effect.succeed(result(call, { type: "error", value: failure.message }))),
|
||||
)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -52,7 +52,7 @@ export class TranscriptionModel<Options extends TranscriptionOptions = Transcrip
|
|||
return new TranscriptionModel<Options>({
|
||||
id: input.id,
|
||||
provider: route.protocol.provider,
|
||||
http: input.http,
|
||||
transport: input.transport,
|
||||
providerOptions: input.providerOptions,
|
||||
route: composeRoute(route, input, collectResponse) as TranscriptionRoute,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -33,7 +33,7 @@ export class VideoModel<Options extends VideoOptions = VideoOptions> extends Med
|
|||
return new VideoModel<Options>({
|
||||
id: input.id,
|
||||
provider: route.protocol.provider,
|
||||
http: input.http,
|
||||
transport: input.transport,
|
||||
providerOptions: input.providerOptions,
|
||||
route: composeQueuedRoute(route, input) as VideoRoute,
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,18 +1,22 @@
|
|||
import { describe, expect } from "bun:test"
|
||||
import { Deferred, Effect, Fiber } from "effect"
|
||||
import { Deferred, Effect, Fiber, Layer, Redacted, Stream } from "effect"
|
||||
import * as TestClock from "effect/testing/TestClock"
|
||||
import { ai } from "../src/effect.js"
|
||||
import { LLMClient, mergeTransport } from "../src/route.js"
|
||||
import { configure } from "../src/providers/openai.js"
|
||||
import { dynamicResponse } from "./lib/http.js"
|
||||
import { ai, AIClient, type AIError, Media } from "../src/effect.js"
|
||||
import { Realtime } from "../src/experimental.js"
|
||||
import { LLMClient, mergeTransport, RequestExecutor } from "../src/route.js"
|
||||
import { AssemblyAI, BytePlus, OpenAI } from "../src/providers.js"
|
||||
import { dynamicResponse, handlerLayer } from "./lib/http.js"
|
||||
import { deltaChunk, finishChunk } from "./lib/openai-chunks.js"
|
||||
import { sseEvents, sseRaw } from "./lib/sse.js"
|
||||
import { it } from "./lib/effect.js"
|
||||
|
||||
const model = configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }).chat("gpt-4.1-mini")
|
||||
const openai = OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" })
|
||||
const model = openai.chat("gpt-4.1-mini")
|
||||
const video = BytePlus.configure({ baseURL: "https://api.byteplus.test/v3", apiKey: "test" }).video("seedance-1-5")
|
||||
const SSE = { headers: { "content-type": "text/event-stream" } }
|
||||
|
||||
const silentServer = dynamicResponse(() => Effect.never)
|
||||
const silentClients = AIClient.layerWith(RequestExecutor.layer.pipe(Layer.provide(handlerLayer(() => Effect.never))))
|
||||
|
||||
const slowHeadersServer = dynamicResponse((input) =>
|
||||
Effect.sleep("10 minutes").pipe(
|
||||
|
|
@ -171,4 +175,112 @@ describe("HTTP transport timeouts", () => {
|
|||
expect(mergeTransport({}, undefined)).toEqual({})
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("applies provider-configured timeouts to every API method", () =>
|
||||
Effect.gen(function* () {
|
||||
const timeout = { headers: 1_000 }
|
||||
const timedOpenAI = OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test", timeout })
|
||||
const timedVideo = BytePlus.configure({ baseURL: "https://api.byteplus.test/v3", apiKey: "test", timeout }).video(
|
||||
"seedance-1-5",
|
||||
)
|
||||
const timedTranscription = AssemblyAI.configure({
|
||||
baseURL: "https://assemblyai.test",
|
||||
apiKey: "test",
|
||||
timeout,
|
||||
}).transcription("universal-2")
|
||||
const audio = Media.bytes(Uint8Array.from([0x49, 0x44, 0x33, 1, 2, 3]), "audio/mpeg")
|
||||
const image = timedOpenAI.image("gpt-image-2")
|
||||
const chat = { model: timedOpenAI.chat("gpt-4.1-mini"), prompt: "Hello" }
|
||||
const drain = <A, E, R>(stream: Stream.Stream<A, E, R>) => Stream.runDrain(stream)
|
||||
|
||||
// Every callable method on `ai` must be listed here (as a provider call or a local helper), so a new method
|
||||
// cannot ship without timeout coverage.
|
||||
const calls: Record<string, Effect.Effect<unknown, AIError, AIClient.Services>> = {
|
||||
generate: ai.generate(chat),
|
||||
stream: drain(ai.stream(chat)),
|
||||
loop: drain(ai.loop(chat)),
|
||||
compact: ai.compact(ai.request({ model: timedOpenAI.responses("gpt-5"), prompt: "Hello" })),
|
||||
"image.generate": ai.image.generate({ model: image, prompt: "A kite" }),
|
||||
"image.stream": drain(ai.image.stream({ model: image, prompt: "A kite" })),
|
||||
"image.start": ai.image.start({ model: image, prompt: "A kite" }),
|
||||
"image.status": ai.image.status(image, "job"),
|
||||
"image.result": ai.image.result(image, "job"),
|
||||
"image.cancel": ai.image.cancel(image, "job"),
|
||||
"decision.generate": ai.decision.generate({
|
||||
model: timedOpenAI.decision("gpt-6-luna"),
|
||||
input: "hello",
|
||||
questions: [{ name: "greeting", type: "choice", instructions: "Greeting?", choices: [{ value: true }] }],
|
||||
}),
|
||||
"embedding.generate": ai.embedding.generate({
|
||||
model: timedOpenAI.embedding("text-embedding-3-small"),
|
||||
values: ["hello"],
|
||||
}),
|
||||
"video.start": ai.video.start({ model: timedVideo, prompt: "A kite" }),
|
||||
"video.status": ai.video.status(timedVideo, "job"),
|
||||
"video.result": ai.video.result(timedVideo, "job"),
|
||||
"video.cancel": ai.video.cancel(timedVideo, "job"),
|
||||
"experimental.speech.generate": ai.experimental.speech.generate({
|
||||
model: timedOpenAI.speech("gpt-4o-mini-tts"),
|
||||
text: "Hello",
|
||||
}),
|
||||
"experimental.speech.stream": drain(
|
||||
ai.experimental.speech.stream({ model: timedOpenAI.speech("gpt-4o-mini-tts"), text: "Hello" }),
|
||||
),
|
||||
"experimental.transcription.generate": ai.experimental.transcription.generate({
|
||||
model: timedTranscription,
|
||||
audio,
|
||||
}),
|
||||
"experimental.transcription.stream": drain(
|
||||
ai.experimental.transcription.stream({ model: timedTranscription, audio }),
|
||||
),
|
||||
"experimental.transcription.start": ai.experimental.transcription.start({ model: timedTranscription, audio }),
|
||||
"experimental.transcription.resume": ai.experimental.transcription.resume(timedTranscription, {
|
||||
transcriptID: "tr_1",
|
||||
}),
|
||||
}
|
||||
const local = [
|
||||
"request",
|
||||
"collect",
|
||||
"canCompact",
|
||||
"image.request",
|
||||
"decision.request",
|
||||
"embedding.request",
|
||||
"video.request",
|
||||
"experimental.speech.request",
|
||||
"experimental.transcription.request",
|
||||
]
|
||||
const listMethods = (value: object, prefix = ""): Array<string> =>
|
||||
Object.entries(value).flatMap(([key, entry]) => {
|
||||
if (typeof entry === "function") return [`${prefix}${key}`]
|
||||
if (typeof entry === "object" && entry !== null) return listMethods(entry, `${prefix}${key}.`)
|
||||
return []
|
||||
})
|
||||
expect(listMethods(ai).toSorted()).toEqual([...Object.keys(calls), ...local].toSorted())
|
||||
|
||||
const check = (effect: Effect.Effect<unknown, AIError, AIClient.Services>) =>
|
||||
Effect.gen(function* () {
|
||||
const fiber = yield* effect.pipe(
|
||||
Effect.provide(silentClients),
|
||||
Effect.flip,
|
||||
Effect.forkChild({ startImmediately: true }),
|
||||
)
|
||||
// Retried status/result reads make up to 9 attempts with exponential backoff (< 4 min total, still under
|
||||
// the 5 min default header timeout), so finishing here proves the 1 s configured timeout applied.
|
||||
for (let i = 0; i < 240 && fiber.pollUnsafe() === undefined; i++) yield* TestClock.adjust("1 second")
|
||||
const error = yield* Fiber.join(fiber)
|
||||
if (error.reason._tag === "UnsupportedOperation") return
|
||||
expect(error.reason).toMatchObject({ _tag: "Transport", operation: "request", code: "Timeout" })
|
||||
})
|
||||
|
||||
for (const effect of Object.values(calls)) yield* check(effect)
|
||||
yield* check(
|
||||
Realtime.connect({
|
||||
model: "gpt-realtime",
|
||||
apiKey: Redacted.make("test"),
|
||||
transport: { type: "websocket" },
|
||||
timeout,
|
||||
}),
|
||||
)
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -40,8 +40,11 @@ export const json = (input: HandlerInput, value: unknown, init?: ResponseInit) =
|
|||
/** Fork the polling program, let the test clock cover `seconds` of polling, and join. */
|
||||
export const settle = <A, E, R>(program: Effect.Effect<A, E, R>, seconds: number) =>
|
||||
Effect.gen(function* () {
|
||||
const fiber = yield* Effect.forkChild(program)
|
||||
yield* TestClock.adjust(`${seconds} seconds`)
|
||||
const fiber = yield* Effect.forkChild(program, { startImmediately: true })
|
||||
for (let i = 0; i < seconds && fiber.pollUnsafe() === undefined; i++) {
|
||||
yield* TestClock.withLive(Effect.sleep("1 millis"))
|
||||
yield* TestClock.adjust("1 second")
|
||||
}
|
||||
return yield* Fiber.join(fiber)
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -1,12 +1,11 @@
|
|||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Fiber, Layer, Stream } from "effect"
|
||||
import * as TestClock from "effect/testing/TestClock"
|
||||
import { Effect, Layer, Stream } from "effect"
|
||||
import { HttpClientRequest } from "effect/http"
|
||||
import { Media } from "../src/effect.js"
|
||||
import { Transcription, TranscriptionClient, type TranscriptionEvent } from "../src/experimental.js"
|
||||
import { AssemblyAI, Deepgram, ElevenLabs, Google, OpenAI } from "../src/providers.js"
|
||||
import { it } from "./lib/effect.js"
|
||||
import { dynamicResponse, json, observe, type Call } from "./lib/http.js"
|
||||
import { dynamicResponse, json, observe, settle, type Call } from "./lib/http.js"
|
||||
import { sseEvents } from "./lib/sse.js"
|
||||
|
||||
const layer = (handler: Parameters<typeof dynamicResponse>[0]) =>
|
||||
|
|
@ -408,9 +407,7 @@ describe("Transcription", () => {
|
|||
),
|
||||
)
|
||||
|
||||
const fiber = yield* Effect.forkChild(program)
|
||||
yield* TestClock.adjust("5 seconds")
|
||||
const { response, failure } = yield* Fiber.join(fiber)
|
||||
const { response, failure } = yield* settle(program, 5)
|
||||
|
||||
expect(calls.slice(0, 2).map((call) => [call.method, call.url, call.auth])).toEqual([
|
||||
["POST", "https://assemblyai.test/v2/upload", "aai-key"],
|
||||
|
|
|
|||
|
|
@ -386,7 +386,9 @@ describe("ai.video / transient read failures", () => {
|
|||
),
|
||||
),
|
||||
),
|
||||
{ startImmediately: true },
|
||||
)
|
||||
yield* TestClock.withLive(Effect.sleep("1 millis"))
|
||||
yield* TestClock.adjust("9 seconds")
|
||||
expect(calls).toHaveLength(1)
|
||||
yield* TestClock.adjust("1 second")
|
||||
|
|
|
|||
|
|
@ -320,6 +320,7 @@ const fromCatalogMedia = Effect.fn("ModelResolver.fromCatalogMedia")(function* <
|
|||
dependencies?: Dependencies,
|
||||
) {
|
||||
const { resolved, configured, module, settings } = yield* loadCatalogPackage(model, credential, dependencies)
|
||||
const timeouts = Provider.timeouts(configured)
|
||||
const tls = Provider.tls(configured)
|
||||
const runtime: unknown = yield* Effect.try({
|
||||
try: () => module.model(resolved.modelID ?? resolved.id, settings),
|
||||
|
|
@ -335,10 +336,14 @@ const fromCatalogMedia = Effect.fn("ModelResolver.fromCatalogMedia")(function* <
|
|||
})
|
||||
: runtime
|
||||
if (!is(adapted)) return yield* unsupported(resolved)
|
||||
if (!tls || !(adapted instanceof DecisionModel || adapted instanceof ImageModel)) return adapted
|
||||
if (!(adapted instanceof DecisionModel || adapted instanceof ImageModel || adapted instanceof VideoModel))
|
||||
return adapted
|
||||
// Media and decision models are plain classes with readonly fields, so copy onto the same prototype.
|
||||
const copy: Runtime = Object.assign(Object.create(Object.getPrototypeOf(adapted)), adapted, {
|
||||
http: { ...adapted.http, tls },
|
||||
transport: mergeTransport(adapted.transport, {
|
||||
timeout: { total: timeouts.timeout, headers: timeouts.headerTimeout, chunk: timeouts.chunkTimeout },
|
||||
http: { tls },
|
||||
}),
|
||||
})
|
||||
return copy
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1616,6 +1616,86 @@ describe("ModelResolver", () => {
|
|||
}),
|
||||
)
|
||||
|
||||
it.effect("applies provider timeouts to resolved image, video, and decision models", () =>
|
||||
Effect.gen(function* () {
|
||||
const settings = { apiKey: "secret", timeout: 12_000, headerTimeout: 3_000, chunkTimeout: 4_000 }
|
||||
const providerID = Provider.ID.make("timed")
|
||||
const entries = [
|
||||
model("@opencode/ai/providers/openai/images", { providerID, modelID: "gpt-image-2", settings }),
|
||||
model("@opencode/ai/providers/xai/videos", { providerID, modelID: "grok-imagine-video-1.5", settings }),
|
||||
model("@opencode/ai/providers/google/decisions", { providerID, modelID: "gemini-2.5-flash", settings }),
|
||||
].map((entry, index) =>
|
||||
Info.make({
|
||||
...entry,
|
||||
id: ID.make(["img", "vid", "dec"][index]!),
|
||||
type: (["image", "video", "decision"] as const)[index],
|
||||
}),
|
||||
)
|
||||
const provider = Provider.Info.make({
|
||||
...Provider.Info.empty(providerID),
|
||||
activation: "enabled",
|
||||
settings,
|
||||
})
|
||||
const resolverLayer = ModelResolver.layer.pipe(
|
||||
Layer.provide(Layer.mock(Provider.Service, { get: () => Effect.succeed(provider) })),
|
||||
Layer.provide(
|
||||
Layer.mock(Model.Service, {
|
||||
available: (types) =>
|
||||
Effect.succeed(entries.filter((entry) => !types || types.includes(entry.type ?? "chat"))),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(Integration.Service, {
|
||||
revision: () => 0,
|
||||
connection: {
|
||||
active: () => Effect.undefined,
|
||||
resolve: () => Effect.die("unused"),
|
||||
key: () => Effect.die("unused"),
|
||||
external: () => Effect.die("unused"),
|
||||
activate: () => Effect.die("unused"),
|
||||
update: () => Effect.die("unused"),
|
||||
remove: () => Effect.die("unused"),
|
||||
status: () => Effect.die("unused"),
|
||||
},
|
||||
oauth: {
|
||||
connect: () => Effect.die("unused"),
|
||||
status: () => Effect.die("unused"),
|
||||
complete: () => Effect.die("unused"),
|
||||
cancel: () => Effect.die("unused"),
|
||||
},
|
||||
command: {
|
||||
connect: () => Effect.die("unused"),
|
||||
status: () => Effect.die("unused"),
|
||||
cancel: () => Effect.die("unused"),
|
||||
},
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
Layer.mock(AISDK.Service, {
|
||||
hook: {
|
||||
sdk: () => Effect.die("unused"),
|
||||
language: () => Effect.die("unused"),
|
||||
},
|
||||
model: () => Effect.die("unused"),
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.mock(Npm.Service, {})),
|
||||
)
|
||||
|
||||
const resolver = yield* ModelResolver.Service.pipe(Effect.provide(resolverLayer))
|
||||
const [image, video, decision] = yield* Effect.all([
|
||||
resolver.resolveImage({ providerID, id: ID.make("img") }),
|
||||
resolver.resolveVideo({ providerID, id: ID.make("vid") }),
|
||||
resolver.resolveDecision({ providerID, id: ID.make("dec") }),
|
||||
])
|
||||
|
||||
const expected = { total: 12_000, headers: 3_000, chunk: 4_000 }
|
||||
expect(image?.transport?.timeout).toEqual(expected)
|
||||
expect(video?.transport?.timeout).toEqual(expected)
|
||||
expect(decision?.transport?.timeout).toEqual(expected)
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("reports whether a catalog model declares a provider package", () =>
|
||||
Effect.sync(() => {
|
||||
expect(ModelResolver.hasPackage(model(Provider.aisdk("@ai-sdk/openai")))).toBe(true)
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue