Lộ trình học›Claude API›Building with the Claude API Mở bản đồ

6.12 · Temperature — Kiểm soát độ ngẫu nhiên của Claude

Bài viếtCơ bản → Trung c20 phút đọc

Hãy tưởng tượng bạn đang điều khiển mixer trong studio âm nhạc. Có 1 núm vặn:

Sau bài này, bạn sẽ
  1. Giải thích cách temperature ảnh hưởng đến sampling của Claude
  2. Chọn temperature phù hợp cho từng loại tác vụ (factual, creative, brainstorm)
  3. Hiểu sự khác biệt giữa temperature=0, 0.5, 1.0
  4. Update chat function accept temperature parameter
  5. Tránh sai lầm thường gặp khi tune temperature

Mở đầu: "Núm điều chỉnh sáng tạo"

  • Xoay sang trái → âm thanh dự đoán được, theo format classical
  • Xoay sang phải → âm thanh bất ngờ, jazzy, improvisational

Cả 2 đều "đúng" — tùy thể loại nhạc bạn muốn.

Temperature của Claude y hệt núm đó. Không có "temperature tốt". Chỉ có temperature phù hợp cho task.

Hiểu temperature = control được Claude. Không hiểu = random behavior không giải thích được.

Tái cập lại quá trình generation

Ở bài 6.4 bạn đã học Claude generate text qua 4 bước: Tokenize → Embed → Contextualize → Generation.

Bước generation cụ thể:

┌───────────────────────────────────────────────┐
│                                               │
│   "Quantum computing is a form of ____"       │
│                                               │
│   Model tính probability cho mỗi token:       │
│                                               │
│      "computation"    → 0.30                  │
│      "technology"     → 0.25                  │
│      "computing"      → 0.15                  │
│      "science"        → 0.10                  │
│      "machine"        → 0.08                  │
│      ...              → 0.12                  │
│                                               │
│   Claude SAMPLE từ distribution này.          │
│                                               │
└───────────────────────────────────────────────┘

Key point: Claude không pick cao nhất mỗi lần. Nó sample theo probability distribution.

Temperature = hệ số reshape distribution trước khi sample.

Temperature làm gì?

Temperature = 0 (deterministic)

Distribution bị "làm nhọn" về token cao nhất:

Before:  0.30  0.25  0.15  0.10  0.08  0.12
After:   1.00  0.00  0.00  0.00  0.00  0.00

Claude luôn pick cao nhất. Cùng input → cùng output mỗi lần (gần như vậy).

Temperature = 0.5 (balanced)

Distribution giữ nguyên, nhưng softer:

Before:  0.30  0.25  0.15  0.10  0.08  0.12
After:   0.40  0.30  0.13  0.06  0.04  0.07

Top token vẫn dominant, nhưng có chance cho #2, #3.

Temperature = 1.0 (max creative)

Distribution giữ nguyên như output thô của model:

After:   0.30  0.25  0.15  0.10  0.08  0.12

Claude có thể pick token #2, #3, #4 khá thường xuyên → output variety cao.

So sánh 3 setting cụ thể

Prompt: "Generate a movie idea"

Temperature = 0

Run 3 lần:

1. "A time-traveling archaeologist must prevent ancient artifacts..."
2. "A time-traveling archaeologist must prevent ancient artifacts..."
3. "A time-traveling archaeologist must prevent ancient artifacts..."

Giống hệt nhau (hoặc sai khác < 5%).

Temperature = 0.5

Run 3 lần:

1. "A time-traveling archaeologist must prevent ancient artifacts..."
2. "A detective with amnesia discovers her past self was the killer..."
3. "An AI becomes sentient in a retirement home, helping residents reconnect..."

Vài variant, nhưng all reasonable.

Temperature = 1.0

Run 3 lần:

1. "A chef quantum-entangles with her sous-chef across parallel kitchens..."
2. "Sentient trash reveals 1000 years of human secrets after apocalypse..."
3. "Robin Hood but in Mars colony, stealing bandwidth from rich..."

Creative, đôi khi weird. Có thể xuất sắc, có thể off.

Khi nào dùng temperature nào?

Low (0.0 - 0.3): Factual, deterministic

Use cases:

  • Coding (code sai 1 token = bug)
  • Data extraction / parsing JSON
  • Classification / categorization
  • Medical / legal information
  • Content moderation
  • Translation (cần consistency)

Lý do: Cần output reproducible, không random.

msg = client.messages.create(
    model=model,
    max_tokens=500,
    messages=messages,
    temperature=0.0,  # ← Deterministic
)

Medium (0.4 - 0.7): Balanced

Use cases:

  • Summarization
  • Q&A educational
  • Problem solving
  • Technical explanation
  • Chatbot general

Lý do: Cần natural variation để không robotic, nhưng cần reliability.

temperature=0.5

High (0.8 - 1.0): Creative

Use cases:

  • Brainstorming
  • Creative writing / fiction
  • Marketing copy (variant)
  • Joke generation
  • Idea generation

Lý do: Cần diversity. Output y hệt = ý tưởng cạn kiệt.

temperature=1.0

Above 1.0?

Anthropic API cap max temperature = 1.0. Khác OpenAI (max 2.0).

Lý do: temperature > 1 thường cho output quá nhiễu, ít dùng trong production.

Thêm vào chat function

Update helper:

def chat(messages: list, system: str = None, temperature: float = 1.0) -> str:
    """Chat với temperature tunable."""
    params = {
        "model": model,
        "max_tokens": 1000,
        "messages": messages,
        "temperature": temperature,
    }
    if system:
        params["system"] = system
    
    msg = client.messages.create(**params)
    return msg.content[0].text

Dùng

answer = chat(messages, temperature=0.0)

idea = chat(messages, temperature=1.0)

general = chat(messages, temperature=0.5)

Ví dụ thực chiến: Cùng prompt, 2 temperature

Prompt

prompt = "Viết tagline cho dịch vụ giao đồ ăn healthy"

Temperature = 0.0

Run 1: "Ăn sạch, sống khỏe — giao tận nhà."
Run 2: "Ăn sạch, sống khỏe — giao tận nhà."
Run 3: "Ăn sạch, sống khỏe — giao tận nhà."

→ Không dùng để brainstorm. Sẽ stuck ở 1 idea.

Temperature = 1.0

Run 1: "Healthy chạm tay bạn — 20 phút giao tới."
Run 2: "Ăn như chuyên gia dinh dưỡng, không cần nấu."
Run 3: "Cơm nhà bà ngoại, phiên bản fit."
Run 4: "Bữa sáng cho người biết yêu cơ thể."
Run 5: "Clean eating, cleaner delivery."

→ Đa dạng, nhiều option. Dev có thể chọn cái hay nhất.

Rule: Brainstorm = temp cao. Final pick = sau khi chọn, dùng temp thấp cho version shipping.

Case studies theo ngành

Developer Tools — Code generation

Setting: temperature=0.0

Lý do:

  • Code cần đúng cú pháp
  • Cùng task → cùng code (reproducible)
  • Dev không muốn "creative"

Ví dụ: Claude Code, Cursor, Copilot tất cả đều dùng temp = 0 hoặc 0.2.

Copywriting — Ad variants

Setting: temperature=0.9-1.0

Lý do:

  • Cần 10 variant để A/B test
  • Creative matter
  • "Safe" copy = không ai click

Data Analysis — Insights

Setting: temperature=0.3

Lý do:

  • Cần reliable insight từ data
  • Chút variation OK (natural language flow)
  • Quá low = output robot, quá high = hallucinate

Legal — Contract analysis

Setting: temperature=0.0

Lý do:

  • Output pháp lý phải accurate
  • Cùng contract → cùng findings
  • Stakes cao, không chấp nhận randomness

Education — Tutoring

Setting: temperature=0.5-0.7

Lý do:

  • Mỗi học sinh học cách khác
  • Giải thích có variation để phù hợp
  • Không quá cao (fact đúng) không quá thấp (robotic)

Interaction với system prompt

Temperature KHÔNG thay thế system prompt.

System prompt → WHAT Claude nên làm (role, constraint)
Temperature   → HOW variation allowed trong khi làm

Ví dụ kết hợp

system = "Viết poem về thu Hà Nội. Chỉ dùng 6-8 câu. Phong cách truyền thống."
msg = chat(messages, system=system, temperature=0.8)

system = "Bạn là lab assistant. Trả lời dựa trên data được cung cấp."
msg = chat(messages, system=system, temperature=0.3)

Anti-patterns

Set temperature=0 cho chatbot general

Hiện tượng
Chatbot trả lời chính xác cùng 1 câu cho mọi biến thể của câu hỏi.
Vấn đề
Robotic, kém tự nhiên. User thấy giả tạo.
Fix
temp=0.5-0.7 cho chatbot.

Set temperature=1 cho data extraction

Hiện tượng
Extract JSON fields, output khi có khi thiếu field.
Vấn đề
Inconsistent → parser crash.
Fix
temp=0 cho parsing/extraction.

Tune temperature thay vì fix prompt

Hiện tượng
Output sai → "Chắc temp cao quá, thử 0.3..."
Vấn đề
Prompt thiếu constraint, temp chỉ là band-aid.
Fix
Review system prompt trước. Temperature là last resort.

Hardcode temp không document

Hiện tượng
temperature=0.7 trong code, không ai biết vì sao.
Fix
Comment lý do:
temperature=0.3

Test temp=0 rồi deploy temp=1

Hiện tượng
Dev test prompt với temp=0 (stable), ship với temp=1.
Vấn đề
Behavior production khác dev hoàn toàn.
Fix
Test với chính temperature sẽ deploy.

Áp dụng ngay

Bài tập 1: Temperature ladder (20 phút)

Cùng prompt: "Generate 1 product idea for Gen Z"

Chạy 5 lần với mỗi temperature: 0.0, 0.3, 0.5, 0.7, 1.0.

Điền bảng:

TempRun 1Run 2Run 3Run 4Run 5Variety
0.0Low/Med/High
0.3
0.5
0.7
1.0

Observation: Ngưỡng nào bắt đầu thấy variety?

Bài tập 2: Pick temp cho use case (15 phút)

Với app của bạn (từ my-goals.md), viết:

Temperature strategy

Endpoint / Feature 1: [tên]

Use case: [mô tả] Temperature: [chọn] Lý do: [tại sao]

Endpoint / Feature 2: [tên]

...


Ít nhất 3 endpoint/feature.

---

Mẹo nâng cao

Mẹo 1: Seed cho reproducibility (không có trên Anthropic)

OpenAI có tham số seed để reproducible. Anthropic chưa có (4/2026).

Workaround: temp=0 thường đủ reproducible cho test.

Mẹo 2: Ensemble với temp=1

Generate 5 output với temp=1, vote hoặc merge → better quality than 1 output temp=0.5.

Chi phí 5x, nhưng cho critical task có thể đáng.

Mẹo 3: Adaptive temperature

def adaptive_chat(user_input, messages):
    # Classify intent
    intent = classify(user_input)  # factual | creative | general
    
    temp_map = {
        "factual": 0.0,
        "creative": 0.9,
        "general": 0.5,
    }
    
    return chat(messages, temperature=temp_map[intent])

Tóm tắt bài học

Những điều cốt lõi
  • Temperature = hệ số reshape probability distribution trước khi Claude sample token.
  • 3 range: Low (0.0-0.3) factual, Medium (0.4-0.7) balanced, High (0.8-1.0) creative.
  • Temperature ≠ replace system prompt. System định what, temp định how variation.
  • Mặc định Anthropic là 1.0 — thường phải giảm cho most production use case.
  • Test với temp thật sẽ deploy — không test 0 rồi ship 1.

Tài liệu tham khảo

Kiểm tra nhanh1 câu hỏi · chọn đáp án để xem giải thích
    Bạn đã hoàn thành bài này chưa?Tiến độ lưu trên trình duyệt của bạn.