Multi-Agent Systems and Workflow Orchestration / Start Here

Watch a multi-agent run before taking it apart

Lesson 3 of 43. Open to read. No account needed.

What You Will Do

Before building anything, you will watch a small team of agents handle one customer ticket from start to finish. A supervisor decides which specialist should work on the ticket next; a shipping specialist checks the delivery; a billing specialist works out a refund; and the refund is not paid but queued for a person's approval. You will run it, read what it prints, change one decision and predict the result.

The point is to see the shape of the whole system before taking it apart. This lesson's script is deliberately simple and does not show how to build each part well; the following lessons rebuild each part properly. You do not need to understand every line of the script yet.

Quillfield Cycles' Records

The course's fictional shop keeps its records in a SQLite file: a whole database in one ordinary file, read and written with Python's built-in sqlite3 module (S22). The shop has eight products, such as a road tyre and a pair of disc brake pads, and twelve orders with IDs from A-1001 to A-1012, each with a status (packing, shipped, delivered or cancelled). Customers appear only as IDs.

The file kit/shop.py creates these records and gives agents two read-only tools: order_status (an order's status and order date) and order_details (its items, prices and total). Each tool is a plain dictionary holding a description for the model, a description of the input it accepts, and the Python function that does the work. That is all a tool is: a function the agent's code will run when the model asks for it.

Exercise: Run the Demo

Goal: save the shop module and the demo, run the demo, then change one decision and predict the new run before you rerun it.

Starting state: the course environment from the setup lesson, activated. Check that kit is importable:

python -c "import kit; print('kit ready')"

Effects: adds kit/shop.py (kept for later lessons) and creates an exercise folder with the demo and a small shop.sqlite3 file. Runs take well under a second; nothing leaves your computer.

  1. Save this as kit/shop.py in your practice folder:

    """Quillfield Cycles, a fictional online bicycle-parts shop, and its read-only tools.
    
    create_shop() writes the shop's records to a SQLite file. shop_tools() returns
    the tools agents may call, as plain dictionaries: a description and a JSON
    Schema for the model, and the Python function that does the work.
    """
    import sqlite3
    from pathlib import Path
    
    PRODUCTS = [
        ("QC-CHAIN-11", "11-speed chain", 32.00),
        ("QC-PADS-DISC", "Disc brake pads (pair)", 18.00),
        ("QC-TUBE-700", "Inner tube 700x28", 7.50),
        ("QC-TYRE-700", "Road tyre 700x28", 42.50),
        ("QC-LIGHT-SET", "Front and rear light set", 36.00),
        ("QC-PUMP-MINI", "Mini pump", 21.00),
        ("QC-GRIPS", "Lock-on grips", 16.00),
        ("QC-BELL", "Bell", 9.00),
    ]
    
    # order_id, customer_id, status, placed_on, [(sku, quantity), ...]
    ORDERS = [
        ("A-1001", "C-2001", "delivered", "2026-09-28", [("QC-TYRE-700", 1)]),
        ("A-1002", "C-2002", "delivered", "2026-09-30", [("QC-PADS-DISC", 1)]),
        ("A-1003", "C-2003", "shipped", "2026-10-12", [("QC-CHAIN-11", 1), ("QC-BELL", 1)]),
        ("A-1004", "C-2001", "packing", "2026-10-15", [("QC-LIGHT-SET", 1)]),
        ("A-1005", "C-2004", "delivered", "2026-10-02", [("QC-TUBE-700", 2), ("QC-PUMP-MINI", 1)]),
        ("A-1006", "C-2005", "cancelled", "2026-10-03", [("QC-GRIPS", 1)]),
        ("A-1007", "C-2006", "shipped", "2026-10-14", [("QC-TYRE-700", 2)]),
        ("A-1008", "C-2002", "delivered", "2026-10-05", [("QC-LIGHT-SET", 1), ("QC-BELL", 1)]),
        ("A-1009", "C-2007", "packing", "2026-10-16", [("QC-PADS-DISC", 2)]),
        ("A-1010", "C-2008", "delivered", "2026-10-07", [("QC-CHAIN-11", 1)]),
        ("A-1011", "C-2003", "shipped", "2026-10-13", [("QC-PUMP-MINI", 1), ("QC-TUBE-700", 1)]),
        ("A-1012", "C-2009", "delivered", "2026-10-09", [("QC-GRIPS", 2)]),
    ]
    
    
    def create_shop(path):
        """Create (or recreate) the shop's records in the SQLite file at path."""
        path = Path(path)
        path.unlink(missing_ok=True)
        with sqlite3.connect(path) as db:
            db.execute("create table products (sku text primary key, name text, price real)")
            db.execute("create table orders (order_id text primary key, customer_id text,"
                       " status text, placed_on text)")
            db.execute("create table order_lines (order_id text, sku text, quantity integer)")
            db.executemany("insert into products values (?, ?, ?)", PRODUCTS)
            for order_id, customer_id, status, placed_on, lines in ORDERS:
                db.execute("insert into orders values (?, ?, ?, ?)", (order_id, customer_id, status, placed_on))
                db.executemany("insert into order_lines values (?, ?, ?)",
                               [(order_id, sku, quantity) for sku, quantity in lines])
        return path
    
    
    def shop_tools(path):
        """Return the shop's read-only tools, each reading the SQLite file at path."""
    
        def query(sql, *args):
            with sqlite3.connect(path) as db:
                return db.execute(sql, args).fetchall()
    
        def order_status(order_id):
            rows = query("select status, placed_on from orders where order_id = ?", order_id)
            if not rows:
                raise LookupError(f"unknown order {order_id}; order IDs look like A-1001")
            status, placed_on = rows[0]
            return {"order_id": order_id, "status": status, "placed_on": placed_on}
    
        def order_details(order_id):
            order_status(order_id)  # raises the same helpful error for an unknown ID
            lines = query("select l.sku, p.name, l.quantity, p.price from order_lines l"
                          " join products p on p.sku = l.sku where l.order_id = ?", order_id)
            items = [{"sku": sku, "name": name, "quantity": qty, "price": price}
                     for sku, name, qty, price in lines]
            total = round(sum(item["quantity"] * item["price"] for item in items), 2)
            return {"order_id": order_id, "items": items, "total": total}
    
        order_id_schema = {
            "type": "object",
            "properties": {"order_id": {"type": "string", "description": "An order ID such as A-1001"}},
            "required": ["order_id"],
            "additionalProperties": False,
        }
        return {
            "order_status": {"description": "Look up an order's status and the date it was placed.",
                             "input_schema": order_id_schema, "fn": order_status},
            "order_details": {"description": "List an order's items, quantities, prices and total.",
                              "input_schema": order_id_schema, "fn": order_details},
        }
    
  2. Create the exercise folder and move into it:

    mkdir -p ~/multi-agent-practice/watch-a-run
    cd ~/multi-agent-practice/watch-a-run
    

    Save this as demo_run.py in it:

    """A preview: a supervisor and two specialist agents handle one support ticket.
    
    Every "model" here is a script of decisions, so the run is the same each time.
    The course rebuilds each part properly in later lessons; this file only lets
    you watch the whole thing work first.
    """
    import sqlite3
    from pathlib import Path
    
    from kit.shop import create_shop, shop_tools
    
    TICKET = {"id": "T-0042", "order_id": "A-1002",
              "text": "My brake pads arrived with a cracked backing plate. Can I have my money back?"}
    
    # What each agent's scripted model decides, one entry per turn.
    SUPERVISOR_SCRIPT = ["shipping", "billing", "finish"]
    SPECIALIST_SCRIPTS = {
        "shipping": [("tool", "order_status"),
                     ("answer", "Delivered on 2026-09-30 with no carrier claim; the damage is a product fault.")],
        "billing": [("tool", "order_details"),
                    ("refund", None),
                    ("answer", "The order total is refundable under the faulty-goods policy.")],
    }
    
    pending_approvals = []
    
    
    def run_specialist(name, tools, depth):
        """Follow one specialist's script, printing each step indented under it."""
        for kind, value in SPECIALIST_SCRIPTS[name]:
            if kind == "tool":
                result = tools[value]["fn"](order_id=TICKET["order_id"])
                shown = result.get("status") or f"total {result['total']}"
                print("  " * depth + f"{name}: tool {value}({TICKET['order_id']}) -> {shown}")
            elif kind == "refund":
                total = tools["order_details"]["fn"](order_id=TICKET["order_id"])["total"]
                pending_approvals.append({"ticket": TICKET["id"], "order_id": TICKET["order_id"], "amount": total})
                print("  " * depth + f"{name}: action refund {total:.2f} -> waiting for approval")
            elif kind == "answer":
                print("  " * depth + f'{name}: "{value}"')
                return value
        return "REFUSE: the script ended without an answer"
    
    
    def main():
        db = create_shop(Path("shop.sqlite3"))
        tools = shop_tools(db)
        with sqlite3.connect(db) as conn:
            orders, products = (conn.execute(f"select count(*) from {table}").fetchone()[0]
                                for table in ("orders", "products"))
        print(f"shop records: {orders} orders, {products} products")
        print(f"run {TICKET['id']}: {TICKET['text']}")
        for decision in SUPERVISOR_SCRIPT:
            if decision == "finish":
                print("  supervisor: finish")
                break
            print(f"  supervisor -> {decision}")
            answer = run_specialist(decision, tools, depth=2)
            if answer.startswith("REFUSE"):
                print("  supervisor: escalate to a person")
                break
        print("pending approvals:", pending_approvals or "none")
    
    
    if __name__ == "__main__":
        main()
    
  3. Run it:

    python demo_run.py
    

    Output (exact; the run is scripted, so it is the same every time):

    shop records: 12 orders, 8 products
    run T-0042: My brake pads arrived with a cracked backing plate. Can I have my money back?
      supervisor -> shipping
        shipping: tool order_status(A-1002) -> delivered
        shipping: "Delivered on 2026-09-30 with no carrier claim; the damage is a product fault."
      supervisor -> billing
        billing: tool order_details(A-1002) -> total 18.0
        billing: action refund 18.00 -> waiting for approval
        billing: "The order total is refundable under the faulty-goods policy."
      supervisor: finish
    pending approvals: [{'ticket': 'T-0042', 'order_id': 'A-1002', 'amount': 18.0}]
    

Success: the shop reports 12 orders and 8 products, the supervisor consults shipping and then billing, and exactly one refund of 18.00 waits for approval. That shows the team, its tools and its approval step all working on one ticket.

Reading the Run

The output is a run tree: each indented line happened inside the line above it. Read it from the top.

  • The supervisor sends the ticket to shipping first. Shipping calls the order_status tool and learns the order was delivered, so the damage is not a delivery problem, and it answers in words.
  • The supervisor then sends the ticket to billing. Billing calls order_details, finds the total of 18.00 and proposes a refund. The refund is a consequential action: it would move money. So instead of happening, it is added to pending_approvals, where a person will decide later.
  • The supervisor finishes. Nothing has been paid; one decision is waiting.

Every agent in this run follows a script: a fixed list of decisions in SUPERVISOR_SCRIPT and SPECIALIST_SCRIPTS. In a real system a language model would make each decision. Scripts make the run identical every time, which is what lets you predict a change exactly.

The Parts You Will Rebuild

Part of the demoWhat is missing hereWhere the course builds it properly
Each specialist following a listA real agent loop with tool requests and resultsThe bridge module (lessons 4 and 5)
The supervisor's fixed listChoosing the next specialist from what has happened, with limitsCoordinating Agents
Strings passed between agentsChecked, versioned contractsState, Context and Contracts
One specialist after anotherSpecialists working at the same timeRunning Agents Concurrently
pending_approvals kept in memoryApproval that survives the program endingDurability and Human Approval
print linesA recorded trace with timing and costObservability

Change One Decision

Open demo_run.py in your editor and change the supervisor's script so it skips shipping:

SUPERVISOR_SCRIPT = ["billing", "finish"]

Before rerunning, predict: which lines disappear, and does the refund still wait for approval? Then run python demo_run.py again and compare. Change the line back when you are done.

Your Turn: Make Billing Refuse

Change billing's script so it refuses the ticket instead of proposing a refund: replace billing's three steps with one answer that starts with REFUSE:, for example "REFUSE: a refund needs a photo of the damage first." Predict what the supervisor does and what pending approvals shows, then run it. The answer is below.

Reset and Clean Up

Keep kit/shop.py: lessons 4 onwards use it. Remove only the exercise folder:

cd ~/multi-agent-practice
case "$PWD" in */multi-agent-practice) rm -rf watch-a-run ;; *) echo "not in the practice folder" ;; esac

PowerShell:

cd ~/multi-agent-practice
if ((Get-Location).Path -like "*multi-agent-practice") { Remove-Item -Recurse -Force watch-a-run }

Check Your Understanding

  1. Why did the refund not happen during the run?
  2. The demo's specialists run one after the other. Name one reason a real system might want them to run at the same time, and one reason that adds difficulty.
  3. Why does the demo use scripts rather than a real model, and what can it therefore not tell you?

Answer and Reasoning

Change one decision. The two shipping lines disappear: the supervisor never consults shipping. The billing lines are unchanged, and the refund of 18.00 still waits for approval, because billing does not depend on shipping in this script.

Your turn. The run prints billing's refusal, then supervisor: escalate to a person, and ends with pending approvals: none: billing never reached the refund step, and the supervisor stopped instead of finishing. In the full course, escalation to a person is a defined outcome you design for, not an accident.

Understanding check.

  1. A refund moves money, so the design puts it in a queue for a person to approve instead of letting an agent do it directly. Lesson 29 makes that queue survive the program ending.
  2. Running them at the same time finishes sooner when each waits on a slow model or service. It adds difficulty because their results can arrive in any order, one can fail while others succeed, and they may try to update the same information at once.
  3. Scripts make every run identical, so you can predict a change and check it exactly, offline and free. They cannot tell you whether a real model would make the same decisions, how good those decisions would be, or what a run would really cost.

References

38 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy