ภาพรวม Agent SDK
สร้าง AI agents ในระดับ production โดยใช้ Claude Code เป็น library
สร้าง AI agents ที่สามารถอ่านไฟล์ รันคำสั่ง ค้นหาเว็บ แก้ไขโค้ด และทำงานอื่น ๆ ได้อย่างอัตโนมัติ Agent SDK มอบเครื่องมือ, agent loop, และการจัดการ context เดียวกันกับที่ขับเคลื่อน Claude Code ซึ่งสามารถเขียนโปรแกรมด้วย Python และ TypeScript
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Find and fix the bug in auth.py",
options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
):
print(message) # Claude reads the file, finds the bug, edits it
asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Find and fix the bug in auth.ts",
options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
console.log(message); // Claude reads the file, finds the bug, edits it
}
Agent SDK มีเครื่องมือในตัวสำหรับการอ่านไฟล์ รันคำสั่ง และแก้ไขโค้ด ดังนั้น agent ของคุณสามารถเริ่มทำงานได้ทันทีโดยไม่ต้องเขียน tool execution เอง
เริ่มต้นใช้งาน
ขั้นตอนที่ 1: ติดตั้ง SDK
TypeScript:
npm install @anthropic-ai/claude-agent-sdk
Python:
pip install claude-agent-sdk
Python package ต้องการ Python 3.10 หรือใหม่กว่า TypeScript SDK รวม Claude Code binary ไว้สำหรับแพลตฟอร์มของคุณ ดังนั้นไม่ต้องติดตั้ง Claude Code แยกต่างหาก
ขั้นตอนที่ 2: ตั้งค่า API key
รับ API key จาก Console จากนั้นตั้งค่าเป็น environment variable:
export ANTHROPIC_API_KEY=your-api-key
SDK ยังรองรับการยืนยันตัวตนผ่าน providers อื่น ๆ:
- Amazon Bedrock: ตั้งค่า
CLAUDE_CODE_USE_BEDROCK=1และกำหนด AWS credentials - Claude Platform on AWS: ตั้งค่า
CLAUDE_CODE_USE_ANTHROPIC_AWS=1และANTHROPIC_AWS_WORKSPACE_ID - Google Vertex AI: ตั้งค่า
CLAUDE_CODE_USE_VERTEX=1และกำหนด Google Cloud credentials - Microsoft Azure: ตั้งค่า
CLAUDE_CODE_USE_FOUNDRY=1และกำหนด Azure credentials
ขั้นตอนที่ 3: รัน agent แรกของคุณ
ตัวอย่างนี้สร้าง agent ที่แสดงรายชื่อไฟล์ในไดเรกทอรีปัจจุบัน:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="What files are in this directory?",
options=ClaudeAgentOptions(allowed_tools=["Bash", "Glob"]),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "What files are in this directory?",
options: { allowedTools: ["Bash", "Glob"] }
})) {
if ("result" in message) console.log(message.result);
}
ความสามารถ
ทุกสิ่งที่ทำให้ Claude Code ทรงพลังสามารถใช้ได้ใน SDK:
เครื่องมือในตัว
| Tool | สิ่งที่ทำ |
|---|---|
| Read | อ่านไฟล์ใด ๆ ในไดเรกทอรีทำงาน |
| Write | สร้างไฟล์ใหม่ |
| Edit | แก้ไขไฟล์ที่มีอยู่อย่างแม่นยำ |
| Bash | รันคำสั่ง terminal, scripts, git operations |
| Monitor | ดูแลสคริปต์ที่ทำงานเบื้องหลังและตอบสนองต่อ output แต่ละบรรทัด |
| Glob | ค้นหาไฟล์ด้วย pattern (**/*.ts, src/**/*.py) |
| Grep | ค้นหาเนื้อหาไฟล์ด้วย regex |
| WebSearch | ค้นหาเว็บสำหรับข้อมูลปัจจุบัน |
| WebFetch | ดึงและแยกวิเคราะห์เนื้อหาเว็บ |
| AskUserQuestion | ถามผู้ใช้คำถามชี้แจงพร้อมตัวเลือกหลายตัว |
Hooks
รันโค้ดที่กำหนดเองในจุดสำคัญของ agent lifecycle:
import asyncio
from datetime import datetime
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher
async def log_file_change(input_data, tool_use_id, context):
file_path = input_data.get("tool_input", {}).get("file_path", "unknown")
with open("./audit.log", "a") as f:
f.write(f"{datetime.now()}: modified {file_path}\n")
return {}
async def main():
async for message in query(
prompt="Refactor utils.py to improve readability",
options=ClaudeAgentOptions(
permission_mode="acceptEdits",
hooks={
"PostToolUse": [
HookMatcher(matcher="Edit|Write", hooks=[log_file_change])
]
},
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
Subagents
สร้าง agents เฉพาะทางเพื่อจัดการงานย่อยที่มุ่งเน้น:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
async def main():
async for message in query(
prompt="Use the code-reviewer agent to review this codebase",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep", "Agent"],
agents={
"code-reviewer": AgentDefinition(
description="Expert code reviewer for quality and security reviews.",
prompt="Analyze code quality and suggest improvements.",
tools=["Read", "Glob", "Grep"],
)
},
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
MCP
เชื่อมต่อกับระบบภายนอกผ่าน Model Context Protocol: databases, browsers, APIs และอื่น ๆ อีกมากมาย:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions
async def main():
async for message in query(
prompt="Open example.com and describe what you see",
options=ClaudeAgentOptions(
mcp_servers={
"playwright": {"command": "npx", "args": ["@playwright/mcp@latest"]}
}
),
):
if hasattr(message, "result"):
print(message.result)
asyncio.run(main())
Sessions
รักษา context ข้ามการสนทนาหลายครั้ง Claude จำไฟล์ที่อ่าน การวิเคราะห์ที่ทำ และประวัติการสนทนา:
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, SystemMessage, ResultMessage
async def main():
session_id = None
# คำถามแรก: จับ session ID
async for message in query(
prompt="Read the authentication module",
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob"]),
):
if isinstance(message, SystemMessage) and message.subtype == "init":
session_id = message.data["session_id"]
# ต่อ session ด้วย context เดิม
async for message in query(
prompt="Now find all places that call it",
options=ClaudeAgentOptions(resume=session_id),
):
if isinstance(message, ResultMessage):
print(message.result)
asyncio.run(main())
คุณลักษณะของ Claude Code
SDK ยังรองรับการกำหนดค่าบนระบบไฟล์ของ Claude Code โดยค่าเริ่มต้น SDK จะโหลดจาก .claude/ ในไดเรกทอรีทำงานและ ~/.claude/
| คุณลักษณะ | คำอธิบาย | ตำแหน่ง |
|---|---|---|
| Skills | ความสามารถเฉพาะทาง | .claude/skills/*/SKILL.md |
| Commands | คำสั่งที่กำหนดเอง | .claude/commands/*.md |
| Memory | context และคำแนะนำของโครงการ | CLAUDE.md หรือ .claude/CLAUDE.md |
| Plugins | ขยายด้วย skills, agents, hooks และ MCP servers | ผ่าน plugins option |
เปรียบเทียบ Agent SDK กับเครื่องมืออื่น
Agent SDK vs Client SDK
Client SDK มอบการเข้าถึง API โดยตรง คุณส่ง prompts และ implement tool execution เอง Agent SDK มอบ Claude พร้อม built-in tool execution
Agent SDK vs Claude Code CLI
| Use case | ตัวเลือกที่ดีที่สุด |
|---|---|
| การพัฒนาเชิงโต้ตอบ | CLI |
| CI/CD pipelines | SDK |
| แอปพลิเคชันที่กำหนดเอง | SDK |
| งานเพียงครั้งเดียว | CLI |
| Automation ใน production | SDK |
Agent SDK vs Managed Agents
| Agent SDK | Managed Agents | |
|---|---|---|
| รันใน | Process ของคุณ, infrastructure ของคุณ | Infrastructure ที่ Anthropic จัดการ |
| Interface | Python หรือ TypeScript library | REST API |
| Agent ทำงานกับ | ไฟล์บน infrastructure ของคุณ | Sandbox ที่จัดการต่อ session |
| ดีสำหรับ | Local prototyping, agents ที่ทำงานกับ filesystem | Production agents โดยไม่ต้องจัดการ sandbox |
Changelog
- TypeScript SDK: ดู CHANGELOG.md
- Python SDK: ดู CHANGELOG.md
แนวทางการใช้แบรนด์
สำหรับ partners ที่ผนวกรวม Claude Agent SDK:
อนุญาต:
- "Claude Agent" (แนะนำสำหรับ dropdown menus)
- "Claude" (เมื่ออยู่ใน menu ที่มีป้ายว่า "Agents")
- "{YourAgentName} Powered by Claude"
ไม่อนุญาต:
- "Claude Code" หรือ "Claude Code Agent"
- ASCII art หรือองค์ประกอบภาพที่เลียนแบบ Claude Code