Home / Articles / Practical notes: MiniMax Agent Team Best Practice: An AI Agent Is a While Loop.

This article is published in English.

Practical notes: MiniMax Agent Team Best Practice: An AI Agent Is a While Loop.

Operable walkthrough of Practical notes: MiniMax Agent Team Best Practice: An AI Agent Is a While Loop.: contracts, checks, and drop-in code slots for teams shipping this pattern.

2148 words

Use this as an operator-facing rebuild of the ideas in “MiniMax Agent Team Best Practice: An AI Agent Is a While Loop. A Reliable One Is a State Machine.”: clear stages, ordered code slots, and recovery notes that survive a handoff. The Overview stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

# naive_loop.py -- a single-agent tool loop,
# Mini-Agent style: summarize if needed ->
# llm.generate(messages, tools) -> execute
# tool_calls -> append results -> repeat.
import json
import subprocess
from openai import OpenAI

client = OpenAI()
MODEL = "gpt-4o-mini"
MAX_HISTORY = 40  # crude context budget


def read_file(path: str) -> str:
    with open(path) as f:
        return f.read()[:4000]


def run_cmd(cmd: str) -> str:
    p = subprocess.run(
        cmd, shell=True, timeout=30,
        capture_output=True, text=True)
    out = p.stdout + p.stderr
    return f"exit={p.returncode}\n{out[-2000:]}"


TOOLS = {"read_file": read_file,
         "run_cmd": run_cmd}


def schema(name, desc, arg):
    return {
        "type": "function",
        "function": {
            "name": name,
            "description": desc,
            "parameters": {
                "type": "object",
                "properties": {
                    arg: {"type": "string"},
                },
                "required": [arg],
            },
        },
    }


SCHEMAS = [
    schema("read_file",
           "Read a local text file.", "path"),
    schema("run_cmd",
           "Run a shell command.", "cmd"),
]



def summarize(msgs):
    # Mini-Agent compresses old turns with an
    # LLM summary call when the context nears
    # its limit; hard truncation is the v0.
    if len(msgs) <= MAX_HISTORY:
        return msgs
    return [msgs[0]] + msgs[-MAX_HISTORY:]


def run(task: str, max_steps: int = 20):
    msgs = [{"role": "user", "content": task}]
    for _ in range(max_steps):
        msgs = summarize(msgs)
        r = client.chat.completions.create(
            model=MODEL,
            messages=msgs,
            tools=SCHEMAS,
        )
        msg = r.choices[0].message
        msgs.append(msg)
        if not msg.tool_calls:
            return msg.content  # model says done
        for call in msg.tool_calls:
            fn = TOOLS[call.function.name]
            args = json.loads(
                call.function.arguments)
            try:
                out = fn(**args)
            except Exception as e:
                out = f"tool error: {e}"
            msgs.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": out,
            })
    return "hit max_steps -- gave up"


if __name__ == "__main__":
    print(run("Count the .py files here, then "
              "summarize naive_loop.py."))
# team_engine.py -- the loop promoted to a
# state machine. One task lifecycle is one
# Session; deterministic code owns every
# transition: producing -> verifying -> done.
from dataclasses import dataclass, field

PRODUCING = "producing"
VERIFYING = "verifying"
DONE = "done"
FAILED = "failed"


@dataclass
class Session:
    goal: str
    state: str = PRODUCING
    attempts: int = 0
    artifact: str = ""
    reviews: list = field(default_factory=list)


def run_session(s, worker, verifier,
                max_retries: int = 3):
    while s.state not in (DONE, FAILED):
        if s.state == PRODUCING:
            s.attempts += 1
            s.artifact = worker(
                s.goal, s.reviews)
            s.state = VERIFYING
        elif s.state == VERIFYING:
            ok, report = verifier(
                s.goal, s.artifact)
            s.reviews.append(report)
            if ok:
                s.state = DONE
            elif s.attempts >= max_retries:
                s.state = FAILED
            else:
                # Reject: wake the worker with
                # the review log in context.
                s.state = PRODUCING
    return s


def run_team(goals, worker, verifier):
    # Leader's job: split the goal, run the
    # sessions (a thread pool in real use),
    # then merge N artifacts into 1 result.
    done, failed = [], []
    for g in goals:
        s = run_session(Session(g),
                        worker, verifier)
        if s.state == DONE:
            done.append(s.artifact)
        else:
            failed.append(s.goal)
    return done, failed


if __name__ == "__main__":
    # Stub roles so the engine runs anywhere;
    # swap in LLM calls for the real thing.
    def worker(goal, reviews):
        v = len(reviews) + 1
        return f"draft v{v}: {goal}"

    def verifier(goal, artifact):
        ok = "v2" in artifact
        return ok, f"review {artifact!r}: {ok}"

    done, failed = run_team(
        ["intro", "benchmarks", "faq"],
        worker, verifier)
    print("delivered:", done)
    print("failed:", failed)
# grounded_verifier.py -- evidence over vibes.
# The verdict comes from exit codes and logs,
# never from the model's self-assessment.
import subprocess
import sys

PY = sys.executable

# pytest exit codes: 0 = all passed,
# 1 = failures, 5 = no tests collected
# (acceptable for a docs-only change).
PYTEST_OK = (0, 5)

CHECKS = [
    ("diff", ["git", "diff", "--stat"], (0,)),
    ("build", [PY, "-m", "compileall",
               "-q", "."], (0,)),
    ("tests", [PY, "-m", "pytest", "-q",
               "--maxfail", "1"], PYTEST_OK),
]


def run_check(name, cmd, ok_codes, cwd):
    p = subprocess.run(
        cmd, cwd=cwd,
        capture_output=True, text=True)
    tail = (p.stdout + p.stderr)[-2000:]
    return {
        "check": name,
        "cmd": " ".join(cmd),
        "exit_code": p.returncode,
        "ok": p.returncode in ok_codes,
        "output_tail": tail,
    }


def verify(repo: str):
    evidence = []
    for name, cmd, ok_codes in CHECKS:
        e = run_check(name, cmd, ok_codes, repo)
        evidence.append(e)
        if not e["ok"]:
            # Reject with logs attached: the
            # worker retries against real
            # errors, not "please improve".
            return False, evidence
    return True, evidence



if __name__ == "__main__":
    ok, ev = verify(".")
    for e in ev:
        print(f"{e['check']:>6} exit "
              f"{e['exit_code']} ok={e['ok']}")
    print("verdict:", "pass" if ok else "fail")

Operational checklist

When working through the Operational checklist stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest.

Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.

Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.

Pin dependency versions and record the image digest that ran the demo. Reproducibility beats tribal knowledge.

Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

Checkpoint after expensive steps. Resume should not re-bill the same LLM call when an operator retries a later node.

Before promoting the stack, freeze versions, capture a golden transcript for the critical path, and confirm rollback steps. Shared environments need rate limits, tenancy checks, and a clear owner for secret rotation. Prefer boring reliability over clever one-off demos.

Batch note for e49728a65412: keep provider keys out of the repo, set a per-session token ceiling, and store transcripts next to the eval fixtures so later model swaps stay comparable.

For the hardening note 0 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.

Hardening detail 0/726: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 1 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.

Hardening detail 1/726: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

The hardening note 2 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

Hardening detail 2/726: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

For the hardening note 3 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

Hardening detail 3/726: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 4 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

Hardening detail 4/726: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

The hardening note 5 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.

Hardening detail 5/726: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

For the hardening note 6 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Record timings and token or query cost next to functional results. Cost visibility early prevents surprise bills when the path moves from demo to shared environments.

Hardening detail 6/726: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 7 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Document the happy path and the recovery path together. Retries, human gates, and dead-letter handling are part of the product, not later polish.

Hardening detail 7/726: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

The hardening note 8 stage works best when treated as a measurable surface. Capture one golden transcript, one failure case, and the rollback note before expanding scope. Treat this stage as a contract between inputs and validated outputs. Name the artifacts, define success checks, and refuse silent partial completion.

Hardening detail 8/726: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

For the hardening note 9 stage, define the inputs, the owner of the step, and the exit criteria before changing code. Operators should be able to re-run the step from a known checkpoint without guessing hidden state. Keep configuration outside application code. Environment files, secret stores, and feature flags belong in one place operators can audit without reading the whole graph.

Hardening detail 9/726: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.

When working through the hardening note 10 stage, write down the contract first: required inputs, success signal, and what happens on partial failure. That checklist keeps later code changes honest. Prefer small, testable units over sprawling scripts. When a step fails, the failure should point at a single responsibility rather than a tangled pipeline.

Hardening detail 10/726: measure wall time, error class, and token spend for this note, then decide whether to keep the change based on a fixed question set rather than anecdote.