Skip to content

Commit 73215c5

Browse files
authored
fix(ai): apply HTTP timeouts to all requests (anomalyco#64692)
1 parent 102efff commit 73215c5

51 files changed

Lines changed: 746 additions & 450 deletions

Some content is hidden

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

‎packages/ai/src/decision.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { tryRequest } from "./media-model.js"
55
import {
66
AIError,
77
type BaseRequest,
8-
type HttpOptions,
8+
type TransportOptions,
99
ModelID,
1010
ProviderID,
1111
ProviderMetadata,
@@ -200,7 +200,8 @@ export class DecisionModel<Options extends DecisionOptions = DecisionOptions> {
200200
readonly id: ModelID
201201
readonly provider: ProviderID
202202
readonly route: DecisionModelRoute<Options>
203-
readonly http?: HttpOptions
203+
/** Deployment headers, timeouts and `http` overlays, below each request's own. */
204+
readonly transport?: TransportOptions
204205
readonly compatibility?: DecisionModelCompatibility
205206
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
206207
readonly providerOptions?: ProviderOptions
@@ -209,7 +210,7 @@ export class DecisionModel<Options extends DecisionOptions = DecisionOptions> {
209210
this.id = input.id
210211
this.provider = input.provider
211212
this.route = input.route
212-
this.http = input.http
213+
this.transport = input.transport
213214
this.compatibility = input.compatibility
214215
this.providerOptions = input.providerOptions
215216
}
@@ -228,7 +229,7 @@ export namespace DecisionModel {
228229
readonly id: ModelID
229230
readonly provider: ProviderID
230231
readonly route: DecisionModelRoute<Options>
231-
readonly http?: HttpOptions
232+
readonly transport?: TransportOptions
232233
readonly compatibility?: DecisionModelCompatibility
233234
readonly providerOptions?: ProviderOptions
234235
}

‎packages/ai/src/embedding.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { tryRequest } from "./media-model.js"
55
import {
66
type AIError,
77
type BaseRequest,
8-
type HttpOptions,
8+
type TransportOptions,
99
ModelID,
1010
ProviderID,
1111
ProviderMetadata,
@@ -38,23 +38,27 @@ export type EmbeddingOptions = Record<string, unknown>
3838
/** What an embedding model's route does; `EmbeddingRoute.make(...).model(...)` builds one from a protocol. */
3939
export interface EmbeddingModelRoute<Options extends EmbeddingOptions = EmbeddingOptions> {
4040
readonly id: string
41-
generate(request: EmbeddingRequest<EmbeddingModel<Options>>, execute: Execute): Effect.Effect<EmbeddingResponse, AIError>
41+
generate(
42+
request: EmbeddingRequest<EmbeddingModel<Options>>,
43+
execute: Execute,
44+
): Effect.Effect<EmbeddingResponse, AIError>
4245
}
4346

4447
export class EmbeddingModel<Options extends EmbeddingOptions = EmbeddingOptions> {
4548
declare protected readonly _Options: Options
4649
readonly id: ModelID
4750
readonly provider: ProviderID
4851
readonly route: EmbeddingModelRoute<Options>
49-
readonly http?: HttpOptions
52+
/** Deployment headers, timeouts and `http` overlays, below each request's own. */
53+
readonly transport?: TransportOptions
5054
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
5155
readonly providerOptions?: ProviderOptions
5256

5357
constructor(input: EmbeddingModel.Input<Options>) {
5458
this.id = input.id
5559
this.provider = input.provider
5660
this.route = input.route
57-
this.http = input.http
61+
this.transport = input.transport
5862
this.providerOptions = input.providerOptions
5963
}
6064

@@ -72,7 +76,7 @@ export namespace EmbeddingModel {
7276
readonly id: ModelID
7377
readonly provider: ProviderID
7478
readonly route: EmbeddingModelRoute<Options>
75-
readonly http?: HttpOptions
79+
readonly transport?: TransportOptions
7680
readonly providerOptions?: ProviderOptions
7781
}
7882

‎packages/ai/src/experimental/cloudflare-run-extraction.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,14 +99,13 @@ export const model = (input: MediaRoute.ModelInput) =>
9999
new ExtractionModel({
100100
id: input.id,
101101
provider: route.provider,
102-
http: input.http,
102+
transport: input.transport,
103103
route: MediaRoute.inline({
104104
protocol,
105105
endpoint: Endpoint.path<MediaProtocol.Body, ExtractionRequest>(({ request }) => `/${request.model.id}`, {
106106
baseURL: input.baseURL,
107107
}),
108108
auth: input.auth,
109-
headers: input.headers,
110109
}),
111110
})
112111

‎packages/ai/src/experimental/realtime.ts‎

Lines changed: 38 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { Clock, Effect, Redacted, Schema } from "effect"
22
import { HttpClientRequest } from "effect/http"
33
import { RequestExecutor } from "../route/executor.js"
4-
import { AIError, InvalidProviderOutputError, InvalidRequestError } from "../schema/index.js"
4+
import { AIError, InvalidProviderOutputError, InvalidRequestError, type RequestTimeout } from "../schema/index.js"
55
import { encodeJson } from "../utils/json.js"
66

77
const OPENAI_BASE_URL = "https://api.openai.com/v1"
@@ -27,6 +27,7 @@ export interface RealtimeConnectInput {
2727
readonly baseURL?: string
2828
/** Headers that host needs besides the API key, such as OpenCode's workspace. */
2929
readonly headers?: Readonly<Record<string, string>>
30+
readonly timeout?: RequestTimeout
3031
readonly session?: RealtimeSession
3132
readonly transport: RealtimeTransportInput
3233
}
@@ -69,16 +70,23 @@ export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeC
6970
input.apiKey,
7071
{ session, transport: input.transport },
7172
LiveSessionResponse,
72-
{ headers: input.headers },
73+
{ headers: input.headers, timeout: input.timeout },
7374
)
7475
return { type: "webrtc" as const, sdp: data.transport.sdp }
7576
}
7677
case "openai-realtime": {
7778
if (input.transport.type === "websocket")
78-
return yield* clientSecret(resolved.id, OPENAI_BASE_URL, input.model, input.apiKey, {
79-
expires_after: { anchor: "created_at", seconds: 60 },
80-
session,
81-
})
79+
return yield* clientSecret(
80+
resolved.id,
81+
OPENAI_BASE_URL,
82+
input.model,
83+
input.apiKey,
84+
{
85+
expires_after: { anchor: "created_at", seconds: 60 },
86+
session,
87+
},
88+
input.timeout,
89+
)
8290
const form = new FormData()
8391
form.append("sdp", input.transport.sdp)
8492
form.append("session", encodeJson(session))
@@ -89,13 +97,21 @@ export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeC
8997
input.apiKey,
9098
form,
9199
Schema.String,
100+
{ timeout: input.timeout },
92101
)
93102
return { type: "webrtc" as const, sdp }
94103
}
95104
case "xai-realtime":
96-
return yield* clientSecret(resolved.id, XAI_BASE_URL, input.model, input.apiKey, {
97-
expires_after: { seconds: 60 },
98-
})
105+
return yield* clientSecret(
106+
resolved.id,
107+
XAI_BASE_URL,
108+
input.model,
109+
input.apiKey,
110+
{
111+
expires_after: { seconds: 60 },
112+
},
113+
input.timeout,
114+
)
99115
case "gemini-live": {
100116
const now = yield* Clock.currentTimeMillis
101117
const expiresAt = now + 60_000
@@ -110,7 +126,7 @@ export const connect = Effect.fn("Realtime.connect")(function* (input: RealtimeC
110126
bidiGenerateContentSetup: { ...input.session, model: `models/${input.model}` },
111127
},
112128
AuthTokenResponse,
113-
{ authHeader: "x-goog-api-key" },
129+
{ authHeader: "x-goog-api-key", timeout: input.timeout },
114130
)
115131
return {
116132
type: "websocket" as const,
@@ -158,11 +174,18 @@ const post = <A>(
158174
apiKey: Redacted.Redacted,
159175
body: Record<string, unknown> | FormData,
160176
response: Schema.Codec<A, string>,
161-
options: { readonly authHeader?: string; readonly headers?: Readonly<Record<string, string>> } = {},
177+
options: {
178+
readonly authHeader?: string
179+
readonly headers?: Readonly<Record<string, string>>
180+
readonly timeout?: RequestTimeout
181+
} = {},
162182
) =>
163183
Effect.gen(function* () {
164184
const executor = yield* RequestExecutor.Service
165-
const res = yield* executor.execute(
185+
const res = yield* RequestExecutor.withTimeout(
186+
executor.execute,
187+
options.timeout,
188+
)(
166189
HttpClientRequest.post(url).pipe(
167190
HttpClientRequest.setHeaders(options.headers ?? {}),
168191
options.authHeader
@@ -176,7 +199,7 @@ const post = <A>(
176199
const http = RequestExecutor.responseHttp(res)
177200
const fail = (message: string, cause?: unknown, raw?: string) =>
178201
new AIError({ reason: new InvalidProviderOutputError({ route, message, body: raw, http, cause }) })
179-
const text = yield* res.text.pipe(Effect.mapError((cause) => fail(`Failed to read ${route} response`, cause)))
202+
const text = yield* RequestExecutor.responseText(res)
180203
return yield* Schema.decodeEffect(response)(text).pipe(
181204
Effect.mapError((cause) => fail(`${route} returned an invalid response`, cause, text)),
182205
)
@@ -188,8 +211,9 @@ const clientSecret = (
188211
model: string,
189212
apiKey: Redacted.Redacted,
190213
body: Record<string, unknown>,
214+
timeout?: RequestTimeout,
191215
) =>
192-
post(route, `${baseURL}/realtime/client_secrets`, apiKey, body, ClientSecretResponse).pipe(
216+
post(route, `${baseURL}/realtime/client_secrets`, apiKey, body, ClientSecretResponse, { timeout }).pipe(
193217
Effect.map(
194218
(data): RealtimeTransport => ({
195219
type: "websocket",

‎packages/ai/src/image.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ export class ImageModel<Options extends ImageOptions = ImageOptions> extends Med
4747
return new ImageModel<Options>({
4848
id: input.id,
4949
provider: route.protocol.provider,
50-
http: input.http,
50+
transport: input.transport,
5151
providerOptions: input.providerOptions,
5252
route: composeRoute(route, input, collectResponse) as ImageRoute,
5353
})

‎packages/ai/src/media-model.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,12 @@ import {
77
InvalidRequestError,
88
ModelID,
99
ProviderID,
10-
type HttpOptions,
1110
type ProviderOptions,
11+
type TransportOptions,
1212
} from "./schema/index.js"
1313

1414
/**
15-
* What every media model carries: ids, the configured route, and deployment `http` overlays. Modality classes
15+
* What every media model carries: ids, the configured route, and deployment transport overlays. Modality classes
1616
* (`ImageModel`, `VideoModel`, `SpeechModel`, `TranscriptionModel`) extend it with their route type and a nominal
1717
* marker so one cannot stand in for the other in requests.
1818
*/
@@ -23,15 +23,16 @@ export class MediaModel<Route, Options> {
2323
readonly id: ModelID
2424
readonly provider: ProviderID
2525
readonly route: Route
26-
readonly http?: HttpOptions
26+
/** Deployment headers, timeouts and `http` overlays, below each request's own. */
27+
readonly transport?: TransportOptions
2728
/** Defaults under each request's `providerOptions`, such as options a provider package reads from its settings. */
2829
readonly providerOptions?: ProviderOptions
2930

3031
constructor(input: MediaModel.Input<Route>) {
3132
this.id = ModelID.make(input.id)
3233
this.provider = ProviderID.make(input.provider)
3334
this.route = input.route
34-
this.http = input.http
35+
this.transport = input.transport
3536
this.providerOptions = input.providerOptions
3637
}
3738
}
@@ -43,7 +44,7 @@ export namespace MediaModel {
4344
readonly id: string | ModelID
4445
readonly provider: string | ProviderID
4546
readonly route: Route
46-
readonly http?: HttpOptions
47+
readonly transport?: TransportOptions
4748
readonly providerOptions?: ProviderOptions
4849
}
4950

@@ -101,8 +102,7 @@ const composition = <Request extends MediaRoute.MediaRequest, Protocol>(
101102
protocol: route.protocol,
102103
endpoint: Endpoint.path(route.path, { baseURL: input.baseURL ?? route.baseURL }),
103104
auth: input.auth,
104-
headers:
105-
route.headers === undefined && input.headers === undefined ? undefined : { ...route.headers, ...input.headers },
105+
headers: route.headers,
106106
})
107107

108108
const isStreamInput = <Request extends MediaRoute.MediaRequest, Event, Response, Frame, State, Token>(

‎packages/ai/src/media.ts‎

Lines changed: 10 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,15 @@ import { Effect, FileSystem, Result, Schema, SchemaGetter, Stream } from "effect
44
import { Base64 } from "effect/encoding"
55
import { HttpClientRequest } from "effect/http"
66
import { ProviderID } from "./schema/ids.js"
7-
import { AIError, InvalidProviderOutputError, InvalidRequestError } from "./schema/errors.js"
7+
import { AIError, InvalidRequestError } from "./schema/errors.js"
88
import { ProviderMetadata } from "./schema/options.js"
9-
import { CurrentMiddleware, type HttpMiddleware, responseHttp, Service } from "./route/executor-service.js"
9+
import {
10+
CurrentMiddleware,
11+
type HttpMiddleware,
12+
responseBytes,
13+
responseStream,
14+
Service,
15+
} from "./route/executor-service.js"
1016
import { detectMediaType, fileMediaType } from "./utils/media-type.js"
1117

1218
export { detectMediaType } from "./utils/media-type.js"
@@ -271,19 +277,7 @@ const download = Effect.fn("Media.download")(function* (
271277
const response = yield* executor
272278
.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})))
273279
.pipe(Effect.provideService(CurrentMiddleware, middleware))
274-
const buffer = yield* response.arrayBuffer.pipe(
275-
Effect.mapError(
276-
(cause) =>
277-
new AIError({
278-
reason: new InvalidProviderOutputError({
279-
message: `Failed to read media from ${source.url}`,
280-
http: responseHttp(response),
281-
cause,
282-
}),
283-
}),
284-
),
285-
)
286-
return new Uint8Array(buffer)
280+
return yield* responseBytes(response)
287281
})
288282

289283
const downloadStream = Effect.fn("Media.downloadStream")(function* (
@@ -295,18 +289,7 @@ const downloadStream = Effect.fn("Media.downloadStream")(function* (
295289
const response = yield* executor
296290
.execute(HttpClientRequest.get(source.url).pipe(HttpClientRequest.setHeaders(headers ?? {})))
297291
.pipe(Effect.provideService(CurrentMiddleware, middleware))
298-
return response.stream.pipe(
299-
Stream.mapError(
300-
(cause) =>
301-
new AIError({
302-
reason: new InvalidProviderOutputError({
303-
message: `Failed to read media from ${source.url}`,
304-
http: responseHttp(response),
305-
cause,
306-
}),
307-
}),
308-
),
309-
)
292+
return responseStream(response)
310293
})
311294

312295
// ---------------------------------------------------------------------------

‎packages/ai/src/protocols/utils/responses-compaction.ts‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { Effect, Schema, Stream } from "effect"
1+
import { Effect, Schema } from "effect"
22
import {
33
AIError,
44
InvalidProviderOutputError,
@@ -125,7 +125,10 @@ export const make = (
125125
auth: route.auth,
126126
encodeBody: Schema.encodeSync(Schema.fromJsonString(Body)),
127127
})
128-
const response = yield* RequestExecutor.withTls(executor.execute, request.http?.tls)(
128+
const response = yield* RequestExecutor.withTimeout(
129+
RequestExecutor.withTls(executor.execute, request.http?.tls),
130+
request.timeout,
131+
)(
129132
ProviderShared.jsonPost({
130133
url: parts.url,
131134
body: parts.bodyText,
@@ -134,13 +137,7 @@ export const make = (
134137
}),
135138
RequestExecutor.withFetch(request.fetch, options?.http),
136139
)
137-
const text = yield* RequestExecutor.responseStream(response).pipe(
138-
Stream.decodeText(),
139-
Stream.runFold(
140-
() => "",
141-
(text, chunk) => text + chunk,
142-
),
143-
)
140+
const text = yield* RequestExecutor.responseText(response)
144141
const invalid = (message: string, cause?: unknown) =>
145142
new AIError({
146143
reason: new InvalidProviderOutputError({

0 commit comments

Comments
 (0)