Merge pull request #8183 from deepseek-harness/fix/pi-ai-leading-http-status
fix(llm): classify pi-ai failures by the leading HTTP status
This commit is contained in:
commit
cc215d9e82
6 files changed
+53
-9
No files matched your search
@@ -93,8 +93,8 @@
|
||||
en: b6bd570c0159ba08
|
||||
zh: 7d2d91eea6a8d830
|
||||
/deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work:
|
||||
en: 3a0cf0d369d25d37
|
||||
zh: 5974f328aea06aa8
|
||||
en: fdbe8ce850250b66
|
||||
zh: d8b9a06a996850c1
|
||||
/deepseek-ai-dsh-llm-pi-ai/known-limitations-and-deferred-work/dev-note:
|
||||
en: 3678dd0f6642c2a5
|
||||
zh: 75cbdd064cc64282
|
||||
@@ -271,7 +271,7 @@ These limits define where the adapter stops and future work begins. They are cur
|
||||
- **`GenerateOptions.stop` is unsupported** — pi-ai's common stream options cannot guarantee stop-sequence behavior across providers.
|
||||
- **Conversation update support comes only from the installed pi-ai catalog** — native system and tool updates require the catalog model’s mid-conversation compat flags, which profiles cannot set. Hand-declared routes and unflagged models receive later system text as user-role reminders and the complete current tool list at the start of each request.
|
||||
- **Images are accepted only in user and tool-result messages** — images in system, developer, or assistant history fail with `UNSUPPORTED_CONTENT` on both conversion paths.
|
||||
- **Provider HTTP status is unavailable** — pi-ai error events do not expose a stable HTTP status across providers.
|
||||
- **Provider HTTP status is unavailable** — pi-ai error events do not expose a stable HTTP status across providers, so failures are classified from the error text. When a message leads with a 4xx or 5xx status, as Anthropic and OpenAI SDK errors do, the status rules read only that status. Other formats, such as `Mistral API error (<status>): <body>`, still match a status quoted anywhere in the message, and the quota, rate-limit, and invalid-request wording rules read the whole message, so a gateway 5xx that relays an upstream `insufficient_quota` or `invalid_request_error` becomes a non-retryable `QUOTA` or `INVALID_REQUEST` failure.
|
||||
- **Retry policy is provider-owned, not an SDK retry** — pi-ai SDK retries stay disabled so durable agent steps and `llm/retry` events own every visible attempt, and direct `ctx.llm.stream()` calls remain single-attempt.
|
||||
- **Streamed JSON tool-call arguments avoid per-delta reparsing** — the installed pi-ai carries [`patches/@[email protected]`](../../../patches/@[email protected]), which removes the per-delta re-parse of the whole accumulated argument JSON in every stream adapter (upstream [earendil-works/pi#9265](https://github.com/earendil-works/pi/issues/9265)); unpatched, a multi-megabyte argument stream costs O(n²) CPU on the event loop and stalls every session in the process. Completion events supply parsed arguments; Responses may parse at both argument completion and output-item completion. This adapter reads only delta strings and finalized arguments. Re-apply or retire the patch on every pi-ai upgrade.
|
||||
- **Stale Anthropic thinking is omitted even where the endpoint would accept it** — prefix checks depend on the model, the account, and the request, which the adapter cannot observe, so every prefix change and every replay state without `prefixDigest` costs the model that reasoning, and Anthropic regenerates it as output tokens. The digest covers the pi-ai context objects, not the wire body: switching authentication or wire-changing compat settings mid-conversation is not detected, a pi-ai upgrade that changes Anthropic message serialization requires a new `DIGEST_SEED` in [`src/prefix-binding.ts`](src/prefix-binding.ts), and any change to how this package builds those objects drops recorded thinking once.
|
||||
|
||||
@@ -271,7 +271,7 @@ pi-ai 事件变成 harness 的推理、文本、工具调用、用量与 finish
|
||||
- **不支持 `GenerateOptions.stop`**——pi-ai 的通用流式选项无法跨提供方保证停止序列行为。
|
||||
- **对话更新支持只来自已安装的 pi-ai 目录**——原生系统与工具更新需要目录模型的对话中 compat 标志,profile 不能设置这些标志。手工声明的路由与未标记的模型会以用户角色提醒接收后续系统文本,并在每次请求开头接收完整的当前工具列表。
|
||||
- **图片只在 user 与工具结果消息中被接受**——system、developer 或 assistant 历史中的图片在两条转换路径上都会以 `UNSUPPORTED_CONTENT` 失败。
|
||||
- **提供方 HTTP 状态不可用**——pi-ai 错误事件不跨提供方暴露稳定 HTTP 状态。
|
||||
- **提供方 HTTP 状态不可用**——pi-ai 错误事件不跨提供方暴露稳定 HTTP 状态,失败按错误文本分类。信息以 4xx 或 5xx 状态码开头时(Anthropic 与 OpenAI SDK 的错误即如此),状态码规则只读取该状态码。其他格式(如 `Mistral API error (<status>): <body>`)仍会匹配信息中任意位置引用的状态码;配额、限流与无效请求的措辞规则读取整条信息,因此网关在 5xx 响应体中转述上游的 `insufficient_quota` 或 `invalid_request_error` 时,会分类为不重试的 `QUOTA` 或 `INVALID_REQUEST`。
|
||||
- **重试策略由提供方自有,而非 SDK 重试**——pi-ai SDK 重试保持禁用,因此持久 agent(智能体)步骤与 `llm/retry` 事件拥有每个可见尝试,直接 `ctx.llm.stream()` 调用仍是单次尝试。
|
||||
- **流式 JSON 工具调用参数避免逐 delta 重复解析**——安装的 pi-ai 带有 [`patches/@[email protected]`](../../../patches/@[email protected]),它移除了每个流适配器中对整段累计参数 JSON 的逐 delta 重新解析(上游 [earendil-works/pi#9265](https://github.com/earendil-works/pi/issues/9265));未打补丁时,数 MB 的参数流会在事件循环上消耗 O(n²) CPU,并使进程内所有会话停滞。完成事件提供解析后的参数;Responses 可能在参数完成和输出项完成时分别解析。本适配器只读取 delta 字符串与最终参数。每次升级 pi-ai 时都要重新应用或撤销该补丁。
|
||||
- **即使端点会接受,过期的 Anthropic thinking 也会被省略**——前缀检查取决于模型、账户和请求,而适配器无法观测这些因素,因此每次前缀变化以及每个不含 `prefixDigest` 的回放状态都会让模型失去这部分推理,Anthropic 会以输出 token 重新生成它。摘要覆盖 pi-ai 上下文对象,而不是线上请求体:对话中途切换认证或会改变线上请求的 compat 设置不会被检测到;改变 Anthropic 消息序列化的 pi-ai 升级需要在 [`src/prefix-binding.ts`](src/prefix-binding.ts) 中使用新的 `DIGEST_SEED`;本包构建这些对象的方式发生任何变化,都会使已记录的 thinking 被丢弃一次。
|
||||
|
||||
@@ -31,6 +31,13 @@ export function mapUsage(usage: PiUsage): TokenUsage {
|
||||
}
|
||||
}
|
||||
|
||||
// pi-ai's SDK-backed providers render an HTTP failure as `<status> <body>`
|
||||
// (Anthropic and OpenAI SDK `APIError`, pi-messages `<status> <statusText>: …`).
|
||||
// The body can quote another hop's status, such as a gateway 500 that embeds its
|
||||
// upstream's 401, so when a message leads with a status the status rules read
|
||||
// only that status; other wordings scan the whole message.
|
||||
const LEADING_HTTP_STATUS = /^[45]\d\d\b/
|
||||
|
||||
// XXX(pi-ai upstream): pi-ai flattens the caught error to `error.message`
|
||||
// (api/anthropic-messages.js: `errorMessage = error instanceof Error ?
|
||||
// error.message : JSON.stringify(error)`), discarding the original Error and its
|
||||
@@ -40,14 +47,15 @@ export function mapUsage(usage: PiUsage): TokenUsage {
|
||||
// If pi-ai ever forwards the original Error (or a fetch/dispatcher hook that lets
|
||||
// us capture the cause ourselves), classify on `code`/`cause` instead of text.
|
||||
function classifyPiAiError(message: string): BuiltinLlmFailureCode {
|
||||
if (/\b(?:401|403)\b/.test(message)) return 'AUTH'
|
||||
const statusSource = LEADING_HTTP_STATUS.exec(message)?.[0] ?? message
|
||||
if (/\b(?:401|403)\b/.test(statusSource)) return 'AUTH'
|
||||
if (isQuotaExceededError(message)) return QUOTA_EXCEEDED_CODE
|
||||
if (/\b429\b|rate.?limit/i.test(message)) return 'RATE_LIMIT'
|
||||
if (/\b429\b/.test(statusSource) || /rate.?limit/i.test(message)) return 'RATE_LIMIT'
|
||||
// A rejected request body (gateway or provider size cap): resending the
|
||||
// same request cannot succeed, so it is invalid, not transient.
|
||||
if (/\b413\b|failed to buffer the request body:\s*length limit exceeded|payload too large|request body too large/i.test(message)) return 'INVALID_REQUEST'
|
||||
if (/\b400\b|invalid.?request/i.test(message)) return 'INVALID_REQUEST'
|
||||
if (/\b5\d\d\b/.test(message)) return 'SERVER'
|
||||
if (/\b413\b/.test(statusSource) || /failed to buffer the request body:\s*length limit exceeded|payload too large|request body too large/i.test(message)) return 'INVALID_REQUEST'
|
||||
if (/\b400\b/.test(statusSource) || /invalid.?request/i.test(message)) return 'INVALID_REQUEST'
|
||||
if (/\b5\d\d\b/.test(statusSource)) return 'SERVER'
|
||||
if (/\btime(?:d)?\s*out\b|timeout/i.test(message)) return 'TIMEOUT'
|
||||
// A stream truncated before the provider's terminal event: each pi-ai provider
|
||||
// throws its own wording when the wire closes mid-response without a terminal
|
||||
|
||||
@@ -474,6 +474,29 @@ describe('PiAiAdapter provider routing', () => {
|
||||
expect(server.paths).toEqual(['/chat/completions'])
|
||||
})
|
||||
|
||||
it('classifies a gateway 500 that relays an upstream 401 as SERVER with the rendered message', async () => {
|
||||
vi.stubEnv('PI_TEST_KEY', 'test-key')
|
||||
// The Anthropic SDK renders the whole JSON body after the gateway's own status.
|
||||
const body = JSON.stringify({
|
||||
error: {
|
||||
origin: 'upstream',
|
||||
message: 'upstream returned an error response: User not found.',
|
||||
type: 'upstream_error',
|
||||
upstream: { provider: 'custom', status: 401, body: { error: { message: 'User not found.' } } },
|
||||
},
|
||||
})
|
||||
const server = await mockServer([{ status: 500, body }])
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(LlmRuntime)
|
||||
await ctx.plugin(LlmPiAi, {
|
||||
providers: {
|
||||
gateway: { apiKeyEnv: 'PI_TEST_KEY', api: 'anthropic-messages', baseURL: server.url, models: [{ id: 'gateway-model' }] },
|
||||
},
|
||||
})
|
||||
const result = await assemble(ctx, { provider: 'gateway', model: 'gateway-model', messages: [] })
|
||||
expect(result.finish).toEqual({ kind: 'error', failure: { message: `500 ${body}`, code: 'SERVER' } })
|
||||
})
|
||||
|
||||
it('uses the resolved catalog context window for usage-based overflow detection', async () => {
|
||||
const model = getBuiltinModels('deepseek').find(candidate => candidate.id === 'deepseek-flash')
|
||||
if (model === undefined) throw new Error('deepseek-flash missing from pi-ai test catalog')
|
||||
|
||||
@@ -939,6 +939,19 @@ describe('mapStopReason / mapUsage', () => {
|
||||
}))).toMatchObject({ kind: 'error', failure: { code: 'PI_AI_ERROR' } })
|
||||
})
|
||||
|
||||
it.each([
|
||||
// The gateway body as the Anthropic SDK renders it: the gateway's own 500 leads.
|
||||
['a gateway 500 relaying an upstream 401', '500 {"error":{"origin":"upstream","message":"upstream returned an error response: User not found.","type":"upstream_error","code":"upstream_response_error","upstream":{"provider":"custom","status":401,"body":{"error":{"type":"<nil>","message":"User not found."},"type":"error"}}}}', 'SERVER'],
|
||||
['a 502 quoting a non-retryable 400', '502 {"error":{"message":"upstream status 400"}}', 'SERVER'],
|
||||
['a 400 quoting a retryable 429', '400 {"error":{"message":"upstream returned 429 Too Many Requests"}}', 'INVALID_REQUEST'],
|
||||
['a 404 quoting a 403', '404 {"error":{"message":"upstream status 403"}}', 'PI_AI_ERROR'],
|
||||
['a leading 401', '401 {"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}', 'AUTH'],
|
||||
['a leading 429', '429 Too Many Requests: slow down', 'RATE_LIMIT'],
|
||||
] as const)('classifies %s by its leading response status', (_label, errorMessage, code) => {
|
||||
expect(mapStopReason(assistant({ stopReason: 'error', errorMessage })))
|
||||
.toEqual({ kind: 'error', failure: { message: errorMessage, code } })
|
||||
})
|
||||
|
||||
it.each([
|
||||
'other side closed',
|
||||
'HTTP2 request did not get a response',
|
||||
|
||||
Reference in new issue
Block a user