跳到正文
DEV Community· Altrouter·· 57 分鐘前AI 評分71

過緊的 max_tokens 上限令 LLM 答案成本增加 15%

A tight max_tokens cap made every good LLM answer 15% more expensive

AI 導讀

作者的模擬顯示,過低的 max_tokens 上限會截斷部分答案並觸發重試,推高每 1,000 個可用答案的成本。在上限設為答案長度第 90 百分位數 859 的情境下,成本由 $8.71 升至 $10.04(+15.3%);數據來自合成分佈。作者建議參考實際回應 usage 中的輸出 token 數設定較高上限,遇到 length 時提高上限再重試。

正文

A common first idea for saving money on an LLM API: output tokens are the expensive ones, so set max_tokens low and the model can't run up the bill. It backfires. A tight cap doesn't make a single normal answer cheaper. It turns some of your answers into paid garbage that you then pay for again.

A few words first

A token is a chunk of text, roughly three quarters of an English word. APIs bill per million tokens. Input tokens are what you send, and output tokens are what the model writes, usually at a much higher price. max_tokens is the request parameter that limits how many output tokens the model may write. Some APIs call it max_completion_tokens or max_output_tokens. When an answer hits that limit, generation just stops mid-sentence and the response's finish_reason field says "length" instead of "stop".

The key fact: you're billed for the tokens the model actually generated, not for the cap. A 300-token answer costs the same with a cap of 400 or 40,000. The cap only matters for answers that would have been longer than it.

What happens to the answers that don't fit

An answer that hits the cap is billed in full: all the input, plus output right up to the cap. Usually it's also useless: unclosed JSON, a summary without its conclusion, half a function. So you send the request again.

You don't get a different answer the second time, either. How long an answer needs to be depends mostly on the request. A question that needs 1,200 tokens to answer still needs about 1,200 tokens on the retry. If the retry uses the same cap, it gets cut off at the same place.

The simulation

I wanted numbers rather than intuition, so I wrote a small script. It sends 10,000 requests, each with a 1,500-token prompt. Each request needs an answer of a fixed length, drawn from a lognormal distribution (a skewed bell curve with a long right tail, which is what answer lengths usually look like). The median is 400 tokens. In the resulting sample the median is 397 tokens, the 90th percentile 859, the 99th 1,602 and the longest 3,800. Prices are gpt-5.6 list prices, $2 per million input tokens and $12 per million output, taken from the catalog snapshot of the LLM gateway I work on.

The baseline cap is 4,096, which no answer reaches. I compared it with caps set at typical answer lengths. When an answer was cut off, the script retried once with the cap raised to 4,096.

Cap Answers cut off Cost per 1,000 usable answers vs. cap 4,096
4,096 (never hit) 0% $8.71 —
1,602 (99th percentile) 1% $8.93 +2.6%
859 (90th percentile) 10% $10.04 +15.3%
397 (median) 50% $12.58 +44.5%

Every line below the first costs more. Each cut-off answer pays its 1,500 input tokens twice, plus the wasted output up to the cap. A tighter cap means more of those double payments.

There's also a trap in how this looks on a dashboard. Cap at the 90th percentile and don't retry, and the bill drops by 4.4% ($83.22 against $87.08 per 10,000 requests). That looks like a saving until you notice that 1,000 users got half an answer.

The naive retry is worse still: resend with the same cap, up to three attempts. At the 90th-percentile cap, the 1,000 long requests get cut off three times each and then fail anyway. You pay 40% more per usable answer than with no tight cap, and one request in ten never gets an answer at all.

What to do instead

Set the cap well above your real answers, so it only catches runaways. Treat "length" as an error. If you retry, retry with a bigger cap:

def ask(client, messages, cap=1024, ceiling=4096):
    while True:
        r = client.chat.completions.create(
            model="gpt-5.6", messages=messages, max_tokens=cap)
        choice = r.choices[0]
        if choice.finish_reason != "length":
            return choice.message.content
        if cap >= ceiling:
            raise RuntimeError("answer longer than the ceiling")
        cap = min(cap * 4, ceiling)

To pick the starting cap, log the output token count from the usage field of real responses for a few days and take a value above the 99th percentile. If you want shorter answers to save money, ask for them in the prompt ("answer in at most three sentences"). The model plans its answer around that instruction. It doesn't plan around the cap and never sees it.

What this doesn't solve

A cap still has a real job: it bounds the worst case. A model that falls into a repetition loop will write until something stops it. With gpt-5.6 prices and this prompt, one call can cost at most $0.052 with a 4,096 cap and $0.39 with a 32,000 cap. Keep a ceiling, just not one set at typical answer lengths.

The numbers above come from a synthetic distribution, not from real traffic. If your answers vary less in length, the penalty is smaller. If they vary more, it's larger. Run the same comparison on your own logged output lengths before you trust my percentages.

Reasoning models complicate this. On many of them, hidden reasoning tokens count against the same cap. A cap that fits the visible answer can still be hit while the model is thinking, and you get a response with no text in it. Size caps for those models from the total output in usage, not from the length of the text you see.

Finally, retries cost time too: a cut-off answer plus a second call roughly doubles that user's wait.

來源:DEV Community · dev.to