Skip to main content

Quickstart

เริ่มต้นใช้งาน Python หรือ TypeScript Agent SDK เพื่อสร้าง AI agents ที่ทำงานอัตโนมัติ

ใช้ Agent SDK เพื่อสร้าง AI agent ที่อ่านโค้ดของคุณ ค้นหา bugs และแก้ไขได้โดยอัตโนมัติ

สิ่งที่จะทำ:

  1. ตั้งค่าโครงการด้วย Agent SDK
  2. สร้างไฟล์ที่มีโค้ดมีข้อผิดพลาด
  3. รัน agent ที่ค้นหาและแก้ไข bugs อัตโนมัติ

ข้อกำหนดเบื้องต้น

การตั้งค่า

ขั้นตอนที่ 1: สร้างโฟลเดอร์โครงการ

สร้างไดเรกทอรีใหม่:

mkdir my-agent
cd my-agent

ขั้นตอนที่ 2: ติดตั้ง SDK

TypeScript:

npm install @anthropic-ai/claude-agent-sdk

Python (uv):

uv เป็น package manager Python ที่รวดเร็ว:

uv init
uv add claude-agent-sdk

Python (pip):

บน macOS หรือ Linux:

python3 -m venv .venv
source .venv/bin/activate
pip install claude-agent-sdk

บน Windows:

py -m venv .venv
.venv\Scripts\Activate.ps1
pip install claude-agent-sdk

ขั้นตอนที่ 3: ตั้งค่า API key

รับ API key จาก Claude Console จากนั้นสร้างไฟล์ .env:

ANTHROPIC_API_KEY=your-api-key

SDK ยังรองรับการยืนยันตัวตนผ่าน providers อื่น ๆ:

  • Amazon Bedrock: ตั้งค่า CLAUDE_CODE_USE_BEDROCK=1 และกำหนด AWS credentials
  • Google Vertex AI: ตั้งค่า CLAUDE_CODE_USE_VERTEX=1 และกำหนด Google Cloud credentials
  • Microsoft Azure: ตั้งค่า CLAUDE_CODE_USE_FOUNDRY=1 และกำหนด Azure credentials

สร้างไฟล์ที่มี bugs

สร้าง utils.py ในไดเรกทอรี my-agent และวางโค้ดต่อไปนี้:

def calculate_average(numbers):
total = 0
for num in numbers:
total += num
return total / len(numbers)


def get_user_name(user):
return user["name"].upper()

โค้ดนี้มีสอง bugs:

  1. calculate_average([]) crash ด้วย division by zero
  2. get_user_name(None) crash ด้วย TypeError

สร้าง agent ที่ค้นหาและแก้ไข bugs

สร้าง agent.py (Python) หรือ agent.ts (TypeScript):

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage


async def main():
# Agentic loop: streams messages ขณะที่ Claude ทำงาน
async for message in query(
prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob"], # อนุมัติ tools เหล่านี้อัตโนมัติ
permission_mode="acceptEdits", # อนุมัติการแก้ไขไฟล์อัตโนมัติ
),
):
# แสดงผลที่อ่านได้
if isinstance(message, AssistantMessage):
for block in message.content:
if hasattr(block, "text"):
print(block.text) # ความคิดของ Claude
elif hasattr(block, "name"):
print(f"Tool: {block.name}") # Tool ที่กำลังเรียก
elif isinstance(message, ResultMessage):
print(f"Done: {message.subtype}") # ผลลัพธ์สุดท้าย


asyncio.run(main())
import { query } from "@anthropic-ai/claude-agent-sdk";

// Agentic loop: streams messages ขณะที่ Claude ทำงาน
for await (const message of query({
prompt: "Review utils.py for bugs that would cause crashes. Fix any issues you find.",
options: {
allowedTools: ["Read", "Edit", "Glob"], // อนุมัติ tools เหล่านี้อัตโนมัติ
permissionMode: "acceptEdits" // อนุมัติการแก้ไขไฟล์อัตโนมัติ
}
})) {
// แสดงผลที่อ่านได้
if (message.type === "assistant" && message.message?.content) {
for (const block of message.message.content) {
if ("text" in block) {
console.log(block.text); // ความคิดของ Claude
} else if ("name" in block) {
console.log(`Tool: ${block.name}`); // Tool ที่กำลังเรียก
}
}
} else if (message.type === "result") {
console.log(`Done: ${message.subtype}`); // ผลลัพธ์สุดท้าย
}
}

โค้ดนี้มีสามส่วนหลัก:

  1. query: จุดเริ่มต้นหลักที่สร้าง agentic loop คืน async iterator ดังนั้นใช้ async for เพื่อ stream messages ขณะที่ Claude ทำงาน
  2. prompt: สิ่งที่คุณต้องการให้ Claude ทำ Claude จะคิดว่าจะใช้ tools ใดตามงาน
  3. options: การกำหนดค่าสำหรับ agent ตัวอย่างนี้ใช้ allowedTools เพื่ออนุมัติ Read, Edit และ Glob ล่วงหน้า และ permissionMode: "acceptEdits" เพื่ออนุมัติการเปลี่ยนแปลงไฟล์อัตโนมัติ

รัน agent ของคุณ

TypeScript:

npx tsx agent.ts

Python (uv):

uv run agent.py

Python (pip):

python agent.py

หลังจากรัน ตรวจสอบ utils.py คุณจะเห็นโค้ดป้องกันที่จัดการ empty lists และ null users agent ของคุณทำงานโดยอัตโนมัติ:

  1. อ่าน utils.py เพื่อเข้าใจโค้ด
  2. วิเคราะห์ logic และระบุ edge cases ที่จะ crash
  3. แก้ไข ไฟล์เพื่อเพิ่มการจัดการ error

ลอง prompts อื่น ๆ

  • "Add docstrings to all functions in utils.py"
  • "Add type hints to all functions in utils.py"
  • "Create a README.md documenting the functions in utils.py"

ปรับแต่ง agent ของคุณ

เพิ่มความสามารถค้นหาเว็บ:

options = ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob", "WebSearch"], permission_mode="acceptEdits"
)

ให้ system prompt ที่กำหนดเอง:

options = ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob"],
permission_mode="acceptEdits",
system_prompt="You are a senior Python developer. Always follow PEP 8 style guidelines.",
)

รันคำสั่ง terminal:

options = ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Glob", "Bash"], permission_mode="acceptEdits"
)

ด้วย Bash ที่เปิดใช้งาน ลอง: "Write unit tests for utils.py, run them, and fix any failures"

แนวคิดหลัก

Tools ควบคุมสิ่งที่ agent สามารถทำได้:

Toolsสิ่งที่ agent ทำได้
Read, Glob, Grepวิเคราะห์แบบอ่านอย่างเดียว
Read, Edit, Globวิเคราะห์และแก้ไขโค้ด
Read, Edit, Bash, Glob, GrepAutomation เต็มรูปแบบ

Permission modes ควบคุมการดูแลของมนุษย์:

ModeพฤติกรรมUse case
acceptEditsอนุมัติการแก้ไขไฟล์และคำสั่ง filesystem อัตโนมัติDevelopment workflows ที่เชื่อถือได้
dontAskปฏิเสธทุกอย่างที่ไม่อยู่ใน allowedToolsHeadless agents ที่ล็อคดาวน์
bypassPermissionsรัน tools ทั้งหมดโดยไม่ถามCI ใน sandbox, environments ที่เชื่อถือได้อย่างสมบูรณ์
defaultต้องการ callback canUseTool เพื่อจัดการการอนุมัติCustom approval flows

การแก้ปัญหา

API error thinking.type.enabled ไม่รองรับสำหรับ model นี้

Claude Opus 4.7 แทนที่ thinking.type.enabled ด้วย thinking.type.adaptive อัปเกรดเป็น Agent SDK v0.2.111 หรือใหม่กว่าเพื่อใช้ Opus 4.7

ขั้นตอนถัดไป

  • Permissions: ควบคุมสิ่งที่ agent ทำได้และเมื่อใดที่ต้องการการอนุมัติ
  • Hooks: รันโค้ดที่กำหนดเองก่อนหรือหลัง tool calls
  • Sessions: สร้าง multi-turn agents ที่รักษา context
  • MCP servers: เชื่อมต่อกับ databases, browsers, APIs และระบบภายนอกอื่น ๆ
  • Hosting: Deploy agents ไปยัง Docker, cloud และ CI/CD