使用 Python 搭建智能体(Agent)完整指南
一、什么是智能体Agent在 AI 领域“智能体Agent”并不是一个抽象的概念而是一个具备目标导向、自主决策能力并能与环境交互的系统。从工程角度可以把智能体拆解为 4 个核心模块感知Perception接收输入用户问题、环境数据、API 返回思考Reasoning使用大模型进行推理、规划行动Action调用工具函数、API、数据库记忆Memory短期上下文 长期知识 简单公式Agent LLM大脑 Tools工具 Memory记忆 Planning规划二、为什么用 Python 搭建 AgentPython 是目前构建 AI Agent 的首选语言原因非常现实1. 生态完整AIOpenAI / Transformers / PyTorchAgent 框架LangChain / LlamaIndex / AutoGen数据处理Pandas / NumPy2. 调用模型方便from openai import OpenAI client OpenAI()3. 易于扩展WebFastAPI数据库SQLite / Redis / Vector DB三、Agent 的基本架构设计一个标准 Agent 系统结构如下用户输入 ↓ Prompt 构建 ↓ LLM 推理思考 ↓ 是否调用工具 ↓ ↓ 否 是 ↓ ↓ 直接回答 执行工具 ↓ 返回结果 ↓ 再次推理 ↓ 输出四、从零开始手写一个最小 Agent1. 安装依赖pip install openai2. 基础 LLM 调用from openai import OpenAI client OpenAI(api_keyyour_api_key) def ask_llm(prompt): response client.responses.create( modelgpt-5.3, inputprompt ) return response.output[0].content[0].text3. 加入“工具能力”定义一个工具例如计算器def calculator(expression): try: return eval(expression) except: return 计算错误4. 让模型决定是否调用工具核心def agent(user_input): prompt f 你是一个智能助手。 如果问题需要计算请输出 CALL_TOOL: calculator: 表达式 否则直接回答。 问题{user_input} result ask_llm(prompt) if CALL_TOOL in result: tool_input result.split(:)[-1].strip() tool_result calculator(tool_input) final_prompt f 工具返回结果{tool_result} 请给出最终答案 return ask_llm(final_prompt) return result5. 测试print(agent(123 * 456 等于多少)) 这就是一个最基础的 Agent。五、进阶使用函数调用Function Calling现代 Agent 不再用字符串解析而是用结构化调用。示例tools [ { type: function, function: { name: calculator, description: 计算数学表达式, parameters: { type: object, properties: { expression: { type: string } }, required: [expression] } } } ]调用response client.responses.create( modelgpt-5.3, toolstools, input帮我算 12 * 99 )六、加入记忆系统Memory1. 短期记忆上下文history [] def chat(user_input): history.append({role: user, content: user_input}) response client.responses.create( modelgpt-5.3, inputhistory ) answer response.output[0].content[0].text history.append({role: assistant, content: answer}) return answer2. 长期记忆向量数据库可以使用FAISSChromaMilvus示例简化版memory_db [] def save_memory(text): memory_db.append(text) def retrieve_memory(query): return memory_db[:3]七、加入规划能力Planning智能体的关键升级从“回答问题” → “解决任务”示例任务拆解def planner(task): prompt f 请把任务拆分成步骤 {task} return ask_llm(prompt)示例输出1. 搜索信息 2. 整理数据 3. 输出总结八、多工具 Agent真实生产形态tools { calculator: calculator, search: lambda x: f搜索结果: {x} }调度逻辑def execute_tool(name, arg): return tools[name](arg)九、使用框架推荐1. LangChain最常用pip install langchain示例from langchain.agents import initialize_agent from langchain.tools import Tool tools [ Tool( nameCalculator, funccalculator, description计算数学问题 ) ] agent initialize_agent( tools, llm, agentzero-shot-react-description )2. AutoGen多智能体适合复杂任务from autogen import AssistantAgent 可以实现AI 自己写代码AI 多角色协作十、完整 Agent 架构工业级一个成熟系统通常包含1. 输入层API / Web / Chat2. Agent 核心LLMTool RouterPlanner3. 工具层搜索数据库文件系统4. 存储层向量数据库日志十一、优化方向关键1. Prompt EngineeringFew-shotChain-of-ThoughtReAct2. RAG检索增强问题 → 检索 → 拼接上下文 → LLM3. 缓存Context Caching减少 token 消耗。4. 多 Agent 协作角色划分PlannerExecutorReviewer十二、实际应用场景1. AI 客服自动回答 查询订单2. 数据分析助手自动写 SQL3. 自动化运维执行脚本4. AI 内容生产写文章、视频脚本十三、常见坑1. 幻觉问题 解决RAG2. 工具调用错误 解决函数调用 schema3. 成本过高 解决缓存限制上下文4. 延迟高 解决流式输出并行调用十四、总结用 Python 搭建智能体本质上是把 AI 从“聊天工具”升级为“执行系统”。核心路径基础调用 → 工具调用 → 记忆 → 规划 → 多 Agent如果你要一句话总结Agent 会思考 会用工具 会记住 会规划 的 AI 系统十五、下一步建议重点如果你要做更高级的系统可以继续深入RAG 架构设计Agent Workflow工作流编排多模态 Agent图像/视频AI 自动化AutoGPT / CrewAI