AI Agent 开发入门:构建能自主完成任务的智能助手
AI Agent(智能代理)是能够自主感知环境、制定计划并使用工具完成任务的 AI 系统。
什么是 AI Agent
与传统 AI 对话不同,Agent 可以:
- 分解任务 — 将复杂任务拆解为多个步骤
- 使用工具 — 调用 API、查询数据库、发送邮件
- 记忆上下文 — 记住之前的结果并用于后续步骤
- 自我纠错 — 如果某个步骤失败,尝试替代方案
Agent vs 传统 Chatbot
| 特性 | 传统 Chatbot | AI Agent |
|---|---|---|
| 交互方式 | 一问一答 | 自主执行任务 |
| 工具使用 | 不能 | 可以调用 API/工具 |
| 任务规划 | 不能 | 能分解和规划 |
| 记忆 | 有限(对话窗口) | 长期记忆 |
| 自主性 | 被动响应 | 主动执行 |
使用 OpenAI Function Calling 构建 Agent
import json
from openai import OpenAI
client = OpenAI()
# 定义 Agent 可使用的工具
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "获取指定城市的天气信息",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "城市名称"}
},
"required": ["city"]
}
}
},
{
"type": "function",
"function": {
"name": "send_email",
"description": "发送邮件",
"parameters": {
"type": "object",
"properties": {
"to": {"type": "string"},
"subject": {"type": "string"},
"body": {"type": "string"}
},
"required": ["to", "subject", "body"]
}
}
}
]
# 实际函数实现
def get_weather(city):
return f"{city}当前温度 25°C,晴"
def send_email(to, subject, body):
print(f"发送邮件到 {to}: {subject}")
return "邮件已发送"
# Agent 循环
def run_agent(user_message):
messages = [
{"role": "system", "content": "你是一个智能助手,可以使用工具帮助用户完成任务。"},
{"role": "user", "content": user_message}
]
while True:
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools
)
choice = response.choices[0]
# 如果 AI 没有调用工具,直接返回
if not choice.finish_reason == "tool_calls":
return choice.message.content
# 执行工具调用
messages.append(choice.message)
for tool_call in choice.message.tool_calls:
func_name = tool_call.function.name
args = json.loads(tool_call.function.arguments)
if func_name == "get_weather":
result = get_weather(**args)
elif func_name == "send_email":
result = send_email(**args)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result
})
# 使用 Agent
result = run_agent("帮我查一下北京的天气,然后把结果用邮件发送到 [email protected]")
print(result)
Agent 框架对比
| 框架 | 语言 | 特点 | 适合场景 |
|---|---|---|---|
| LangChain | Python/JS | 最流行,生态丰富 | 复杂 Agent |
| CrewAI | Python | 多 Agent 协作 | 团队任务 |
| AutoGen | Python | Microsoft 出品 | 多 Agent 对话 |
| OpenAI Assistants | API | 托管服务 | 快速原型 |
16IDC 观察
AI Agent 是 AI 应用的下一个演进方向。2026 年我们已经看到 Agent 在客服、数据分析和自动化运营中的实际应用。对于网站开发者来说,Function Calling 是最容易上手的 Agent 构建方式——不需要额外框架,直接通过 API 即可实现。