Velamuvi AIAcademy
AutoGen

Lesson 5 of 6 · AutoGen

Project: Coding Assistant Team

Build an AutoGen team that writes, tests and reviews code: a coder, a code executor with an approval check and a reviewer in a SelectorGroupChat. With Python.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Combine a coder, an executor and a reviewer into one team
  • Fix the speaking order with selector_func
  • Run tests through an approval-checked executor
  • Let failing tests and review feedback drive revisions
  • Know what changes for production use

What you'll build

A small team that turns a specification into tested code. It must:

  • Write a function and its tests (the coder).
  • Run the tests, but only code that passes an approval check (the executor).
  • Review the code and the test output against the specification, and either approve or say what to fix (the reviewer).
  • Stop when the reviewer approves, or after a message limit.

The specification is a delivery-fee rule for Velamuvi Bikes: free to Lisbon and Porto, 25 EUR elsewhere, 2 EUR per kg above 20 kg, and no delivery for bikes over 35 kg.

The loop in plain Python

First the loop itself, with stand-ins for the models; the tests really run:

Try it yourselfPython
# The coding team's loop in plain Python: coder -> executor -> reviewer, until the reviewer approves.
# (Stand-ins replace the models; the executor really runs the code, here with exec.)
VERSIONS = [
    "def delivery_fee(city, kg):\n    return (0 if city in ('Lisbon', 'Porto') else 25) + max(0, kg - 20) * 2\n",
    "def delivery_fee(city, kg):\n    if kg > 35:\n        raise ValueError('too heavy')\n"
    "    return (0 if city in ('Lisbon', 'Porto') else 25) + max(0, kg - 20) * 2\n",
]
TESTS = [("Lisbon", 18, 0), ("Faro", 24, 33), ("Porto", 40, "error")]

def executor(code):
    scope = {}
    exec(code, scope)                       # a real team runs this in a container (lesson 4)
    failures = []
    for city, kg, want in TESTS:
        try:
            got = scope["delivery_fee"](city, kg)
        except ValueError:
            got = "error"
        if got != want:
            failures.append(f"delivery_fee({city!r}, {kg}) gave {got!r}, expected {want!r}")
    return "All tests passed" if not failures else "; ".join(failures)

def reviewer(test_output):
    return "APPROVE" if test_output == "All tests passed" else f"Fix this: {test_output}"

for attempt, code in enumerate(VERSIONS, start=1):          # each loop: coder, executor, reviewer
    output = executor(code)
    verdict = reviewer(output)
    print(f"attempt {attempt}: executor says {output!r}\n           reviewer says {verdict!r}")
    if verdict == "APPROVE":
        break

The first version forgot the weight limit, a test caught it, the reviewer passed on the exact failure, and the second version passed.

The AutoGen version

import asyncio, tempfile
from autogen_agentchat.agents import ApprovalRequest, ApprovalResponse, AssistantAgent, CodeExecutorAgent
from autogen_agentchat.conditions import MaxMessageTermination, TextMentionTermination
from autogen_agentchat.messages import TextMessage
from autogen_agentchat.teams import SelectorGroupChat
from autogen_ext.code_executors.local import LocalCommandLineCodeExecutor
from autogen_ext.models.anthropic import AnthropicChatCompletionClient

TASK = """Write a Python function delivery_fee(city, weight_kg) for Velamuvi Bikes:
- delivery to Lisbon or Porto is free; anywhere else costs 25 EUR
- add 2 EUR for every kg above 20 kg
- bikes over 35 kg can't be delivered: raise ValueError
Include tests in the same code block and print "All tests passed" if they pass."""

def approve(request: ApprovalRequest) -> ApprovalResponse:
    banned = [w for w in ("import os", "subprocess", "open(", "requests", "socket") if w in request.code]
    return ApprovalResponse(approved=not banned, reason=f"Blocked: {banned}" if banned else "Pure Python only")

def next_speaker(messages):
    """Fixed order: coder -> executor -> reviewer -> coder ..."""
    order = {"user": "coder", "coder": "executor", "executor": "reviewer", "reviewer": "coder"}
    return order.get(messages[-1].source)

async def main():
    model_client = AnthropicChatCompletionClient(model="MODEL_NAME")
    coder = AssistantAgent("coder", model_client=model_client,
        system_message="You write clean Python with tests, in one Markdown code block marked as python. "
                       "Fix the code when the reviewer or the test output shows a problem.")
    reviewer = AssistantAgent("reviewer", model_client=model_client,
        system_message="Check the latest code and its test output against the task. If every requirement "
                       "is met and the tests pass, reply APPROVE. Otherwise say exactly what to fix.")
    with tempfile.TemporaryDirectory() as work_dir:              # use a Docker executor in production
        executor = CodeExecutorAgent("executor", approval_func=approve,
            code_executor=LocalCommandLineCodeExecutor(work_dir=work_dir, timeout=30))
        team = SelectorGroupChat(
            [coder, executor, reviewer], model_client=model_client, selector_func=next_speaker,
            termination_condition=TextMentionTermination("APPROVE", sources=["reviewer"]) | MaxMessageTermination(12),
        )
        result = await team.run(task=TASK)
        for m in result.messages[1:]:
            if isinstance(m, TextMessage):
                print(f"--- {m.source} ---\n{m.content.strip()}")
    await model_client.close()

asyncio.run(main())
Output
--- coder ---
```python
def delivery_fee(city, weight_kg):
    base = 0 if city.lower() in {"lisbon", "porto"} else 25
    return base + max(0, weight_kg - 20) * 2

assert delivery_fee("Lisbon", 18) == 0
assert delivery_fee("Faro", 24) == 33
try:
    delivery_fee("Porto", 40)
    print("TEST FAILED: a 40 kg bike should be refused")
except ValueError:
    print("All tests passed")
```
--- executor ---
TEST FAILED: a 40 kg bike should be refused
--- reviewer ---
The 35 kg limit is missing: delivery_fee must raise ValueError for bikes over 35 kg, as the failed test shows.
--- coder ---
```python
def delivery_fee(city, weight_kg):
    if weight_kg > 35:
        raise ValueError("Bikes over 35 kg can't be delivered")
    base = 0 if city.lower() in {"lisbon", "porto"} else 25
    return base + max(0, weight_kg - 20) * 2

assert delivery_fee("Lisbon", 18) == 0
assert delivery_fee("Faro", 24) == 33
try:
    delivery_fee("Porto", 40)
    print("TEST FAILED: a 40 kg bike should be refused")
except ValueError:
    print("All tests passed")
```
--- executor ---
All tests passed
--- reviewer ---
All three requirements are met and the tests pass. APPROVE

How it works

  1. Three agents, three jobs. The coder writes code with tests; the CodeExecutorAgent runs the code block it finds; the reviewer compares code and output with the task.
  2. A fixed order. SelectorGroupChat normally asks a model who speaks next. Here selector_func always answers (coder, then executor, then reviewer, then coder again), so no selection calls are needed and the order can't drift. You could return None in some situations to let the model decide.
  3. Approval before execution. The approval function blocks file, network and process access. Pure calculation and tests pass.
  4. Feedback drives revisions. The executor's output (“TEST FAILED: a 40 kg bike should be refused”) and the reviewer's comment go back to the coder in the shared conversation, and the coder fixes exactly that.
  5. Safe ending. Only the reviewer's “APPROVE” ends the run; MaxMessageTermination(12) stops a team that can't converge.

For production use

  • Replace LocalCommandLineCodeExecutor with DockerCommandLineCodeExecutor (lesson 4), with no secrets and a timeout.
  • Keep a person in the loop for code that will be merged or deployed: the reviewer's approval should trigger a pull request for human review, not a deployment.
  • Record every run (messages, code versions, outputs) so you can audit what was executed.
  • For new systems, build the same design on a maintained framework such as Microsoft Agent Framework, as lesson 1 explained.

Common mistakes

Practice exercise

Be the coder: write the function the team was asked for, so that the tests below print the expected results.

Your solutionPython
def delivery_fee(city, weight_kg):
    # Lisbon and Porto (any capitalisation): free; elsewhere: 25.
    # Add 2 for every kg above 20. Over 35 kg: raise ValueError.
    pass

for city, kg in [("Lisbon", 18), ("faro", 24), ("PORTO", 22), ("Faro", 40)]:
    try:
        print(delivery_fee(city, kg))
    except ValueError:
        print("refused")
Knowledge check

Why does the project use selector_func in its SelectorGroupChat?

Summary

  • A coder, an approval-checked executor and a reviewer turn a specification into tested code.
  • selector_func fixes the speaking order; only the reviewer's APPROVE ends the run, with a message limit as a backstop.
  • Test output and review comments drive the coder's revisions.
  • In production: a container executor, human review before merging, audit logs, and a maintained framework for new systems.

Next: AutoGen's status, its limitations, and migrating this team to Microsoft Agent Framework.