Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 25 min · revision 3

Lab: One Request, Several Tools

Build a tool loop that answers one support request with several tools: run parallel calls concurrently, send every result and error back in the Claude and OpenAI formats, gate a side-effecting tool, and stop at a turn cap. Runs offline against a scripted fake model.

Contentsand lesson path

What you will learn

  • Execute tool calls, including parallel calls, and return results and errors in the provider's message format.

Prerequisites: LLM API Integration

01. Goal and setup

A customer writes: "I was charged twice at Cafe Rio today. Check my balance and recent transactions, and freeze my card if it looks like fraud." Answering takes several tools, and two of them (balance and transactions) do not depend on each other, so a capable model asks for both in one reply. That is a parallel tool call: one assistant turn, two calls, and your code must answer both before the model can continue.

In this lab you build the loop that handles it, for both wire formats. It runs independent calls concurrently, sends every result and error back in the provider's format, turns bad calls into results the model can read, refuses model-chosen accounts and unconfirmed freezes, and stops a model that never stops.

You need: Python 3.12 or later. No packages, no API key and no network: a scripted fake model plays the provider. It returns responses in the real shapes and, like the real APIs, rejects a history in which a tool call has no result. Step 8 shows how to swap in a real client. Wall times are printed in units of the simulated tool latency and rounded, so the trace is the same on every machine.

Project layout at the end of the lab
tool-lab/
├── card_tools.py     step 1: session, tool definitions, handlers
├── runner.py         step 2: validate and run a batch of calls
├── loops.py          step 3: the loop for Claude and for OpenAI
├── fake_models.py    step 4: scripted stand-ins for both APIs
├── scenarios.py      step 4: what the fake model "decides"
├── run_lab.py        step 5: run a scenario and print the trace
├── test_lab.py       step 7: negative tests
└── real_clients.py   step 8: optional, real providers
Terminal
mkdir tool-lab && cd tool-lab

02. Step 1: Tools that cannot be pointed at another account

The tools take no account or user ID. The account comes from a Session that your login code creates; the model never sees it and cannot change it. freeze_card has a side effect, so it checks session.confirmed, which only your user interface can fill (for example when the customer presses a "Freeze card" button). Without confirmation it does nothing and says why. The handlers sleep for 0.3 seconds to stand in for a database call, so you can see the effect of running calls in parallel.

Python · card_tools.py
"""Card-support tools. The account always comes from the session."""
import time
from dataclasses import dataclass, field

LATENCY = 0.3  # seconds; stands in for a database or HTTP call


@dataclass
class Session:
    account_id: str                      # set by your auth layer, not the model
    confirmed: set = field(default_factory=set)  # actions the user approved


TOOLS = [
    {"name": "get_balance",
     "description": "Get the signed-in customer's card balance and pending "
                    "amount. Read-only. Use when asked about balance or "
                    "available funds.",
     "properties": {}, "required": []},
    {"name": "list_transactions",
     "description": "List the signed-in customer's most recent card "
                    "transactions, newest first. Read-only. Use to check "
                    "charges the customer asks about.",
     "properties": {"limit": {"type": "integer",
                              "description": "How many, 1 to 50."}},
     "required": ["limit"]},
    {"name": "freeze_card",
     "description": "Freeze the signed-in customer's card. SIDE EFFECT: the "
                    "card stops working until unfrozen. Needs the customer's "
                    "explicit confirmation; if it is missing the tool returns "
                    "confirmation_required and does nothing.",
     "properties": {"reason": {"type": "string",
                               "enum": ["suspected_fraud", "lost", "other"]}},
     "required": ["reason"]},
]


def get_balance(s: Session) -> dict:
    time.sleep(LATENCY)
    return {"currency": "EUR", "available": "1420.50", "pending": "23.80"}


def list_transactions(s: Session, limit: int) -> list:
    time.sleep(LATENCY)
    rows = [
        {"id": "tx-881", "merchant": "Cafe Rio", "amount": "11.90",
         "time": "12:41"},
        {"id": "tx-880", "merchant": "Cafe Rio", "amount": "11.90",
         "time": "12:41"},
        {"id": "tx-874", "merchant": "Metro", "amount": "2.40",
         "time": "08:05"},
    ]
    return rows[:limit]


def freeze_card(s: Session, reason: str) -> dict:
    if "freeze_card" not in s.confirmed:
        return {"status": "confirmation_required",
                "message": "Not frozen. Ask the customer to confirm the "
                           "freeze, then call freeze_card again."}
    time.sleep(LATENCY)
    return {"status": "frozen", "reason": reason}


HANDLERS = {"get_balance": get_balance,
            "list_transactions": list_transactions,
            "freeze_card": freeze_card}


def to_claude(t: dict) -> dict:
    return {"name": t["name"], "description": t["description"], "strict": True,
            "input_schema": {"type": "object", "properties": t["properties"],
                             "required": t["required"],
                             "additionalProperties": False}}


def to_openai(t: dict) -> dict:
    # Every property here is required, so no null-able types are needed.
    return {"type": "function", "name": t["name"],
            "description": t["description"], "strict": True,
            "parameters": {"type": "object", "properties": t["properties"],
                           "required": t["required"],
                           "additionalProperties": False}}

03. Step 2: Run a batch of calls without crashing

runner.py turns one call into one result, whatever happens. check_args accepts arguments either as an object (Claude) or as a JSON string (OpenAI) and raises ValueError with a message that tells the model what to fix: unknown tool, unexpected or missing argument, wrong type, value outside the enum. Strict mode on the tool definitions makes most of these rare, but the loop must not depend on it: strict mode can be off, a schema feature can be unsupported, and a handler can still fail.

run_batch starts every read-only call in a thread pool, waits for each with a timeout, and only then runs side-effecting calls one at a time, so a freeze does not start until every read has finished or timed out. A read that timed out can still be running in its thread, which is why real tools also need their own timeouts (stretch task 2). Results keep the order of the calls. How you execute calls is your choice; independent reads are the safe case to run in parallel.

Python · runner.py
"""Run a batch of tool calls; never let one failure crash the loop."""
import json
import time
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import TimeoutError as CallTimeout

from card_tools import HANDLERS, TOOLS

SCHEMAS = {t["name"]: t for t in TOOLS}
SIDE_EFFECTS = {"freeze_card"}  # run these one at a time, after the reads
TYPES = {"integer": int, "string": str}


def check_args(name: str, raw) -> dict:
    """Parse and check arguments; raise ValueError with a fixable message."""
    if name not in SCHEMAS:
        raise ValueError(f"Unknown tool {name!r}. Available: "
                         f"{', '.join(SCHEMAS)}.")
    args = json.loads(raw) if isinstance(raw, str) else raw  # OpenAI: str
    if not isinstance(args, dict):
        raise ValueError("Arguments must be a JSON object.")
    spec = SCHEMAS[name]
    extra = set(args) - set(spec["properties"])
    if extra:
        raise ValueError(f"Unexpected argument(s) {sorted(extra)}. The account "
                         "comes from the session; do not pass it.")
    for key in spec["required"]:
        if key not in args:
            raise ValueError(f"Missing required argument {key!r}.")
    for key, value in args.items():
        schema = spec["properties"][key]
        want = TYPES[schema["type"]]
        if not isinstance(value, want) or isinstance(value, bool):
            raise ValueError(f"{key} must be {schema['type']}, got "
                             f"{json.dumps(value)}.")
        if "enum" in schema and value not in schema["enum"]:
            raise ValueError(f"{key} must be one of {schema['enum']}.")
    return args


def run_one(call: dict, session) -> dict:
    """call = {"id", "name", "args"} -> {"id", "ok", "content", "seconds"}"""
    start = time.perf_counter()
    result = _run(call, session)
    result["seconds"] = time.perf_counter() - start
    return result


def _run(call: dict, session) -> dict:
    try:
        args = check_args(call["name"], call["args"])
    except json.JSONDecodeError as e:
        return {"id": call["id"], "ok": False,
                "content": f"Arguments are not valid JSON ({e.msg}). Resend "
                           "the call with a complete JSON object."}
    except ValueError as e:
        return {"id": call["id"], "ok": False, "content": str(e)}
    try:
        result = HANDLERS[call["name"]](session, **args)
    except Exception as e:  # a tool bug must not end the conversation
        return {"id": call["id"], "ok": False,
                "content": f"{call['name']} failed ({type(e).__name__}). "
                           "Tell the customer to try again later."}
    return {"id": call["id"], "ok": True, "content": json.dumps(result)}


def run_batch(calls: list, session, timeout: float = 5.0) -> list:
    """Reads run in parallel, then side effects one by one. Order is kept."""
    pool = ThreadPoolExecutor(max_workers=8)
    reads = {c["id"]: pool.submit(run_one, c, session)
             for c in calls if c["name"] not in SIDE_EFFECTS}
    done = {}
    for call_id, future in reads.items():
        try:
            done[call_id] = future.result(timeout=timeout)
        except CallTimeout:
            done[call_id] = {"id": call_id, "ok": False,
                             "content": f"Timed out after {timeout:.0f} s. "
                                        "Try once more, then give up."}
    pool.shutdown(wait=False, cancel_futures=True)
    for call in calls:
        if call["name"] in SIDE_EFFECTS:
            done[call["id"]] = run_one(call, session)
    return [done[c["id"]] for c in calls]

04. Step 3: The loop, in both wire formats

Both loops take a create function that returns the response as a plain dictionary, so the same code works with the fake and with a real SDK. Read them side by side:

  • Claude: append the whole assistant content (it can include text and thinking blocks as well as tool_use), then one user message with a tool_result block per call, each with its tool_use_id, and "is_error": true on failures. Stop without running anything when stop_reason is max_tokens or refusal, because a cut-off call may have incomplete arguments.
  • OpenAI Responses: append every output item, then one function_call_output item per call with the same call_id. There is no error flag, so a failure is sent as {"error": ...} in the output text. parallel_tool_calls=True is the default; set it to False to get at most one call per reply.

Both loops stop after max_turns model requests. This loop resends the full history every turn; the Responses API could keep it on the server with previous_response_id instead.

Python · loops.py
"""The same tool loop for two wire formats. `create` returns a plain dict."""
import json
import time

from runner import run_batch


def claude_loop(create, model, tools, question, session, max_turns=6,
                on_turn=print):
    messages = [{"role": "user", "content": question}]
    for turn in range(1, max_turns + 1):
        resp = create(model=model, max_tokens=4096, tools=tools,
                      messages=messages)
        # Keep the whole assistant turn: text, tool_use (and thinking) blocks.
        messages.append({"role": "assistant", "content": resp["content"]})
        if resp["stop_reason"] in ("max_tokens", "refusal"):
            return f"stopped: {resp['stop_reason']}"  # never run cut-off calls
        if resp["stop_reason"] != "tool_use":
            return "".join(b["text"] for b in resp["content"]
                           if b["type"] == "text")
        calls = [{"id": b["id"], "name": b["name"], "args": b["input"]}
                 for b in resp["content"] if b["type"] == "tool_use"]
        start = time.perf_counter()
        results = run_batch(calls, session)
        on_turn(turn, calls, results, time.perf_counter() - start)
        blocks = []
        for r in results:
            block = {"type": "tool_result", "tool_use_id": r["id"],
                     "content": r["content"]}
            if not r["ok"]:
                block["is_error"] = True
            blocks.append(block)
        # One user message holds every result of the turn, before any text.
        messages.append({"role": "user", "content": blocks})
    return "stopped: turn cap reached"


def openai_loop(create, model, tools, question, session, max_turns=6,
                on_turn=print):
    items = [{"role": "user", "content": question}]
    for turn in range(1, max_turns + 1):
        resp = create(model=model, tools=tools, input=items,
                      parallel_tool_calls=True)  # the default, shown for clarity
        items += resp["output"]  # the model's calls must stay in the history
        if resp["status"] != "completed":
            return f"stopped: {resp['status']}"
        calls = [{"id": i["call_id"], "name": i["name"], "args": i["arguments"]}
                 for i in resp["output"] if i["type"] == "function_call"]
        if not calls:
            return "".join(part["text"] for i in resp["output"]
                           if i["type"] == "message" for part in i["content"]
                           if part["type"] == "output_text")
        start = time.perf_counter()
        results = run_batch(calls, session)
        on_turn(turn, calls, results, time.perf_counter() - start)
        # No error flag here: an error is a result whose output says so.
        items += [{"type": "function_call_output", "call_id": r["id"],
                   "output": r["content"] if r["ok"]
                   else json.dumps({"error": r["content"]})}
                  for r in results]
    return "stopped: turn cap reached"

05. Step 4: A scripted fake model

The fake replaces the provider. Each scenario is a list of steps; a step receives the latest tool results and returns the next reply, either text or calls. Before replying, the fake checks the history the way the real APIs do: every call needs a matching result, placed after the assistant turn and before any text. Like the real Claude API, it merges consecutive user messages, so split results are accepted (step 5 explains why you should still not split them). A broken history raises ApiError. It also rejects temperature, as current Claude models do.

Python · fake_models.py
"""Scripted stand-ins for the Claude and OpenAI APIs (no network, no key).

Each script step is a function that receives the latest tool results as
{tool_name: (content, is_error)} and returns the parts of the next reply:
("text", "...") or ("call", tool_name, arguments). Like the real APIs,
the fakes reject a history in which a tool call has no matching result.
Like the real Claude API, FakeClaude merges consecutive user messages.
"""
import json


class ApiError(Exception):
    """Stands in for an HTTP 400 from the provider."""


class FakeClaude:
    def __init__(self, script):
        self.script, self.ids, self.sent = iter(script), 0, []

    def create(self, *, model, max_tokens, tools, messages, **extra):
        if "temperature" in extra:  # current Claude models reject it
            raise ApiError("temperature is not supported for this model")
        self.sent.append(json.loads(json.dumps(messages)))  # a snapshot
        results = _claude_results(messages)
        content = []
        for part in next(self.script)(results):
            if part[0] == "text":
                content.append({"type": "text", "text": part[1]})
            else:
                self.ids += 1
                content.append({"type": "tool_use", "id": f"toolu_{self.ids:02d}",
                                "name": part[1], "input": part[2]})
        calls = any(b["type"] == "tool_use" for b in content)
        return {"role": "assistant", "content": content,
                "stop_reason": "tool_use" if calls else "end_turn"}


def _claude_results(messages):
    names, results = {}, {}
    for i, msg in enumerate(messages):
        if msg["role"] != "assistant" or isinstance(msg["content"], str):
            continue
        pending = [b["id"] for b in msg["content"] if b["type"] == "tool_use"]
        if not pending:
            continue
        names.update({b["id"]: b["name"] for b in msg["content"]
                      if b["type"] == "tool_use"})
        # The API merges consecutive user messages into one turn, so collect
        # every block until the next assistant message.
        blocks, j = [], i + 1
        while j < len(messages) and messages[j]["role"] == "user":
            content = messages[j]["content"]
            if isinstance(content, str):
                content = [{"type": "text", "text": content}]
            blocks, j = blocks + content, j + 1
        if not blocks:
            raise ApiError("tool_use ids were found without tool_result "
                           "blocks immediately after")
        kinds = [b["type"] for b in blocks]
        if "text" in kinds and "tool_result" in kinds[kinds.index("text"):]:
            raise ApiError("tool_result blocks must come first")
        answered = [b["tool_use_id"] for b in blocks
                    if b["type"] == "tool_result"]
        if sorted(answered) != sorted(pending):
            raise ApiError(f"missing tool_result for {set(pending) - set(answered)}")
        results = {names[b["tool_use_id"]]: (b["content"], b.get("is_error", False))
                   for b in blocks if b["type"] == "tool_result"}
    return results


class FakeOpenAI:
    def __init__(self, script):
        self.script, self.ids, self.sent = iter(script), 0, []

    def create(self, *, model, tools, input, **extra):
        self.sent.append(json.loads(json.dumps(input)))  # a snapshot
        names, outputs = {}, {}
        for item in input:
            if item.get("type") == "function_call":
                names[item["call_id"]] = item["name"]
            elif item.get("type") == "function_call_output":
                outputs[item["call_id"]] = item["output"]
        missing = set(names) - set(outputs)
        if missing:
            raise ApiError(f"No tool output found for function call {missing}")
        latest = {names[c]: (o, '"error"' in o) for c, o in outputs.items()}
        output = []
        for part in next(self.script)(latest):
            if part[0] == "text":
                output.append({"type": "message", "role": "assistant",
                               "content": [{"type": "output_text",
                                            "text": part[1]}]})
            else:
                self.ids += 1
                args = part[2] if isinstance(part[2], str) else json.dumps(part[2])
                output.append({"type": "function_call", "name": part[1],
                               "call_id": f"call_{self.ids:02d}",
                               "arguments": args})
        return {"status": "completed", "output": output}
Python · scenarios.py
"""What the scripted model 'decides' at each turn of each scenario."""
import itertools

QUESTION = ("I was charged twice at Cafe Rio today. Check my balance and "
            "recent transactions, and freeze my card if it looks like fraud.")


def fraud_final(results):
    content, _ = results["freeze_card"]
    if '"frozen"' in content:
        return [("text", "I found two charges of EUR 11.90 at Cafe Rio at "
                         "12:41 and have frozen your card.")]
    return [("text", "I found two charges of EUR 11.90 at Cafe Rio at 12:41. "
                     "Your card is not frozen yet: please confirm and I will "
                     "freeze it.")]


FRAUD = [
    lambda r: [("text", "I'll check your balance and transactions."),
               ("call", "get_balance", {}),
               ("call", "list_transactions", {"limit": 10})],
    lambda r: [("call", "freeze_card", {"reason": "suspected_fraud"})],
    fraud_final,
]

ERRORS = [
    lambda r: [("call", "list_transactions", {"limit": "ten"}),
               ("call", "get_statement", {}),
               ("call", "freeze_card", {"reason": "suspected_fraud",
                                        "account_id": "ACC-999"})],
    lambda r: [("call", "list_transactions", {"limit": 10})],
    lambda r: [("text", "I can see two charges at Cafe Rio. Shall I freeze "
                        "your card?")],
]

LOOP = itertools.repeat(lambda r: [("call", "get_balance", {})])

SCENARIOS = {"fraud": FRAUD, "errors": ERRORS, "loop": LOOP}

06. Step 5: Run the fraud scenario

run_lab.py wires everything together and prints one block per turn. With --show-wire it also prints the part of the second request that answers turn 1, so you can see the exact format sent back.

Python · run_lab.py
"""Run one scenario against a scripted fake model and print the trace."""
import argparse
import json
import os
import textwrap

from card_tools import LATENCY, TOOLS, Session, to_claude, to_openai
from fake_models import FakeClaude, FakeOpenAI
from loops import claude_loop, openai_loop
from scenarios import QUESTION, SCENARIOS


def show_turn(turn, calls, results, seconds):
    print(f"turn {turn}: {len(calls)} tool call(s) in one response")
    for call, res in zip(calls, results):
        args = call["args"] if isinstance(call["args"], str) \
            else json.dumps(call["args"])
        status = "ok" if res["ok"] else "ERROR"
        print(f"  {call['name']} {args}")
        print(f"    -> {status}: {res['content'][:62].rstrip()}")
    total = sum(r["seconds"] for r in results)
    # In units of LATENCY, rounded, so the trace is the same on every machine:
    # 1 means "about as long as one simulated database call".
    print(f"  wall time {seconds / LATENCY:.0f} x LATENCY "
          f"(calls added up: {total / LATENCY:.0f} x LATENCY)")


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--provider", choices=["claude", "openai"], default="claude")
    p.add_argument("--scenario", choices=sorted(SCENARIOS), default="fraud")
    p.add_argument("--confirm", action="store_true",
                   help="the customer has confirmed the freeze in the UI")
    p.add_argument("--max-turns", type=int, default=6)
    p.add_argument("--show-wire", action="store_true",
                   help="print the tool results sent in the second request")
    a = p.parse_args()
    session = Session(account_id="ACC-100")  # from your login, never the model
    if a.confirm:
        session.confirmed.add("freeze_card")
    script = SCENARIOS[a.scenario]
    if a.provider == "claude":
        fake, loop = FakeClaude(script), claude_loop
        tools = [to_claude(t) for t in TOOLS]
        model = os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5-5")
    else:
        fake, loop = FakeOpenAI(script), openai_loop
        tools = [to_openai(t) for t in TOOLS]
        model = os.environ.get("OPENAI_MODEL", "gpt-6-astra")
    print(f"provider={a.provider} scenario={a.scenario} model={model} (fake)")
    answer = loop(fake.create, model, tools, QUESTION, session,
                  max_turns=a.max_turns, on_turn=show_turn)
    print(textwrap.fill(f"final: {answer}", 78, subsequent_indent="  "))
    print(f"model requests: {len(fake.sent)}")
    if a.show_wire and len(fake.sent) > 1:
        print("tool results in request 2:")
        print(wire(fake.sent[1], a.provider))


def wire(sent, provider):
    """The part of request 2 that answers turn 1, with long text cut."""
    if provider == "claude":
        part = sent[-1]  # the last message: one user message
    else:
        part = [i for i in sent if i.get("type") == "function_call_output"]
    return "\n".join(cut(line) for line in
                     json.dumps(part, indent=1).splitlines())


def cut(line, width=66):
    if len(line) <= width:
        return line
    comma = "," if line.endswith(",") else ""
    return line[:width - 6].rstrip("\\") + '..."' + comma


if __name__ == "__main__":
    main()
Terminal
python3 run_lab.py --show-wire
Expected output
provider=claude scenario=fraud model=claude-sonnet-5-5 (fake)
turn 1: 2 tool call(s) in one response
  get_balance {}
    -> ok: {"currency": "EUR", "available": "1420.50", "pending": "23.80"
  list_transactions {"limit": 10}
    -> ok: [{"id": "tx-881", "merchant": "Cafe Rio", "amount": "11.90", "
  wall time 1 x LATENCY (calls added up: 2 x LATENCY)
turn 2: 1 tool call(s) in one response
  freeze_card {"reason": "suspected_fraud"}
    -> ok: {"status": "confirmation_required", "message": "Not frozen. As
  wall time 0 x LATENCY (calls added up: 0 x LATENCY)
final: I found two charges of EUR 11.90 at Cafe Rio at 12:41. Your card is not
  frozen yet: please confirm and I will freeze it.
model requests: 3
tool results in request 2:
{
 "role": "user",
 "content": [
  {
   "type": "tool_result",
   "tool_use_id": "toolu_01",
   "content": "{\"currency\": \"EUR\", \"available\": \"1420..."
  },
  {
   "type": "tool_result",
   "tool_use_id": "toolu_02",
   "content": "[{\"id\": \"tx-881\", \"merchant\": \"Cafe Ri..."
  }
 ]
}

Read the trace from the top. In turn 1 the model asked for two tools in one response, and both results went back in one user message: two tool_result blocks with the ids toolu_01 and toolu_02. Splitting them over two messages is a common bug; Anthropic's parallel tool use guide warns that it teaches the model to stop making parallel calls. The two calls ran concurrently: one LATENCY (0.3 s) of wall time instead of two. In general, parallel execution brings a turn down to roughly its slowest call rather than the sum of all calls.

In turn 2 the model tried to freeze the card. Nothing happened, because the customer had not confirmed, and the tool said so in a normal result: it is an outcome, not an error. The model then asked the customer.

Now run the same scenario in the OpenAI format.

Terminal
python3 run_lab.py --provider openai --show-wire
Expected output
provider=openai scenario=fraud model=gpt-6-astra (fake)
turn 1: 2 tool call(s) in one response
  get_balance {}
    -> ok: {"currency": "EUR", "available": "1420.50", "pending": "23.80"
  list_transactions {"limit": 10}
    -> ok: [{"id": "tx-881", "merchant": "Cafe Rio", "amount": "11.90", "
  wall time 1 x LATENCY (calls added up: 2 x LATENCY)
turn 2: 1 tool call(s) in one response
  freeze_card {"reason": "suspected_fraud"}
    -> ok: {"status": "confirmation_required", "message": "Not frozen. As
  wall time 0 x LATENCY (calls added up: 0 x LATENCY)
final: I found two charges of EUR 11.90 at Cafe Rio at 12:41. Your card is not
  frozen yet: please confirm and I will freeze it.
model requests: 3
tool results in request 2:
[
 {
  "type": "function_call_output",
  "call_id": "call_01",
  "output": "{\"currency\": \"EUR\", \"available\": \"1420.5..."
 },
 {
  "type": "function_call_output",
  "call_id": "call_02",
  "output": "[{\"id\": \"tx-881\", \"merchant\": \"Cafe Rio..."
 }
]

Each request carries the whole history, so one request's context grows linearly with the turns, while the total input tokens you pay for over a task grow roughly with their square. Parallel calls mean fewer turns and less waiting per turn.

07. Step 6: Errors, confirmation and a runaway model

The errors scenario sends three bad calls at once: a wrong type, a tool that does not exist, and a freeze that tries to name another account.

Terminal
python3 run_lab.py --scenario errors --show-wire
Expected output
provider=claude scenario=errors model=claude-sonnet-5-5 (fake)
turn 1: 3 tool call(s) in one response
  list_transactions {"limit": "ten"}
    -> ERROR: limit must be integer, got "ten".
  get_statement {}
    -> ERROR: Unknown tool 'get_statement'. Available: get_balance, list_tra
  freeze_card {"reason": "suspected_fraud", "account_id": "ACC-999"}
    -> ERROR: Unexpected argument(s) ['account_id']. The account comes from
  wall time 0 x LATENCY (calls added up: 0 x LATENCY)
turn 2: 1 tool call(s) in one response
  list_transactions {"limit": 10}
    -> ok: [{"id": "tx-881", "merchant": "Cafe Rio", "amount": "11.90", "
  wall time 1 x LATENCY (calls added up: 1 x LATENCY)
final: I can see two charges at Cafe Rio. Shall I freeze your card?
model requests: 3
tool results in request 2:
{
 "role": "user",
 "content": [
  {
   "type": "tool_result",
   "tool_use_id": "toolu_01",
   "content": "limit must be integer, got \"ten\".",
   "is_error": true
  },
  {
   "type": "tool_result",
   "tool_use_id": "toolu_02",
   "content": "Unknown tool 'get_statement'. Available: get_...",
   "is_error": true
  },
  {
   "type": "tool_result",
   "tool_use_id": "toolu_03",
   "content": "Unexpected argument(s) ['account_id']. The ac...",
   "is_error": true
  }
 ]
}

Every call got an answer marked "is_error": true, the loop kept going, and the model fixed the call it could fix. The attempt to pass account_id was refused by the argument check, so no prompt, however persuasive, can point this tool at account ACC-999. Run the same scenario with --provider openai and compare: the results arrive as function_call_output items whose output starts with {"error": ...}.

With --confirm the session holds the customer's approval and the freeze goes through. In the loop scenario the model calls get_balance forever until the turn cap stops it.

Terminal
python3 run_lab.py --confirm
python3 run_lab.py --scenario loop --max-turns 3
Expected output
provider=claude scenario=fraud model=claude-sonnet-5-5 (fake)
turn 1: 2 tool call(s) in one response
  get_balance {}
    -> ok: {"currency": "EUR", "available": "1420.50", "pending": "23.80"
  list_transactions {"limit": 10}
    -> ok: [{"id": "tx-881", "merchant": "Cafe Rio", "amount": "11.90", "
  wall time 1 x LATENCY (calls added up: 2 x LATENCY)
turn 2: 1 tool call(s) in one response
  freeze_card {"reason": "suspected_fraud"}
    -> ok: {"status": "frozen", "reason": "suspected_fraud"}
  wall time 1 x LATENCY (calls added up: 1 x LATENCY)
final: I found two charges of EUR 11.90 at Cafe Rio at 12:41 and have frozen
  your card.
model requests: 3
provider=claude scenario=loop model=claude-sonnet-5-5 (fake)
turn 1: 1 tool call(s) in one response
  get_balance {}
    -> ok: {"currency": "EUR", "available": "1420.50", "pending": "23.80"
  wall time 1 x LATENCY (calls added up: 1 x LATENCY)
turn 2: 1 tool call(s) in one response
  get_balance {}
    -> ok: {"currency": "EUR", "available": "1420.50", "pending": "23.80"
  wall time 1 x LATENCY (calls added up: 1 x LATENCY)
turn 3: 1 tool call(s) in one response
  get_balance {}
    -> ok: {"currency": "EUR", "available": "1420.50", "pending": "23.80"
  wall time 1 x LATENCY (calls added up: 1 x LATENCY)
final: stopped: turn cap reached
model requests: 3

08. Step 7: Negative tests

Write the failure cases down as tests, so a later refactor cannot quietly remove a safeguard. Each test below attacks one rule: no freeze without confirmation, no model-chosen account, no crash on broken JSON or on a failing tool, errors marked and grouped in one message, a missing result rejected, and a turn cap that holds. One more test checks that the fake, like the API, accepts split results. The sed at the end of the command removes the run time from the Ran 8 tests line, because it differs on every run.

Python · test_lab.py
"""Negative tests: the loop must fail safely, not crash or overreach."""
import json
import unittest

import runner
from card_tools import TOOLS, Session, to_claude
from fake_models import ApiError, FakeClaude
from loops import claude_loop
from scenarios import ERRORS, LOOP, QUESTION

TOOLS_C = [to_claude(t) for t in TOOLS]


def quiet(*args):
    pass


class LabTests(unittest.TestCase):
    def call(self, name, args):
        return runner.run_batch([{"id": "c1", "name": name, "args": args}],
                                Session("ACC-100"))[0]

    def test_freeze_needs_confirm(self):
        res = self.call("freeze_card", {"reason": "lost"})
        self.assertIn("confirmation_required", res["content"])

    def test_model_cannot_pick_account(self):
        res = self.call("freeze_card", {"reason": "lost", "account_id": "X"})
        self.assertFalse(res["ok"])

    def test_bad_json(self):
        res = self.call("list_transactions", '{"limit": 5')
        self.assertFalse(res["ok"])
        self.assertIn("not valid JSON", res["content"])

    def test_tool_crash(self):
        def broken(session):
            raise ConnectionError("db down")
        original = runner.HANDLERS["get_balance"]
        runner.HANDLERS["get_balance"] = broken
        try:
            res = self.call("get_balance", {})
        finally:
            runner.HANDLERS["get_balance"] = original
        self.assertFalse(res["ok"])
        self.assertIn("ConnectionError", res["content"])

    def test_errors_in_one_message(self):
        fake = FakeClaude(ERRORS)
        claude_loop(fake.create, "m", TOOLS_C, QUESTION, Session("ACC-100"),
                    on_turn=quiet)
        reply = fake.sent[1][-1]
        self.assertEqual(reply["role"], "user")
        self.assertEqual([b.get("is_error") for b in reply["content"]],
                         [True, True, True])

    def test_missing_result_rejected(self):
        history = [{"role": "user", "content": "hi"},
                   {"role": "assistant", "content": [
                       {"type": "tool_use", "id": "t1", "name": "get_balance",
                        "input": {}}]},
                   {"role": "user", "content": [{"type": "text", "text": "?"}]}]
        with self.assertRaises(ApiError):
            FakeClaude(LOOP).create(model="m", max_tokens=10, tools=TOOLS_C,
                                    messages=history)

    def test_split_results_accepted(self):
        history = [{"role": "user", "content": "hi"},
                   {"role": "assistant", "content": [
                       {"type": "tool_use", "id": "t1", "name": "get_balance",
                        "input": {}},
                       {"type": "tool_use", "id": "t2", "name": "get_balance",
                        "input": {}}]},
                   {"role": "user", "content": [{"type": "tool_result",
                                                 "tool_use_id": "t1",
                                                 "content": "{}"}]},
                   {"role": "user", "content": [{"type": "tool_result",
                                                 "tool_use_id": "t2",
                                                 "content": "{}"}]}]
        reply = FakeClaude(LOOP).create(model="m", max_tokens=10, tools=TOOLS_C,
                                        messages=history)
        self.assertEqual(reply["stop_reason"], "tool_use")  # accepted

    def test_turn_cap(self):
        answer = claude_loop(FakeClaude(LOOP).create, "m", TOOLS_C, QUESTION,
                             Session("ACC-100"), max_turns=2, on_turn=quiet)
        self.assertEqual(answer, "stopped: turn cap reached")


if __name__ == "__main__":
    unittest.main(verbosity=1)
Terminal
python3 -m unittest -v test_lab 2>&1 | sed -E 's/ in [0-9.]+s$//'
Expected output (Python 3.12)
test_bad_json (test_lab.LabTests.test_bad_json) ... ok
test_errors_in_one_message (test_lab.LabTests.test_errors_in_one_message) ... ok
test_freeze_needs_confirm (test_lab.LabTests.test_freeze_needs_confirm) ... ok
test_missing_result_rejected (test_lab.LabTests.test_missing_result_rejected) ... ok
test_model_cannot_pick_account (test_lab.LabTests.test_model_cannot_pick_account) ... ok
test_split_results_accepted (test_lab.LabTests.test_split_results_accepted) ... ok
test_tool_crash (test_lab.LabTests.test_tool_crash) ... ok
test_turn_cap (test_lab.LabTests.test_turn_cap) ... ok

----------------------------------------------------------------------
Ran 8 tests

OK

09. Step 8 (optional): Use a real provider

The loops only need a create function that returns a dictionary. Both official SDKs return response objects with a to_dict() method, so the adapters are short. They need an API key and the provider's SDK, and cost money, so they were not run for this lesson. Set the model in an environment variable, for example ANTHROPIC_MODEL=claude-sonnet-5-5, and do not send temperature. A real trace will differ from the fake's.

Python · real_clients.py (not run here: needs an API key)
"""Real `create` functions for loops.py. Needs a key; costs money.

    from real_clients import claude_create
    claude_loop(claude_create(), os.environ["ANTHROPIC_MODEL"], tools, ...)
"""


def claude_create():
    import anthropic  # pip install anthropic; reads ANTHROPIC_API_KEY
    client = anthropic.Anthropic()
    return lambda **req: client.messages.create(**req).to_dict()


def openai_create():
    from openai import OpenAI  # pip install openai; reads OPENAI_API_KEY
    client = OpenAI()
    return lambda **req: client.responses.create(**req).to_dict()

10. Check your understanding

Practice check · 3 questions

Reading the loop

Use the code you wrote in this lab to answer. Each question has one best answer.

Q1. A teammate changes `claude_loop` to send each `tool_result` in its own user message. The API still accepts it. What is the problem?
Q2. In one turn the model lists two calls: `freeze_card` first, then `list_transactions`. In what order does `run_batch` run them?
Q3. In the OpenAI loop a call fails validation. How does the model learn that it failed?
Practice only: not graded, not saved, not evidence.

11. Apply it: stretch tasks

  1. Order tools. Replace the card tools with the three tools of the practice project (look up an order, list a customer's orders, request a refund) and write a scenario in which the model looks up two orders in parallel and one of them does not exist.
  2. Real timeout. Give get_balance a 10-second sleep, call run_batch with timeout=1, and check that the model receives a timeout error while the other result still arrives. Note that the slow thread keeps running in the background: real code also needs a timeout inside the tool.
  3. Chat Completions. Write a third loop for the Chat Completions format (tool_calls on the assistant message, results as role: "tool" messages) and a matching fake.

12. Review prompt

Without looking back:

  1. What must the request after a parallel tool call contain, for Claude and for the OpenAI Responses API?
  2. How does each provider learn that a tool failed?
  3. Which calls in a batch is it safe to run concurrently, and why does run_batch run side effects last?
  4. Name three things the loop does so that one bad call or a looping model cannot crash or stall it.
  5. How does this design stop the model from acting on another customer's account?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check