5.1 Context Window Management
Context Window คืออะไร
Context Window คือจำนวน tokens สูงสุดที่ Claude สามารถ “เห็น” ได้ในครั้งเดียว — รวม system prompt, conversation history, tool definitions, และ response ที่กำลังสร้าง ถ้าข้อมูลรวมกันเกิน context window Claude จะไม่สามารถ process ได้ เหมือนโต๊ะทำงานที่มีขนาดจำกัด — ของที่วางได้มีจำกัด ต้องจัดการว่าอะไรควรอยู่บนโต๊ะ
Model Context Sizes
| Model | Context Window | Notes |
|---|---|---|
| Claude Opus 4 | 200K tokens | ~150K words of text |
| Claude Sonnet 4 | 200K tokens | Best price/performance |
| Claude Haiku 3.5 | 200K tokens | Fastest, cheapest |
1 token ≈ 0.75 English words ≈ 1-2 Thai characters
Token Budget Planning
def estimate_token_budget(system_prompt, tools, max_turns):
"""Plan token allocation before starting a conversation"""
budget = {
"total": 200_000,
"system_prompt": count_tokens(system_prompt), # ~500-2000
"tools": count_tokens(json.dumps(tools)), # ~200 per tool
"reserved_output": 4_096, # max_tokens for response
}
available = budget["total"] - sum([
budget["system_prompt"],
budget["tools"],
budget["reserved_output"]
])
per_turn = available // max_turns # tokens per conversation turn
budget["available_per_turn"] = per_turn
return budget
Strategies เมื่อ Context ใกล้เต็ม
1. Summarization
สรุป conversation เก่าเป็น condensed format:
def summarize_old_messages(messages, keep_recent=5):
old_messages = messages[:-keep_recent]
recent_messages = messages[-keep_recent:]
summary = client.messages.create(
messages=[{
"role": "user",
"content": f"Summarize this conversation history concisely:\n{format(old_messages)}"
}]
)
return [{
"role": "user",
"content": f"[Previous conversation summary: {summary.content[0].text}]"
}] + recent_messages
2. Sliding Window
เก็บแค่ N messages ล่าสุด:
def sliding_window(messages, max_messages=20):
if len(messages) > max_messages:
return messages[-max_messages:]
return messages
3. Selective Context Loading
โหลดเฉพาะข้อมูลที่เกี่ยวข้อง:
def load_relevant_context(query, documents, max_tokens=50000):
# Rank documents by relevance to current query
ranked = rank_by_relevance(query, documents)
context = []
tokens_used = 0
for doc in ranked:
doc_tokens = count_tokens(doc)
if tokens_used + doc_tokens > max_tokens:
break
context.append(doc)
tokens_used += doc_tokens
return context
4. Extended Thinking
ใช้ extended thinking เพื่อให้ Claude คิดก่อนตอบ (ไม่นับใน output tokens):
response = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 10000 # Claude thinks internally up to 10K tokens
},
messages=[{"role": "user", "content": complex_question}]
)
Context Window Pitfalls
- Tool definitions eat tokens — 20 tools × 200 tokens each = 4,000 tokens ก่อนเริ่ม conversation
- System prompts accumulate — elaborate prompts 2-3K tokens กิน budget ทุก turn
- Long tool results — single tool_result ที่ return full file content อาจ 10K+ tokens
- Image tokens — รูปใน messages ใช้ tokens ตาม resolution
Key Concepts
- Input vs Output tokens — input = ทุกอย่างที่ Claude อ่าน; output = response ที่ Claude สร้าง
- Attention degradation — ข้อมูลตรงกลาง context window ได้รับ attention น้อยกว่า ต้น/ท้าย (“lost in the middle” problem)
- Token counting — ใช้ Anthropic’s tokenizer หรือ approximate (4 chars ≈ 1 token for English)
- Prompt caching — ลด cost ของ repeated prefix (system + few-shot) แต่ไม่ลด context usage
Exam Tips
- Context window = 200K tokens สำหรับ Claude 3.5+ models
- ข้อสอบจะถามว่า: เมื่อ context เต็ม ทำอย่างไร — ตอบ: summarize, sliding window, selective loading
- “Lost in the middle” = ข้อมูลกลาง context ได้รับ attention น้อย — ใส่ข้อมูลสำคัญไว้ต้นหรือท้าย
- Tool definitions count toward context — ยิ่ง tools เยอะ ยิ่งเหลือ space น้อย
- Extended thinking ช่วย reasoning quality แต่ budget tokens ไม่นับใน output