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:
- Giải thích cách temperature ảnh hưởng đến sampling của Claude
- Chọn temperature phù hợp cho từng loại tác vụ (factual, creative, brainstorm)
- Hiểu sự khác biệt giữa temperature=0, 0.5, 1.0
- Update chat function accept temperature parameter
- Tránh sai lầm thường gặp khi tune temperature
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ể:
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.
┌───────────────────────────────────────────────┐ │ │ │ "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. │ │ │ └───────────────────────────────────────────────┘
Temperature làm gì?
Temperature = 0 (deterministic)
Distribution bị "làm nhọn" về token cao nhất:
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: 1.00 0.00 0.00 0.00 0.00 0.00Temperature = 0.5 (balanced)
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:
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.07Temperature = 1.0 (max creative)
Claude có thể pick token #2, #3, #4 khá thường xuyên → output variety cao.
After: 0.30 0.25 0.15 0.10 0.08 0.12So sánh 3 setting cụ thể
Prompt: "Generate a movie idea"
Temperature = 0
Run 3 lần:
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 time-traveling archaeologist must prevent ancient artifacts..."
3. "A time-traveling archaeologist must prevent ancient artifacts..."Temperature = 0.5
Vài variant, nhưng all reasonable.
Temperature = 1.0
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..."Temperature = 1.0
Creative, đôi khi weird. Có thể xuất sắc, có thể off.
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..."Khi nào dùng temperature nào?
Low (0.0 - 0.3): Factual, deterministic
Use cases:
Lý do: Cần output reproducible, không random.
Medium (0.4 - 0.7): Balanced
Use cases:
Lý do: Cần natural variation để không robotic, nhưng cần reliability.
- Coding (code sai 1 token = bug)
- Data extraction / parsing JSON
- Classification / categorization
- Medical / legal information
- Content moderation
- Translation (cần consistency)
- Summarization
- Q&A educational
- Problem solving
- Technical explanation
- Chatbot general
msg = client.messages.create(
model=model,
max_tokens=500,
messages=messages,
temperature=0.0, # ← Deterministic
)Medium (0.4 - 0.7): Balanced
High (0.8 - 1.0): Creative
Use cases:
Lý do: Cần diversity. Output y hệt = ý tưởng cạn kiệt.
- Brainstorming
- Creative writing / fiction
- Marketing copy (variant)
- Joke generation
- Idea generation
temperature=0.5High (0.8 - 1.0): Creative
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.
temperature=1.0Thêm vào chat function
Update helper:
Dùng
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].textDùng
# Factual — dùng temp thấp
answer = chat(messages, temperature=0.0)
# Creative — dùng temp cao
idea = chat(messages, temperature=1.0)
# Balanced — default
general = chat(messages, temperature=0.5)Ví dụ thực chiến: Cùng prompt, 2 temperature
Prompt
Temperature = 0.0
prompt = "Viết tagline cho dịch vụ giao đồ ăn healthy"Temperature = 0.0
→ Không dùng để brainstorm. Sẽ stuck ở 1 idea.
Temperature = 1.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à."Temperature = 1.0
→ Đ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.
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."Case studies theo ngành
💻 Developer Tools — Code generation
Setting: temperature=0.0
Lý do:
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:
📊 Data Analysis — Insights
Setting: temperature=0.3
Lý do:
⚖️ Legal — Contract analysis
Setting: temperature=0.0
Lý do:
🎓 Education — Tutoring
Setting: temperature=0.5-0.7
Lý do:
- Code cần đúng cú pháp
- Cùng task → cùng code (reproducible)
- Dev không muốn "creative"
- Cần 10 variant để A/B test
- Creative matter
- "Safe" copy = không ai click
- Cần reliable insight từ data
- Chút variation OK (natural language flow)
- Quá low = output robot, quá high = hallucinate
- Output pháp lý phải accurate
- Cùng contract → cùng findings
- Stakes cao, không chấp nhận randomness
- 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.
Ví dụ kết hợp
System prompt → WHAT Claude nên làm (role, constraint)
Temperature → HOW variation allowed trong khi làmVí dụ kết hợp
# Creative với constraint
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)
# → Creative trong khuôn khổ traditional Hanoi poem
# Factual với flexibility
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)
# → Accurate nhưng có natural phrasingAnti-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:
❌ 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.
# temp=0.3: balance giữa accuracy (từ cao → fact đúng)
# và natural flow (tránh quá robot)
temperature=0.3Á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:
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:
Ít nhất 3 endpoint/feature.
| Temp | Run 1 | Run 2 | Run 3 | Run 4 | Run 5 | Variety |
|---|---|---|---|---|---|---|
| 0.0 | Low/Med/High | |||||
| 0.3 | ||||||
| 0.5 | ||||||
| 0.7 | ||||||
| 1.0 |
## Temperature strategy
### Endpoint / Feature 1: [tên]
Use case: [mô tả]
Temperature: [chọn]
Lý do: [tại sao]
### Endpoint / Feature 2: [tên]
...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
🎯 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.
- Temperature docs
- Anthropic blog: Sampling strategies