Microsoft 的 AutoGen 是构建多智能体 AI 系统最强大的开源框架之一。开发者用它把专业智能体串成链路——一个写代码、一个审代码、第三个调外部 API——全程通过干净的 Python 接口编排。问题在于:网上的教程和示例几乎都假设你用 OpenAI 的 GPT-4 作为后端。
GLM 5.2(Zhipu AI 的 glm-4-plus 模型)凭借完全兼容 OpenAI 的 API,接入 AutoGen 不需要任何自定义代码。本教程带你走完整个配置流程:从安装依赖、配置 llm_config,到搭起一个双智能体管线,再扩展到带管理智能体的群聊。
痛点:AutoGen 教程都用 OpenAI
搜索「AutoGen tutorial Python」,你会找到几十篇教程——而它们几乎都以 api_key = os.getenv("OPENAI_API_KEY") 开头。这制造了一个隐形假设:AutoGen 只能和 OpenAI 的模型一起用。
这个假设是错的。AutoGen 的 llm_config 接受任意 base_url,任何暴露 OpenAI 兼容端点的供应商都能直接使用。问题是没人给替代品写教程,想用 GLM 5.2 的开发者只能自己摸索。
这篇指南彻底补上这个缺口。
差异化优势:为什么 AutoGen 管线选 GLM 5.2
在写代码之前,先说说为什么 GLM 5.2 值得费这番配置功夫:
成本。 GPT-4o 的定价大约是每百万输入 token $5.00、每百万输出 token $15.00。GLM 5.2 是每百万输入 token $1.40、每百万输出 token $4.40。对 AutoGen 管线来说——智能体之间来回交换大量消息——这个差距会迅速滚雪球。一场用 GPT-4o 要花 $15 的长时间群聊,用 GLM 5.2 大约只要 $4–5,省下差不多 3 倍。
上下文窗口。 GLM 5.2 提供 1,048,576 token(1M)的上下文窗口。这意味着你可以把整个代码库传给 AutoGen 编码智能体,让它在一轮里基于完整上下文推理。GPT-4o 的 128K 窗口迫使你做分块策略,徒增复杂度。
性能。 在 GPQA Diamond——衡量研究生级科学推理的基准测试——上,GLM 5.2 拿到 89%。在 SWE-bench Pro——真实世界的软件工程基准——上拿到 62.1%。这些数字让 GLM 5.2 成为智能体编码工作流的可信引擎。
速度。 大约每秒 158 token(Artificial Analysis 实测),GLM 5.2 让多轮智能体对话保持流畅推进。
更多模型能力细节,可阅读我们详细的 GLM 5.2 API 概览。
前置条件
安装所需包。AutoGen 当前稳定版以 pyautogen 发布。本教程使用经典的 0.2.x API,这是文档最全、生产验证最多的版本。
pip install pyautogen python-dotenv
在项目根目录创建 .env 文件:
GLM_API_KEY=your_zhipu_ai_key_here
API key 从 Zhipu AI 开放平台 open.bigmodel.cn 获取。免费额度相当慷慨,足够做实验。
第 1 步:为 GLM 5.2 配置 llm_config
llm_config 字典是 AutoGen 与任何 LLM 后端之间的唯一连接点。把 model 设为 glm-4-plus,把 base_url 指向 Zhipu AI 的端点,把 api_type 设为 openai,让 AutoGen 使用其 OpenAI 兼容的请求格式。
import os
from dotenv import load_dotenv
import autogen
load_dotenv()
llm_config = {
"model": "glm-4-plus",
"api_key": os.getenv("GLM_API_KEY"),
"base_url": "https://open.bigmodel.cn/api/paas/v4/",
"api_type": "openai",
"temperature": 0.1,
}
# Quick sanity check — make sure AutoGen can reach GLM 5.2
assistant = autogen.AssistantAgent(
name="assistant",
llm_config=llm_config,
system_message="You are a helpful Python coding assistant.",
)
user_proxy = autogen.UserProxyAgent(
name="user_proxy",
human_input_mode="NEVER",
max_consecutive_auto_reply=1,
is_termination_msg=lambda msg: "TERMINATE" in msg.get("content", ""),
code_execution_config=False,
)
user_proxy.initiate_chat(
assistant,
message="What is 2 + 2? Reply with just the answer and then say TERMINATE.",
)
运行这个脚本。如果看到 assistant 回复 4 然后跟上 TERMINATE,说明 GLM 5.2 连接正常。
第 2 步:构建双智能体编码管线
AutoGen 的经典模式是一个 UserProxyAgent 配一个 AssistantAgent。assistant 写代码;user proxy 在沙箱里执行并把输出喂回去。GLM 5.2 出色的 SWE-bench Pro 成绩让它非常适合这个工作流。
import os
from dotenv import load_dotenv
import autogen
load_dotenv()
llm_config = {
"model": "glm-4-plus",
"api_key": os.getenv("GLM_API_KEY"),
"base_url": "https://open.bigmodel.cn/api/paas/v4/",
"api_type": "openai",
"temperature": 0.1,
}
# AssistantAgent: writes Python code to solve the task
coder = autogen.AssistantAgent(
name="Coder",
llm_config=llm_config,
system_message=(
"You are an expert Python developer. "
"When given a task, write a complete, runnable Python script. "
"Wrap all code in a ```python ... ``` block. "
"After the code runs successfully, say TERMINATE."
),
)
# UserProxyAgent: executes the code and returns stdout
executor = autogen.UserProxyAgent(
name="Executor",
human_input_mode="NEVER",
max_consecutive_auto_reply=5,
is_termination_msg=lambda msg: "TERMINATE" in msg.get("content", ""),
code_execution_config={
"work_dir": "coding_workspace",
"use_docker": False, # set True for isolated execution
},
)
# Start the task
task = """
Write a Python script that:
1. Fetches the list of public repositories for the GitHub user 'microsoft'
using the GitHub REST API (no authentication needed for public data).
2. Prints the name and star count of the top 5 repositories by stars.
"""
executor.initiate_chat(coder, message=task)
运行后,AutoGen 会进入循环:GLM 5.2 写代码、executor 执行、输出返回、GLM 5.2 判断任务是否完成或是否需要修复错误。当 GLM 5.2 输出 TERMINATE 时循环终止。
几个值得强调的配置要点:
human_input_mode="NEVER"让管线全自动运行。想手动批准每一步代码执行,就改成"ALWAYS"。max_consecutive_auto_reply=5把循环上限设为五次迭代,防止智能体对话失控。work_dir="coding_workspace"把生成的脚本写进本地文件夹,运行后可以检查。
第 3 步:扩展为多智能体群聊
双智能体管线已经很强大,但 AutoGen 的群聊功能让你组合出更专业的智能体。软件开发工作流中的常见模式是规划者、编码者、审查者——三个各司其职的角色协作产出更高质量的成果。
import os
from dotenv import load_dotenv
import autogen
load_dotenv()
llm_config = {
"model": "glm-4-plus",
"api_key": os.getenv("GLM_API_KEY"),
"base_url": "https://open.bigmodel.cn/api/paas/v4/",
"api_type": "openai",
"temperature": 0.1,
}
# Agent 1: breaks the task into a step-by-step plan
planner = autogen.AssistantAgent(
name="Planner",
llm_config=llm_config,
system_message=(
"You are a software architect. Given a task, output a numbered "
"step-by-step implementation plan. Do not write code yourself."
),
)
# Agent 2: implements the plan as Python code
coder = autogen.AssistantAgent(
name="Coder",
llm_config=llm_config,
system_message=(
"You are a Python developer. Take the Planner's steps and implement "
"them as a complete Python script inside a ```python ... ``` block."
),
)
# Agent 3: reviews the code for correctness and style
reviewer = autogen.AssistantAgent(
name="Reviewer",
llm_config=llm_config,
system_message=(
"You are a senior code reviewer. Examine the code written by Coder. "
"Point out bugs, missing error handling, or style issues. "
"If the code is acceptable, say 'APPROVED' and then TERMINATE."
),
)
# UserProxyAgent: executes any code and provides human turn in the group
user_proxy = autogen.UserProxyAgent(
name="User",
human_input_mode="NEVER",
max_consecutive_auto_reply=0,
is_termination_msg=lambda msg: "TERMINATE" in msg.get("content", ""),
code_execution_config={
"work_dir": "group_workspace",
"use_docker": False,
},
)
# GroupChat wires all agents together; GroupChatManager drives turn selection
groupchat = autogen.GroupChat(
agents=[user_proxy, planner, coder, reviewer],
messages=[],
max_round=12,
speaker_selection_method="auto", # GLM 5.2 decides who speaks next
)
manager = autogen.GroupChatManager(
groupchat=groupchat,
llm_config=llm_config,
)
# Kick off the group workflow
user_proxy.initiate_chat(
manager,
message=(
"Build a Python utility that reads a CSV file passed as a command-line "
"argument, computes basic descriptive statistics (mean, median, std) "
"for all numeric columns, and prints a formatted summary table."
),
)
当 speaker_selection_method="auto" 时,GroupChatManager 用 GLM 5.2 自己根据对话历史决定下一个该谁发言。这在实践中效果很好,因为 GLM 5.2 的 1M 上下文窗口意味着它能装下整段多智能体对话历史而不截断,即使会话很长。
用 GLM 5.2 搭建生产级 AutoGen 管线的技巧
设置明确的终止条件。 is_termination_msg lambda 和 max_consecutive_auto_reply 上限都很重要,两个都要用——lambda 处理干净的任务完成,上限兜住模糊输出引发的失控循环。
编码任务用 temperature 0.1。 更低的 temperature 减少生成代码的随机波动,而 executor 要直接运行这些代码,这点很关键。
不可信任务开启 Docker 执行。 上面的示例为了简单用了 "use_docker": False。任何运行未经你检查的智能体生成代码的管线,都改成 True 并确保 Docker 在运行。AutoGen 的 Docker 集成能干净地隔离执行。
记录 token 用量。 GLM 5.2 定价是输入 $1.40/M、输出 $4.40/M。一场 12 轮三个智能体的群聊,单次运行轻松产生 20,000–50,000 token。开发期间加一个 usage 回调或解析 AutoGen 的成本输出,跟踪开销。
把大代码库作为上下文传入。 GLM 5.2 的 1M token 上下文对智能体编码是实打实的优势。你可以把整个仓库 read() 成字符串,放进给 UserProxyAgent 的初始消息里,让 Coder 智能体无需分块就拿到完整上下文。
准备好动手了吗?在 glm5.app 试用 GLM 5.2 —— 接入 AutoGen 之前可以先交互式测试模型,这是在把系统提示词写进智能体配置之前迭代它们的有效方式。
常见问题与修复
首次运行报 AuthenticationError。 双重检查你的 .env 文件和脚本在同一个目录,且 load_dotenv() 在 os.getenv() 之前调用。打印 key 长度(len(os.getenv("GLM_API_KEY", "")))确认它被读到了。
智能体说话超过了 max_consecutive_auto_reply。 max_consecutive_auto_reply 上限是按智能体算的,不是全局的。在群聊里,在 GroupChat 对象上设置 max_round——那才是全局轮数上限。
代码执行卡住。 AutoGen 的代码执行器为每个代码块都派生一个子进程。如果生成的脚本有死循环或等待网络 I/O,子进程会被阻塞。给 code_execution_config 加一个 timeout 键:{"work_dir": "coding_workspace", "use_docker": False, "timeout": 60}。
GroupChatManager 选错发言者。 speaker_selection_method="auto" 时,manager 的提示词会让 GLM 5.2 选择下一位发言者。你可以设置 speaker_selection_method="round_robin" 用固定轮转覆盖它,调试时更可预测。
GLM 5.2 把强劲的基准成绩、1M 上下文和 OpenAI 兼容 API 组合在一起,使它成为任何目前依赖 GPT-4 的 AutoGen 项目即插即用的选择。配置只在 llm_config 里多三行,而多智能体管线的成本节省相当可观。
想深入了解 API 本身——认证、流式输出、函数调用和批量模式——GLM 5.2 API 指南覆盖了所有主题。
在 glm5.app 探索 GLM 5.2 的完整功能集,看看它如何融入你的智能体工作流技术栈。
来源
(来源链接)
- Zhipu AI GLM-4-Plus 模型卡与 API 文档:https://open.bigmodel.cn/dev/howuse/model
- Microsoft AutoGen 文档(v0.2):https://microsoft.github.io/autogen/0.2/docs/Getting-Started
- AutoGen GitHub 仓库:https://github.com/microsoft/autogen
- Artificial Analysis GLM-4-Plus 基准成绩:https://artificialanalysis.ai/models/glm-4-plus
- SWE-bench 排行榜:https://www.swebench.com
- GPQA Diamond 基准测试(Rein et al., 2023):https://arxiv.org/abs/2311.12022




