GLM 5.2 with AutoGen: Build Multi-Agent AI Workflows in Python

GLM 5.2 with AutoGen: Build Multi-Agent AI Workflows in Python

Step-by-step guide to using GLM 5.2 as the LLM backend in AutoGen — configure AssistantAgent, UserProxyAgent, and build multi-agent pipelines with Python code examples.

Microsoft's AutoGen is one of the most capable open-source frameworks for building multi-agent AI systems. Developers use it to chain specialized agents together — one writes code, another reviews it, a third calls external APIs — all orchestrated through a clean Python interface. The catch? Nearly every tutorial and example in the wild assumes you are using OpenAI's GPT-4 as the backend.

GLM 5.2 (the glm-4-plus model from Zhipu AI) plugs into AutoGen without any custom code, thanks to its fully OpenAI-compatible API. This tutorial walks you through the complete setup: from installing dependencies and configuring your llm_config, to wiring up a two-agent pipeline and then scaling to a group chat with a manager agent.


Pain Point: AutoGen Tutorials Always Use OpenAI

If you search for "AutoGen tutorial Python," you will find dozens of guides — and essentially all of them start with api_key = os.getenv("OPENAI_API_KEY"). This creates an invisible assumption that AutoGen only works with OpenAI models.

That assumption is wrong. AutoGen's llm_config accepts any base_url, so any provider that exposes an OpenAI-compatible endpoint works immediately. The problem is that nobody writes tutorials for the alternatives, which leaves developers who want to use GLM 5.2 on their own to figure it out.

This guide fills that gap entirely.


Competitive Differentiator: Why Use GLM 5.2 for AutoGen Pipelines

Before diving into code, here is why GLM 5.2 is worth the configuration effort:

Cost. GPT-4o is priced at roughly $5.00 per million input tokens and $15.00 per million output tokens. GLM 5.2 costs $1.40 per million input tokens and $4.40 per million output tokens. For AutoGen pipelines — where agents exchange many messages back and forth — this difference compounds quickly. A long-running group chat that costs $15 with GPT-4o costs approximately $4–5 with GLM 5.2, roughly a 3x saving.

Context window. GLM 5.2 provides a 1,048,576-token (1M) context window. This means you can pass an entire codebase to an AutoGen coding agent and have it reason over the full context in a single turn. GPT-4o's 128K window forces chunking strategies that add complexity.

Performance. On GPQA Diamond — a benchmark measuring graduate-level scientific reasoning — GLM 5.2 scores 89%. On SWE-bench Pro, a real-world software engineering benchmark, it scores 62.1%. These are numbers that make GLM 5.2 a credible engine for agentic coding workflows.

Speed. At approximately 158 tokens per second (as measured by Artificial Analysis), GLM 5.2 keeps multi-turn agent conversations moving quickly.

You can read more about the model's capabilities in our detailed GLM 5.2 API overview.


Prerequisites

Install the required packages. AutoGen's current stable release is available as pyautogen. This tutorial uses the classic 0.2.x API, which is the most widely documented and production-tested version.

pip install pyautogen python-dotenv

Create a .env file in your project root:

GLM_API_KEY=your_zhipu_ai_key_here

Get your API key from the Zhipu AI open platform at open.bigmodel.cn. The free tier includes a generous allowance for experimenting.


Step 1: Configure llm_config for GLM 5.2

The llm_config dictionary is the single connection point between AutoGen and any LLM backend. Set model to glm-4-plus, point base_url at Zhipu AI's endpoint, and set api_type to openai so AutoGen uses its OpenAI-compatible request format.

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.",
)

Run this script. If you see the assistant reply with 4 followed by TERMINATE, your GLM 5.2 connection is working correctly.


Step 2: Build a Two-Agent Coding Pipeline

The classic AutoGen pattern is a UserProxyAgent paired with an AssistantAgent. The assistant writes code; the user proxy executes it in a sandbox and feeds the output back. GLM 5.2's strong SWE-bench Pro score makes it well-suited for this workflow.

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)

When you run this, AutoGen enters a loop: GLM 5.2 writes the code, the executor runs it, the output comes back, and GLM 5.2 decides whether the task is complete or whether to fix any errors. The loop terminates when GLM 5.2 outputs TERMINATE.

A few configuration notes worth highlighting:

  • human_input_mode="NEVER" makes the pipeline fully automated. Change to "ALWAYS" if you want to approve each code execution step manually.
  • max_consecutive_auto_reply=5 caps the loop at five iterations, preventing runaway agent conversations.
  • work_dir="coding_workspace" writes generated scripts to a local folder, so you can inspect them after the run.

Step 3: Scale to a Group Chat with Multiple Agents

Two-agent pipelines are powerful, but AutoGen's group chat feature allows you to compose more specialized agents. A common pattern in software development workflows is a planner, a coder, and a reviewer — three distinct roles that collaborate to produce higher-quality output.

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."
    ),
)

With speaker_selection_method="auto", the GroupChatManager uses GLM 5.2 itself to decide which agent should speak next based on the conversation history. This works well in practice because GLM 5.2's 1M context window means it can hold the entire multi-agent conversation history without truncation, even in long sessions.


Tips for Production AutoGen Pipelines with GLM 5.2

Set explicit termination conditions. The is_termination_msg lambda and max_consecutive_auto_reply cap are both important. Always use both — the lambda handles clean task completion, the cap handles runaway loops from ambiguous outputs.

Use temperature 0.1 for coding tasks. Lower temperature reduces random variation in generated code, which matters when the executor is going to run that code directly.

Enable Docker execution for untrusted tasks. The examples above use "use_docker": False for simplicity. For any pipeline running agent-generated code you did not inspect, set it to True and make sure Docker is running. AutoGen's Docker integration sandboxes execution cleanly.

Log token usage. GLM 5.2's pricing is $1.40/M input and $4.40/M output. For a group chat with 12 rounds and three agents, you can easily generate 20,000–50,000 tokens in a single run. Add a usage callback or parse AutoGen's cost output to track spend during development.

Pass large codebases as context. GLM 5.2's 1M token context is a genuine advantage for agentic coding. You can read() an entire repository into a string and include it in the initial message to UserProxyAgent, giving the Coder agent full context without chunking.


Ready to start building? Try GLM 5.2 on glm5.app — you can test the model interactively before wiring it into AutoGen, which is a useful way to iterate on system prompts before committing them to agent configurations.


Common Issues and Fixes

AuthenticationError on first run. Double-check that your .env file is in the same directory as your script and that load_dotenv() is called before os.getenv(). Print the key length (len(os.getenv("GLM_API_KEY", ""))) to confirm it is being read.

Agents keep talking past max_consecutive_auto_reply. The max_consecutive_auto_reply limit applies per agent, not globally. In a group chat, set max_round on the GroupChat object — this is the global round cap.

Code execution hangs. AutoGen's code executor spawns a subprocess for each code block. If the generated script has an infinite loop or waits for network I/O, the subprocess blocks. Add a timeout key to code_execution_config: {"work_dir": "coding_workspace", "use_docker": False, "timeout": 60}.

GroupChatManager picks the wrong agent. With speaker_selection_method="auto", the manager prompt instructs GLM 5.2 to choose the next speaker. You can override this by setting speaker_selection_method="round_robin" for a fixed rotation, which is more predictable during debugging.


GLM 5.2's combination of strong benchmark performance, 1M context, and OpenAI-compatible API makes it a practical drop-in for any AutoGen project that currently relies on GPT-4. The configuration is three extra lines in llm_config, and the cost savings on multi-agent pipelines are substantial.

If you want to go deeper on the API itself — authentication, streaming, function calling, and batch modes — the GLM 5.2 API guide covers all of those topics.

Explore GLM 5.2's full feature set at glm5.app and see how it fits into your agentic workflow stack.


Sources

Start Using GLM 5 Today

Try GLM 5 free — reasoning, coding, agents, and image generation in one platform.