第 2 课:环境搭建
需要准备什么
1. Python 3.10 或更高版本
2. Claude Agent SDK
3. Anthropic API Key
4. 一个代码编辑器(VS Code 推荐)
第一步:创建项目
# 创建项目目录
mkdir smart-support && cd smart-support
# 创建虚拟环境(推荐)
python -m venv venv
source venv/bin/activate # Mac/Linux
# venv\Scripts\activate # Windows
第二步:安装 SDK
pip install claude-agent-sdk
验证安装成功:
python -c "from claude_agent_sdk import query; print('SDK 安装成功!')"
第三步:配置 API Key
# 设置环境变量
export ANTHROPIC_API_KEY="sk-ant-你的密钥"
把这行加到 ~/.bashrc 或 ~/.zshrc,这样每次打开终端都不用重新设置。
第四步:跑通 Hello World
创建 hello_support.py:
"""智能客服 Hello World"""
import anyio
from claude_agent_sdk import (
query,
ClaudeAgentOptions,
AssistantMessage,
ResultMessage,
TextBlock,
)
async def main():
# 给 AI 一个客服角色
options = ClaudeAgentOptions(
system_prompt="你是一个友好的客服助手,用中文回复客户问题。回复要简洁、专业。",
max_turns=1, # 只处理一轮
)
print("📞 智能客服已上线!\n")
# 模拟一个客户咨询
customer_question = "你好,我想问一下怎么修改收货地址?"
print(f"客户: {customer_question}\n")
async for msg in query(prompt=customer_question, options=options):
if isinstance(msg, AssistantMessage):
for block in msg.content:
if isinstance(block, TextBlock):
print(f"客服: {block.text}")
elif isinstance(msg, ResultMessage):
if msg.total_cost_usd and msg.total_cost_usd > 0:
print(f"\n💰 本次费用: ${msg.total_cost_usd:.4f}")
anyio.run(main)
运行:
python hello_support.py
你会看到 AI 客服自动回复了客户的问题。恭喜,第一步搞定!
第五步:试试多轮对话
创建 hello_chat.py:
"""多轮对话 Hello World"""
import asyncio
from claude_agent_sdk import (
ClaudeSDKClient,
ClaudeAgentOptions,
AssistantMessage,
ResultMessage,
TextBlock,
)
async def main():
options = ClaudeAgentOptions(
system_prompt="""你是智能客服助手。规则:
1. 用中文回复
2. 回答要简洁,不超过 3 句话
3. 如果不确定,说"我帮您转接人工客服"
""",
)
print("📞 智能客服已上线(输入 quit 退出)\n")
async with ClaudeSDKClient(options=options) as client:
while True:
user_input = input("客户: ").strip()
if user_input.lower() in ['quit', 'exit', 'q']:
print("👋 感谢咨询,再见!")
break
if not user_input:
continue
await client.query(user_input)
async for msg in client.receive_response():
if isinstance(msg, AssistantMessage):
for block in msg.content:
if isinstance(block, TextBlock):
print(f"客服: {block.text}")
elif isinstance(msg, ResultMessage):
pass # 不显示费用信息
print()
asyncio.run(main)
运行后你可以和 AI 客服来回聊天了。试试问几个问题,看看它的回复。
项目目录规划
后面的课程,我们会逐步搭建这样的项目结构:
smart-support/
├── main.py ← 主程序
├── tools/
│ ├── __init__.py
│ ├── knowledge_base.py ← 知识库检索工具
│ ├── ticket_db.py ← 工单数据库操作
│ └── order_query.py ← 订单查询工具
├── hooks/
│ ├── __init__.py
│ ├── safety.py ← 安全 Hook
│ └── pii_filter.py ← PII 脱敏
├── agents/
│ ├── __init__.py
│ └── definitions.py ← Agent 定义
├── data/
│ ├── faq.json ← FAQ 知识库
│ └── tickets.json ← 模拟工单数据
└── requirements.txt
现在先不用创建所有文件,后面每一课会一步步带你完成。
常见问题
Q: 报错 "claude-agent-sdk not found"
A: 确认虚拟环境已激活(终端前面有 (venv) 字样)
Q: 报错 "API key not set"
A: 检查环境变量 echo $ANTHROPIC_API_KEY,确保有值
Q: AI 回复是英文 A: 在 system_prompt 里明确写"用中文回复"
本课小结
- 安装了 claude-agent-sdk
- 跑通了两个 Hello World:单次查询和多轮对话
- 规划了项目目录结构