---
site: "zyx.tw"
title: "LLM 每次只預測下一個 token，長回覆靠反覆生成"
description: "理解文字生成的迴圈，判斷回覆速度、記憶與正確性的限制。"
url: "https://www.zyx.tw/map/harness/llm-basics"
---

# LLM 每次只預測下一個 token，長回覆靠反覆生成

紀錄 053，觀念 L1，590 字，1 分鐘，v2.0.0，更新 2026-11-16

LLM 是大型語言模型，輸入文字會先切成 token，也就是模型處理文字的單位。

LLM 只依前面的文字預測下一個 token，長回覆是重複預測的結果，其餘都是外圍程式的工作。

## 新產生的文字會成為下一步的輸入

模型依照前面的 token，算出每個可能的下一個 token 的機率。程式依機率選出 1 個 token，接回輸入，再重複計算，直到模型輸出結束記號。

temperature 控制選取 token 的隨機程度。數值越低，越傾向選機率最高的 token，但設為 0 也不保證每次輸出相同。

下圖示範這個過程：文字先被切開，模型給出候選機率，選出的 blue 再接回輸入。

```text
 "The sky is"
      │ tokenize
      v
 [The] [sky] [is]                 TOKENS
      │
╭─────┴──────╮
│   MODEL    │                    fixed weights
╰─────┬──────╯
      v
 blue 0.62   clear 0.21   ...     PROBABILITIES
      │ sample
      v
 [blue]  ──>  append to the input, REPEAT
```

Figure: Text is split into tokens. A model with fixed weights turns the tokens into a probability for each possible next token. One token is sampled, appended to the input, and the step repeats.

1. Tokens: 文字先切成 token。token 可能是一個字、半個字或一個符號。
2. Model: 模型的參數在訓練後就固定。對話不會改變模型。
3. Probabilities: 模型輸出每個候選 token 的機率。
4. Sample: 程式依機率選出 1 個 token。
5. Repeat: 選出的 token 接到輸入後面，再預測下一個。

## 輸入決定模型能讀到什麼

模型只知道這次送來的 token。前一段對話若沒有重送，模型就不知道那段內容。

訓練資料有截止日期。之後發生的事，要靠工具查詢，或寫進一次請求送給模型的全部內容，也就是 context。

模型一次能讀的 token 數量也有上限，稱為 context window。超過上限的內容，模型讀不到。

## 輸出必須逐個產生，所以長回覆比較慢

輸入的 token 可以一起計算，輸出的每個 token 則要等前一個產生後才能接著算，所以長回覆比較慢。

下圖用 pseudo code 示範生成迴圈，對照模型計算、程式選取與停止生成的位置。

```text
def generate(prompt, max_tokens):
    tokens = tokenize(prompt)
    for _ in range(max_tokens):
        probs = model(tokens)            # one forward pass
        nxt = sample(probs, temperature)
        if nxt is END:
            break
        tokens.append(nxt)               # output becomes input
    return detokenize(tokens)
```

Figure: Pseudo code of text generation: tokenize the prompt, then repeatedly run the model, sample the next token, stop at the end token, and append the token to the input.

1. Tokenize: 輸入的文字轉成 token。
2. Forward: 模型讀完整段 token，算出下一個的機率。
3. Sample: 依機率與 temperature 選出 1 個 token。
4. Stop: 選到結束記號或達到上限，生成停止。
5. Append: 新的 token 成為下一次計算的輸入。

## 機率高的 token 不等於查證過的事實

模型選的是機率高的 token，不是查證過的事實。重要結論要用工具驗證，具體做法見 怎樣才算完成。

## 來源

- [Glossary](https://platform.claude.com/docs/en/about-claude/glossary), Claude API docs
- [Context windows](https://platform.claude.com/docs/en/build-with-claude/context-windows), Claude API docs
- [Token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting), Claude API docs
- [Attention Is All You Need](https://arxiv.org/abs/1706.03762), Vaswani et al.
- [The Illustrated GPT-2](https://jalammar.github.io/illustrated-gpt2/), Jay Alammar

## 地圖

- 相關：[Agent Loop 讓模型提出請求，由程式執行並送回結果](https://www.zyx.tw/map/harness/agent-loop.md)
- 相關：[Prompt cache 只重用完全相同的前段，變動內容要放後面](https://www.zyx.tw/map/harness/prompt-cache.md)
- 回到：[Harness](https://www.zyx.tw/map.md)
