Python AI Agent 零基础教程 | 第5篇:手把手构建你的第一个AI Agent
前言
经过前四期的学习,你已经掌握了 Python 基础和 API 调用。今天我们正式进入核心环节——构建你的第一个 AI Agent!
我将手把手带你写出完整的 Agent 代码,保证你能运行成功!
一、AI Agent 核心架构
1.1 Agent 架构回顾
Python 代码
┌─────────────────────────────────────────────────────────────┐
│ AI Agent 核心架构 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 用户 ──▶ 接收输入 │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ Agent Core │ ◀── 系统提示词(角色设定) │
│ │ Agent 核心 │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ LLM 调用 │ ◀── AI 大脑(思考和决策) │
│ │ 大脑思考 │ │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ 输出结果 │ ──▶ 返回给用户 │
│ │ 返回结果 │ │
│ └─────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
1.2 核心组件
| 组件 | 作用 |
|---|
| Agent Core | Agent 的核心逻辑 |
| System Prompt | 系统提示词,定义 Agent 角色 |
| LLM | 大语言模型,负责思考和决策 |
| Memory | 记忆系统,存储对话历史 |
---
二、基础版 Agent 实现
2.1 最小 Agent 代码
只需要 30 行代码,就能创建一个最简单的 AI Agent!
Python 代码
import requests
import json
class SimpleAgent:
"""最简单的 AI Agent"""
def __init__(self, api_key, model="gpt-3.5-turbo"):
self.api_key = api_key
self.model = model
self.messages = []
def think(self, user_input):
"""思考:调用 AI 获取回复"""
# 添加用户消息
self.messages.append({
"role": "user",
"content": user_input
})
# 调用 API
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
data = {
"model": self.model,
"messages": self.messages
}
response = requests.post(url, headers=headers, json=data)
result = response.json()
# 提取 AI 回复
ai_message = result["choices"][0]["message"]
self.messages.append(ai_message)
return ai_message["content"]
使用
agent = SimpleAgent("sk-xxxxxx") # 替换为你的 API Key
response = agent.think("你好,请介绍一下自己")
print(response)
2.2 代码解析
Python 代码
┌─────────────────────────────────────────────────────────────┐
│ SimpleAgent 工作流程 │
├─────────────────────────────────────────────────────────────┤
│ │
│ 1. __init__() 初始化 │
│ ├── 保存 API Key │
│ ├── 设置模型 │
│ └── 初始化消息列表 [] │
│ │
│ 2. think() 思考方法 │
│ ├── 接收用户输入 │
│ ├── 添加到消息列表 │
│ ├── 调用 API │
│ ├── 提取回复 │
│ └── 返回结果 │
│ │
│ 3. messages 列表结构 │
│ [ │
│ {"role": "user", "content": "你好"}, │
│ {"role": "assistant", "content": "你好,我是..."}, │
│ {"role": "user", "content": "你是谁"}, │
│ ] │
│ │
└─────────────────────────────────────────────────────────────┘
三、带角色设定的 Agent
3.1 什么是 System Prompt?
System Prompt(系统提示词) 用于定义 AI Agent 的角色、性格和行为规则。
Python 代码
定义不同角色的 System Prompt
助手角色
ASSISTANT_PROMPT = """你是一个友好的 AI 助手。
请用简洁、有帮助的方式回答用户的问题。"""
编程导师角色
TUTOR_PROMPT = """你是一个经验丰富的 Python 编程导师。
- 解释概念时使用简单的语言
- 提供代码示例时添加注释
- 鼓励学习者尝试和探索"""
客服角色
CUSTOMER_SERVICE_PROMPT = """你是一个专业的电商客服。
- 保持礼貌和耐心
- 回答关于产品、订单、物流的问题
- 遇到无法解决的问题时转人工"""
3.2 带角色设定的 Agent
Python 代码
import requests
import json
class RoleAgent:
"""带角色设定的 AI Agent"""
def __init__(self, api_key, role_prompt, model="gpt-3.5-turbo"):
self.api_key = api_key
self.model = model
# 设置系统提示词
self.messages = [
{"role": "system", "content": role_prompt}
]
def think(self, user_input):
"""思考"""
self.messages.append({
"role": "user",
"content": user_input
})
response = self._call_api()
ai_message = response["choices"][0]["message"]
self.messages.append(ai_message)
return ai_message["content"]
def _call_api(self):
"""调用 API"""
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
data = {
"model": self.model,
"messages": self.messages
}
response = requests.post(url, headers=headers, json=data)
return response.json()
使用示例
TUTOR_PROMPT = """你是一个经验丰富的 Python 编程导师。
要求:
- 解释概念时使用简单的语言
- 提供代码示例时添加详细注释
- 鼓励学习者多动手实践
- 如果代码有错误,温和地指出并给出建议"""
tutor = RoleAgent("sk-xxxxxx", TUTOR_PROMPT)
测试
question = "什么是变量?"
answer = tutor.think(question)
print(f"问题:{question}")
print(f"回答:{answer}")
3.3 效果对比
没有角色设定:
Python 代码
问:帮我写一个函数
答:当然可以,请告诉我具体需求。
有角色设定(编程导师):
Python 代码
问:帮我写一个函数
答:当然可以!我来帮你写一个函数。
函数是封装代码的一种方式,让我用一个简单的例子来说明:
python
def say_hello():
'''这是一个打招呼的函数'''
print("你好!")
调用函数
say_hello()
Python 代码
💡 小贴士:
- def 是定义函数的关键字
- 函数名后面的 () 用来传递参数
- 函数内部的代码需要缩进
动手试试看,有问题随时问我!
四、完整版 Agent 实现
4.1 增强版 Agent 类
Python 代码
import requests
import json
from datetime import datetime
class Agent:
"""完整的 AI Agent"""
def __init__(self, api_key, name="助手", model="gpt-3.5-turbo"):
self.api_key = api_key
self.name = name
self.model = model
self.messages = []
self.tools = []
def set_system_prompt(self, prompt):
"""设置系统提示词"""
# 找到并删除已有的 system 消息
self.messages = [msg for msg in self.messages if msg.get("role") != "system"]
# 添加新的 system 消息
self.messages.insert(0, {"role": "system", "content": prompt})
def think(self, user_input, show_thinking=False):
"""思考并返回结果"""
print(f"\n【{self.name}】收到消息:{user_input}")
# 添加用户消息
self.messages.append({
"role": "user",
"content": user_input
})
# 调用 API
response = self._call_api()
if "error" in response:
return f"❌ 错误:{response['error']['message']}"
# 提取回复
ai_message = response["choices"][0]["message"]
self.messages.append(ai_message)
content = ai_message["content"]
if show_thinking:
print(f"【{self.name}】思考中...")
return content
def _call_api(self):
"""调用 OpenAI API"""
url = "https://api.openai.com/v1/chat/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}"
}
data = {
"model": self.model,
"messages": self.messages,
"temperature": 0.7
}
try:
response = requests.post(url, headers=headers, json=data, timeout=30)
return response.json()
except Exception as e:
return {"error": {"message": str(e)}}
def reset(self):
"""重置对话"""
system_msg = self.messages[0] if self.messages and self.messages[0].get("role") == "system" else None
self.messages = []
if system_msg:
self.messages.append(system_msg)
print("✓ 对话已重置")
def show_history(self):
"""显示对话历史"""
print("\n" + "="*50)
print(f"📋 {self.name} 对话历史")
print("="*50)
for i, msg in enumerate(self.messages):
role = {"system": "⚙️ 系统", "user": "👤 用户", "assistant": "🤖 AI"}[msg["role"]]
content = msg["content"][:100] + "..." if len(msg["content"]) > 100 else msg["content"]
print(f"{i+1}. {role}: {content}")
print("="*50)
def save_conversation(self, filename=None):
"""保存对话"""
if filename is None:
filename = f"conversation_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
with open(filename, "w", encoding="utf-8") as f:
json.dump(self.messages, f, ensure_ascii=False, indent=2)
print(f"✓ 对话已保存到 {filename}")
4.2 使用示例
Python 代码
创建 Agent
agent = Agent(
api_key="sk-xxxxxx", # 替换为你的 API Key
name="AI学习助手",
model="gpt-3.5-turbo"
)
设置角色
system_prompt = """你是一个专业的 AI 学习助手,名叫小智。
你的特点:
- 知识渊博,熟悉 AI 和编程领域
- 回答问题耐心细致
- 善于用例子解释复杂概念
- 鼓励用户多动手实践
遇到不会的问题,你会坦诚说明,并尝试给出建议。"""
agent.set_system_prompt(system_prompt)
开始对话
print("="*50)
print("🤖 AI Agent 对话开始!输入 'quit' 退出")
print("="*50)
while True:
user_input = input("\n👤 你:")
if user_input.lower() == "quit":
print("再见!")
break
elif user_input.lower() == "reset":
agent.reset()
elif user_input.lower() == "history":
agent.show_history()
else:
response = agent.think(user_input)
print(f"\n🤖 小智:{response}")
4.3 运行效果
Python 代码
==================================================
🤖 AI Agent 对话开始!输入 'quit' 退出
==================================================
👤 你:什么是AI Agent?
【AI学习助手】收到消息:什么是AI Agent?
🤖 小智:AI Agent(人工智能代理)是一种能够自主理解和执行任务的智能系统。
简单来说,它可以:
- 🔍 理解你的意图
- 📝 制定执行计划
- 🔧 调用工具完成任务
- 💬 返回结果给你
就像一个聪明的助手,可以帮你处理各种复杂任务!
👤 你:给我举个例子
【AI学习助手】收到消息:给我举个例子
🤖 小智:当然可以!让我举几个常见的例子:
📧 智能邮件助手
- 自动阅读邮件内容
- 判断邮件类型(重要/普通/垃圾)
- 安排日程提醒
📊 数据分析助手
- 接收分析需求
- 自动获取数据
- 生成分析报告
🤖 代码审查助手
- 接收代码
- 检查错误
- 提供改进建议
你还有什么想了解的吗?
👤 你:quit
再见!
五、Agent 对话系统
5.1 交互式对话系统
Python 代码
def run_interactive_chat(agent):
"""运行交互式对话"""
print("\n" + "="*60)
print("🎯 AI Agent 交互式对话系统")
print("="*60)
print("命令:")
print(" - quit: 退出程序")
print(" - reset: 重置对话")
print(" - history: 查看历史")
print(" - save: 保存对话")
print(" - help: 显示帮助")
print("="*60 + "\n")
while True:
try:
user_input = input("👤 你:").strip()
if not user_input:
continue
if user_input.lower() == "quit":
print("\n感谢使用,再见!👋")
break
elif user_input.lower() == "reset":
agent.reset()
elif user_input.lower() == "history":
agent.show_history()
elif user_input.lower() == "save":
agent.save_conversation()
elif user_input.lower() == "help":
print("\n帮助信息...")
else:
response = agent.think(user_input)
print(f"\n🤖 {agent.name}:{response}\n")
except KeyboardInterrupt:
print("\n\n程序被中断,再见!")
break
except Exception as e:
print(f"\n❌ 发生错误:{str(e)}\n")
<h1 style="font-size:24px;color:#1a1a2e;text-align:center;margin:25px 0;padding:15px;background:linear-gradient(135deg,#f8fafc,#e2e8f0);border-radius:10px;">运行</h1>
if __name__ == "__main__":
# 配置
api_key = "sk-xxxxxx" # 替换为你的 API Key
# 创建 Agent
agent = Agent(api_key, name="智能助手")
# 设置系统提示词
agent.set_system_prompt("""你是一个有帮助的 AI 助手。
请用友好、专业的态度回答用户的问题。""")
# 运行交互式对话
run_interactive_chat(agent)
六、常见问题与调试
6.1 API 调用失败
Python 代码
def safe_call(agent, user_input):
"""安全的 API 调用"""
try:
response = agent.think(user_input)
# 检查是否包含错误
if response.startswith("❌"):
print("请检查:")
print("1. API Key 是否正确")
print("2. 账户余额是否充足")
print("3. 网络连接是否正常")
return response
except Exception as e:
print(f"发生错误:{str(e)}")
return None
6.2 Token 数量限制
Python 代码
def count_tokens(messages):
"""估算 token 数量(简化版)"""
total = 0
for msg in messages:
# 粗略估算:中文每个字约 2 个 token
total += len(msg["content"]) // 2
return total
def trim_history(messages, max_tokens=3000):
"""修剪过长的历史"""
# 简单策略:保留最近的对话
if count_tokens(messages) > max_tokens:
# 保留 system 消息和最近的对话
return messages[:1] + messages[-10:]
return messages
七、本章小结
今天我们创建了:
| 版本 | 功能 |
|---|
| ✅ SimpleAgent | 最简单的 Agent,30 行代码 |
| ✅ RoleAgent | 带角色设定的 Agent |
| ✅ Agent | 完整版 Agent,支持重置、保存、历史 |
核心代码结构:
Python 代码
class Agent:
def __init__(api_key, name, model)
def set_system_prompt(prompt)
def think(user_input) -> response
def _call_api() -> result
def reset()
def show_history()
def save_conversation()
下期预告
第6篇:提示词工程——与 AI 有效沟通的艺术
下一期我们将学习:
- 如何写出好的提示词
- Few-shot 提示技巧
- 角色扮演提示法
- 实战案例
👨💻 作者:鹏鹏 | 专注于 AI + 编程教育
📱 关注公众号「跟着鹏鹏学技术」,
💬 动手练习:运行上面的代码,创建你的第一个 AI Agent!
往期精选
- 📖 [第1-4篇回顾:Python基础与API调用]()
- 🔧 [10个实用的Python代码片段]()
- 🤖 [AI Agent vs 传统AI的区别]()
👨💻 作者:鹏鹏
📱 关注公众号「跟着鹏鹏学技术」
🔔 点赞 + 在看,让更多人看到!