Claude Agent SDK 入门
了解如何使用 Claude Agent SDK 构建 AI Agent 应用,通过 QCode.cc API 接入
Claude Agent SDK 入门¶
Claude Agent SDK 是 Anthropic 官方提供的开发工具包,用于构建基于 Claude 模型的 AI Agent 应用。与 Claude Code(CLI 工具)不同,SDK 面向开发者,允许你将 Claude 能力集成到自己的应用程序中。
什么是 Claude Agent SDK?¶
Claude Agent SDK 提供了一套构建块,帮助你创建能够:
- 理解自然语言指令并执行复杂任务
- 使用工具(搜索、代码执行、文件操作等)
- 维护对话上下文进行多轮交互
- 连接外部服务(通过 MCP 服务器)
的应用。
安装 SDK¶
Python SDK¶
pip install anthropic
TypeScript SDK¶
npm install @anthropic-ai/sdk
快速开始¶
基本消息调用¶
from anthropic import Anthropic
# 通过 QCode.cc API
client = Anthropic(
base_url="https://api.qcode.cc/claude/v1",
api_key="cr_your_api_key"
)
message = client.messages.create(
model="claude-opus-4-7-20250514",
max_tokens=4096,
messages=[
{"role": "user", "content": "解释什么是 RESTful API"}
]
)
print(message.content[0].text)
流式响应¶
with client.messages.stream(
model="claude-opus-4-7-20250514",
max_tokens=1024,
messages=[
{"role": "user", "content": "写一个 Python 快速排序函数"}
]
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
工具使用(Tool Use)¶
Tool Use 是 Agent 的核心能力,允许模型调用外部工具。
定义工具¶
from anthropic import Anthropic, NotGiven, NOT_GIVEN
from anthropic.types import ToolParam
client = Anthropic(
base_url="https://api.qcode.cc/claude/v1",
api_key="cr_your_api_key"
)
# 定义搜索工具
tools = [
{
"name": "search_web",
"description": "搜索网络获取信息",
"input_schema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "搜索关键词"
}
},
"required": ["query"]
}
},
{
"name": "calculate",
"description": "执行数学计算",
"input_schema": {
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "数学表达式,如 '2 + 3 * 4'"
}
},
"required": ["expression"]
}
}
]
# 发送带工具的消息
message = client.messages.create(
model="claude-opus-4-7-20250514",
max_tokens=4096,
messages=[
{"role": "user", "content": "帮我计算 (15 + 25) * 2 并搜索一下这个结果的含义"}
],
tools=tools
)
# 处理工具调用
for content in message.content:
if content.type == "text":
print(content.text)
elif content.type == "tool_use":
print(f"调用工具: {content.name}")
print(f"参数: {content.input}")
# 模拟工具执行
if content.name == "calculate":
result = eval(content.input["expression"])
tool_result = str(result)
elif content.name == "search_web":
tool_result = f"搜索 '{content.input['query']}' 的结果..."
# 将结果返回给模型
message = client.messages.create(
model="claude-opus-4-7-20250514",
max_tokens=4096,
messages=[
{"role": "user", "content": "帮我计算 (15 + 25) * 2 并搜索一下这个结果的含义"},
message,
{
"role": "user",
"content": None,
"type": "tool_result",
"tool_use_id": content.id,
"content": tool_result
}
],
tools=tools
)
流式工具调用¶
with client.messages.stream(
model="claude-opus-4-7-20250514",
max_tokens=4096,
messages=[
{"role": "user", "content": "创建一个名为 hello.py 的文件,内容是打印 'Hello, World!'"}
],
tools=[
{
"name": "write_file",
"description": "写入文件内容",
"input_schema": {
"type": "object",
"properties": {
"filename": {"type": "string"},
"content": {"type": "string"}
},
"required": ["filename", "content"]
}
}
]
) as stream:
for event in stream:
if event.type == "content_block_start":
print(f"开始: {event.content_block.type}")
elif event.type == "content_block_delta":
if event.delta.type == "text_delta":
print(event.delta.text, end="", flush=True)
elif event.delta.type == "tool_use_delta":
print(f"\n[工具调用] {event.delta.name}")
elif event.type == "message_delta":
print(f"\n[完成] 实际完成: {event.usage}")
Prompt Caching¶
Prompt Caching 可以显著降低长时间对话的成本:
# 系统提示(会被缓存)
system_prompt = """你是一个专业的代码审查助手。
你的职责是:
1. 检查代码安全性
2. 识别性能问题
3. 验证代码规范
4. 提供改进建议
"""
# 使用 cache_control 标记可缓存内容
message = client.messages.create(
model="claude-opus-4-7-20250514",
max_tokens=4096,
system=[
{
"type": "text",
"text": system_prompt,
"cache_control": {"type": "ephemeral"}
}
],
messages=[
{"role": "user", "content": "请审查 @src/auth/login.ts"}
]
)
Agent 构建示例¶
from anthropic import Anthropic
from typing import List, Dict, Any
class CodeReviewAgent:
def __init__(self, api_key: str):
self.client = Anthropic(
base_url="https://api.qcode.cc/claude/v1",
api_key=api_key
)
self.system_prompt = """你是一个专业的代码审查助手。
审查时关注:安全性、性能、可读性、最佳实践。
每次审查输出:问题列表、严重程度、修复建议。"""
def review(self, code_snippet: str) -> str:
message = self.client.messages.create(
model="claude-opus-4-7-20250514",
max_tokens=4096,
system=self.system_prompt,
messages=[
{"role": "user", "content": f"审查以下代码:\n\n{code_snippet}"}
]
)
return message.content[0].text
def review_with_tools(self, code_snippet: str, issues: List[str]) -> str:
tools = [{
"name": "mark_resolved",
"description": "标记问题为已解决",
"input_schema": {
"type": "object",
"properties": {
"issue_id": {"type": "string"},
"notes": {"type": "string"}
}
}
}]
message = self.client.messages.create(
model="claude-opus-4-7-20250514",
max_tokens=4096,
system=self.system_prompt,
messages=[
{"role": "user", "content": f"审查代码并解决以下已知问题:\n\n已知问题:\n" + "\n".join(f"- {i}" for i in issues)},
{"role": "user", "content": f"代码:\n{code_snippet}"}
],
tools=tools
)
return message
# 使用
agent = CodeReviewAgent("cr_your_api_key")
issues = ["SQL 注入风险", "缺少输入验证"]
result = agent.review_with_tools("SELECT * FROM users WHERE id = " + user_id, issues)
与 Claude Code 的区别¶
| 特性 | Claude Agent SDK | Claude Code |
|---|---|---|
| 目标用户 | 开发者 | 开发者个人 |
| 运行环境 | 你的应用 | 命令行 |
| 文件操作 | 需自己实现 | 内置 |
| 终端命令 | 需自己实现 | 内置 |
| Git 集成 | 需自己实现 | 内置 |
| 使用场景 | 构建 AI 应用 | 辅助编程 |
QCode.cc 配置¶
import os
# 方式 1:环境变量
os.environ["ANTHROPIC_BASE_URL"] = "https://api.qcode.cc/claude/v1"
os.environ["ANTHROPIC_API_KEY"] = "cr_your_key"
client = Anthropic() # 自动读取环境变量
# 方式 2:深圳直连(推荐国内)
client = Anthropic(
base_url="http://103.236.53.153/api/claude/v1",
api_key="cr_your_key"
)