当然可以以下是完整、可直接发布到 CSDN的技术博客内容已根据你的原始框架进行润色与优化确保逻辑清晰、语言专业、代码完整且注释详尽适合读者快速上手并实践。 AI Agent 实战微软 AutoGen 多智能体框架技术使用方法详解作者[你的名字]发布于2025年4月5日平台CSDN标签#AI #Agent #AutoGen #LLM #多智能体系统 #Python #人工智能✅ 前言随着大语言模型LLM的爆发式发展AI Agent智能体已从概念走向落地。从单个智能体自主完成任务到多个智能体协同解决复杂问题各类框架如雨后春笋般涌现——如 AutoGPT、MetaGPT、CrewAI 等。其中微软开源的 AutoGen 框架凭借其灵活的多智能体对话机制、强大的代码执行能力以及对“人机协作”的深度支持成为构建下一代 AI 应用的首选工具之一。本文将带你从零开始通过真实可运行的完整代码示例系统掌握 AutoGen 的核心用法 安装配置 单/多智能体对话 工具调用与函数执行 人机回环Human-in-the-loop 多 Agent 协作实战 —— 编程助手场景⚠️ 本文所有代码均可直接复制运行无需额外依赖仅需安装pyautogen即可。 目录AI Agent 与 AutoGen 简介环境准备与安装第一个 AutoGen 对话两个 Agent 聊天多 Agent 协作编程助手示例工具调用与函数执行人机回环Human-in-the-loop总结与展望1. AI Agent 与 AutoGen 简介 什么是 AI AgentAI Agent智能体是具备以下能力的智能实体感知环境接收用户输入或外部数据自主决策基于目标规划行动路径执行动作调用工具、生成代码、发送消息等在 LLM 驱动下现代 Agent 可实现任务分解记忆管理工具调用如计算器、搜索引擎、代码解释器多轮对话协作 什么是 AutoGenAutoGen 是由微软研究院MSR开发的开源框架专为构建多智能体对话系统而设计。其核心优势包括特性说明✅ 多智能体协作支持多个角色并行或串行对话✅ 自动化流程可自动触发代码执行、函数调用✅ 人机协同支持人类介入提升可控性✅ 灵活扩展可自定义角色、工具、消息流✅ 本地代码执行内置代码解释器安全沙箱运行相比早期的 AutoGPT单智能体循环AutoGen 更强调可控性、可调试性、可组合性非常适合企业级应用开发。2. 环境准备与安装 前提要求Python ≥ 3.8推荐使用虚拟环境如venv/conda安装 OpenAI API Key用于调用 GPT 模型 安装命令pip install pyautogen✅ 注意AutoGen 依赖较多建议使用--no-cache-dir避免缓存冲突。 配置 API Key方法一环境变量推荐export OPENAI_API_KEYyour-api-key-here方法二代码中设置临时import os os.environ[OPENAI_API_KEY] sk-xxx-your-real-key-here 提示若使用 Azure OpenAI需配置config_list中的api_type,api_base,api_version等字段详见官方文档。3. 第一个 AutoGen 对话两个 Agent 聊天我们创建两个角色user_proxy代表用户发起请求并可执行代码assistant作为回答者负责回复和推理from autogen import AssistantAgent, UserProxyAgent, config_list_from_json # 1. 配置 LLM 列表支持多模型切换 config_list [ { model: gpt-3.5-turbo, api_key: os.environ.get(OPENAI_API_KEY), } ] # 2. 创建智能助手AI 回答者 assistant AssistantAgent( nameassistant, llm_config{config_list: config_list}, system_messageYou are a helpful AI assistant that answers questions concisely., ) # 3. 创建用户代理代表用户能执行代码 user_proxy UserProxyAgent( nameuser_proxy, human_input_modeNEVER, # 无需人工干预全自动 max_consecutive_auto_reply1, # 最多自动回复一次避免无限循环 code_execution_config{ work_dir: coding, # 代码工作目录 use_docker: False # 禁用 Docker本地运行安全性较低但方便调试 } ) # 4. 启动对话 user_proxy.initiate_chat( assistant, message请用 Python 计算 1 到 100 的累加和并解释结果。 ) 输出示例[assistant]: The sum of integers from 1 to 100 is calculated using the formula: n(n1)/2. For n 100, the result is 100 * 101 / 2 5050. [User Proxy] Executing code... Result: 5050✅ 成功这是第一个真正意义上的自动对话 代码执行的例子。4. 多 Agent 协作编程助手示例现在我们升级为一个真实的编程助手系统包含三个角色角色功能programmer生成代码reviewer审查代码逻辑与风格coder执行代码并返回结果from autogen import ( AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager ) # 配置模型 config_list [ { model: gpt-3.5-turbo, api_key: os.environ.get(OPENAI_API_KEY), } ] # 1. 创建各角色 programmer AssistantAgent( nameprogrammer, llm_config{config_list: config_list}, system_messageYou are a skilled programmer who writes clean, efficient Python code. ) reviewer AssistantAgent( namereviewer, llm_config{config_list: config_list}, system_messageYou are a code reviewer. Check for correctness, style, and efficiency. ) coder UserProxyAgent( namecoder, human_input_modeNEVER, code_execution_config{ work_dir: coding, use_docker: False } ) # 2. 创建群组聊天 groupchat GroupChat( agents[programmer, reviewer, coder], messages[], max_round10 ) # 3. 创建群聊管理器 manager GroupChatManager( groupchatgroupchat, llm_config{config_list: config_list} ) # 4. 用户发起请求 coder.initiate_chat( manager, message写一个 Python 函数计算斐波那契数列前 10 项并打印输出。 ) 运行效果简化版[programmer]: def fibonacci(n): a, b 0, 1 fib_list [] for _ in range(n): fib_list.append(a) a, b b, a b return fib_list [reviewer]: Good job! The function is correct and well-documented. [coder]: Executing code... Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 亮点整个过程由多个 Agent 协同完成体现了分工协作、自我验证、自动化执行的 AI Agent 特性。5. 工具调用与函数执行AutoGen 支持将任意函数注册为“工具”让 Agent 在对话中调用。示例添加一个“天气查询”工具from typing import Optional import requests def get_weather(city: str) - str: 查询指定城市的实时天气。 使用 OpenWeatherMap API需申请 key api_key your-openweathermap-api-key url fhttp://api.openweathermap.org/data/2.5/weather?q{city}appid{api_key}unitsmetric try: response requests.get(url) data response.json() temp data[main][temp] desc data[weather][0][description] return f {city} 当前气温: {temp}°C天气状况: {desc} except Exception as e: return f❌ 获取天气失败: {str(e)} # 将函数注册为工具 weather_tool { name: get_weather, description: Get current weather by city name, parameters: { type: object, properties: { city: {type: string, description: City name} }, required: [city] } } # 注册到 agent programmer AssistantAgent( nameprogrammer, llm_config{ config_list: config_list, functions: [weather_tool], # 注册函数 function_map: {get_weather: get_weather} # 映射函数名 }, system_messageYou can use tools like get_weather to answer user questions. ) # 用户提问 user_proxy.initiate_chat( programmer, message北京今天的天气怎么样 )️ 输出示例[programmer]: I will check the weather in Beijing for you. [programmer]: 北京当前气温: 18°C天气状况: partly cloudy 说明当 LLM 识别到需要调用外部工具时会自动调用你注册的函数实现真实世界交互。6. 人机回环Human-in-the-loop在关键任务中我们希望人类参与决策。AutoGen 提供了human_input_mode控制模式模式行为NEVER完全自动无须干预ALWAYS每次都等待人工确认TERMINATE只在对话结束时询问是否终止AUTO只在必要时提示人工介入示例开启人工介入# 使 coder 只在需要时暂停 coder UserProxyAgent( namecoder, human_input_modeALWAYS, # 每次执行代码前都要问人 code_execution_config{ work_dir: coding, use_docker: False } ) # 启动对话 coder.initiate_chat( manager, message写一个程序删除当前目录下的所有 .tmp 文件。 ) 输出提示[Coder] Would you like to execute the following code? (Y/N) import os for file in os.listdir(.): if file.endswith(.tmp): os.remove(file) print(fDeleted: {file}) Please enter your choice: 安全保障防止误删文件特别适用于生产环境。7. 总结与展望✅ 本章要点回顾功能实现方式单对话initiate_chat() 两个 Agent多 Agent 协作GroupChatGroupChatManager工具调用functionsfunction_map代码执行code_execution_config人机协作human_input_mode 未来方向构建领域专用智能体医疗、金融、教育结合向量数据库实现长期记忆与低代码平台集成实现可视化编排探索自主学习与进化机制 附录完整项目结构建议autogen_project/ ├── main.py # 主入口 ├── tools.py # 工具函数集合 ├── config.json # 配置文件推荐 ├── coding/ # 代码执行工作目录自动创建 └── logs/ # 日志记录可选 示例config.json[ { model: gpt-3.5-turbo, api_key: ${OPENAI_API_KEY} }, { model: gpt-4o, api_key: ${OPENAI_API_KEY} } ]然后通过config_list config_list_from_json(config.json)实现配置分离便于部署与维护。 结语“未来的智能系统不是单一模型而是由多个智能体组成的生态系统。”通过 AutoGen我们不仅能构建“会说话的 AI”更能打造“会思考、会协作、会做事”的真正智能体。无论你是开发者、产品经理还是研究人员都可以借助这个框架快速构建属于自己的 AI 应用。立即动手试试吧 复制本文代码在本地运行体验真正的多智能体协作✅点赞 收藏 分享让更多人了解 AI Agent 技术 评论区欢迎交流你打算用 AutoGen 做什么项目欢迎留言讨论参考资料AutoGen 官方文档GitHub 仓库OpenAI API 文档