AI Agent开发实战:从LangChain单智能体到AutoGen多智能体系统构建
在AI技术浪潮席卷全球的今天AI Agent智能体作为连接大模型与现实世界的桥梁正成为开发者、创业者乃至企业数字化转型的核心焦点。你是否曾对网上零散的Agent教程感到困惑是否想系统掌握从零搭建一个能感知、决策、执行的智能体甚至构建协同工作的多智能体系统本文将为你提供一份从入门到实战的完整指南涵盖主流框架选择、核心概念拆解、单智能体开发、多智能体系统搭建以及面向就业的工程化实践。无论你是刚接触AI的开发者还是希望将Agent技术落地的工程师都能在这里找到清晰的路径和可复现的代码。1. AI Agent 核心概念与价值为什么它如此重要在深入代码之前我们必须先理解AI Agent究竟是什么以及它为何能成为当前AI应用开发的热点。1.1 什么是AI Agent简单来说AI Agent是一个能够感知环境、自主决策并执行行动以实现特定目标的智能程序。它超越了传统“问答式”的大模型具备了自主性、反应性、目标导向性和社会性在多智能体场景下等特征。一个典型的AI Agent工作流程可以概括为“感知-思考-行动”循环Perception-Thought-Action Loop感知通过API、传感器、用户输入或数据库获取环境信息。思考基于大模型如GPT、Claude、GLM等的核心能力对信息进行分析、规划、推理和决策。行动调用工具Tools来执行决策如运行代码、操作文件、调用第三方服务等。观察获取行动结果作为下一轮循环的输入。1.2 AI Agent vs. 传统大模型应用很多初学者容易混淆两者。传统的大模型应用如聊天机器人通常是被动响应的用户问模型答交互结束。而AI Agent是主动驱动的你给它一个目标例如“帮我分析本周销售数据并生成报告”它会自动分解任务、查找数据、运行分析、生成报告并可能将报告通过邮件发送给你。整个过程无需你逐步指导。1.3 主流应用场景理解场景能帮助我们更好地设计Agent个人效率助手自动处理邮件、安排日程、总结文档、编写代码。客户服务与销售7x24小时智能客服能查询订单、处理退换货、进行产品推荐。数据分析与报告连接数据库自动执行数据查询、清洗、分析和可视化。自动化运维与测试监控系统日志自动诊断问题、执行修复脚本或部署流程。多智能体模拟构建模拟市场、社交网络或游戏环境研究智能体间的协作与竞争。2. 开发环境与主流框架选型工欲善其事必先利其器。选择一款合适的开发框架能极大提升开发效率。以下是目前主流的AI Agent开发框架及其特点。2.1 环境准备我们将以Python作为主要开发语言这是目前AI Agent生态最丰富的语言。基础环境要求操作系统Windows 10/11, macOS, 或 Linux (Ubuntu 20.04 推荐)。Python版本3.8 或 3.93.10 也兼容但部分库可能有适配问题建议使用3.9。包管理工具pip(Python自带) 或conda(适合科学计算环境)。代码编辑器VS Code (推荐有丰富的Python和AI插件) 或 PyCharm。API密钥你需要一个大型语言模型LLM的API访问权限例如OpenAI GPT (推荐用于学习和原型开发)Anthropic Claude智谱AI GLM百度文心一言阿里通义千问初始化项目# 创建一个新的项目目录 mkdir ai_agent_tutorial cd ai_agent_tutorial # 创建虚拟环境强烈推荐避免包冲突 python -m venv venv # 激活虚拟环境 # Windows: venv\Scripts\activate # macOS/Linux: source venv/bin/activate # 升级pip pip install --upgrade pip2.2 主流框架对比与选择框架名称主要特点适合场景上手难度LangChain生态最丰富模块化设计工具链完善社区活跃。快速原型开发复杂工作流编排需要大量现有工具集成。中等LlamaIndex专注于数据索引与检索为Agent提供强大的“长期记忆”和知识库。构建基于私有文档、数据库的问答和决策Agent。中等AutoGen(微软)专注于多智能体对话与协作支持定义角色和对话模式。构建多智能体对话系统、模拟人类协作场景。中等偏高Semantic Kernel(微软)面向企业级应用与.NET生态结合紧密规划能力强。.NET技术栈的企业级AI应用集成。中等Haystack更偏向于构建端到端的问答系统但也可用于Agent开发。构建文档检索、问答管道清晰的系统。中等选择建议初学者/快速入门从LangChain开始它的教程和示例最多能让你最快看到效果。专注数据与记忆如果你的Agent核心是处理大量私有数据选择LlamaIndex。研究多智能体如果想搭建多个Agent对话协作的系统AutoGen是最佳选择。企业级/.NET环境考虑Semantic Kernel。本文将以LangChain和AutoGen为例分别讲解单智能体和多智能体的开发因为它们覆盖了最广泛的需求且社区支持最好。3. 使用 LangChain 构建你的第一个单智能体让我们从一个最简单的例子开始创建一个能使用搜索引擎和计算器工具的Agent。3.1 安装依赖# 安装 LangChain 及其 OpenAI 集成包 pip install langchain langchain-openai # 安装用于创建Agent的工具链和社区工具 pip install langchain-community # 安装一个模拟搜索引擎的工具实际开发中可使用SerpAPI等 pip install duckduckgo-search # 安装用于数学计算的工具 pip install numexpr3.2 核心代码实现创建一个名为simple_agent.py的文件。# simple_agent.py import os from langchain.agents import AgentExecutor, create_react_agent from langchain.tools import Tool from langchain_community.tools import DuckDuckGoSearchRun from langchain_community.utilities import WikipediaAPIWrapper from langchain.prompts import PromptTemplate from langchain_openai import ChatOpenAI # 1. 设置你的OpenAI API密钥请替换成你自己的 os.environ[OPENAI_API_KEY] sk-your-openai-api-key-here # 2. 初始化大语言模型 # 使用 GPT-3.5-turbo成本较低适合实验 llm ChatOpenAI(modelgpt-3.5-turbo, temperature0) # 3. 定义工具Tools # 工具是Agent执行动作的“手”和“脚” # 工具1网络搜索 search_tool DuckDuckGoSearchRun(nameSearch, descriptionUseful for searching the internet for current information.) # 工具2维基百科查询需要安装 wikipedia-api # wikipedia WikipediaAPIWrapper() # wiki_tool Tool( # nameWikipedia, # funcwikipedia.run, # descriptionUseful for getting detailed factual information from Wikipedia. # ) # 工具3自定义计算器 from langchain.chains import LLMMathChain math_chain LLMMathChain.from_llm(llmllm, verboseTrue) math_tool Tool( nameCalculator, funcmath_chain.run, descriptionUseful for performing mathematical calculations. Input should be a mathematical expression. ) # 将所有工具放入列表 tools [search_tool, math_tool] # 4. 创建Agent提示词模板 # ReAct (Reason Act) 是一种经典的Agent推理框架 prompt_template Answer the following questions as best you can. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original question Begin! Question: {input} Thought:{agent_scratchpad} prompt PromptTemplate.from_template(prompt_template) # 5. 创建Agent并执行 agent create_react_agent(llm, tools, prompt) agent_executor AgentExecutor(agentagent, toolstools, verboseTrue, handle_parsing_errorsTrue) # 6. 运行Agent if __name__ __main__: # 示例问题1需要计算 question1 What is 15% of 280? # 示例问题2需要搜索 question2 Who is the current CEO of OpenAI, and what is the square root of 144? print(fQuestion: {question1}) result1 agent_executor.invoke({input: question1}) print(f\nFinal Answer: {result1[output]}\n{*50}\n) print(fQuestion: {question2}) result2 agent_executor.invoke({input: question2}) print(f\nFinal Answer: {result2[output]})3.3 运行与解析在终端运行python simple_agent.py预期输出节选Question: What is 15% of 280? Thought: I need to calculate 15% of 280. I should use the Calculator tool. Action: Calculator Action Input: 0.15 * 280 Observation: Answer: 42.0 Thought: I now know the final answer. Final Answer: 15% of 280 is 42. Question: Who is the current CEO of OpenAI, and what is the square root of 144? Thought: This question has two parts. First, I need to find the current CEO of OpenAI, which requires current information. Second, I need to calculate the square root of 144. Action: Search Action Input: current CEO of OpenAI Observation: Sam Altman is the CEO of OpenAI... Thought: Now I need to calculate the square root of 144. Action: Calculator Action Input: sqrt(144) Observation: Answer: 12.0 Thought: I now have both answers. Final Answer: The current CEO of OpenAI is Sam Altman, and the square root of 144 is 12.代码解析工具定义我们定义了Search和Calculator两个工具。Agent在思考时会参考工具的描述(description)来决定使用哪个。ReAct框架提示词模板强制Agent按照“思考-行动-观察”的循环工作这使其推理过程透明化。AgentExecutor这是运行Agent的“引擎”负责管理工具调用、解析LLM输出、处理错误。verboseTrue这个参数让整个过程在控制台打印出来非常适合调试和学习。4. 进阶为Agent赋予“记忆”与“知识”一个健壮的Agent需要记住对话历史短期记忆并能访问专属知识库长期记忆。4.1 添加对话记忆修改上面的代码让Agent能记住上下文。创建agent_with_memory.py。# agent_with_memory.py from langchain.memory import ConversationBufferMemory from langchain.agents import AgentExecutor, create_react_agent from langchain.tools import Tool from langchain_community.tools import DuckDuckGoSearchRun from langchain.prompts import PromptTemplate, MessagesPlaceholder from langchain_openai import ChatOpenAI import os os.environ[OPENAI_API_KEY] sk-your-openai-api-key-here llm ChatOpenAI(modelgpt-3.5-turbo, temperature0) search_tool DuckDuckGoSearchRun(nameSearch) tools [search_tool] # 关键创建记忆对象 memory ConversationBufferMemory(memory_keychat_history, return_messagesTrue) # 修改提示词模板加入记忆部分 prompt_template You are a helpful assistant. You have access to the following tools: {tools} Use the following format: Question: the input question you must answer Thought: you should always think about what to do Action: the action to take, should be one of [{tool_names}] Action Input: the input to the action Observation: the result of the action ... (this Thought/Action/Action Input/Observation can repeat N times) Thought: I now know the final answer Final Answer: the final answer to the original question Previous conversation history: {chat_history} Begin! Question: {input} Thought:{agent_scratchpad} prompt PromptTemplate.from_template(prompt_template) agent create_react_agent(llm, tools, prompt) # 创建执行器时传入memory agent_executor AgentExecutor( agentagent, toolstools, memorymemory, verboseTrue, handle_parsing_errorsTrue ) if __name__ __main__: questions [ What is LangChain?, What are its main features? # 这个问题会基于上一个问题的记忆来回答 ] for q in questions: print(fUser: {q}) result agent_executor.invoke({input: q}) print(fAgent: {result[output]}\n)4.2 连接私有知识库使用LlamaIndex当Agent需要回答关于公司文档、产品手册等非公开信息时就需要知识库。首先安装LlamaIndexpip install llama-index假设我们有一个company_docs.txt文件内容是关于某产品的介绍。我们让Agent能基于此文件回答问题。# agent_with_knowledge.py from llama_index.core import VectorStoreIndex, SimpleDirectoryReader from llama_index.core.tools import QueryEngineTool from langchain.agents import AgentExecutor, create_react_agent from langchain_openai import ChatOpenAI import os os.environ[OPENAI_API_KEY] sk-your-openai-api-key-here # 1. 加载文档并创建索引知识库 documents SimpleDirectoryReader(input_dir./data).load_data() # 假设文档在./data目录下 index VectorStoreIndex.from_documents(documents) query_engine index.as_query_engine() # 2. 将查询引擎包装成LangChain可用的工具 knowledge_tool QueryEngineTool.from_defaults( query_enginequery_engine, nameCompany_Knowledge_Base, descriptionUseful for answering questions about the companys products, policies, and internal documents. Input should be a specific question. ) # 3. 创建Agent可以结合其他工具如搜索 from langchain_community.tools import DuckDuckGoSearchRun search_tool DuckDuckGoSearchRun(nameWeb_Search) llm ChatOpenAI(modelgpt-4, temperature0) # 知识库问答建议使用更强的模型 tools [knowledge_tool, search_tool] # ... (创建Agent和Executor的代码与之前类似此处省略) # Agent会优先使用知识库工具如果知识库没有答案再使用网络搜索。5. 使用AutoGen搭建多智能体协作系统多智能体系统由多个具有不同角色和能力的Agent组成它们通过对话协作解决复杂问题。微软的AutoGen是这方面的佼佼者。5.1 环境安装与基础概念pip install pyautogenAutoGen的核心概念AssistantAgent负责处理任务、推理、调用工具或代码执行。UserProxyAgent代表用户可以执行代码、接收输入、触发Assistant工作。GroupChatGroupChatManager管理多个Agent的群聊。5.2 双智能体代码示例程序员与评审员创建一个multi_agent_chat.py文件。# multi_agent_chat.py import autogen import os os.environ[OPENAI_API_KEY] sk-your-openai-api-key-here # 配置LLM config_list [ { model: gpt-4, api_key: os.environ[OPENAI_API_KEY], } ] # 创建用户代理可以执行代码 user_proxy autogen.UserProxyAgent( nameUser_Proxy, system_messageA human admin who can execute code and provide feedback., code_execution_config{ work_dir: coding, # 代码将在这个目录下运行 use_docker: False, # 设置为True如果需要在Docker中运行代码 }, human_input_modeNEVER, # 设置为“ALWAYS”则在每步都需要人工输入“NEVER”则自动进行 ) # 创建程序员智能体 coder autogen.AssistantAgent( nameCoder, system_messageYou are a senior Python programmer. You write correct, efficient, and well-documented code. Reply TERMINATE when the task is done., llm_config{config_list: config_list}, ) # 创建评审员智能体 reviewer autogen.AssistantAgent( nameReviewer, system_messageYou are a code reviewer. You check the code written by the Coder for bugs, style, and efficiency. Provide constructive feedback., llm_config{config_list: config_list}, ) # 定义一个任务编写一个函数计算斐波那契数列并测试它。 task Write a Python function to calculate the nth Fibonacci number. Then, write a test to verify it works for n0, 5, and 10. Save the code to a file named fibonacci.py. # 初始化聊天用户代理先向程序员发起任务 user_proxy.initiate_chat( coder, messagetask, ) # 现在让评审员审查刚才生成的代码 # 我们需要从聊天历史中获取代码。这里简化处理直接让用户代理发起新对话。 print(\n *60) print(Starting Code Review Phase) print(*60 \n) # 假设我们从coding/fibonacci.py读取了代码实际中可以从coder的回复中提取 # 这里我们模拟一个评审请求 review_task f Please review the code in the file coding/fibonacci.py generated by the Coder. Check for: 1. Correctness of the Fibonacci algorithm. 2. Edge cases (e.g., n0, negative input). 3. Code style and documentation. 4. Efficiency (time/space complexity). Provide your feedback. user_proxy.initiate_chat( reviewer, messagereview_task, )5.3 运行与观察运行此脚本你将在控制台看到三个Agent之间自动进行的对话User_Proxy向Coder发布任务。Coder思考并生成代码User_Proxy自动执行代码如果配置了的话并返回结果。然后User_Proxy将代码文件交给Reviewer进行审查。Reviewer提出修改意见这个对话可以持续进行直到代码被认可。这模拟了一个简单的软件开发生命周期。你可以通过修改system_message来定义更多角色如产品经理、测试工程师等构建更复杂的协作流程。6. 工程化与生产环境最佳实践将原型Agent转化为稳定、可靠的生产系统需要关注以下方面6.1 配置管理与安全绝不硬编码密钥使用环境变量或专业的密钥管理服务如AWS Secrets Manager, HashiCorp Vault。# .env 文件 # OPENAI_API_KEYsk-... # SERPAPI_API_KEY... # Python中读取 from dotenv import load_dotenv load_dotenv() api_key os.getenv(OPENAI_API_KEY)配置分离将模型配置、工具列表、提示词模板等放入配置文件如config.yaml或config.py便于不同环境开发/测试/生产切换。6.2 性能与成本优化模型选择根据任务复杂度选择模型。简单分类用gpt-3.5-turbo复杂推理用gpt-4。考虑使用开源模型通过Ollama、vLLM本地部署以控制成本。缓存对频繁且结果不变的LLM调用或工具调用实施缓存LangChain内置了InMemoryCache、RedisCache等。限制与超时为Agent执行设置最大步骤数max_iterations和超时时间防止陷入死循环或产生过高费用。agent_executor AgentExecutor( agentagent, toolstools, max_iterations10, # 限制循环次数 early_stopping_methodgenerate, handle_parsing_errorsTrue )6.3 可观测性与监控日志记录详细记录每个Agent的输入、思考过程、工具调用、输出和最终结果。使用结构化日志如JSON格式便于后续分析。链路追踪在分布式系统中使用OpenTelemetry等工具追踪一个用户请求在所有Agent和微服务间的流转。关键指标监控Token消耗量、请求延迟、工具调用成功率、任务完成率等。6.4 错误处理与鲁棒性工具调用容错工具可能失败如网络超时、API限流。实现重试机制和优雅降级。LLM输出解析LLM的输出可能不符合预期格式。使用handle_parsing_errorsTrue并准备后备解析逻辑。输入验证与清理对用户输入进行清洗防止Prompt注入攻击。6.5 部署模式API服务使用FastAPI、Flask将Agent封装成RESTful API或WebSocket服务。异步与流式响应对于长任务使用异步处理并提供进度更新或流式输出Server-Sent Events。容器化使用Docker将Agent及其依赖打包确保环境一致性。编排在Kubernetes上部署和管理多个Agent实例实现扩缩容。7. 常见问题与排查指南在开发过程中你一定会遇到各种问题。以下是典型问题及解决思路。问题现象可能原因排查步骤与解决方案Agent陷入无限循环提示词设计有误导致Agent反复调用同一工具或无意义思考。1. 检查max_iterations参数是否设置。2. 分析verbose日志看思考步骤是否重复。3. 优化工具描述(description)使其更精确。4. 在提示词中明确终止条件。工具调用失败工具依赖的API不可用、网络错误、参数格式错误。1. 单独测试工具函数是否正常工作。2. 检查API密钥和网络连接。3. 查看工具返回的错误信息。4. 在工具函数内部添加更详细的异常捕获和日志。LLM不按格式输出模型未遵循提示词中规定的输出格式如ReAct格式。1. 降低temperature参数如设为0减少随机性。2. 强化提示词中的格式指令使用更明确的示例Few-shot。3. 使用LangChain的OutputParser来强制解析和修正格式。处理速度慢网络延迟、LLM响应慢、工具执行耗时、未使用缓存。1. 为网络请求设置合理的超时。2. 考虑使用更快的模型或LLM API端点。3. 对耗时工具进行异步调用。4. 引入缓存层。知识库检索不准文档切分不合理、嵌入模型不匹配、检索策略不佳。1. 调整文档切分chunk的大小和重叠度。2. 尝试不同的嵌入模型如text-embedding-3-small。3. 优化检索策略如结合关键词检索BM25和向量检索Hybrid Search。4. 在检索后使用LLM进行重排序Re-ranking。多智能体通信混乱Agent角色定义不清对话无明确协议。1. 为每个Agent编写清晰、无歧义的system_message。2. 在GroupChat中设置清晰的发言顺序和规则。3. 使用GroupChatManager来协调对话。4. 让一个Agent担任“主持人”角色总结并推进讨论。8. 从学习到就业下一步行动路线掌握以上内容你已经具备了AI Agent开发的核心能力。要迈向就业或更高级的项目建议按以下路径深化深入一个框架在LangChain和AutoGen中选一个通读其官方文档理解其高级特性如Custom Agents, Callbacks, Streaming。精通工具开发学习为Agent开发自定义工具这是解决实际业务问题的关键。例如开发连接内部CRM、ERP系统的工具。构建一个端到端项目选择一个真实场景如智能客服、自动化报表生成、游戏NPC从需求分析、技术选型、开发、测试到部署完整走一遍。学习模型微调虽然大多数Agent基于通用大模型但对特定领域任务微调一个专属的小模型如利用LoRA技术微调开源模型能极大提升效果和降低成本。关注多模态与具身智能未来的Agent不仅能处理文本还能看CV、听ASR、操控物理世界机器人。学习LangChain的多模态工具或ROS机器人操作系统。参与开源社区在GitHub上关注LangChain、AutoGen等项目阅读源码提交Issue甚至PR这是提升技术视野和影响力的最佳方式。AI Agent的开发是一场结合了软件工程、提示词工程和大模型能力的综合实践。它没有银弹最好的学习方式就是动手去构建在解决具体问题的过程中不断踩坑和总结。本文提供的代码和框架是你的起点真正的精通源于持续的项目实践和对技术本质的思考。