Skip to main content

ภาพรวม 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
Memorycontext และคำแนะนำของโครงการ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 pipelinesSDK
แอปพลิเคชันที่กำหนดเองSDK
งานเพียงครั้งเดียวCLI
Automation ใน productionSDK

Agent SDK vs Managed Agents

Agent SDKManaged Agents
รันในProcess ของคุณ, infrastructure ของคุณInfrastructure ที่ Anthropic จัดการ
InterfacePython หรือ TypeScript libraryREST API
Agent ทำงานกับไฟล์บน infrastructure ของคุณSandbox ที่จัดการต่อ session
ดีสำหรับLocal prototyping, agents ที่ทำงานกับ filesystemProduction agents โดยไม่ต้องจัดการ sandbox

Changelog

แนวทางการใช้แบรนด์

สำหรับ partners ที่ผนวกรวม Claude Agent SDK:

อนุญาต:

  • "Claude Agent" (แนะนำสำหรับ dropdown menus)
  • "Claude" (เมื่ออยู่ใน menu ที่มีป้ายว่า "Agents")
  • "{YourAgentName} Powered by Claude"

ไม่อนุญาต:

  • "Claude Code" หรือ "Claude Code Agent"
  • ASCII art หรือองค์ประกอบภาพที่เลียนแบบ Claude Code