spinny:~/writing $ less building-ai-agents-claude-agent-sdk.md
12Claude Agent SDK ให้คุณเข้าถึง Agent Loop เดียวกันกับที่ขับเคลื่อน Claude Code ผ่านโค้ด Agent ของคุณสามารถอ่านไฟล์ รันคำสั่ง Shell ค้นหาเว็บ แก้ไขโค้ด เรียก API ภายนอกผ่าน MCP Server และจัดการ Sub-Agent - ทั้งหมดนี้ด้วยโค้ด TypeScript หรือ Python เพียงไม่กี่บรรทัด34ต่างจาก Anthropic Client SDK มาตรฐานที่คุณต้องสร้าง Tool Loop เอง Agent SDK จัดการการรันเครื่องมือ การจัดการ Context การลองใหม่ และการจัดการ (Orchestration) ภายในทั้งหมด คุณเพียงอธิบายสิ่งที่ต้องการ จัดเตรียมเครื่องมือ แล้ว Agent จะจัดการส่วนที่เหลือเอง56## สถาปัตยกรรม78SDK ทำงานตาม Loop ง่ายๆ: **รวบรวม Context, ดำเนินการ, ตรวจสอบ, ทำซ้ำ**910```mermaid11graph TD12 Input[User Prompt] --> Loop[Agent Loop]13 Loop --> Reason[Claude Reasons]14 Reason --> Tool[Call Tool]15 Tool --> Result[Tool Result]16 Result --> Loop17 Reason --> Done[Final Response]1819 subgraph "Built-in Tools"20 T1[Read / Write / Edit]21 T2[Bash / Terminal]22 T3[Glob / Grep]23 T4[WebSearch / WebFetch]24 end2526 subgraph "Custom Tools via MCP"27 M1[Your API]28 M2[Database]29 M3[Slack / GitHub / etc.]30 end3132 Tool --> T133 Tool --> M134```3536Entry Point หลักคือ `query()` ซึ่งส่งคืน Async Iterator ที่สตรีมข้อความขณะ Agent ทำงาน แต่ละข้อความบอกคุณว่า Agent กำลังทำอะไร: กำลังคิด เรียกเครื่องมือ รับผลลัพธ์ หรือส่งมอบผลลัพธ์สุดท้าย3738## เริ่มต้นใช้งาน3940### การติดตั้ง4142```bash43# TypeScript44npm install @anthropic-ai/claude-agent-sdk4546# Python47pip install claude-agent-sdk48```4950คุณต้องตั้งค่า Anthropic API Key เป็น `ANTHROPIC_API_KEY` ในตัวแปรสภาพแวดล้อม5152### Agent ตัวแรกของคุณ5354```typescript55import { query } from "@anthropic-ai/claude-agent-sdk";5657const conversation = query({58 prompt: "Find all TODO comments in the codebase and create a summary",59 options: {60 allowedTools: ["Read", "Glob", "Grep"],61 },62});6364for await (const message of conversation) {65 if (message.type === "assistant") {66 process.stdout.write(message.content);67 }68 if (message.type === "result" && message.subtype === "success") {69 console.log("\nDone:", message.result);70 }71}72```7374เท่านี้เอง Agent จะใช้ Glob ค้นหาไฟล์ Grep ค้นหาแพทเทิร์น TODO, Read ตรวจสอบผลลัพธ์ที่ตรงกัน และส่งคืนสรุปที่มีโครงสร้าง คุณไม่ต้องเขียน Orchestration Logic เอง - SDK จัดการให้7576### เวอร์ชัน Python7778```python79from claude_agent_sdk import query8081async for message in query(82 prompt="Find all TODO comments in the codebase and create a summary",83 options={"allowed_tools": ["Read", "Glob", "Grep"]},84):85 if message.type == "assistant":86 print(message.content, end="")87 if message.type == "result" and message.subtype == "success":88 print(f"\nDone: {message.result}")89```9091## เครื่องมือในตัว9293SDK มาพร้อมกับเครื่องมือเดียวกันกับที่มีใน Claude Code:9495| เครื่องมือ | คำอธิบาย |96|------|-------------|97| **Read** | อ่านเนื้อหาไฟล์ |98| **Write** | สร้างไฟล์ใหม่ |99| **Edit** | แก้ไขไฟล์ที่มีอยู่แบบเจาะจง |100| **Bash** | รันคำสั่ง Shell |101| **Glob** | ค้นหาไฟล์ตามแพทเทิร์น |102| **Grep** | ค้นหาเนื้อหาไฟล์ด้วย Regex |103| **WebSearch** | ค้นหาเว็บ |104| **WebFetch** | ดึง URL และส่งคืนเนื้อหา |105| **AskUserQuestion** | ถามผู้ใช้เพื่อรับข้อมูล |106107คุณควบคุมว่า Agent จะใช้เครื่องมือใดได้ผ่าน `allowedTools` หากเครื่องมือไม่อยู่ในรายการ Agent จะไม่สามารถเรียกใช้ได้108109## โหมดสิทธิ์110111เนื่องจาก Agent รันคำสั่งจริงบนระบบจริง สิทธิ์จึงมีความสำคัญ112113| โหมด | พฤติกรรม | กรณีใช้งาน |114|------|----------|----------|115| `default` | Callback `canUseTool` ที่กำหนดเองตัดสินใจทีละการเรียก | การควบคุมแบบละเอียด |116| `acceptEdits` | อนุมัติการดำเนินการไฟล์อัตโนมัติ ถาม Bash | เวิร์กโฟลว์การพัฒนา |117| `dontAsk` | ปฏิเสธทุกอย่างที่ไม่อยู่ใน allowedTools | Agent ที่ถูกจำกัด |118| `bypassPermissions` | อนุมัติทุกอย่างอัตโนมัติ | สภาพแวดล้อม Sandbox ที่เชื่อถือได้ |119| `auto` | ตัวจำแนกของโมเดลตัดสินความปลอดภัย | การทำงานอัตโนมัติแบบสมดุล |120121```typescript122const conversation = query({123 prompt: "Refactor the auth module to use JWT",124 options: {125 allowedTools: ["Read", "Edit", "Glob", "Grep", "Bash"],126 permissionMode: "acceptEdits",127 },128});129```130131สำหรับการใช้งานจริง ควรรัน Agent ในสภาพแวดล้อมแบบ Sandbox (Container, VM) เสมอ และใช้โหมดสิทธิ์ที่จำกัดที่สุดที่ยังให้ Agent ทำงานได้132133## การสร้างเครื่องมือที่กำหนดเองด้วย MCP134135พลังที่แท้จริงของ SDK มาจากการขยาย Agent ด้วยเครื่องมือของคุณเอง เครื่องมือที่กำหนดเองถูกนิยามเป็น In-process MCP Server - ไม่ต้องจัดการ Subprocess ไม่มี Network Overhead136137### ตัวอย่าง: เครื่องมือสภาพอากาศ138139```typescript140import { tool, createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk";141import { z } from "zod";142143const getTemperature = tool(144 "get_temperature",145 "Get the current temperature at a location",146 {147 latitude: z.number().describe("Latitude"),148 longitude: z.number().describe("Longitude"),149 },150 async ({ latitude, longitude }) => {151 const res = await fetch(152 `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t=temperature_2m&temperature_unit=celsius`153 );154 const data = await res.json();155 return {156 content: [157 {158 type: "text",159 text: `Current temperature: ${data.current.temperature_2m}C`,160 },161 ],162 };163 }164);165166const weatherServer = createSdkMcpServer({167 name: "weather",168 version: "1.0.0",169 tools: [getTemperature],170});171172for await (const message of query({173 prompt: "What's the weather like in Rome?",174 options: {175 mcpServers: { weather: weatherServer },176 allowedTools: ["mcp__weather__get_temperature"],177 },178})) {179 if (message.type === "result" && message.subtype === "success") {180 console.log(message.result);181 }182}183```184185เครื่องมือที่กำหนดเองใช้รูปแบบการตั้งชื่อ `mcp__{server_name}__{tool_name}` คุณสามารถใช้ Wildcard ใน `allowedTools`: `"mcp__weather__*"` อนุญาตเครื่องมือทั้งหมดจาก Weather Server186187### ตัวอย่าง: เครื่องมือ Query ฐานข้อมูล188189```typescript190const queryDb = tool(191 "query_database",192 "Run a read-only SQL query against the application database",193 {194 sql: z.string().describe("SQL SELECT query to execute"),195 },196 async ({ sql }) => {197 // Validate: only allow SELECT queries198 if (!sql.trim().toUpperCase().startsWith("SELECT")) {199 return {200 content: [{ type: "text", text: "Error: Only SELECT queries are allowed." }],201 };202 }203204 const result = await pool.query(sql);205 return {206 content: [207 {208 type: "text",209 text: JSON.stringify(result.rows, null, 2),210 },211 ],212 };213 }214);215```216217## การเชื่อมต่อ MCP Server ภายนอก218219นอกเหนือจากเครื่องมือ In-process คุณสามารถเชื่อมต่อกับ MCP Server ที่มีอยู่ใดก็ได้ - เซิร์ฟเวอร์เดียวกันที่ทำงานกับ Claude Desktop, Cursor และ MCP Client อื่นๆ220221```typescript222for await (const message of query({223 prompt: "Check the latest issues in the frontend repo and summarize them",224 options: {225 mcpServers: {226 github: {227 command: "npx",228 args: ["-y", "@modelcontextprotocol/server-github"],229 env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN },230 },231 },232 allowedTools: ["mcp__github__*"],233 },234})) {235 // ...236}237```238239คุณสามารถรวม MCP Server หลายตัวเข้าด้วยกัน Agent จะเห็นเครื่องมือทั้งหมดจากทุกเซิร์ฟเวอร์ที่เชื่อมต่อและใช้ตามความจำเป็น240241```mermaid242graph LR243 Agent[Your Agent] --> SDK[Agent SDK]244 SDK --> InProcess[In-process MCP\nCustom Tools]245 SDK --> GitHub[GitHub MCP Server]246 SDK --> Postgres[PostgreSQL MCP Server]247 SDK --> Slack[Slack MCP Server]248```249250## การจัดการหลาย Agent (Multi-Agent Orchestration)251252สำหรับเวิร์กโฟลว์ที่ซับซ้อน คุณสามารถกำหนด Sub-Agent เฉพาะทางที่ Agent หลักมอบหมายงานให้ Sub-Agent แต่ละตัวมี Prompt เครื่องมือ และพื้นที่เฉพาะทางของตัวเอง253254```typescript255for await (const message of query({256 prompt: "Review the PR, check for security issues, and update the changelog",257 options: {258 allowedTools: ["Read", "Edit", "Bash", "Glob", "Grep", "Agent"],259 agents: [260 {261 name: "security-reviewer",262 description: "Reviews code for security vulnerabilities",263 prompt: "You are a security expert. Analyze code for OWASP Top 10 vulnerabilities.",264 allowedTools: ["Read", "Glob", "Grep"],265 },266 {267 name: "changelog-writer",268 description: "Updates the CHANGELOG.md file based on recent changes",269 prompt: "You maintain the project changelog. Follow Keep a Changelog format.",270 allowedTools: ["Read", "Edit", "Bash"],271 },272 ],273 },274})) {275 // The parent agent will:276 // 1. Read the PR diff277 // 2. Delegate security review to security-reviewer278 // 3. Delegate changelog update to changelog-writer279 // 4. Synthesize results280}281```282283ใส่ `"Agent"` ใน `allowedTools` ของ Agent หลักเพื่อเปิดใช้การมอบหมาย Sub-Agent รันด้วยเครื่องมือของตัวเองและไม่สามารถเข้าถึงเครื่องมือของ Agent หลักได้เว้นแต่จะได้รับอนุญาตอย่างชัดเจน284285```mermaid286graph TD287 Parent[Parent Agent] --> SR[Security Reviewer\nRead, Glob, Grep]288 Parent --> CW[Changelog Writer\nRead, Edit, Bash]289 SR --> Report[Security Report]290 CW --> Updated[Updated CHANGELOG]291 Report --> Parent292 Updated --> Parent293 Parent --> Final[Final Summary]294```295296## Session และความต่อเนื่อง297298Agent สามารถรักษา Context ข้ามหลาย Query ได้โดยใช้ Session จับ `session_id` จากการโต้ตอบครั้งแรกและส่งใน `resume` สำหรับ Query ถัดไป299300```typescript301let sessionId: string | undefined;302303// First query304for await (const message of query({305 prompt: "Read the project structure and understand the architecture",306 options: { allowedTools: ["Read", "Glob", "Grep"] },307})) {308 if (message.type === "init") {309 sessionId = message.session_id;310 }311}312313// Follow-up query (same session, full context preserved)314for await (const message of query({315 prompt: "Now refactor the auth module based on what you learned",316 resume: sessionId,317 options: { allowedTools: ["Read", "Edit", "Bash"] },318})) {319 // Agent remembers the full project context from the first query320}321```322323## Claude Managed Agents324325หากคุณไม่ต้องการโฮสต์โครงสร้างพื้นฐานของ Agent ด้วยตัวเอง **Claude Managed Agents** (เปิดตัวเมษายน 2026) ให้บริการคลาวด์แบบ Fully Managed Anthropic รัน Container จัดการ Scaling และให้ Streaming API326327```mermaid328graph LR329 subgraph "Self-hosted (Agent SDK)"330 Code[Your Code] --> SDK2[Agent SDK]331 SDK2 --> API[Claude API]332 SDK2 --> Tools[Your Tools]333 end334335 subgraph "Managed Agents"336 App[Your App] --> MAPI[Managed Agents API]337 MAPI --> Container[Anthropic-hosted Container]338 Container --> API2[Claude API]339 Container --> Tools2[Tools in Container]340 end341```342343ความแตกต่างสำคัญ: ด้วย Agent SDK คุณรัน Agent Loop ในโครงสร้างพื้นฐานของคุณเอง ด้วย Managed Agents Anthropic โฮสต์และรัน Agent ให้คุณ คุณโต้ตอบผ่าน API แบบ Session และรับ Event ผ่าน Server-Sent Events344345**ราคา:**346- **Agent SDK**: อัตรา Token ของ Claude API มาตรฐานเท่านั้น คุณจัดการโฮสติ้งเอง347- **Managed Agents**: อัตรา Token บวก $0.08 ต่อชั่วโมง Session (คิดค่าบริการต่อมิลลิวินาที)348349## แนวทางปฏิบัติที่ดีสำหรับ Production350351### 1. ใช้ Sandbox เสมอ352353อย่ารัน Agent ด้วยสิทธิ์ไม่จำกัดบนเครื่อง Production ใช้ Container (Docker, Fly.io, Modal) หรือสภาพแวดล้อม Sandbox (E2B, Vercel Sandbox)354355### 2. จำกัดการเข้าถึงเครื่องมือ356357ปฏิบัติตามหลักสิทธิ์น้อยที่สุด Agent ที่สร้างรายงานไม่จำเป็นต้องมี `Bash` หรือ `Write`358359```typescript360// Too permissive361allowedTools: ["Read", "Write", "Edit", "Bash", "Glob", "Grep"]362363// Better: only what's needed364allowedTools: ["Read", "Glob", "Grep"]365```366367### 3. ใช้ Hook เป็นราวกั้น368369Hook ให้คุณดักจับการเรียกเครื่องมือก่อนและหลังการทำงาน ใช้สำหรับการบันทึก Log การตรวจสอบ และการจำกัดอัตรา370371```typescript372const conversation = query({373 prompt: "Analyze the codebase",374 options: {375 allowedTools: ["Read", "Glob", "Grep"],376 hooks: {377 PreToolUse: async (toolName, input) => {378 console.log(`Tool call: ${toolName}`, input);379 // Return false to block the call380 if (toolName === "Bash" && input.command.includes("rm")) {381 return false;382 }383 return true;384 },385 },386 },387});388```389390### 4. จัดการข้อผิดพลาดอย่างสง่างาม391392Agent Loop อาจเกิดข้อผิดพลาด - เครื่องมือล้มเหลว API Rate Limit Context Window ล้น ตรวจสอบประเภทข้อความเสมอ393394```typescript395for await (const message of conversation) {396 switch (message.type) {397 case "assistant":398 // Agent reasoning399 break;400 case "tool_use":401 // Agent is calling a tool402 break;403 case "result":404 if (message.subtype === "error") {405 console.error("Agent failed:", message.error);406 }407 break;408 }409}410```411412### 5. ตรวจสอบการใช้ Token413414Agent Loop อาจใช้ Token จำนวนมาก โดยเฉพาะกับ Codebase ขนาดใหญ่ SDK มี Context Compaction อัตโนมัติ แต่คุณยังควรตรวจสอบการใช้งาน415416## สรุป417418Claude Agent SDK เปลี่ยน LLM จากเครื่องตอบคำถามให้เป็นสิ่งที่ใกล้เคียงกับนักพัฒนารุ่นใหม่ Agent ของคุณสามารถอ่าน เขียน รัน ตรวจสอบ และทำซ้ำ - เวิร์กโฟลว์เดียวกับที่มนุษย์ทำ419420เริ่มจากเล็กๆ: สร้าง Agent ด้วยเครื่องมือในตัวสักสองสามตัว จากนั้นเพิ่มเครื่องมือ MCP ที่กำหนดเองสำหรับโดเมนเฉพาะของคุณ ขยายไปสู่ Multi-Agent Orchestration เมื่อเวิร์กโฟลว์ของคุณต้องการความเชี่ยวชาญเฉพาะทาง421422Agent Loop เดียวกันกับที่ขับเคลื่อน Claude Code หากมันสร้างซอฟต์แวร์ได้ Agent ของคุณก็ทำได้เช่นกัน423424> **รายการตรวจสอบสำหรับเริ่มต้น:**425>426> - [x] ติดตั้ง SDK (`npm install @anthropic-ai/claude-agent-sdk`)427> - [x] ตั้งค่า `ANTHROPIC_API_KEY` ในตัวแปรสภาพแวดล้อม428> - [x] สร้าง Agent อย่างง่ายด้วยเครื่องมือในตัว (Read, Glob, Grep)429> - [x] เพิ่มเครื่องมือที่กำหนดเองผ่าน In-process MCP Server430> - [x] เชื่อมต่อ MCP Server ภายนอก (GitHub, PostgreSQL เป็นต้น)431> - [x] สร้าง Multi-Agent Orchestration ด้วย Sub-Agent432> - [x] ตั้งค่าสภาพแวดล้อม Sandbox สำหรับ Production433> - [x] เพิ่ม Hook สำหรับการบันทึก Log และราวกั้น434
:การสร้าง AI Agent ด้วย Claude Agent SDK - คู่มือปฏิบัติlines 1-434 (END) — press q to close