<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>大模型API on Ambertu</title><link>https://ambertu.com/tags/%E5%A4%A7%E6%A8%A1%E5%9E%8Bapi/</link><description>Recent content in 大模型API on Ambertu</description><generator>Hugo</generator><language>zh-CN</language><copyright>2026 Ambertu · 粤ICP备18071259号</copyright><lastBuildDate>Fri, 04 Sep 2026 00:00:00 +0000</lastBuildDate><atom:link href="https://ambertu.com/tags/%E5%A4%A7%E6%A8%A1%E5%9E%8Bapi/index.xml" rel="self" type="application/rss+xml"/><item><title>大模型 API 中转站怎么选：直连、自建、用现成的，三条路的真实成本</title><link>https://ambertu.com/posts/ai-api-relay-how-to-choose/</link><pubDate>Fri, 04 Sep 2026 00:00:00 +0000</pubDate><guid>https://ambertu.com/posts/ai-api-relay-how-to-choose/</guid><description>调用大模型 API 有三条路：直连官方、自己搭网关、用现成的中转站。本文把三条路的真实成本拆开算——不只是钱，还有你要为此承担的运维责任。文末介绍我自己运营的 aizhuan.fun，一个偏向 AI 图像与视频生产的中转站。</description><content:encoded><![CDATA[<blockquote>
<p><strong>利益披露</strong>：本文最后介绍的中转站是我自己在运营的。前面三分之二的取舍分析对任何人都成立，
你完全可以看完分析之后选择另外两条路——那也是这篇文章想说清楚的事。</p>
</blockquote>
<p>调用大模型 API 有三条路，大多数人只比较了价格，然后在别的地方付出了没预料到的成本。</p>
<h2 id="三条路的取舍">三条路的取舍</h2>
<h3 id="路一直连官方">路一：直连官方</h3>
<p>最干净的一条，也是最应该优先考虑的。你和供应商之间没有中间人，出问题时责任边界清晰，
额度、限速、模型上线时间都以官方为准。</p>
<p><strong>它的实际成本不在价格上，而在这几处</strong>：</p>
<ul>
<li><strong>支付方式。</strong> 需要能付美元的卡，且部分供应商对特定地区的支付有限制。</li>
<li><strong>网络可达性。</strong> 从国内直连的延迟和稳定性，取决于你的出口线路，而不是供应商。</li>
<li><strong>多供应商的碎片化。</strong> 一旦你同时用 OpenAI、Google、Anthropic，就要维护三套 SDK、
三套密钥、三套计费口径。这个成本随供应商数量线性增长，而且很容易被低估。</li>
</ul>
<h3 id="路二自己搭网关">路二：自己搭网关</h3>
<p>用 new-api、one-api 这类开源网关，把多家供应商收敛成一个 OpenAI 兼容接口。
我自己就是这么做的，前面几篇文章都在写这件事。</p>
<p><strong>它解决了碎片化，但把运维责任整个搬到了你身上</strong>：</p>
<table>
	<thead>
			<tr>
					<th>你要负责的事</th>
					<th>做错的后果</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>反向代理的流式配置</td>
					<td>流式输出变成一次性返回，用户体验直接崩</td>
			</tr>
			<tr>
					<td>超时分层与重试策略</td>
					<td>一次 504 触发客户端重试，账单翻倍</td>
			</tr>
			<tr>
					<td>限流的真实 IP 判定</td>
					<td>按可伪造的头限流，等于没限</td>
			</tr>
			<tr>
					<td>TLS 证书生命周期</td>
					<td>过期后所有 SDK 客户端一起硬失败</td>
			</tr>
			<tr>
					<td>数据库与日志保留</td>
					<td>用量表无限增长，半年后磁盘满、服务停摆</td>
			</tr>
			<tr>
					<td>上游账号与额度管理</td>
					<td>某个 key 额度耗尽，整条链路静默失败</td>
			</tr>
	</tbody>
</table>
<p>这张表里的每一行，我都单独写过一篇文章，因为每一行我都实际踩过。
如果你打算走这条路，那几篇可以直接拿去用：
<a href="/posts/new-api-binary-vs-docker/">部署形态</a>、
<a href="/posts/llm-api-sse-proxy-buffering/">流式缓冲</a>、
<a href="/posts/llm-api-timeout-retry-double-billing/">超时与重复计费</a>、
<a href="/posts/api-gateway-real-ip-ratelimit/">限流与真实 IP</a>、
<a href="/posts/caddy-vs-nginx-api-gateway-tls/">证书自动化</a>、
<a href="/posts/api-gateway-database-choice-small-vps/">数据库选型</a>。</p>
<p><strong>什么时候值得自建</strong>：你有稳定的上游渠道、有运维精力、且用量大到中转的差价能覆盖你的时间成本。
<strong>什么时候不值得</strong>：你只是想赶紧把功能做出来，网关不是你的核心业务。</p>
<h3 id="路三用现成的中转站">路三：用现成的中转站</h3>
<p>省掉了运维，代价是<strong>你把可用性、计费准确性和数据流向都托付给了运营方</strong>。</p>
<p>这条路最大的问题不是价格，是<strong>你没有办法验证对方说的话</strong>。
几乎每个中转站都说自己&quot;稳定、快速、官方直连&quot;，但这些词没有一个是可证伪的。
所以选中转站真正该看的是：</p>
<ol>
<li><strong>它敢不敢说自己不做什么。</strong> 只讲优点的介绍页，等于没有信息量。</li>
<li><strong>出问题时有没有人。</strong> 售后渠道是否真实存在、响应大概多久。</li>
<li><strong>计费是否可对账。</strong> 你能不能自己拉到用量明细，而不是只看一个余额数字。</li>
<li><strong>技术细节经不经得起问。</strong> 流式是不是真流式、超时怎么配的、限流按什么算——
这些问题问出去，答不上来的多半没认真做过。</li>
</ol>
<!-- 图 1：三条路的成本结构对比图。建议内容：横轴是"用量规模"，纵轴是"总成本（金钱+时间）"，
     三条曲线交叉，标出各自的拐点。或者简单点：三列对照表的可视化。 -->
<h2 id="我自己那个站">我自己那个站</h2>
<p>前面说的第四条——&ldquo;技术细节经不经得起问&rdquo;——我把答案提前写好了。</p>
<p><a href="https://aizhuan.fun"><strong>aizhuan.fun</strong></a> 是我自己搭的 new-api 实例。它跑在首尔的一台机器上，
用的是裸二进制 + Caddy + 本机 MariaDB 的组合，不是 Docker。
这个选择的理由、以及上面那张表里六行的具体做法，都在前面那六篇文章里写着——
<strong>你可以拿那些文章当作对这个站的技术审查材料</strong>，这也是我写它们的原因之一。</p>
<h3 id="名字的意思aizhuan--ai--赚">名字的意思：aizhuan = AI + 赚</h3>
<p>这个站从一开始就不是给「研究大模型」的人准备的，而是给<strong>用大模型干活、并且要靠产出换钱</strong>的人准备的。</p>
<p>这解释了它的模型清单为什么长成那样——五个分组里三个是生图和视频，而不是清一色的文本对话模型：</p>
<table>
	<thead>
			<tr>
					<th>你实际在做的事</th>
					<th>会用到的</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>电商主图、详情页配图、商品换背景</td>
					<td>gpt-image-2 系列、gemini-3.x 生图、<code>2k生图</code> / <code>4k生图</code> 分组</td>
			</tr>
			<tr>
					<td>小说插画、角色设定、同人图</td>
					<td>NAI diffusion 系列、Stable Diffusion 系列</td>
			</tr>
			<tr>
					<td>短视频素材、分镜、动态封面</td>
					<td>doubao-seedance、grok-imagine-video、<code>SD视频</code> 分组</td>
			</tr>
			<tr>
					<td>图文内容批量生产</td>
					<td>GPT-5.x 系列配合生图模型串起来调</td>
			</tr>
			<tr>
					<td>自己做工具再卖给别人</td>
					<td>OpenAI 兼容接口，客户端改个 <code>base_url</code> 就能接</td>
			</tr>
	</tbody>
</table>
<p>分辨率分组（2k / 4k）单独拆出来也是同一个逻辑：<strong>做商用素材的人在乎能不能直接交付</strong>，
而不是能不能出个缩略图看看效果。</p>
<p>需要说清楚的一句：<strong>这个站提供的是工具和算力，不是收入。</strong>
能不能赚到钱取决于你做什么、做得怎么样、有没有出货渠道——这三件事都和 API 没关系。
任何把「接入某个 API 就能赚钱」当卖点的说法都不要信，包括从我这里听到的。
这个品类里充斥着承诺收入的宣传，我不打算加入它们。</p>
<p>如果你的需求是纯文本对话或者代码补全，市面上专做文本的中转可能更划算；
这里的模型覆盖是往内容生产那一侧偏的。</p>
<h3 id="功能一一个接口替掉一堆-sdk">功能一：一个接口，替掉一堆 SDK</h3>
<p>这是中转站最实在的价值，也是最容易被&quot;模型多&quot;这种话术盖过去的一点。</p>
<figure>
<svg viewBox="0 0 900 300" role="img" aria-label="对比图：不用中转时应用需要分别对接 OpenAI、Google、xAI、字节、Stable Diffusion 五家供应商，各有各的 SDK、密钥和计费口径；用中转时应用只需改一行 base_url，通过一个 OpenAI 兼容接口访问文本、图像、视频三类产出" style="width:100%;height:auto;color:currentColor">
  <defs>
    <marker id="u1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto">
      <path d="M 0 1 L 10 5 L 0 9 z" fill="currentColor"/>
    </marker>
  </defs>
  <text x="0" y="14" font-size="10.5" font-family="monospace" fill="currentColor" opacity="0.6">不用中转</text>
  <line x1="430" y1="24" x2="430" y2="286" stroke="currentColor" stroke-width="1" opacity="0.25" stroke-dasharray="3 5"/>
  <g font-family="monospace" font-size="10.5" fill="currentColor">
    <rect x="10" y="118" width="100" height="44" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="60" y="145" text-anchor="middle">你的应用</text>
    <rect x="240" y="8"   width="176" height="32" fill="none" stroke="currentColor" stroke-width="1.2"/>
    <text x="252" y="28">OpenAI</text>
    <rect x="240" y="52"  width="176" height="32" fill="none" stroke="currentColor" stroke-width="1.2"/>
    <text x="252" y="72">Google Gemini</text>
    <rect x="240" y="96"  width="176" height="32" fill="none" stroke="currentColor" stroke-width="1.2"/>
    <text x="252" y="116">xAI Grok</text>
    <rect x="240" y="140" width="176" height="32" fill="none" stroke="currentColor" stroke-width="1.2"/>
    <text x="252" y="160">字节 Seedance</text>
    <rect x="240" y="184" width="176" height="32" fill="none" stroke="currentColor" stroke-width="1.2"/>
    <text x="252" y="204">Stable Diffusion / NAI</text>
    <line x1="110" y1="136" x2="236" y2="26"  stroke="currentColor" stroke-width="1.1" opacity="0.55" marker-end="url(#u1)"/>
    <line x1="110" y1="138" x2="236" y2="70"  stroke="currentColor" stroke-width="1.1" opacity="0.55" marker-end="url(#u1)"/>
    <line x1="110" y1="140" x2="236" y2="114" stroke="currentColor" stroke-width="1.1" opacity="0.55" marker-end="url(#u1)"/>
    <line x1="110" y1="144" x2="236" y2="158" stroke="currentColor" stroke-width="1.1" opacity="0.55" marker-end="url(#u1)"/>
    <line x1="110" y1="146" x2="236" y2="202" stroke="currentColor" stroke-width="1.1" opacity="0.55" marker-end="url(#u1)"/>
  </g>
  <text x="10" y="252" font-size="10" font-family="monospace" fill="currentColor" font-weight="bold">5 套 SDK · 5 个密钥 · 5 种计费口径 · 5 种错误格式</text>
  <text x="10" y="272" font-size="10" font-family="monospace" fill="currentColor" opacity="0.7">任何一家改接口或涨价，你都要跟着改代码</text>
  <text x="452" y="14" font-size="10.5" font-family="monospace" fill="currentColor" opacity="0.6">用中转</text>
  <g font-family="monospace" font-size="10.5" fill="currentColor">
    <rect x="452" y="118" width="100" height="44" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="502" y="145" text-anchor="middle">你的应用</text>
    <line x1="552" y1="140" x2="594" y2="140" stroke="currentColor" stroke-width="1.4" marker-end="url(#u1)"/>
    <text x="573" y="122" font-size="9" text-anchor="middle" opacity="0.75">改一行</text>
    <text x="573" y="133" font-size="9" text-anchor="middle" opacity="0.75">base_url</text>
    <rect x="596" y="110" width="160" height="60" fill="currentColor" fill-opacity="0.1" stroke="currentColor" stroke-width="1.6"/>
    <text x="676" y="134" text-anchor="middle" font-weight="bold">aizhuan.fun</text>
    <text x="676" y="152" text-anchor="middle" font-size="9" opacity="0.75">OpenAI 兼容</text>
    <rect x="800" y="76"  width="88" height="32" fill="none" stroke="currentColor" stroke-width="1.2"/>
    <text x="844" y="96"  text-anchor="middle" font-size="10">文本</text>
    <rect x="800" y="124" width="88" height="32" fill="none" stroke="currentColor" stroke-width="1.2"/>
    <text x="844" y="144" text-anchor="middle" font-size="10">图像</text>
    <rect x="800" y="172" width="88" height="32" fill="none" stroke="currentColor" stroke-width="1.2"/>
    <text x="844" y="192" text-anchor="middle" font-size="10">视频</text>
    <line x1="756" y1="134" x2="796" y2="94"  stroke="currentColor" stroke-width="1.1" opacity="0.55" marker-end="url(#u1)"/>
    <line x1="756" y1="140" x2="796" y2="140" stroke="currentColor" stroke-width="1.1" opacity="0.55" marker-end="url(#u1)"/>
    <line x1="756" y1="146" x2="796" y2="186" stroke="currentColor" stroke-width="1.1" opacity="0.55" marker-end="url(#u1)"/>
  </g>
  <text x="452" y="252" font-size="10" font-family="monospace" fill="currentColor" font-weight="bold">1 个接口 · 1 个密钥 · 1 份账单 · 53 个模型</text>
  <text x="452" y="272" font-size="10" font-family="monospace" fill="currentColor" opacity="0.7">换模型只改一个字符串，不动代码结构</text>
</svg>
<figcaption>
左边那五条线不是画着好看——<strong>它们代表你要长期维护的五套东西</strong>：五份文档、五个密钥的轮换、
五种限流策略、五套错误码的兼容代码。中转站把这五条线收敛成一条，代价是你多了一个依赖方。
这个交换划不划算，取决于你打算同时用几家。
</figcaption>
</figure>
<h3 id="功能二53-个模型覆盖三类产出">功能二：53 个模型，覆盖三类产出</h3>
<figure>
<svg viewBox="0 0 880 370" role="img" aria-label="模型能力全景：文本对话包含 GPT-5.2 到 5.6 系列与 codex；图像生成包含 gpt-image 系列、gemini 系列、grok-imagine 与 Stable Diffusion、NAI；视频生成包含 doubao-seedance、grok-imagine-video 与 SD 视频。合计 53 个模型，分属 openai、openai-video、image-generation 三类端点" style="width:100%;height:auto;color:currentColor">
  <text x="0" y="14" font-size="10.5" font-family="monospace" fill="currentColor" opacity="0.6">按「你要交付什么」组织，而不是按模型热度</text>
  <g font-family="monospace" font-size="10" fill="currentColor">
    <rect x="0" y="28" width="278" height="252" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <rect x="0" y="28" width="278" height="30" fill="currentColor" fill-opacity="0.09"/>
    <text x="14" y="48" font-size="11.5" font-weight="bold">文本对话 · 代码</text>
    <text x="14" y="80">GPT-5.6（luna / sol / terra）</text>
    <text x="14" y="102">GPT-5.5</text>
    <text x="14" y="124">GPT-5.4 · 5.4-mini</text>
    <text x="14" y="146">GPT-5.2</text>
    <text x="14" y="168">gpt-5.3-codex-spark</text>
    <text x="14" y="190">codex-auto-review</text>
    <text x="14" y="212" opacity="0.7">各系列另有 openai-compact 变体</text>
    <text x="14" y="252" opacity="0.6">分组</text>
    <text x="14" y="268" font-weight="bold">自建号池plus · 官方号池plus</text>
    <rect x="298" y="28" width="278" height="252" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <rect x="298" y="28" width="278" height="30" fill="currentColor" fill-opacity="0.09"/>
    <text x="312" y="48" font-size="11.5" font-weight="bold">图像生成</text>
    <text x="312" y="80">gpt-image-1 · 1.5 · 2 · 2-plus</text>
    <text x="312" y="102">gemini-3-pro-image</text>
    <text x="312" y="124">gemini-3.1-flash-image</text>
    <text x="312" y="146">gemini-2.5-flash-image</text>
    <text x="312" y="168">grok-imagine-image（含 edit）</text>
    <text x="312" y="190">Stable Diffusion 2 / 2.5 系列</text>
    <text x="312" y="212">nai-diffusion-4.5-full</text>
    <text x="312" y="252" opacity="0.6">分组</text>
    <text x="312" y="268" font-weight="bold">2k生图 · 4k生图</text>
    <rect x="596" y="28" width="284" height="252" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <rect x="596" y="28" width="284" height="30" fill="currentColor" fill-opacity="0.09"/>
    <text x="610" y="48" font-size="11.5" font-weight="bold">视频生成</text>
    <text x="610" y="80">doubao-seedance-2.0 · 2.5</text>
    <text x="610" y="102">doubao-seedance-2.0-mini</text>
    <text x="610" y="124">grok-imagine-video · 1.5</text>
    <text x="610" y="146">first_frame（首帧控制）</text>
    <text x="610" y="168">first_last_frame（首尾帧）</text>
    <text x="610" y="190" opacity="0.7">异步任务，出片后回调</text>
    <text x="610" y="252" opacity="0.6">分组</text>
    <text x="610" y="268" font-weight="bold">SD视频</text>
  </g>
  <line x1="0" y1="300" x2="860" y2="300" stroke="currentColor" stroke-width="1" opacity="0.25"/>
  <g font-family="monospace" font-size="10.5" fill="currentColor">
    <text x="0" y="322">端点类型</text>
    <text x="110" y="322" font-weight="bold">openai 42</text>
    <text x="250" y="322" font-weight="bold">openai-video 11</text>
    <text x="430" y="322" font-weight="bold">image-generation 6</text>
    <text x="650" y="322" opacity="0.7">合计 53 个模型</text>
  </g>
  <text x="0" y="348" font-size="10" font-family="monospace" fill="currentColor" opacity="0.65">同一能力有多个变体（preview / -c 后缀 / 分辨率分组），是为了在质量、速度、成本之间留选择</text>
  <text x="0" y="366" font-size="10" font-family="monospace" fill="currentColor" opacity="0.65">数据取自站点公开的 /api/pricing 接口，可自行核对</text>
</svg>
<figcaption>
分辨率单独拆成 <code>2k生图</code> 和 <code>4k生图</code> 两个分组，是这份清单里最能说明定位的细节——
<strong>做商用素材的人要的是能直接交付的成品尺寸</strong>，而不是先出个缩略图看效果。
视频走异步任务队列，提交后回调取结果，这是视频生成必须的形态。
</figcaption>
</figure>
<!-- 图（待你提供）：站点模型列表页截图，展示分组切换和模型数量。
     注意打码：API key、用户邮箱、余额数字全部要遮掉。 -->
<h3 id="功能三不只是裸-api">功能三：不只是裸 API</h3>
<p>如果只有 API，那和自己搭一个没区别。实际能省事的是这些配套：</p>
<table>
	<thead>
			<tr>
					<th>功能</th>
					<th>具体规格</th>
					<th>解决什么</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><strong>Image Studio</strong></td>
					<td>独立图形界面 <a href="https://studio.aizhuan.fun">studio.aizhuan.fun</a></td>
					<td>不写代码也能出图，团队里非技术成员可直接用</td>
			</tr>
			<tr>
					<td><strong>表单转提示词</strong></td>
					<td>填表单 → 自动改写成生图/视频提示词</td>
					<td>不用背 prompt 写法，降低上手门槛</td>
			</tr>
			<tr>
					<td><strong>参考图</strong></td>
					<td>单次最多 <strong>9 张</strong></td>
					<td>图生图、垫图、风格迁移、角色一致性</td>
			</tr>
			<tr>
					<td><strong>文档解析</strong></td>
					<td>最大 <strong>20 MB / 5 万字符</strong></td>
					<td>长文档喂给模型，不用自己切分</td>
			</tr>
			<tr>
					<td><strong>生成图保留</strong></td>
					<td><strong>7 天</strong></td>
					<td>出图后不用立刻下载，但也别当网盘用</td>
			</tr>
			<tr>
					<td><strong>用量数据导出</strong></td>
					<td>可导出，最小粒度<strong>按小时</strong></td>
					<td>自己对账，不用只看一个余额数字</td>
			</tr>
			<tr>
					<td><strong>可用性监控</strong></td>
					<td>接了 Uptime Kuma</td>
					<td>站点状态对外可查，不是嘴上说稳定</td>
			</tr>
			<tr>
					<td><strong>用量排行榜</strong></td>
					<td>日榜 / 周榜</td>
					<td>看别人在用什么模型，选型时有参考</td>
			</tr>
	</tbody>
</table>
<p>第六行值得单独说：前面我列过选中转站要看的四条，其中一条是**「计费是否可对账」——
你能不能自己拉到用量明细，而不是只看一个余额数字**。按小时粒度的数据导出就是对这条的回答。
这不是我事后找补的说法，那四条标准和这个功能都在，你可以自己对。</p>
<!-- 图（待你提供）：Image Studio 的实际出图界面，或一组由站上模型生成的图像样例。
     这是唯一能直观说明"图像能力"的东西，比任何文字描述都有效。 -->
<h3 id="功能四客户端一键接入">功能四：客户端一键接入</h3>
<p>不想写代码的话，主流 AI 客户端可以直接一键导入配置，不用手动填 base_url 和 key：</p>
<figure>
<svg viewBox="0 0 900 210" role="img" aria-label="四步接入流程：注册获得 1 美元额度、创建 API key、客户端一键导入或手动改 base_url、开始调用。支持一键导入的客户端包括 Cherry Studio、CC Switch、DeepChat、Lobe Chat、AionUI、OpenCat、AMA 问天、AI as Workspace、流畅阅读" style="width:100%;height:auto;color:currentColor">
  <defs>
    <marker id="s1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto">
      <path d="M 0 1 L 10 5 L 0 9 z" fill="currentColor"/>
    </marker>
  </defs>
  <g font-family="monospace" font-size="10.5" fill="currentColor">
    <rect x="0" y="30" width="170" height="56" fill="currentColor" fill-opacity="0.1" stroke="currentColor" stroke-width="1.4"/>
    <text x="85" y="54" text-anchor="middle" font-weight="bold">① 注册</text>
    <text x="85" y="72" text-anchor="middle" font-size="9.5">送 $1 额度</text>
    <line x1="170" y1="58" x2="228" y2="58" stroke="currentColor" stroke-width="1.3" marker-end="url(#s1)"/>
    <rect x="230" y="30" width="170" height="56" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="315" y="54" text-anchor="middle" font-weight="bold">② 创建 key</text>
    <text x="315" y="72" text-anchor="middle" font-size="9.5">选分组、设额度</text>
    <line x1="400" y1="58" x2="458" y2="58" stroke="currentColor" stroke-width="1.3" marker-end="url(#s1)"/>
    <rect x="460" y="30" width="200" height="56" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="560" y="54" text-anchor="middle" font-weight="bold">③ 接入</text>
    <text x="560" y="72" text-anchor="middle" font-size="9.5">一键导入 或 改 base_url</text>
    <line x1="660" y1="58" x2="718" y2="58" stroke="currentColor" stroke-width="1.3" marker-end="url(#s1)"/>
    <rect x="720" y="30" width="170" height="56" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="805" y="54" text-anchor="middle" font-weight="bold">④ 调用</text>
    <text x="805" y="72" text-anchor="middle" font-size="9.5">先用 $1 验证</text>
  </g>
  <line x1="0" y1="106" x2="880" y2="106" stroke="currentColor" stroke-width="1" opacity="0.25"/>
  <text x="0" y="128" font-size="10.5" font-family="monospace" fill="currentColor" opacity="0.6">③ 支持一键导入的客户端</text>
  <g font-family="monospace" font-size="10" fill="currentColor">
    <rect x="0"   y="140" width="132" height="26" fill="none" stroke="currentColor" stroke-width="1.1"/>
    <text x="66"  y="157" text-anchor="middle">Cherry Studio</text>
    <rect x="144" y="140" width="132" height="26" fill="none" stroke="currentColor" stroke-width="1.1"/>
    <text x="210" y="157" text-anchor="middle">CC Switch</text>
    <rect x="288" y="140" width="132" height="26" fill="none" stroke="currentColor" stroke-width="1.1"/>
    <text x="354" y="157" text-anchor="middle">DeepChat</text>
    <rect x="432" y="140" width="132" height="26" fill="none" stroke="currentColor" stroke-width="1.1"/>
    <text x="498" y="157" text-anchor="middle">Lobe Chat</text>
    <rect x="576" y="140" width="132" height="26" fill="none" stroke="currentColor" stroke-width="1.1"/>
    <text x="642" y="157" text-anchor="middle">AionUI</text>
    <rect x="720" y="140" width="132" height="26" fill="none" stroke="currentColor" stroke-width="1.1"/>
    <text x="786" y="157" text-anchor="middle">OpenCat</text>
    <rect x="0"   y="172" width="132" height="26" fill="none" stroke="currentColor" stroke-width="1.1"/>
    <text x="66"  y="189" text-anchor="middle">AMA 问天</text>
    <rect x="144" y="172" width="180" height="26" fill="none" stroke="currentColor" stroke-width="1.1"/>
    <text x="234" y="189" text-anchor="middle">AI as Workspace</text>
    <rect x="336" y="172" width="132" height="26" fill="none" stroke="currentColor" stroke-width="1.1"/>
    <text x="402" y="189" text-anchor="middle">流畅阅读</text>
    <text x="486" y="189" opacity="0.7">另有 Windows / Mac 客户端与配置教程</text>
  </g>
</svg>
<figcaption>
一键导入走的是各客户端自己的协议链接（<code>cherrystudio://</code>、<code>aionui://</code> 之类），
点一下把 base_url 和 key 直接写进客户端，<strong>不用手抄密钥</strong>——手抄是这一步最常见的出错点。
不在列表里的客户端，改 <code>base_url</code> 手动填也一样能用，它是标准 OpenAI 兼容接口。
</figcaption>
</figure>
<h3 id="怎么开始">怎么开始</h3>
<ul>
<li><strong>直接在 <a href="https://aizhuan.fun">aizhuan.fun</a> 注册</strong>，不需要邀请码。</li>
<li><strong>注册即送 $1 额度</strong>，够把下面的接入示例跑通、把想用的模型挨个试一遍。</li>
<li><strong>充值支持微信和支付宝，没有起充门槛。</strong></li>
</ul>
<p>后两条正好对上前面提出的两个问题。</p>
<p>第三条对应「直连官方」那节说的支付摩擦——不需要能付美元的卡，这是选中转站相对直连的主要实际收益之一。</p>
<p>第二条对应更重要的那个：<strong>你没有办法验证一个中转站说的话。</strong>
所以别信我上面写的任何一句，用那 $1 自己验：流式是不是真流式、首字节多久、
你要的模型在不在、并发起来会不会掉。验完再决定要不要充钱。</p>
<p>一个中转站敢不敢让你先验证再付费，本身就是个信号。</p>
<!-- 图 4：注册到拿到 key 的流程截图（2-3 张拼一张即可）。
     或者一张最简单的调用示例截图（终端里 curl 成功返回）。 -->
<h3 id="接入示例">接入示例</h3>
<p>它是 OpenAI 兼容接口，绝大多数客户端和 SDK 改两行就能用：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">openai</span> <span class="kn">import</span> <span class="n">OpenAI</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">client</span> <span class="o">=</span> <span class="n">OpenAI</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">base_url</span><span class="o">=</span><span class="s2">&#34;https://aizhuan.fun/v1&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">api_key</span><span class="o">=</span><span class="s2">&#34;你的 key&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">max_retries</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>   <span class="c1"># 按 token 计费的接口，务必显式关掉自动重试</span>
</span></span><span class="line"><span class="cl">    <span class="n">timeout</span><span class="o">=</span><span class="mf">600.0</span><span class="p">,</span>   <span class="c1"># 生成慢是正常的，别让客户端先放弃</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><p>那两行注释不是客套。<code>max_retries</code> 默认是 2，一次超时会让上游生成两次、计费两次——
<a href="/posts/llm-api-timeout-retry-double-billing/">这条链路我单独写过一篇</a>，
无论你用哪家中转都建议先看一眼。</p>
<h2 id="我不承诺什么">我不承诺什么</h2>
<p>这一节比上面所有内容都重要，因为它是可证伪的。</p>
<ul>
<li><strong>不承诺 100% 可用。</strong> 上游会抖、机房会抽风、模型会临时下线。
我能承诺的是出问题时有人在，以及事后会说清楚发生了什么。</li>
<li><strong>不承诺永远最便宜。</strong> 中转站的价格随上游成本浮动，任何&quot;永久最低价&quot;的说法都不可信。</li>
<li><strong>不承诺模型和官方完全同步。</strong> 新模型上线需要时间接入和测试。</li>
<li><strong>不承诺替代直连。</strong> 如果你有稳定的官方渠道和付款方式，直连仍然是更干净的选择——
这话写在推广文里看着奇怪，但它是真的。</li>
</ul>
<!-- 图 5（可选）：站点的实际可用性或用量统计截图。
     只有在数据真实且你愿意公开时才放；数据不好看就不要放，
     放一张修饰过的图比不放伤害大得多。 -->
<h2 id="最后">最后</h2>
<p>选哪条路取决于你在乎什么：</p>
<ul>
<li>在乎<strong>责任边界清晰</strong> → 直连官方</li>
<li>在乎<strong>掌控力，且愿意承担运维</strong> → 自建，那六篇文章拿去用</li>
<li>在乎<strong>尽快开始做正事</strong> → 用现成的，包括但不限于我这个</li>
</ul>
<p>三条路我都走过，所以这篇文章里没有一句&quot;中转站是唯一选择&quot;。
如果看完你决定自建，我反而挺高兴——那六篇文章就没白写。</p>
<h2 id="相关阅读">相关阅读</h2>
<ul>
<li><a href="/posts/new-api-binary-vs-docker/">new-api 部署选型：2G 小内存机器上裸二进制比 Docker 省多少</a></li>
<li><a href="/posts/llm-api-sse-proxy-buffering/">反代把大模型 API 的 SSE 流式响应缓冲了：五个缓冲点与三层排查法</a></li>
<li><a href="/posts/llm-api-timeout-retry-double-billing/">大模型 API 中转的超时与重试：一次 504 可能让你双倍计费</a></li>
</ul>
]]></content:encoded></item><item><title>大模型 API 中转的超时与重试：一次 504 可能让你双倍计费</title><link>https://ambertu.com/posts/llm-api-timeout-retry-double-billing/</link><pubDate>Fri, 04 Sep 2026 00:00:00 +0000</pubDate><guid>https://ambertu.com/posts/llm-api-timeout-retry-double-billing/</guid><description>nginx 的 proxy_read_timeout 默认 60 秒，而长上下文生成常常超过它。超时返回 504 后客户端 SDK 会自动重试，上游却已经生成并计费——一次超时变成两次账单。本文拆解这条链路并给出正确的超时分层。</description><content:encoded><![CDATA[<p>nginx 的 <code>proxy_read_timeout</code> 默认是 <strong>60 秒</strong>，而长上下文或推理模型的单次生成经常超过这个数。超时之后 nginx 返回 504，看起来只是&quot;一次失败&quot;——但真实后果比这严重：<strong>上游很可能已经把生成做完并计了费，而客户端 SDK 收到 504 会自动重试，于是上游又生成一次、又计一次费。</strong></p>
<p>客户端最终只拿到一个响应，你的账单上是两笔。更麻烦的是这件事在监控里几乎看不出来：错误率只涨了一点，成本却在悄悄翻倍。</p>
<h2 id="先纠正一个常见的误解">先纠正一个常见的误解.</h2>
<p>网上很多文章会告诉你 nginx 的 <code>proxy_next_upstream</code> 会把超时请求转给下一个上游、导致重复计费。<strong>这个说法对 LLM API 来说是不准确的</strong>，值得先说清楚，否则你会去改一个本来没问题的配置。</p>
<p><code>proxy_next_upstream</code> 的默认值确实是 <code>error timeout</code>，但 nginx 从 <strong>1.9.13</strong> 起有一条额外规则：</p>
<blockquote>
<p>非幂等方法（POST、LOCK、PATCH）的请求，<strong>一旦已经发送给上游，就不会</strong>再转给下一台服务器——除非你显式加上 <code>non_idempotent</code> 选项。</p>
</blockquote>
<p>LLM 的 chat completions 走的是 POST，所以 nginx 默认行为是安全的。<strong>真正的重复计费来源有两个，都不是 nginx 的默认配置：</strong></p>
<ol>
<li><strong>有人手工加了 <code>non_idempotent</code></strong>——一些&quot;提升可用性&quot;的高可用教程会教这个，在普通 Web 服务上无害，在按 token 计费的接口上是直接烧钱。</li>
<li><strong>客户端 SDK 自己在重试</strong>——这是绝大多数情况的元凶。OpenAI 官方 Python SDK 的 <code>max_retries</code> <strong>默认是 2</strong>，重试触发条件包含连接错误、408、409、429 和所有 5xx。nginx 吐的 504 正好落在 5xx 里。</li>
</ol>
<h2 id="双倍计费是怎么发生的">双倍计费是怎么发生的</h2>
<figure>
<svg viewBox="0 0 820 340" role="img" aria-label="时序图：客户端请求经 nginx 转发给上游，上游生成耗时 75 秒；nginx 在 60 秒时触发 proxy_read_timeout 返回 504，但上游继续生成完并计费；客户端 SDK 收到 504 后自动重试，上游第二次生成并再次计费，最终客户端得到一个响应而产生两笔账单" style="width:100%;height:auto;color:currentColor">
  <defs>
    <marker id="t1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto">
      <path d="M 0 1 L 10 5 L 0 9 z" fill="currentColor"/>
    </marker>
  </defs>
  <g font-family="monospace" font-size="11" fill="currentColor">
    <text x="40" y="16" text-anchor="middle">客户端</text>
    <text x="300" y="16" text-anchor="middle">nginx</text>
    <text x="600" y="16" text-anchor="middle">上游 API</text>
  </g>
  <line x1="40"  y1="26" x2="40"  y2="300" stroke="currentColor" stroke-width="1" opacity="0.3" stroke-dasharray="3 4"/>
  <line x1="300" y1="26" x2="300" y2="300" stroke="currentColor" stroke-width="1" opacity="0.3" stroke-dasharray="3 4"/>
  <line x1="600" y1="26" x2="600" y2="300" stroke="currentColor" stroke-width="1" opacity="0.3" stroke-dasharray="3 4"/>
  <g font-family="monospace" font-size="9.5" fill="currentColor">
    <!-- t0 -->
    <text x="0" y="52" opacity="0.6">t=0s</text>
    <line x1="40" y1="48" x2="296" y2="48" stroke="currentColor" stroke-width="1.2" marker-end="url(#t1)"/>
    <line x1="300" y1="48" x2="596" y2="48" stroke="currentColor" stroke-width="1.2" marker-end="url(#t1)"/>
    <text x="450" y="41" text-anchor="middle" opacity="0.7">POST /v1/chat/completions</text>
    <!-- generating 1 -->
    <rect x="586" y="56" width="28" height="70" fill="currentColor" opacity="0.2"/>
    <text x="626" y="80">生成中</text>
    <text x="626" y="94" opacity="0.7">第 1 次</text>
    <text x="626" y="112" font-weight="bold">已计费 ①</text>
    <!-- timeout -->
    <text x="0" y="136" opacity="0.6">t=60s</text>
    <line x1="296" y1="132" x2="44" y2="132" stroke="currentColor" stroke-width="1.4" marker-end="url(#t1)"/>
    <text x="170" y="125" text-anchor="middle" font-weight="bold">504 Gateway Timeout</text>
    <text x="170" y="146" text-anchor="middle" opacity="0.7">proxy_read_timeout 到点</text>
    <text x="626" y="140" opacity="0.7">上游不知道</text>
    <text x="626" y="154" opacity="0.7">nginx 放弃了，</text>
    <text x="626" y="168" opacity="0.7">继续把生成做完</text>
    <!-- retry -->
    <text x="0" y="196" opacity="0.6">t=60s</text>
    <line x1="40" y1="192" x2="296" y2="192" stroke="currentColor" stroke-width="1.4" marker-end="url(#t1)"/>
    <line x1="300" y1="192" x2="596" y2="192" stroke="currentColor" stroke-width="1.4" marker-end="url(#t1)"/>
    <text x="450" y="185" text-anchor="middle" font-weight="bold">SDK 自动重试（max_retries=2）</text>
    <!-- generating 2 -->
    <rect x="586" y="200" width="28" height="70" fill="currentColor" opacity="0.2"/>
    <text x="626" y="224">生成中</text>
    <text x="626" y="238" opacity="0.7">第 2 次</text>
    <text x="626" y="256" font-weight="bold">又计费 ②</text>
    <!-- success -->
    <text x="0" y="288" opacity="0.6">t=135s</text>
    <line x1="596" y1="284" x2="304" y2="284" stroke="currentColor" stroke-width="1.2" marker-end="url(#t1)"/>
    <line x1="296" y1="284" x2="44" y2="284" stroke="currentColor" stroke-width="1.2" marker-end="url(#t1)"/>
    <text x="170" y="277" text-anchor="middle" opacity="0.7">200 OK</text>
  </g>
  <line x1="0" y1="306" x2="800" y2="306" stroke="currentColor" stroke-width="1" opacity="0.2"/>
  <text x="0" y="326" font-size="10.5" font-family="monospace" fill="currentColor" font-weight="bold">客户端拿到 1 个响应 · 账单上 2 笔 · 监控里只是错误率轻微上升</text>
</svg>
<figcaption>
链条的关键一环是<strong>上游并不知道 nginx 已经放弃</strong>——它按自己的节奏把生成做完。是否计费取决于供应商策略，
但<strong>安全假设是"已经计了"</strong>：连接中断后仍收费的供应商很常见，你无法事后核对。
</figcaption>
</figure>
<h2 id="流式请求几乎不会撞上这个问题">流式请求几乎不会撞上这个问题</h2>
<p>这是很多人不知道的一点，也是&quot;默认就该用流式&quot;的一个纯运维理由。<code>proxy_read_timeout</code> 的官方定义是：</p>
<blockquote>
<p>该超时只作用于<strong>两次连续读操作之间</strong>，而不是整个响应的传输时长。</p>
</blockquote>
<p>所以：</p>
<ul>
<li><strong>非流式请求</strong>：从发出到收到完整 JSON，中间是一个长长的空隙。生成花 75 秒，就是一个 75 秒的读间隔 → 撞上 60 秒超时。</li>
<li><strong>流式请求</strong>：token 一个接一个到达，每两次读之间只隔几百毫秒 → 无论总时长多久都不会触发超时。</li>
</ul>
<figure>
<svg viewBox="0 0 780 220" role="img" aria-label="对比图：非流式请求在整个生成期间没有任何数据到达，形成一个 75 秒的读间隔从而在 60 秒处触发超时；流式请求每几百毫秒到达一个 token，读间隔始终很小，永不触发超时" style="width:100%;height:auto;color:currentColor">
  <text x="0" y="14" font-size="10.5" font-family="monospace" fill="currentColor" opacity="0.6">nginx 眼中的「两次读操作之间的间隔」</text>
  <!-- timeout threshold -->
  <line x1="130" y1="30" x2="130" y2="180" stroke="currentColor" stroke-width="0" />
  <line x1="530" y1="26" x2="530" y2="186" stroke="currentColor" stroke-width="1.4" stroke-dasharray="5 4"/>
  <text x="538" y="40" font-size="9.5" font-family="monospace" fill="currentColor" font-weight="bold">60s 超时线</text>
  <g font-family="monospace" font-size="10.5" fill="currentColor">
    <text x="0" y="66">非流式</text>
    <line x1="130" y1="70" x2="700" y2="70" stroke="currentColor" stroke-width="1" opacity="0.25"/>
    <rect x="130" y="60" width="10" height="20" fill="currentColor" opacity="0.75"/>
    <rect x="620" y="60" width="80" height="20" fill="currentColor" opacity="0.4"/>
    <path d="M 142 90 L 616 90" stroke="currentColor" stroke-width="1.2" marker-end="url(#t1)"/>
    <text x="370" y="106" text-anchor="middle" font-size="9.5" font-weight="bold">一个 75s 的读间隔 → 在 60s 处被切断</text>
    <text x="0" y="152">流式</text>
    <line x1="130" y1="156" x2="700" y2="156" stroke="currentColor" stroke-width="1" opacity="0.25"/>
  </g>
  <g fill="currentColor" opacity="0.75">
    <rect x="130" y="146" width="8" height="20"/><rect x="152" y="146" width="8" height="20"/>
    <rect x="174" y="146" width="8" height="20"/><rect x="196" y="146" width="8" height="20"/>
    <rect x="218" y="146" width="8" height="20"/><rect x="240" y="146" width="8" height="20"/>
    <rect x="262" y="146" width="8" height="20"/><rect x="284" y="146" width="8" height="20"/>
    <rect x="306" y="146" width="8" height="20"/><rect x="328" y="146" width="8" height="20"/>
    <rect x="350" y="146" width="8" height="20"/><rect x="372" y="146" width="8" height="20"/>
    <rect x="394" y="146" width="8" height="20"/><rect x="416" y="146" width="8" height="20"/>
    <rect x="438" y="146" width="8" height="20"/><rect x="460" y="146" width="8" height="20"/>
    <rect x="482" y="146" width="8" height="20"/><rect x="504" y="146" width="8" height="20"/>
    <rect x="548" y="146" width="8" height="20"/><rect x="570" y="146" width="8" height="20"/>
    <rect x="592" y="146" width="8" height="20"/><rect x="614" y="146" width="8" height="20"/>
    <rect x="636" y="146" width="8" height="20"/><rect x="658" y="146" width="8" height="20"/>
  </g>
  <text x="130" y="188" font-size="9.5" font-family="monospace" fill="currentColor" font-weight="bold">每个间隔都远小于 60s → 穿过超时线也毫发无伤</text>
  <text x="0" y="212" font-size="10" font-family="monospace" fill="currentColor" opacity="0.6">本图为示意，用于说明超时的计量方式</text>
</svg>
<figcaption>
同一个总时长、同一个超时配置，结果完全不同。<strong>非流式请求才是超时的重灾区。</strong>
如果你的中转站还有大量非流式调用，这就是优先要治的地方——而不是一味把超时往上调。
</figcaption>
</figure>
<h2 id="正确的超时分层">正确的超时分层</h2>
<p>关键是<strong>区分&quot;连不上&quot;和&quot;生成慢&quot;</strong>：前者应该快速失败，后者必须耐心等。用一个统一的大数字把三个超时都拉长，是把两种完全不同的故障混在一起处理。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-nginx" data-lang="nginx"><span class="line"><span class="cl"><span class="k">location</span> <span class="s">/v1/</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_pass</span> <span class="s">http://upstream_pool</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># 连不上 → 快速失败。请求还没发出去，此时重试是安全的
</span></span></span><span class="line"><span class="cl">    <span class="kn">proxy_connect_timeout</span>  <span class="s">5s</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># 发送请求体 → 大 prompt 也就几百 KB，给足但不必夸张
</span></span></span><span class="line"><span class="cl">    <span class="kn">proxy_send_timeout</span>     <span class="s">60s</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># 读响应 → 生成慢是正常的，不是故障。这里必须放宽
</span></span></span><span class="line"><span class="cl">    <span class="kn">proxy_read_timeout</span>     <span class="s">600s</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># LLM 是非幂等的：绝不要开 non_idempotent
</span></span></span><span class="line"><span class="cl">    <span class="c1"># 保守起见连 timeout 重试也去掉，只保留连接阶段的重试
</span></span></span><span class="line"><span class="cl">    <span class="kn">proxy_next_upstream</span>    <span class="s">error</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_next_upstream_tries</span> <span class="mi">2</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_next_upstream_timeout</span> <span class="s">10s</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># 流式必须配套，否则响应被攒起来又变回一个长读间隔
</span></span></span><span class="line"><span class="cl">    <span class="kn">proxy_buffering</span>        <span class="no">off</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">gzip</span>                   <span class="no">off</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_http_version</span>     <span class="mi">1</span><span class="s">.1</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_set_header</span>       <span class="s">Connection</span> <span class="s">&#34;&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><figure>
<svg viewBox="0 0 740 200" role="img" aria-label="超时分层示意：连接超时 5 秒对应连不上的情况且重试安全，发送超时 60 秒，读取超时 600 秒对应生成慢的情况不应视为故障，客户端 SDK 重试次数应设为 0 或 1" style="width:100%;height:auto;color:currentColor">
  <text x="0" y="14" font-size="10.5" font-family="monospace" fill="currentColor" opacity="0.6">按故障性质分层，而不是统一拉长</text>
  <g font-family="monospace" font-size="10.5" fill="currentColor">
    <rect x="0" y="30" width="700" height="34" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="12" y="52">proxy_connect_timeout</text>
    <text x="200" y="52" font-weight="bold">5s</text>
    <text x="250" y="52" opacity="0.7">连不上 → 快速失败</text>
    <text x="500" y="52" opacity="0.7">请求未发出，重试安全 ✓</text>
    <rect x="0" y="72" width="700" height="34" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="12" y="94">proxy_send_timeout</text>
    <text x="200" y="94" font-weight="bold">60s</text>
    <text x="250" y="94" opacity="0.7">上传 prompt</text>
    <text x="500" y="94" opacity="0.7">已发出，重试即重复计费 ⚠</text>
    <rect x="0" y="114" width="700" height="34" fill="currentColor" fill-opacity="0.1" stroke="currentColor" stroke-width="1.5"/>
    <text x="12" y="136">proxy_read_timeout</text>
    <text x="200" y="136" font-weight="bold">600s</text>
    <text x="250" y="136" opacity="0.7">生成慢 → 不是故障</text>
    <text x="500" y="136" font-weight="bold">这一层千万别按 60s 算 ⚠</text>
    <rect x="0" y="156" width="700" height="34" fill="none" stroke="currentColor" stroke-width="1.3" stroke-dasharray="4 3"/>
    <text x="12" y="178">SDK max_retries</text>
    <text x="200" y="178" font-weight="bold">0 或 1</text>
    <text x="250" y="178" opacity="0.7">客户端侧</text>
    <text x="500" y="178" opacity="0.7">默认 2，是双倍计费主因</text>
  </g>
</svg>
<figcaption>灰底那一行是唯一需要显著放宽的；虚线那一行不在服务端，<strong>但它才是账单翻倍的直接原因</strong>，容易被漏掉。</figcaption>
</figure>
<h2 id="客户端侧要做的事">客户端侧要做的事</h2>
<p>服务端配对了，客户端如果还在盲目重试，问题只是变少而不是消失。</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-python" data-lang="python"><span class="line"><span class="cl"><span class="kn">from</span> <span class="nn">openai</span> <span class="kn">import</span> <span class="n">OpenAI</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">client</span> <span class="o">=</span> <span class="n">OpenAI</span><span class="p">(</span>
</span></span><span class="line"><span class="cl">    <span class="n">base_url</span><span class="o">=</span><span class="s2">&#34;https://your-gateway/v1&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">api_key</span><span class="o">=</span><span class="s2">&#34;...&#34;</span><span class="p">,</span>
</span></span><span class="line"><span class="cl">    <span class="n">max_retries</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>   <span class="c1"># 默认是 2，对按 token 计费的接口必须显式关掉</span>
</span></span><span class="line"><span class="cl">    <span class="n">timeout</span><span class="o">=</span><span class="mf">600.0</span><span class="p">,</span>   <span class="c1"># 客户端超时也要放宽，否则轮到它先放弃</span>
</span></span><span class="line"><span class="cl"><span class="p">)</span>
</span></span></code></pre></div><p>关掉自动重试之后，重试逻辑要自己写，并且<strong>只在明确安全的错误上重试</strong>：</p>
<table>
	<thead>
			<tr>
					<th>错误</th>
					<th>能否重试</th>
					<th>原因</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>连接失败 / DNS 失败</td>
					<td><strong>可以</strong></td>
					<td>请求没发出去，上游没开始生成</td>
			</tr>
			<tr>
					<td><code>429</code> 限流</td>
					<td><strong>可以</strong></td>
					<td>上游明确拒绝了，没有生成</td>
			</tr>
			<tr>
					<td><code>400</code> 参数错误</td>
					<td>不该重试</td>
					<td>重试一万次也是同样结果</td>
			</tr>
			<tr>
					<td><code>401</code> / <code>403</code></td>
					<td>不该重试</td>
					<td>凭据问题</td>
			</tr>
			<tr>
					<td><code>504</code> / <code>502</code></td>
					<td><strong>危险</strong></td>
					<td>上游可能已经生成完了，重试就是第二笔账单</td>
			</tr>
			<tr>
					<td>流式中途断开</td>
					<td><strong>危险</strong></td>
					<td>已经生成了一部分，且已产生费用</td>
			</tr>
	</tbody>
</table>
<h2 id="更彻底的办法在中转层做请求去重">更彻底的办法：在中转层做请求去重</h2>
<p>如果你控制中转层（自建 new-api 之类就是这种情况），可以在网关上加一层短窗口去重，把重复计费在源头掐掉：</p>
<p>思路是给每个请求算一个指纹——模型名 + 消息体 + 关键参数的哈希——配上客户端标识，在 Redis 里存一个几十秒的短 key。窗口内出现相同指纹时，不再打上游，直接返回上一次的结果或一个明确的&quot;重复请求&quot;错误。</p>
<p>这个做法的取舍要讲清楚：</p>
<ul>
<li><strong>好处</strong>：无论客户端怎么重试，上游只被打一次，账单可控。</li>
<li><strong>代价</strong>：LLM 本身是有随机性的（temperature &gt; 0 时同样输入本该有不同输出），去重会让窗口内的重复请求拿到相同结果。对聊天场景通常无害，对&quot;故意重新生成一次&quot;的功能就是 bug。</li>
<li><strong>所以</strong>：窗口要短（几十秒量级），并且给客户端一个显式绕过的办法（比如一个请求头或一个随机 nonce 参数）。</li>
</ul>
<h2 id="怎么发现自己已经在被双倍计费">怎么发现自己已经在被双倍计费</h2>
<p>从日志里找证据，不用等账单。特征是：<strong>同一客户端在很短时间内发出内容完全相同的请求，且其中至少一个返回了 504。</strong></p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># 找 504：如果这个数不是 0，就值得往下查</span>
</span></span><span class="line"><span class="cl">awk <span class="s1">&#39;$9==504 {print $1, $7}&#39;</span> /var/log/nginx/access.log <span class="p">|</span> sort <span class="p">|</span> uniq -c <span class="p">|</span> sort -rn <span class="p">|</span> head
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># 找 504 之后紧跟着重试的模式：同 IP、同路径、几秒内连续多次</span>
</span></span><span class="line"><span class="cl">awk <span class="s1">&#39;$9==504 || $9==200 {print $1, $4, $9, $7}&#39;</span> /var/log/nginx/access.log <span class="se">\
</span></span></span><span class="line"><span class="cl">  <span class="p">|</span> grep <span class="s1">&#39;/v1/chat/completions&#39;</span> <span class="p">|</span> tail -50
</span></span></code></pre></div><p>更可靠的信号是把<strong>上游用量与自己记录的成功响应数对账</strong>：如果上游统计的请求数明显高于你返回给客户端的成功数，差额基本就是被白烧掉的重试。</p>
<h2 id="相关阅读">相关阅读</h2>
<ul>
<li><a href="/posts/llm-api-sse-proxy-buffering/">反代把大模型 API 的 SSE 流式响应缓冲了：五个缓冲点与三层排查法</a> —— 本文说流式不容易超时，前提是流式真的没被缓冲掉</li>
<li><a href="/posts/caddy-vs-nginx-api-gateway-tls/">Caddy 还是 nginx 给 API 中转做反代：证书自动化是决定性差异</a> —— 另一类会让全部请求一起失败的运维故障</li>
<li><a href="/posts/new-api-binary-vs-docker/">new-api 部署选型：2G 小内存机器上裸二进制比 Docker 省多少</a> —— 超时配置所在的那层反代怎么部署</li>
<li><a href="/posts/api-gateway-database-choice-small-vps/">给 API 中转站选数据库：SQLite / MySQL / PostgreSQL 在小机器上的取舍</a> —— 本文说的&quot;拿用量日志对账&quot;，那张表本身也会变成问题</li>
</ul>
]]></content:encoded></item><item><title>反代把大模型 API 的 SSE 流式响应缓冲了：五个缓冲点与三层排查法</title><link>https://ambertu.com/posts/llm-api-sse-proxy-buffering/</link><pubDate>Thu, 03 Sep 2026 00:00:00 +0000</pubDate><guid>https://ambertu.com/posts/llm-api-sse-proxy-buffering/</guid><description>大模型 API 中转后流式输出变成一次性返回，首字节延迟等于整个生成时长？问题几乎不在应用。本文列出请求路径上真实存在的五个缓冲点，给出一套从应用往外逐层二分的排查方法。</description><content:encoded><![CDATA[<p>自建大模型 API 中转后最常见的故障是：<strong>后端明明是流式的，经过反向代理就变成一次性返回</strong>——客户端等十几秒没有任何输出，然后整段文字一次吐完。首字节延迟几乎等于整个生成时长，流式的意义全部丧失。</p>
<p>这个问题九成不在应用代码里，而在 <strong>nginx 的 <code>proxy_buffering</code> 默认是开启的</strong>。但真正麻烦的地方是：请求路径上会缓冲的地方不止 nginx 一个，实际有五个，而且<strong>其中一个是你用来排查的 curl 自己</strong>。如果不知道这一点，你会在错误的层上改半天配置。</p>
<h2 id="先分清-sse-和-websocket">先分清 SSE 和 WebSocket</h2>
<p>这是配置写错的根源。大模型 API 的流式输出用的是 <strong>SSE（Server-Sent Events）</strong>：一个普通的 HTTP 响应，<code>Content-Type: text/event-stream</code>，靠 chunked 编码持续往下写。<strong>它不涉及协议升级。</strong></p>
<p>而网上大量&quot;流式接口反代配置&quot;教程给的是 WebSocket 的写法：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-nginx" data-lang="nginx"><span class="line"><span class="cl"><span class="c1"># ❌ 这是 WebSocket 的配置，SSE 不需要，而且硬编码有害
</span></span></span><span class="line"><span class="cl"><span class="k">proxy_set_header</span> <span class="s">Upgrade</span> <span class="nv">$http_upgrade</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="k">proxy_set_header</span> <span class="s">Connection</span> <span class="s">&#34;upgrade&#34;</span><span class="p">;</span>
</span></span></code></pre></div><p>问题出在第二行<strong>硬编码</strong>了 <code>&quot;upgrade&quot;</code>：它会给经过这个 location 的<strong>所有</strong>请求都带上 <code>Connection: upgrade</code>，包括根本没有 <code>Upgrade</code> 头的普通请求和 SSE 请求。<code>Connection</code> 是逐跳（hop-by-hop）首部，被这么滥用会破坏到上游的 keepalive，某些上游实现还会因此行为异常。</p>
<p>正确的写法是用 <code>map</code> 按客户端是否真的请求升级来取值：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-nginx" data-lang="nginx"><span class="line"><span class="cl"><span class="c1"># http 块内
</span></span></span><span class="line"><span class="cl"><span class="k">map</span> <span class="nv">$http_upgrade</span> <span class="nv">$connection_upgrade</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="kn">default</span> <span class="s">upgrade</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">&#39;&#39;</span>      <span class="s">close</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># location 内
</span></span></span><span class="line"><span class="cl"><span class="k">proxy_http_version</span> <span class="mi">1</span><span class="s">.1</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="k">proxy_set_header</span> <span class="s">Upgrade</span>    <span class="nv">$http_upgrade</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="k">proxy_set_header</span> <span class="s">Connection</span> <span class="nv">$connection_upgrade</span><span class="p">;</span>
</span></span></code></pre></div><p>如果这个 location 只服务 SSE、完全没有 WebSocket，那更简单——两行都不要写，改成让 nginx 复用到上游的连接：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-nginx" data-lang="nginx"><span class="line"><span class="cl"><span class="k">proxy_http_version</span> <span class="mi">1</span><span class="s">.1</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="k">proxy_set_header</span> <span class="s">Connection</span> <span class="s">&#34;&#34;</span><span class="p">;</span>
</span></span></code></pre></div><h2 id="请求路径上真实存在的五个缓冲点">请求路径上真实存在的五个缓冲点</h2>
<figure>
<svg viewBox="0 0 800 240" role="img" aria-label="从应用到客户端的请求路径上有五个缓冲点：应用是否调用 flush、nginx 的 proxy_buffering、nginx 的 gzip 压缩、CDN 层缓冲、以及客户端 curl 自身的输出缓冲" style="width:100%;height:auto;color:currentColor">
  <defs>
    <marker id="a1" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto">
      <path d="M 0 1 L 10 5 L 0 9 z" fill="currentColor"/>
    </marker>
  </defs>
  <text x="0" y="14" font-size="11" font-family="monospace" fill="currentColor" opacity="0.6">token 的流动方向 →</text>
  <g font-family="monospace" font-size="11.5" fill="currentColor">
    <rect x="0" y="42" width="118" height="42" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="59" y="68" text-anchor="middle">应用</text>
    <line x1="118" y1="63" x2="198" y2="63" stroke="currentColor" stroke-width="1.2" marker-end="url(#a1)"/>
    <rect x="200" y="42" width="118" height="42" fill="currentColor" fill-opacity="0.09" stroke="currentColor" stroke-width="1.3"/>
    <text x="259" y="68" text-anchor="middle">nginx</text>
    <line x1="318" y1="63" x2="398" y2="63" stroke="currentColor" stroke-width="1.2" marker-end="url(#a1)"/>
    <rect x="400" y="42" width="118" height="42" fill="none" stroke="currentColor" stroke-width="1.3" stroke-dasharray="4 3"/>
    <text x="459" y="62" text-anchor="middle">CDN</text>
    <text x="459" y="77" text-anchor="middle" font-size="9" opacity="0.6">若有</text>
    <line x1="518" y1="63" x2="598" y2="63" stroke="currentColor" stroke-width="1.2" marker-end="url(#a1)"/>
    <rect x="600" y="42" width="118" height="42" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="659" y="68" text-anchor="middle">客户端</text>
  </g>
  <g font-family="monospace" font-size="9.5" fill="currentColor">
    <text x="0" y="112" opacity="0.55">默认</text>
    <text x="0" y="130">看代码</text>
    <text x="0" y="158" opacity="0.55">开关</text>
    <text x="0" y="176">flusher.Flush()</text>
    <text x="200" y="112" opacity="0.55">默认</text>
    <text x="200" y="130" font-weight="bold">缓冲 ⚠ 主因</text>
    <text x="200" y="158" opacity="0.55">开关</text>
    <text x="200" y="176">proxy_buffering off</text>
    <text x="200" y="194">gzip off ← 第二个</text>
    <text x="400" y="112" opacity="0.55">默认</text>
    <text x="400" y="130">多数缓冲 ⚠</text>
    <text x="400" y="158" opacity="0.55">开关</text>
    <text x="400" y="176">控制台流式配置</text>
    <text x="600" y="112" opacity="0.55">默认</text>
    <text x="600" y="130">curl 自己缓冲 ⚠</text>
    <text x="600" y="158" opacity="0.55">开关</text>
    <text x="600" y="176">curl -N</text>
  </g>
  <line x1="0" y1="212" x2="780" y2="212" stroke="currentColor" stroke-width="1" opacity="0.2"/>
  <text x="0" y="232" font-size="10" font-family="monospace" fill="currentColor" opacity="0.6">共 5 个缓冲点：应用 flush · proxy_buffering · gzip · CDN · 客户端</text>
</svg>
<figcaption>nginx 那一格是灰底的，因为它同时贡献了两个缓冲点：<code>proxy_buffering</code> 和 <code>gzip</code>。<strong>最容易误导排查的是最右边那格</strong>——不加 <code>-N</code> 的 curl 自己会缓冲输出，你会以为是服务端问题。</figcaption>
</figure>
<p>第五个缓冲点最坑人，所以单独强调：<strong><code>curl</code> 默认会缓冲输出</strong>。用不带 <code>-N</code> 的 curl 去验证流式，看到的永远是&quot;一次性返回&quot;，无论服务端配得对不对。排查流式问题的第一条纪律是所有 curl 都加 <code>-N</code>（等价于 <code>--no-buffer</code>）。</p>
<h2 id="症状长什么样">症状长什么样</h2>
<figure>
<svg viewBox="0 0 720 180" role="img" aria-label="示意图：缓冲开启时客户端长时间无输出然后一次性收到全部内容；缓冲关闭时 token 从一开始就持续到达" style="width:100%;height:auto;color:currentColor">
  <text x="0" y="14" font-size="11" font-family="monospace" fill="currentColor" opacity="0.6">客户端收到数据的时间轴（示意）</text>
  <g font-family="monospace" font-size="10.5" fill="currentColor">
    <text x="0" y="48">缓冲开启</text>
    <line x1="130" y1="52" x2="660" y2="52" stroke="currentColor" stroke-width="1" opacity="0.25"/>
    <rect x="560" y="38" width="100" height="18" fill="currentColor" opacity="0.75"/>
    <text x="130" y="76" opacity="0.6">↑ 全程无输出 ——————————————————→ 一次吐完</text>
    <text x="0" y="118">缓冲关闭</text>
    <line x1="130" y1="122" x2="660" y2="122" stroke="currentColor" stroke-width="1" opacity="0.25"/>
    <rect x="140" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <rect x="162" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <rect x="184" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <rect x="206" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <rect x="228" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <rect x="250" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <rect x="272" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <rect x="294" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <rect x="316" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <rect x="338" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <rect x="360" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <rect x="382" y="108" width="14" height="18" fill="currentColor" opacity="0.75"/>
    <text x="140" y="146" opacity="0.6">↑ 首字节很快，token 持续到达</text>
  </g>
  <text x="0" y="174" font-size="10" font-family="monospace" fill="currentColor" opacity="0.6">本图为示意，非实测数据</text>
</svg>
<figcaption>判据不是"感觉慢"，而是一个可量化的信号：<strong>首字节时间约等于总时长</strong>。下一节给出怎么量。</figcaption>
</figure>
<p>用 curl 的计时字段可以把这件事量化，不用凭感觉：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">curl -N -o /dev/null -s <span class="se">\
</span></span></span><span class="line"><span class="cl">  -w <span class="s2">&#34;首字节 %{time_starttransfer}s / 总计 %{time_total}s\n&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">  -H <span class="s2">&#34;Authorization: Bearer </span><span class="nv">$KEY</span><span class="s2">&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">  -H <span class="s2">&#34;Content-Type: application/json&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">  -d <span class="s1">&#39;{&#34;model&#34;:&#34;gpt-4o-mini&#34;,&#34;stream&#34;:true,&#34;messages&#34;:[{&#34;role&#34;:&#34;user&#34;,&#34;content&#34;:&#34;数到二十&#34;}]}&#39;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">  https://your-domain/v1/chat/completions
</span></span></code></pre></div><ul>
<li><code>首字节 ≈ 总计</code> → 被完整缓冲了</li>
<li><code>首字节 ≪ 总计</code> → 流式正常</li>
</ul>
<p>另一个免费信号在响应头里：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">curl -N -D - -o /dev/null -s ... <span class="p">|</span> grep -iE <span class="s1">&#39;content-length|transfer-encoding|content-type&#39;</span>
</span></span></code></pre></div><p><strong>出现 <code>Content-Length</code> 就说明响应被完整缓冲过</strong>——只有知道全部长度才能写出这个头。正常流式应该是 <code>Transfer-Encoding: chunked</code>（HTTP/1.1）或 HTTP/2 的分帧，加上 <code>Content-Type: text/event-stream</code>。</p>
<h2 id="三层二分排查法">三层二分排查法</h2>
<p>不要直接去猜哪一层，按下面这棵树走，两三条命令就能定位。核心思路是<strong>从最里层往外逐层加一跳</strong>，第一次出问题的那跳就是元凶。</p>
<figure>
<svg viewBox="0 0 780 350" role="img" aria-label="排查决策树：先用 curl -N 直连应用确认后端本身流式，再经 nginx，再经 CDN，每一步不流式就定位到该层" style="width:100%;height:auto;color:currentColor">
  <defs>
    <marker id="a2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto">
      <path d="M 0 1 L 10 5 L 0 9 z" fill="currentColor"/>
    </marker>
  </defs>
  <g font-family="monospace" font-size="10.5" fill="currentColor">
    <rect x="180" y="14" width="270" height="38" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="315" y="31" text-anchor="middle">① curl -N 直连 127.0.0.1:3000</text>
    <text x="315" y="45" text-anchor="middle" opacity="0.6">绕过全部反代</text>
    <line x1="200" y1="52" x2="120" y2="88" stroke="currentColor" stroke-width="1.2" marker-end="url(#a2)"/>
    <text x="140" y="74" text-anchor="end" opacity="0.75">不流式</text>
    <rect x="10" y="90" width="200" height="38" fill="currentColor" fill-opacity="0.09" stroke="currentColor" stroke-width="1.3"/>
    <text x="110" y="107" text-anchor="middle">应用没有 flush</text>
    <text x="110" y="121" text-anchor="middle" opacity="0.6">改代码，见下节</text>
    <line x1="360" y1="52" x2="430" y2="88" stroke="currentColor" stroke-width="1.2" marker-end="url(#a2)"/>
    <text x="404" y="74" opacity="0.75">流式 ✓</text>
    <rect x="330" y="90" width="270" height="38" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="465" y="107" text-anchor="middle">② curl -N 经 nginx（内网 IP）</text>
    <text x="465" y="121" text-anchor="middle" opacity="0.6">加上反代这一跳</text>
    <line x1="350" y1="128" x2="230" y2="164" stroke="currentColor" stroke-width="1.2" marker-end="url(#a2)"/>
    <text x="252" y="150" text-anchor="end" opacity="0.75">不流式</text>
    <rect x="60" y="166" width="230" height="52" fill="currentColor" fill-opacity="0.09" stroke="currentColor" stroke-width="1.3"/>
    <text x="175" y="183" text-anchor="middle">nginx 缓冲</text>
    <text x="175" y="197" text-anchor="middle" opacity="0.6">proxy_buffering / gzip</text>
    <text x="175" y="211" text-anchor="middle" opacity="0.6">最常见的一档</text>
    <line x1="520" y1="128" x2="570" y2="164" stroke="currentColor" stroke-width="1.2" marker-end="url(#a2)"/>
    <text x="548" y="150" opacity="0.75">流式 ✓</text>
    <rect x="450" y="166" width="270" height="38" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="585" y="183" text-anchor="middle">③ curl -N 经公网域名</text>
    <text x="585" y="197" text-anchor="middle" opacity="0.6">加上 CDN 这一跳</text>
    <line x1="480" y1="204" x2="400" y2="242" stroke="currentColor" stroke-width="1.2" marker-end="url(#a2)"/>
    <text x="420" y="228" text-anchor="end" opacity="0.75">不流式</text>
    <rect x="250" y="244" width="200" height="38" fill="currentColor" fill-opacity="0.09" stroke="currentColor" stroke-width="1.3"/>
    <text x="350" y="261" text-anchor="middle">CDN 在缓冲</text>
    <text x="350" y="275" text-anchor="middle" opacity="0.6">去控制台配流式</text>
    <line x1="650" y1="204" x2="680" y2="242" stroke="currentColor" stroke-width="1.2" marker-end="url(#a2)"/>
    <text x="670" y="228" opacity="0.75">流式 ✓</text>
    <rect x="530" y="244" width="240" height="52" fill="none" stroke="currentColor" stroke-width="1.3"/>
    <text x="650" y="261" text-anchor="middle">服务端没问题</text>
    <text x="650" y="275" text-anchor="middle" opacity="0.6">查客户端：漏了 -N，</text>
    <text x="650" y="289" text-anchor="middle" opacity="0.6">或 SDK 未开 stream</text>
  </g>
  <text x="0" y="330" font-size="10" font-family="monospace" fill="currentColor" opacity="0.6">每一步都必须带 -N，否则测的是 curl 自己的缓冲</text>
</svg>
<figcaption>这套方法的价值在于<strong>每次只增加一跳</strong>，所以定位是确定的，不需要靠猜。灰底的三个是终点结论。</figcaption>
</figure>
<h2 id="nginx-侧的完整配置">nginx 侧的完整配置</h2>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-nginx" data-lang="nginx"><span class="line"><span class="cl"><span class="k">location</span> <span class="s">/v1/</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_pass</span> <span class="s">http://127.0.0.1:3000/v1/</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># 关掉响应缓冲 —— 解决问题的主开关
</span></span></span><span class="line"><span class="cl">    <span class="kn">proxy_buffering</span>    <span class="no">off</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_request_buffering</span> <span class="no">off</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_cache</span>        <span class="no">off</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># gzip 压缩也会攒数据，流式 location 里必须关
</span></span></span><span class="line"><span class="cl">    <span class="kn">gzip</span>               <span class="no">off</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># chunked 需要 HTTP/1.1；清空 Connection 让 nginx 复用上游连接
</span></span></span><span class="line"><span class="cl">    <span class="kn">proxy_http_version</span> <span class="mi">1</span><span class="s">.1</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_set_header</span>   <span class="s">Connection</span> <span class="s">&#34;&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># 长生成会超过默认的 60s，放宽读超时
</span></span></span><span class="line"><span class="cl">    <span class="kn">proxy_read_timeout</span> <span class="s">600s</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_send_timeout</span> <span class="s">600s</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_set_header</span>   <span class="s">Host</span>      <span class="nv">$host</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_set_header</span>   <span class="s">X-Real-IP</span> <span class="nv">$remote_addr</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p>几个容易漏的点：</p>
<ul>
<li><strong><code>gzip off</code> 不是可选项。</strong> nginx 的 gzip 模块要攒够数据才能压缩，开着它等于重新引入缓冲。很多人只关了 <code>proxy_buffering</code> 就以为完事，结果症状减轻但没消失，就是 gzip 在作祟。</li>
<li><strong><code>proxy_read_timeout</code> 默认 60 秒。</strong> 长上下文生成很容易超，超了会收到截断的响应或 504，且现象酷似&quot;流式坏了&quot;。</li>
<li><strong><code>proxy_request_buffering off</code></strong> 管的是请求方向，上传大 prompt 时有用，和响应流式无关但顺手一起配。</li>
</ul>
<h3 id="不想改-nginx-配置用响应头">不想改 nginx 配置？用响应头</h3>
<p>如果你没有 nginx 的配置权限，或者不想为一个接口改全局配置，<strong>应用可以自己让 nginx 关掉缓冲</strong>——返回这个响应头：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-fallback" data-lang="fallback"><span class="line"><span class="cl">X-Accel-Buffering: no
</span></span></code></pre></div><p>nginx 识别这个头并对该响应禁用缓冲。这是 nginx 特有的机制，非常实用：<strong>开关从运维侧移到了应用侧</strong>，随代码走，不会因为换机器忘配而复发。</p>
<h2 id="caddy-侧">Caddy 侧</h2>
<p>Caddy 的 <code>reverse_proxy</code> 对 <code>text/event-stream</code> 会自动刷新，多数情况下开箱即用。如果确实需要强制：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-caddyfile" data-lang="caddyfile"><span class="line"><span class="cl"><span class="gh">your-domain.com</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="k">reverse_proxy</span> <span class="n">127.0.0.1</span><span class="p">:</span><span class="mi">3000</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">        <span class="k">flush_interval</span> <span class="s">-1</span>
</span></span><span class="line"><span class="cl">    <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p><code>flush_interval -1</code> 表示每次写入立即刷新。另外 Caddy 默认会对文本类型启用压缩，如果显式配了 <code>encode gzip</code>，记得把流式路径排除掉，理由和 nginx 的 <code>gzip off</code> 一样。</p>
<h2 id="应用侧反代配对了也可能不流式">应用侧：反代配对了也可能不流式</h2>
<p>如果排查树的第一步就不通过，那是应用自己没有 flush。反代关掉缓冲只是&quot;不主动攒&quot;，它没法把应用攒着不发的数据变出来。Go 里的标准写法：</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-go" data-lang="go"><span class="line"><span class="cl"><span class="kd">func</span><span class="w"> </span><span class="nf">stream</span><span class="p">(</span><span class="nx">w</span><span class="w"> </span><span class="nx">http</span><span class="p">.</span><span class="nx">ResponseWriter</span><span class="p">,</span><span class="w"> </span><span class="nx">r</span><span class="w"> </span><span class="o">*</span><span class="nx">http</span><span class="p">.</span><span class="nx">Request</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nx">flusher</span><span class="p">,</span><span class="w"> </span><span class="nx">ok</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">w</span><span class="p">.(</span><span class="nx">http</span><span class="p">.</span><span class="nx">Flusher</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="p">!</span><span class="nx">ok</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nx">http</span><span class="p">.</span><span class="nf">Error</span><span class="p">(</span><span class="nx">w</span><span class="p">,</span><span class="w"> </span><span class="s">&#34;streaming unsupported&#34;</span><span class="p">,</span><span class="w"> </span><span class="nx">http</span><span class="p">.</span><span class="nx">StatusInternalServerError</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">return</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nx">w</span><span class="p">.</span><span class="nf">Header</span><span class="p">().</span><span class="nf">Set</span><span class="p">(</span><span class="s">&#34;Content-Type&#34;</span><span class="p">,</span><span class="w"> </span><span class="s">&#34;text/event-stream&#34;</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nx">w</span><span class="p">.</span><span class="nf">Header</span><span class="p">().</span><span class="nf">Set</span><span class="p">(</span><span class="s">&#34;Cache-Control&#34;</span><span class="p">,</span><span class="w"> </span><span class="s">&#34;no-cache&#34;</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nx">w</span><span class="p">.</span><span class="nf">Header</span><span class="p">().</span><span class="nf">Set</span><span class="p">(</span><span class="s">&#34;X-Accel-Buffering&#34;</span><span class="p">,</span><span class="w"> </span><span class="s">&#34;no&#34;</span><span class="p">)</span><span class="w"> </span><span class="c1">// 顺手把 nginx 也关掉</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">for</span><span class="w"> </span><span class="nx">chunk</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="k">range</span><span class="w"> </span><span class="nx">chunks</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nx">fmt</span><span class="p">.</span><span class="nf">Fprintf</span><span class="p">(</span><span class="nx">w</span><span class="p">,</span><span class="w"> </span><span class="s">&#34;data: %s\n\n&#34;</span><span class="p">,</span><span class="w"> </span><span class="nx">chunk</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nx">flusher</span><span class="p">.</span><span class="nf">Flush</span><span class="p">()</span><span class="w"> </span><span class="c1">// 少了这行，前面全白配</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nx">fmt</span><span class="p">.</span><span class="nf">Fprint</span><span class="p">(</span><span class="nx">w</span><span class="p">,</span><span class="w"> </span><span class="s">&#34;data: [DONE]\n\n&#34;</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nx">flusher</span><span class="p">.</span><span class="nf">Flush</span><span class="p">()</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>注意 <code>w.Header().Set</code> 必须在第一次 <code>Write</code> 之前调用，否则不生效——这是另一个安静失败的经典来源。</p>
<h2 id="相关阅读">相关阅读</h2>
<ul>
<li><a href="/posts/new-api-binary-vs-docker/">new-api 部署选型：2G 小内存机器上裸二进制比 Docker 省多少</a> —— 反代前面那一层，部署形态怎么选</li>
<li><a href="/posts/api-gateway-real-ip-ratelimit/">API 中转站的限流为什么不能信 X-Forwarded-For</a> —— 本文配置里那行 <code>X-Real-IP</code> 为什么不能省</li>
</ul>
]]></content:encoded></item></channel></rss>