Skip to content

Commit 8a57d42

Browse files
authored
fix(ai,coding-agent): report HTTP error responses to onResponse (#12502)
Refs #12376 Problem: `onResponse` (and the `after_provider_response` extension event) never fired for 4xx/5xx responses on SDK-based adapters. Example on `openai-completions`: a 429 makes `client.chat.completions.create(...).withResponse()` reject with the SDK's `APIError`, so the `onResponse` call after it never runs, and the catch block keeps only `errorMessage` (`"429 ..."`). The status and `retry-after` header on the `APIError` were dropped. The fetch-based adapters (OpenAI Codex SSE, Mistral, pi-messages) and Amazon Bedrock already reported error responses, once per attempt. Change: - `retryProviderRequest` gets `onErrorResponse`, called for each failed attempt that carries an HTTP status, before the retry decision. Not called after an abort or for failures without a status (connection errors). A throwing callback fails the request, like every other pi-ai callback. - Wired into `openai-completions`, `openai-responses`, `azure-openai-responses`, `anthropic-messages`, OpenRouter images and Google (`retryGoogleRequest` now takes the model). Google's `ApiError` has no headers, so Google reports the status with `{}`; Google still reports no successful responses (unchanged). - Classifiers (`classifier-shared`, `llama-cpp-classify`) call `onResponse` right after `fetch`, before reading the body, like the fetch-based chat adapters, so an error whose body fails to arrive still reports its status. - Docs: `onResponse` and `AfterProviderResponseEvent` comments, `docs/extensions.md`, changelogs. Behavior change: one request can now fire the hook several times (each retried attempt, Anthropic thread and strict-tools fallbacks report the rejected 400 and then the 200). Codex already behaved this way. Extensions are not affected by throwing handlers: the extension runner catches them. Other changes: - Classifiers now call `onResponse` before reading the body instead of after parsing it. On success it fires before JSON parsing, and the callback runs inside the attempt's `timeoutMs` window. - `retryGoogleRequest` (`api/google-shared.ts`, reachable through the `./api/*` export) takes `model` as its second parameter. No caller outside pi-ai in the repo. Not covered: errors inside an already started stream (SSE error event after a 200) and the Codex WebSocket transport have no HTTP status to report; documented in `docs/extensions.md`. Tests: `provider-error-response.test.ts` runs a local server answering 429 with `retry-after` against five adapters (fails without the fix); unit tests in `provider-retry.test.ts`, `google-shared-retry.test.ts`, `pi-classifier.test.ts`, `llama-cpp-classify.test.ts`.
1 parent 433c1fd commit 8a57d42

22 files changed

Lines changed: 305 additions & 25 deletions

‎packages/ai/CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
### Changed
1212

1313
- Upgraded `@google/genai` from 2.32.0 to 3.6.1. `GoogleApiThinkingLevel` now includes `"XHIGH"` and `ResolvedGoogleThinkingLevel` now includes `"xhigh"`
14+
- Changed `onResponse` to also fire for HTTP error responses (4xx/5xx) and for each retried attempt in the `openai-completions`, `openai-responses`, `azure-openai-responses`, `anthropic-messages`, `google-generative-ai`, and `google-vertex` APIs, OpenRouter image generation, and classifiers, as it already did for `openai-codex-responses`, `mistral-conversations`, `pi-messages`, and Amazon Bedrock. Callers can now read the status and headers such as `retry-after` of a failed request; Google reports error responses with empty headers ([#12376](https://github.com/earendil-works/pi/issues/12376))
1415

1516
### Fixed
1617

‎packages/ai/src/api/anthropic-messages.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -886,6 +886,7 @@ export const stream: StreamFunction<"anthropic-messages", AnthropicOptions> = (
886886
maxRetries: options?.maxRetries,
887887
maxRetryDelayMs: options?.maxRetryDelayMs,
888888
signal: options?.signal,
889+
onErrorResponse: (errorResponse) => options?.onResponse?.(errorResponse, model),
889890
});
890891
let disablePreferredStrictTools = hasExceededStrictToolLimits(options?.sessionId);
891892
let response: Response;

‎packages/ai/src/api/azure-openai-responses.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,7 @@ export const stream: StreamFunction<"azure-openai-responses", AzureOpenAIRespons
8989
maxRetries: options?.maxRetries,
9090
maxRetryDelayMs: options?.maxRetryDelayMs,
9191
signal: options?.signal,
92+
onErrorResponse: (errorResponse) => options?.onResponse?.(errorResponse, model),
9293
},
9394
);
9495
await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);

‎packages/ai/src/api/classifier-shared.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ export async function postClassifierRequest(
7474
const transformed = await options.onPayload?.(payload, model);
7575
if (transformed !== undefined) payload = transformed;
7676
const requestFetch = options.fetch ?? globalThis.fetch;
77-
const { response, json } = await retryProviderRequest(
77+
return retryProviderRequest(
7878
async () => {
7979
const timeoutSignal = options.timeoutMs !== undefined ? AbortSignal.timeout(options.timeoutMs) : undefined;
8080
const signal =
@@ -88,8 +88,10 @@ export async function postClassifierRequest(
8888
body: JSON.stringify(payload),
8989
signal,
9090
});
91+
// Reported before the body is read, so a body that fails to arrive still reports its status.
92+
await options.onResponse?.({ status: next.status, headers: headersToRecord(next.headers) }, model);
9193
if (!next.ok) throw httpError(label, next, await next.text());
92-
return { response: next, json: (await next.json()) as unknown };
94+
return (await next.json()) as unknown;
9395
} catch (error) {
9496
if (timeoutSignal?.aborted && !options.signal?.aborted) throw timeoutError(options.timeoutMs!);
9597
throw error;
@@ -102,8 +104,6 @@ export async function postClassifierRequest(
102104
noRetryStatuses,
103105
},
104106
);
105-
await options.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
106-
return json;
107107
}
108108

109109
function tokenCount(value: unknown): number {

‎packages/ai/src/api/google-generative-ai.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,11 @@ export const stream: StreamFunction<"google-generative-ai", GoogleOptions> = (
9797
if (nextParams !== undefined) {
9898
params = nextParams as GenerateContentParameters;
9999
}
100-
const googleStream = await retryGoogleRequest(() => client.models.generateContentStream(params), options);
100+
const googleStream = await retryGoogleRequest(
101+
() => client.models.generateContentStream(params),
102+
model,
103+
options,
104+
);
101105

102106
stream.push({ type: "start", partial: output });
103107
let currentBlock: TextContent | ThinkingContent | null = null;

‎packages/ai/src/api/google-shared.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
} from "@google/genai";
1414
import { clampThinkingLevel } from "../models.ts";
1515
import type {
16+
Api,
1617
ImageContent,
1718
Model,
1819
StopReason,
@@ -613,11 +614,13 @@ export function mapStopReason(reason: FinishReason): StopReason {
613614
* retryProviderRequest. The SDK's ApiError has a `status` property but no
614615
* `headers` property, and retryProviderRequest only retries errors that carry
615616
* both, so normalize the error by adding the missing `headers` before
616-
* rethrowing.
617+
* rethrowing. Failed attempts reach `onResponse` with their status and no
618+
* headers.
617619
*/
618620
export function retryGoogleRequest<T>(
619621
request: () => Promise<T>,
620-
options?: Pick<StreamOptions, "maxRetries" | "maxRetryDelayMs" | "signal">,
622+
model: Model<Api>,
623+
options?: Pick<StreamOptions, "maxRetries" | "maxRetryDelayMs" | "signal" | "onResponse">,
621624
): Promise<T> {
622625
return retryProviderRequest(
623626
async () => {
@@ -634,6 +637,7 @@ export function retryGoogleRequest<T>(
634637
maxRetries: options?.maxRetries,
635638
maxRetryDelayMs: options?.maxRetryDelayMs,
636639
signal: options?.signal,
640+
onErrorResponse: (errorResponse) => options?.onResponse?.(errorResponse, model),
637641
},
638642
);
639643
}

‎packages/ai/src/api/google-vertex.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,11 @@ export const stream: StreamFunction<"google-vertex", GoogleVertexOptions> = (
113113
if (nextParams !== undefined) {
114114
params = nextParams as GenerateContentParameters;
115115
}
116-
const googleStream = await retryGoogleRequest(() => client.models.generateContentStream(params), options);
116+
const googleStream = await retryGoogleRequest(
117+
() => client.models.generateContentStream(params),
118+
model,
119+
options,
120+
);
117121

118122
stream.push({ type: "start", partial: output });
119123
let currentBlock: TextContent | ThinkingContent | null = null;

‎packages/ai/src/api/llama-cpp-classify.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ async function post(request: RequestContext, path: string, body: unknown, observ
243243
model.headers,
244244
options?.headers,
245245
) ?? {};
246-
const { response, json } = await retryProviderRequest(
246+
return retryProviderRequest(
247247
async () => {
248248
const timeoutSignal = options?.timeoutMs !== undefined ? AbortSignal.timeout(options.timeoutMs) : undefined;
249249
const signal =
@@ -257,19 +257,19 @@ async function post(request: RequestContext, path: string, body: unknown, observ
257257
body: JSON.stringify(payload),
258258
signal,
259259
});
260+
// Reported before the body is read, so a body that fails to arrive still reports its status.
261+
if (observe) {
262+
await options?.onResponse?.({ status: next.status, headers: headersToRecord(next.headers) }, model);
263+
}
260264
if (!next.ok) throw httpError(next, await next.text());
261-
return { response: next, json: (await next.json()) as unknown };
265+
return (await next.json()) as unknown;
262266
} catch (error) {
263267
if (timeoutSignal?.aborted && !options?.signal?.aborted) throw timeoutError(options!.timeoutMs!);
264268
throw error;
265269
}
266270
},
267271
{ maxRetries: options?.maxRetries ?? 2, maxRetryDelayMs: options?.maxRetryDelayMs, signal: options?.signal },
268272
);
269-
if (observe) {
270-
await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
271-
}
272-
return json;
273273
}
274274

275275
function tokenIds(body: unknown): number[] {

‎packages/ai/src/api/openai-completions.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,7 @@ export const stream: StreamFunction<"openai-completions", OpenAICompletionsOptio
391391
maxRetries: options?.maxRetries,
392392
maxRetryDelayMs: options?.maxRetryDelayMs,
393393
signal: options?.signal,
394+
onErrorResponse: (errorResponse) => options?.onResponse?.(errorResponse, model),
394395
},
395396
);
396397
await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);

‎packages/ai/src/api/openai-responses.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ export const stream: StreamFunction<"openai-responses", OpenAIResponsesOptions>
219219
maxRetries: options?.maxRetries,
220220
maxRetryDelayMs: options?.maxRetryDelayMs,
221221
signal: options?.signal,
222+
onErrorResponse: (errorResponse) => options?.onResponse?.(errorResponse, model),
222223
},
223224
);
224225
await options?.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);

0 commit comments

Comments
 (0)