สถานะ: 🟢 Complete | อัพเดท: 2026-07-18
Claude Agent SDK
คืออะไร
Claude Agent SDK คือ library สำหรับสร้าง AI agents ที่ใช้ Claude — handle agentic loop, tool routing, multi-agent coordination
เริ่มต้น (Python)
pip install anthropicimport anthropic
client = anthropic.Anthropic()
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
tools=[{
"name": "get_weather",
"description": "Get weather for a city",
"input_schema": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}],
messages=[{"role": "user", "content": "อากาศกรุงเทพวันนี้เป็นยังไง?"}]
)Tool Loop
หลังจาก Claude ตอบมาพร้อม tool_use block ต้องรัน tool แล้วส่งผลลัพธ์กลับด้วย tool_result message
ดูตัวอย่างเต็มที่ Tool Use API
ทางเลือก: เรียกผ่าน CLI subprocess แทน SDK
อีกวิธีสร้าง agent ของตัวเอง (นอกเหนือจาก SDK/anthropic package) คือเรียก claude binary ตรงๆ ผ่าน subprocess — เหมาะกับเครื่องที่มีแค่ Claude Code CLI ติดตั้งอยู่แล้ว ไม่ต้องจัดการ API key/package แยก:
claude --model <model> --system-prompt "<system>" -p "<prompt>"ข้อควรรู้เมื่อใช้แบบนี้:
- Stateless ทุก call — ไม่มี memory ข้าม process การทำ multi-turn ต้อง resend conversation history เต็มทุกครั้ง (join เป็น string list แล้วส่งซ้ำ)
- Parse JSON ต้อง strip fence เอง — ถ้าสั่งให้ตอบเป็น JSON บางครั้งจะมี prose ปนมาก่อน/หลัง
```json ... ```ต้อง regex ดึง fence block ออกมาก่อน parse ไม่ใช่ parse ทั้งข้อความตรงๆ - Model split ตามงาน — งานวางแผน/ตัดสิน/ให้คะแนนที่ซับซ้อน ใช้โมเดลตัวแรงกว่า งานพูดยาว/สอน/merge state ง่ายๆ ใช้โมเดลตัวเบากว่า หลักคิดเดียวกับ model routing ใน Subagent แค่ทำเองนอก Claude Code