Claude Code实战教程(14):Agent SDK 构建 AI 应用——从工具使用者到产品创造者
《从零开始的 Claude Code 实战系列教程》第 14 篇 · 公众号「麒麟剑的AI自动化Lab」连载
▲ 从使用工具到创造工具,这是开发者进阶的关键一步
一、从用户到创造者的跃迁
到目前为止,我们一直在学习如何使用 Claude Code。现在,我们要学习如何构建基于 Claude Code 的应用。
这是从”消费者”到”生产者”的关键跃迁。
想想看:
- 你会开车 → 你可以成为赛车手
- 你用 Excel → 你可以开发财务软件
- 你用 Claude Code → 你可以构建 AI 应用
二、什么是 Agent SDK?
Agent SDK 是 Anthropic 提供的开发工具包,让你能够:
- 嵌入 Claude 到你的应用中
- 自定义 Agent 行为
- 构建多步骤工作流
- 集成外部工具和 API
SDK 包含的核心组件
| 组件 | 功能 | 用途 |
|---|---|---|
| Messages API | 发送和接收消息 | 基本对话功能 |
| Tools | 定义工具函数 | 让 AI 能调用外部功能 |
| System Prompts | 设置系统提示 | 定义 AI 角色和行为 |
| Streaming | 流式输出 | 实时响应用户体验 |
三、使用 Claude API 构建 Agent
基础示例:聊天机器人
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
messages=[
{"role": "user", "content": "你好,请介绍一下你自己"}
]
)
print(message.content)进阶示例:带工具的 Agent
import anthropic
client = anthropic.Anthropic()
tools = [
{
"name": "get_weather",
"description": "获取指定城市的天气",
"input_schema": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
]
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "北京天气怎么样?"}
]
)
# 处理工具调用
if message.stop_reason == "tool_use":
tool_result = call_tool(message.content[0].input)
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=1024,
tools=tools,
messages=[
{"role": "user", "content": "北京天气怎么样?"},
{"role": "assistant", "content": message.content},
{"role": "user", "content": tool_result}
]
)
print(message.content[0].text)四、构建你的第一个 AI 应用
应用场景:代码审查 Bot
import anthropic
import subprocess
def review_code(pr_diff):
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-opus-5",
max_tokens=4096,
messages=[
{"role": "user", "content": f"""
请审查以下 PR 的代码:
{pr_diff}
重点关注:
1. 安全性问题
2. 性能问题
3. 代码规范
4. 潜在 Bug
输出格式化的审查报告
"""}
]
)
return message.content[0].text
# 使用示例
diff = subprocess.run(["git", "diff", "origin/main...HEAD"], capture_output=True).stdout
review = review_code(diff)
print(review)五、高级技巧:多 Agent 协作
并行 Agent 模式
from concurrent.futures import ThreadPoolExecutor
import anthropic
def analyze_security(diff):
client = anthropic.Anthropic()
# 安全审查逻辑
...
def analyze_performance(diff):
client = anthropic.Anthropic()
# 性能审查逻辑
...
def analyze_quality(diff):
client = anthropic.Anthropic()
# 代码质量审查逻辑
...
# 并行执行
with ThreadPoolExecutor(max_workers=3) as executor:
results = list(executor.map(
lambda fn: fn(diff),
[analyze_security, analyze_performance, analyze_quality]
))六、实战项目:AI 测试生成器
项目结构
ai-test-generator/
├── main.py
├── requirements.txt
└── templates/
├── jest.json
└── pytest.json核心代码
import anthropic
class TestGenerator:
def __init__(self, code):
self.code = code
self.client = anthropic.Anthropic()
def generate_tests(self, framework="jest"):
prompt = f"""
分析以下代码并生成 {framework} 测试:
```
{self.code}
```
要求:
1. 覆盖所有边界情况
2. 包含正向和负向测试
3. 使用 {framework} 最佳实践
"""
message = self.client.messages.create(
model="claude-sonnet-5",
max_tokens=2048,
messages=[{"role": "user", "content": prompt}]
)
return message.content[0].text
# 使用
code = """
def add(a, b):
return a + b
"""
generator = TestGenerator(code)
tests = generator.generate_tests("pytest")
print(tests)七、部署与集成
Docker 部署
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "main.py"]API 封装
from fastapi import FastAPI
import anthropic
app = FastAPI()
client = anthropic.Anthropic()
@app.post("/analyze")
async def analyze_code(code: str):
message = client.messages.create(
model="claude-opus-5",
max_tokens=1024,
messages=[{"role": "user", "content": f"分析以下代码:\n{code}"}]
)
return {"analysis": message.content[0].text}八、本章小结
| 主题 | 说明 |
|---|---|
| Agent SDK | Anthropic 提供的开发工具包 |
| 基础用法 | 创建消息、调用 API |
| 工具集成 | 定义工具 schema、处理工具调用 |
| 多 Agent | 并行执行、结果汇总 |
| 部署方式 | Docker、FastAPI、云端服务 |
下期预告(第 15 篇):多模态与未来展望——图片、音频、视频与 AI 编程的融合
关注本系列,从入门到专家,系统掌握 Claude Code 的全部技能。