AutoGen Tutorial (Python): adding human-in-the-loop for advanced developers

By Cyprian AaronsUpdated 2026-04-21
autogenadding-human-in-the-loop-for-advanced-developerspython

This tutorial shows how to add a human approval loop to an AutoGen agent workflow in Python. You need this when an agent is allowed to draft, analyze, or propose actions, but a person must review and approve anything risky before it executes.

What You'll Need

  • Python 3.10+
  • autogen-agentchat
  • autogen-ext[openai]
  • An OpenAI API key set as OPENAI_API_KEY
  • A terminal with access to run Python scripts
  • Basic familiarity with AutoGen agents, messages, and group chats

Step-by-Step

  1. Start by installing the packages and setting your API key. I’m using the current AutoGen split packages here, which is what you want for production code rather than older monolithic examples.
pip install autogen-agentchat autogen-ext[openai]
export OPENAI_API_KEY="your-key-here"
  1. Next, create an assistant agent that will do the actual work. Keep the model config explicit so you can swap models later without changing the rest of the workflow.
import asyncio

from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient

model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")

assistant = AssistantAgent(
    name="assistant",
    model_client=model_client,
    system_message=(
        "You are a careful assistant. "
        "When asked for a decision or action, produce a concise recommendation."
    ),
)
  1. Add a small human-in-the-loop gate before any final action is taken. In production, this is where you would wire in Slack, Teams, a web UI, or an internal approval service; here we use terminal input so the control flow is explicit and executable.
async def get_human_approval(summary: str) -> bool:
    print("\n=== HUMAN REVIEW REQUIRED ===")
    print(summary)
    answer = input("Approve this action? [y/N]: ").strip().lower()
    return answer in {"y", "yes"}
  1. Run the agent on a task, then pause for human approval before continuing. This pattern is useful when the agent generates something that should be reviewed before execution, like an email draft, policy exception, or transaction recommendation.
async def main():
    result = await assistant.run(task=(
        "Draft a short recommendation for whether we should "
        "approve a customer refund request of $450 based on missing receipts."
    ))

    summary = result.messages[-1].content
    approved = await get_human_approval(summary)

    if approved:
        print("\nApproved by human.")
        print("Final output:")
        print(summary)
    else:
        print("\nRejected by human. No action taken.")

if __name__ == "__main__":
    asyncio.run(main())
  1. If you need stricter control, move from “review after generation” to “review before execution.” The right pattern is to have the agent produce a structured proposal, then let the human approve only specific fields such as amount, recipient, or policy reason.
import json

proposal = {
    "action": "refund",
    "amount": 450,
    "currency": "USD",
    "reason": "Customer claims missing receipts",
}

print(json.dumps(proposal, indent=2))
approved = input("Approve proposal JSON? [y/N]: ").strip().lower() in {"y", "yes"}

if approved:
    print("Executing approved proposal...")
else:
    print("Proposal rejected.")

Testing It

Run the script and confirm the assistant generates a recommendation first, then waits for your input before proceeding. Type n and verify that no final action is printed; then rerun and type y to confirm the approved path executes.

If you want to test this like a real system, replace the terminal prompt with a function that reads from your approval service or message queue. The important behavior is unchanged: generation happens automatically, execution happens only after explicit human consent.

Next Steps

  • Wire the approval step into Slack or Microsoft Teams instead of input()
  • Add structured outputs with Pydantic so humans approve fields instead of free text
  • Move from single-agent approval to multi-agent workflows with tool-use gating

Keep learning

By Cyprian Aarons, AI Consultant at Topiax.

Want the complete 8-step roadmap?

Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.

Get the Starter Kit

Related Guides