先把当时的情况摆出来。异步服务用 FastAPI 加 httpx 0.27 调上游模型,走非流式请求。回答超过 800 字时大约每 10 次有 1 次抛 httpx.ReadTimeout,堆栈停在 await client.post 那一行。给单次请求加 timeout=20 还是会断,又套了 tenacity 重试三次,尾延迟翻倍且重复计费。
把日志和配置对完,能解释这个现象的基本就这几处。httpx 默认 timeout 是 5 秒,直接盖在 read 阶段上。也可能是非流式请求要等整段生成完才回,读超时按整段算。
还有一种情况,重试包在超时外层,断开后整段重新生成。另外,网关还有一层 30 秒空闲断开,客户端设再长也没用。
手动打一次看整段耗时
python -c "import time,httpx;t=time.time();r=httpx.post('https://api.example.com/v1/chat/completions',json={'model':'x','messages':[{'role':'user','content':'写 800 字'}]},timeout=90);print(r.status_code,round(time.time()-t,1))"
随后按阶段拆开设置超时
python -c "import httpx;print(httpx.Timeout(connect=5.0,read=120.0,write=10.0,pool=5.0))"
接着改流式逐块读避免整段等待
curl -N https://api.example.com/v1/chat/completions -H 'Content-Type: application/json' -d '{"model":"x","stream":true,"messages":[{"role":"user","content":"写 800 字"}]}'
只对连接失败做重试
python -c "print('retry only on ConnectTimeout, not ReadTimeout')"
别只看报错消失,验证要多做一步。同一批长回答请求 200 次没有 ReadTimeout,p99 延迟从 118 秒降到 62 秒,重复计费消失。
补一句。超时要按阶段分开设,非流式请求的读超时等于整段生成时间,统一给 5 秒只会在长输出上必然失败。拖得越久,排查成本越高,因为现场状态会被后续操作覆盖。
