1. 项目概述:用Python构建你的第一个AI Agent
在咖啡馆里看到朋友用手机语音助手点单时,你有没有想过自己也能造一个这样的智能小助手?今天我们就用Python和OpenAI API,从零开始构建一个能理解自然语言并执行简单任务的Agent系统。这个项目特别适合刚学完Python基础语法,想尝试AI应用开发的初学者。
我去年带实习生时就用这个案例作为入门项目,有位文科背景的同学仅用周末两天就做出了能查询天气和设置提醒的对话助手。你需要的只是一台能上网的电脑,以及最基础的Python知识——连"类"和"面向对象"都不必精通,我们会用最直白的方式实现功能。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 环境准备与API配置
2.1 Python环境搭建
推荐使用Python 3.8+版本,这个区间既有良好的库兼容性又支持最新特性。安装时务必勾选"Add Python to PATH"选项,这样终端才能识别python命令。验证安装成功的正确姿势是:
bash复制python --version
pip --version
如果遇到"python不是内部命令"的错误,需要手动配置环境变量。具体路径取决于你的安装位置,通常在:
code复制C:\Users\你的用户名\AppData\Local\Programs\Python\Python38
注意:网上有些教程会推荐Anaconda,但对这个项目来说反而会增加复杂度。官方Python+VS Code的组合足够轻量高效。
2.2 获取OpenAI API密钥
- 登录OpenAI官网并进入API页面
- 点击"Create new secret key"生成密钥
- 立即复制保存(页面刷新后会不可见)
测试密钥是否有效的最快方法是用curl命令:
bash复制curl https://api.openai.com/v1/models \
-H "Authorization: Bearer your-api-key"
应该会返回包含"gpt-3.5-turbo"等模型的JSON数据。如果遇到402错误,说明账号未设置付款方式,需要在Billing页面绑定信用卡(新用户有5美元免费额度)。
3. Agent核心架构设计
3.1 最简对话循环实现
我们先构建一个能持续对话的基础框架:
python复制import openai
openai.api_key = "your-api-key"
def chat_loop():
history = []
while True:
user_input = input("You: ")
if user_input.lower() in ['exit', 'quit']:
break
history.append({"role": "user", "content": user_input})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=history,
temperature=0.7
)
ai_reply = response.choices[0].message.content
history.append({"role": "assistant", "content": ai_reply})
print(f"AI: {ai_reply}")
chat_loop()
这段代码实现了:
- 持续读取用户输入
- 维护对话历史上下文
- 调用GPT-3.5模型生成回复
- 温度参数控制回答随机性(0-1之间)
3.2 添加工具调用能力
真正的Agent需要能执行具体操作。我们给助手添加报时功能:
python复制from datetime import datetime
def get_current_time():
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
def execute_function(function_name):
if function_name == "get_time":
return get_current_time()
return "Unknown function"
def enhanced_agent():
functions = [
{
"name": "get_time",
"description": "Get the current time",
"parameters": {
"type": "object",
"properties": {}
}
}
]
history = [{"role": "system", "content": "You're a helpful assistant."}]
while True:
user_input = input("You: ")
if not user_input:
continue
history.append({"role": "user", "content": user_input})
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=history,
functions=functions,
function_call="auto"
)
reply = response.choices[0].message
if reply.get("function_call"):
function_name = reply.function_call.name
result = execute_function(function_name)
history.append({
"role": "function",
"name": function_name,
"content": result
})
# 自动发送执行结果给模型
second_response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=history
)
ai_reply = second_response.choices[0].message.content
else:
ai_reply = reply.content
history.append({"role": "assistant", "content": ai_reply})
print(f"AI: {ai_reply}")
现在当你问"现在几点了",Agent会:
- 识别需要调用get_time函数
- 执行本地函数获取时间
- 将结果返回给GPT生成自然语言回复
4. 工程化改进与性能优化
4.1 添加速率限制与错误处理
免费API账号有每分钟3次的调用限制,需要添加防护:
python复制import time
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))
def safe_api_call(messages, functions=None):
try:
params = {
"model": "gpt-3.5-turbo",
"messages": messages,
"temperature": 0.7
}
if functions:
params.update({
"functions": functions,
"function_call": "auto"
})
return openai.ChatCompletion.create(**params)
except openai.error.RateLimitError:
print("达到速率限制,等待10秒...")
time.sleep(10)
raise
except openai.error.APIError as e:
print(f"API错误: {e}")
raise
4.2 上下文窗口管理
GPT-3.5有4096个token的上下文限制,长对话需要压缩历史:
python复制def summarize_history(history):
# 只保留最近3轮对话
if len(history) > 6: # 每轮包含user和assistant消息
summary = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "请用100字以内总结对话要点"},
*history[:-6]
]
).choices[0].message.content
return [
{"role": "system", "content": f"先前对话总结: {summary}"},
*history[-6:]
]
return history
5. 实际应用场景扩展
5.1 集成外部API
让Agent能查询天气:
python复制import requests
def get_weather(city):
api_key = "your-weather-api-key"
url = f"http://api.weatherapi.com/v1/current.json?key={api_key}&q={city}"
response = requests.get(url)
data = response.json()
return f"{city}当前天气: {data['current']['condition']['text']}, 温度{data['current']['temp_c']}℃"
# 在functions列表中添加:
{
"name": "get_weather",
"description": "Get current weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "City name"
}
},
"required": ["city"]
}
}
5.2 本地知识库增强
用FAISS实现本地文档检索:
python复制from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import FAISS
from langchain.text_splitter import CharacterTextSplitter
def init_knowledge_base(file_path):
with open(file_path) as f:
text = f.read()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
docs = text_splitter.create_documents([text])
db = FAISS.from_documents(docs, OpenAIEmbeddings())
return db
def query_knowledge(question, db):
docs = db.similarity_search(question)
return "\n".join([d.page_content for d in docs])
6. 部署与生产环境建议
6.1 使用异步提升性能
改用async/await处理并发请求:
python复制import aiohttp
async def async_chat(message_history):
async with aiohttp.ClientSession() as session:
payload = {
"model": "gpt-3.5-turbo",
"messages": message_history
}
headers = {
"Authorization": f"Bearer {openai.api_key}",
"Content-Type": "application/json"
}
async with session.post(
"https://api.openai.com/v1/chat/completions",
json=payload,
headers=headers
) as resp:
return await resp.json()
6.2 敏感信息处理
永远不要将API密钥硬编码在代码中!推荐做法:
- 使用环境变量:
bash复制export OPENAI_API_KEY='your-key'
- 在Python中读取:
python复制import os
openai.api_key = os.getenv("OPENAI_API_KEY")
或者使用dotenv库从.env文件加载:
python复制from dotenv import load_dotenv
load_dotenv()
7. 常见问题与解决方案
7.1 模块导入错误
如果遇到"No module named 'openai'",说明缺少依赖库:
bash复制pip install openai langchain faiss-cpu
7.2 中文回复不流畅
在系统消息中明确指定语言:
python复制history = [{
"role": "system",
"content": "你是一个中文助手,请用简体中文回答"
}]
7.3 函数调用不触发
检查三点:
- functions参数是否正确传入
- 函数描述是否清晰(GPT依赖description判断何时调用)
- 模型版本是否支持函数调用(gpt-3.5-turbo-0613及以上)
8. 项目进阶方向
当你完成基础版本后,可以尝试:
- 添加语音输入输出(使用SpeechRecognition和pyttsx3库)
- 实现多Agent协作系统
- 接入微信/Telegram等IM平台
- 用LlamaIndex构建个性化知识图谱
我在首次实现这个项目时,最大的收获是理解了AI应用的"思考-行动-观察"循环模式。这种架构不仅能用于对话系统,稍加改造就能变成自动化办公助手、智能客服等实用工具。建议先从一个小功能点开始,逐步迭代完善,你会惊讶于短短几百行代码能实现的效果。
