Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

errors.ts

330 lines10.8 KB

1import * as AiError from "effect/ai/AiError"
2import * as Clock from "effect/Clock"
3import type * as Duration from "effect/Duration"
4import * as Effect from "effect/Effect"
5import type * as Sse from "effect/encoding/Sse"
6import { dual } from "effect/Function"
7import * as Headers from "effect/http/Headers"
8import type * as HttpClientError from "effect/http/HttpClientError"
9import type * as HttpClientResponse from "effect/http/HttpClientResponse"
10import * as Number from "effect/Number"
11import * as Option from "effect/Option"
12import * as Predicate from "effect/Predicate"
13import * as Redactable from "effect/Redactable"
14import * as Result from "effect/Result"
15import * as Schema from "effect/Schema"
16import type { AnthropicErrorMetadata } from "../AnthropicError.ts"
17import type * as Generated from "../Generated.ts"
18​
19// =============================================================================
20// Anthropic Error Body Schema
21// =============================================================================
22​
23/** @internal */
24export const AnthropicErrorBody = Schema.Struct({
25 type: Schema.Literal("error"),
26 error: Schema.Struct({
27 type: Schema.String,
28 message: Schema.String
29 })
30})
31​
32/** @internal */
33export type AnthropicClientErrorBody = {
34 readonly type: "error"
35 readonly error: {
36 readonly type: string
37 readonly message: string
38 }
39 readonly request_id: string | null
41​
42// =============================================================================
43// Error Mappers
44// =============================================================================
45​
46/** @internal */
47export const mapSchemaError = dual<
48 (method: string) => (error: Schema.SchemaError) => AiError.AiError,
49 (error: Schema.SchemaError, method: string) => AiError.AiError
50>(2, (error, method) =>
51 AiError.make({
52 module: "AnthropicClient",
53 method,
54 reason: AiError.InvalidResponseError.fromSchemaError(error)
55 }))
56​
57/** @internal */
58export const mapSseError = dual<
59 (method: string) => (error: Sse.SseError) => AiError.AiError,
60 (error: Sse.SseError, method: string) => AiError.AiError
61>(2, (error, method) =>
62 AiError.make({
63 module: "AnthropicClient",
64 method,
65 reason: new AiError.InvalidResponseError({ description: error.message })
66 }))
67​
68type ClientError = Generated.AnthropicClientError<string, AnthropicClientErrorBody>
69​
70/** @internal */
71export const mapClientError = dual<
72 (method: string) => (error: ClientError) => Effect.Effect<never, AiError.AiError>,
73 (error: ClientError, method: string) => Effect.Effect<never, AiError.AiError>
74>(
75 2,
76 Effect.fnUntraced(function*(error: ClientError, method: string) {
77 const now = yield* Clock.currentTimeMillis
78 const { request, response, cause } = error
79 const status = response.status
80 const headers = response.headers as Record<string, string>
81 const metadata: AnthropicErrorMetadata = {
82 errorType: cause.error.type,
83 requestId: cause.request_id
84 }
85 const http = buildHttpContext({ response, body: JSON.stringify(cause) })
86 const reason = mapStatusCodeToReason({
87 now,
88 status,
89 method: request.method,
90 url: request.url,
91 headers,
92 message: cause.error.message,
93 metadata,
94 http
95 })
96 return yield* AiError.make({ module: "AnthropicClient", method, reason })
97 })
99​
100/** @internal */
101export const mapHttpClientError = dual<
102 (method: string) => (error: HttpClientError.HttpClientError) => Effect.Effect<never, AiError.AiError>,
103 (error: HttpClientError.HttpClientError, method: string) => Effect.Effect<never, AiError.AiError>
104>(2, (error, method) => {
105 const reason = error.reason
106 switch (reason._tag) {
107 case "TransportError":
108 case "EncodeError":
109 case "InvalidUrlError": {
110 return Effect.fail(AiError.make({
111 module: "AnthropicClient",
112 method,
113 reason: AiError.NetworkError.fromHttpClientError(
114 error as HttpClientError.HttpClientError & { readonly reason: typeof reason }
115 )
116 }))
117 }
118 case "StatusCodeError": {
119 return mapStatusCodeError(reason, method)
120 }
121 case "DecodeError": {
122 return Effect.fail(AiError.make({
123 module: "AnthropicClient",
124 method,
125 reason: new AiError.InvalidOutputError({
126 description: reason.description ?? "Failed to decode response"
127 })
128 }))
129 }
130 case "EmptyBodyError": {
131 return Effect.fail(AiError.make({
132 module: "AnthropicClient",
133 method,
134 reason: new AiError.InvalidOutputError({
135 description: reason.description ?? "Response body was empty"
136 })
137 }))
138 }
139 }
140})
141​
142/** @internal */
143const mapStatusCodeError = Effect.fnUntraced(function*(
144 error: HttpClientError.StatusCodeError,
145 method: string
146) {
147 const { request, response, description } = error
148 const status = response.status
149 const headers = response.headers as Record<string, string>
150 const requestId = headers["request-id"]
151​
152 let body: string | undefined = description
153 if (!description || !description.startsWith("{")) {
154 const responseBody = yield* Effect.option(response.text)
155 if (Option.isSome(responseBody) && responseBody.value) {
156 body = responseBody.value
157 }
158 }
159​
160 let json: unknown = undefined
161 // @effect-diagnostics effect/tryCatchInEffectGen:off
162 try {
163 json = Predicate.isNotUndefined(body) ? JSON.parse(body) : undefined
164 } catch {
165 json = undefined
166 }
167 const decoded = Schema.decodeUnknownOption(AnthropicErrorBody)(json)
168​
169 const now = yield* Clock.currentTimeMillis
170 const reason = mapStatusCodeToReason({
171 now,
172 status,
173 method: request.method,
174 url: request.url,
175 headers,
176 message: Option.isSome(decoded) ? decoded.value.error.message : undefined,
177 http: buildHttpContext({ response, body }),
178 metadata: {
179 errorType: Option.isSome(decoded) ? decoded.value.error.type : null,
180 requestId: requestId ?? null
181 }
182 })
183​
184 return yield* AiError.make({ module: "AnthropicClient", method, reason })
185})
186​
187// =============================================================================
188// Rate Limits
189// =============================================================================
190​
191const retryAfterFromHeader = (raw: string, now: number): Duration.Duration | undefined => {
192 const retryAfter = Headers.parseRetryAfter(raw)
193 return Result.isSuccess(retryAfter) ? Headers.retryAfterDelay(retryAfter.success, now) : undefined
195​
196/** @internal */
197export const parseRateLimitHeaders = (headers: Record<string, string>, now: number) => {
198 const retryAfterRaw = headers["retry-after"]
199 // an invalid Retry-After is treated as absent
200 const retryAfter = retryAfterRaw === undefined ? undefined : retryAfterFromHeader(retryAfterRaw, now)
201 const requestsLimitRaw = headers["anthropic-ratelimit-requests-limit"]
202 const requestsRemainingRaw = headers["anthropic-ratelimit-requests-remaining"]
203 const tokensLimitRaw = headers["anthropic-ratelimit-tokens-limit"]
204 const tokensRemainingRaw = headers["anthropic-ratelimit-tokens-remaining"]
205 return {
206 retryAfter,
207 requestsLimit: Predicate.isNotUndefined(requestsLimitRaw) ? Option.getOrNull(Number.parse(requestsLimitRaw)) : null,
208 requestsRemaining: Predicate.isNotUndefined(requestsRemainingRaw)
209 ? Option.getOrNull(Number.parse(requestsRemainingRaw))
210 : null,
211 requestsReset: headers["anthropic-ratelimit-requests-reset"] ?? null,
212 tokensLimit: Predicate.isNotUndefined(tokensLimitRaw) ? Option.getOrNull(Number.parse(tokensLimitRaw)) : null,
213 tokensRemaining: Predicate.isNotUndefined(tokensRemainingRaw)
214 ? Option.getOrNull(Number.parse(tokensRemainingRaw))
215 : null,
216 tokensReset: headers["anthropic-ratelimit-tokens-reset"] ?? null
217 }
219​
220// =============================================================================
221// HTTP Context
222// =============================================================================
223​
224/** @internal */
225export const buildHttpContext = (params: {
226 readonly response?: HttpClientResponse.HttpClientResponse
227 readonly body?: string | undefined
228}): typeof AiError.HttpContext.Type => ({
229 response: Predicate.isNotUndefined(params.response)
230 ? {
231 status: params.response.status,
232 headers: Redactable.redact(params.response.headers) as Record<string, string>
233 }
234 : undefined,
235 body: params.body
236})
237​
238// =============================================================================
239// HTTP Status Code
240// =============================================================================
241​
242/** @internal */
243export const mapStatusCodeToReason = ({ status, method, url, headers, message, metadata, http, now }: {
244 readonly status: number
245 /** Current time in epoch milliseconds, used to measure a Retry-After date. */
246 readonly now: number
247 readonly method: string
248 readonly url: string
249 readonly headers: Record<string, string>
250 readonly message: string | undefined
251 readonly metadata: AnthropicErrorMetadata
252 readonly http: typeof AiError.HttpContext.Type
253}): AiError.AiErrorReason => {
254 const errorDescription = AiError.buildErrorDescription({
255 status,
256 message,
257 method,
258 url,
259 errorType: metadata.errorType,
260 requestId: metadata.requestId,
261 body: http.body
262 })
263​
264 switch (status) {
265 case 400:
266 return new AiError.InvalidRequestError({
267 description: errorDescription,
268 metadata: { anthropic: metadata },
269 http
270 })
271 case 401:
272 return new AiError.AuthenticationError({
273 kind: "InvalidKey",
274 description: errorDescription,
275 metadata: { anthropic: metadata },
276 http
277 })
278 case 403:
279 return new AiError.AuthenticationError({
280 kind: "InsufficientPermissions",
281 description: errorDescription,
282 metadata: { anthropic: metadata },
283 http
284 })
285 case 404:
286 return new AiError.InvalidRequestError({
287 description: errorDescription,
288 metadata: { anthropic: metadata },
289 http
290 })
291 case 422:
292 return new AiError.InvalidRequestError({
293 description: errorDescription,
294 metadata: { anthropic: metadata },
295 http
296 })
297 case 429: {
298 const { retryAfter, ...rateLimitMetadata } = parseRateLimitHeaders(headers, now)
299 return new AiError.RateLimitError({
300 retryAfter,
301 metadata: {
302 anthropic: {
303 ...metadata,
304 ...rateLimitMetadata
305 }
306 },
307 http
308 })
309 }
310 case 529:
311 return new AiError.InternalProviderError({
312 description: message ?? "Anthropic API is overloaded",
313 metadata: { anthropic: metadata },
314 http
315 })
316 default:
317 if (status >= 500) {
318 return new AiError.InternalProviderError({
319 description: message ?? "Server error",
320 metadata: { anthropic: metadata },
321 http
322 })
323 }
324 return new AiError.UnknownError({
325 description: message,
326 metadata: { anthropic: metadata },
327 http
328 })
329 }