fix(ai): 按官方 Error codes 页重写 OpenAI 错误映射
CI / ai-gates (push) Successful in 55s

拿到 doc_temp/gpt错误码.md 后核对,**此前猜的六个键里错了五个**:
rate_limit_exceeded / moderation_blocked / content_policy_violation /
invalid_api_key / image_generation_user_error 在官方文档里都不存在。真实的是
type rate_limit_error + code slow_down、type service_unavailable_error + code
server_is_overloaded、四个 billing 码。唯一对的 insufficient_quota 也是宽 type
而非 code。这段历史留在 errors.py 顶部,作为凭记忆列错误码表代价的记录。

官方表的 13 条全是基础设施与计费,**没有任何内容审核/侵权码**——但图片接口确有
moderation 参数,说明审核存在、只是错误形态未文档化。直接后果:一次侵权或违规
拒绝很可能以普通 400 到达,只带一句人类可读消息。若一律归「服务端错误」,用户会
看到「服务出错了」并反复重试一个注定被拒的提示词。

故用 error.param 的有无做结构化区分(带 param = 参数错,不带 = 按内容被拒),
三条依据:文档的 service_tier 那条明确说参数错会带 param;内容拒绝不指向任何
具体参数;我方已在调用前校验过尺寸/画质/格式,能被 400 拒掉的参数嫌疑本就不大。
这一条是推断,走到时记 WARNING——那是日后校正它的唯一素材。client.py 相应补上
param 的解析。

两处顺带收获:
- 无 code 的 429 按限流处理,现在是**文档支持的默认**(六种 429 里只有「Rate
  limit reached for requests」没有文档化的 code),不再是猜测。
- 文档提醒视频过载已从 429 改判为 503。我们两者都归可重试,故不受影响;加了一条
  测试钉住这个「无影响」。

同一张表按 code 与 type 两个字段分别查:文档把标识列在哪个字段下,不保证响应里
它就在那个字段,查错的代价是把配额耗尽降级成限流、白烧一轮重试预算。

未接 Retry-After 并记录理由:Java 侧退避基线 30 秒、上限 10 分钟,已长于服务商
通常给的值,忽略只会偏慢、不会加剧限流;接它是一次跨语言契约变更。

测试 271 → 284。四道门禁逐条读退出码,全绿。
This commit is contained in:
2026-09-21 15:52:25 +08:00
parent 8275a04903
commit 541376e9be
6 changed files with 345 additions and 122 deletions
+34 -6
View File
@@ -8,7 +8,7 @@ from __future__ import annotations
import httpx
import pytest
from app.domain.generation import Retry
from app.domain.generation import Retry, UserFacing
from app.providers.openai.client import (
DEFAULT_BASE_URL,
OpenAiClient,
@@ -130,9 +130,9 @@ class TestErrorUnwrapping:
429,
json={
"error": {
"message": "Rate limit reached",
"type": "rate_limit_exceeded",
"code": None,
"message": "Your request rate increased too quickly",
"type": "rate_limit_error",
"code": "slow_down",
"param": None,
}
},
@@ -144,10 +144,38 @@ class TestErrorUnwrapping:
error = caught.value
assert error.http_status == 429
assert error.failure.retry is Retry.BACKOFF
assert "Rate limit reached" in error.failure.message
assert error.failure.provider_code == "slow_down"
assert "increased too quickly" in error.failure.message
def test_the_param_field_is_extracted_because_classification_needs_it(self):
"""`param` 是区分「参数错」与「内容被拒」的唯一结构化线索。
漏了它,所有 400 都会被当成内容被拒——包括真正的参数错。
"""
def handler(request):
return httpx.Response(
400,
json={
"error": {
"message": "Invalid service_tier argument",
"type": "invalid_request_error",
"param": "service_tier",
}
},
)
with pytest.raises(OpenAiError) as caught:
client_with(handler).post_json("/x", {})
# 带 param ⇒ 参数错 ⇒ 服务端错误,而不是让用户去改提示词。
assert caught.value.failure.user_facing is UserFacing.SERVER_ERROR
def test_a_non_json_error_body_still_classifies_by_status(self):
"""错误体形状未经文档证实,解析不出时不能静默丢掉线索。"""
"""错误体不一定是文档描述的那个形状(网关、代理会插自己的页面)。
解析不出时不能静默丢掉线索。
"""
def handler(request):
return httpx.Response(502, text="<html>bad gateway</html>")