MAX guide 23 min read

LLM Tool Calling: Write Tool Descriptions and Build the Loop for Claude and OpenAI

Max, hands on hips, beside two empty boxes, a red cross on the return arrow, a green check: "send the error back as a result"

How does LLM tool calling work, and how do you build the loop and write the tool descriptions?

In LLM tool calling, the model asks for a tool, a function your code offers it; your code runs it and sends the result back, and this repeats until the model answers in text.

It lets a model look things up, here at a city library: one tool finds a book’s ISBN, another checks the shelf. On a MacBook Air M3 the loop ran for Claude and OpenAI against a fake API; when we broke it on purpose, our checks caught every break.

No model answered in our run: a fake API returned replies we wrote after the vendors’ documentation examples. It proves the messages your code sends, not what a real model or API does.

This guide belongs to tool use in prompts, also called function calling: our function calling explainer explains it, here you build it.

Vendor details below are from the vendors’ documentation, read on 4 December 2026.

Step 1: Install and define the tools

A tool definition is a name, a description the model reads, and a schema: the inputs and their types, written in json schema. requirements.txt fixes the versions of the SDKs (the vendors’ Python libraries) and of jsonschema, which checks inputs against a schema:

anthropic==2.17.0
openai==3.63.0
jsonschema==4.26.0
# pulled in by the SDKs (pinned from pip freeze): httpx2==2.17.2, pydantic==2.14.4, pydantic_core==2.50.5, referencing==0.37.0, jsonschema-specifications==2025.9.1

On Python 3.14.6 the three scripts ran in 1.7 s. From tools.py (whole at the end), both tools in each API’s shape:

TOOLS = [
    {'name': 'search_books',
     'description': 'Call this when the user names a book by title or author. Returns matching books with their ISBN. '
                    'Do NOT use it to check availability.',
     'schema': {'type': 'object',
                'properties': {'query': {'type': 'string', 'description': 'Title or author words, e.g. "Dune"'}},
                'required': ['query'], 'additionalProperties': False}},
    {'name': 'get_book_availability',
     'description': 'Call this only with an ISBN from search_books. Returns whether the city library has a copy on the shelf.',
     'schema': {'type': 'object',
                'properties': {'isbn': {'type': 'string', 'pattern': '^97[89][0-9]{10}$', 'description': 'ISBN-13, digits only'}},
                'required': ['isbn'], 'additionalProperties': False}},
]
BY_NAME = {t['name']: t for t in TOOLS}


def anthropic_tools():
    return [{'name': t['name'], 'description': t['description'], 'input_schema': t['schema']} for t in TOOLS]


def openai_responses_tools():  # flat shape, strict as the docs recommend
    return [{'type': 'function', 'name': t['name'], 'description': t['description'], 'parameters': t['schema'], 'strict': True} for t in TOOLS]


def openai_chat_tools():  # nested shape: function.parameters
    return [{'type': 'function', 'function': {'name': t['name'], 'description': t['description'], 'parameters': t['schema']}} for t in TOOLS]

Step 2: Write descriptions, test the schema

Anthropic’s tool definition guide calls the description “by far the most important factor in tool performance”. Our pattern, from its advice and OpenAI’s:

  • when to call the tool;
  • what each input means, with its format;
  • when not to call it.

check_schema.py checks both schemas against a JSON Schema draft (a version of the standard), then tries inputs:

'''Do the two tool schemas validate (Draft 2020-12)? Does a bare "string" accept isbn="Dune"? The pattern is what rejects it.'''
import copy
import jsonschema
from tools import TOOLS, BY_NAME, DUNE_ISBN

for t in TOOLS:
    jsonschema.Draft202012Validator.check_schema(t['schema'])
print('schemas valid (Draft 2020-12):', [t['name'] for t in TOOLS])

with_pattern = jsonschema.Draft202012Validator(BY_NAME['get_book_availability']['schema'])
bare_schema = copy.deepcopy(BY_NAME['get_book_availability']['schema'])
del bare_schema['properties']['isbn']['pattern']
bare = jsonschema.Draft202012Validator(bare_schema)


def verdict(v, args):
    errors = [e.message for e in v.iter_errors(args)]
    return 'PASS' if not errors else 'FAIL ' + errors[0]


for label, args in [('good ISBN', {'isbn': DUNE_ISBN}), ('isbn="Dune"', {'isbn': 'Dune'}), ('isbn missing', {}),
                    ('extra key', {'isbn': DUNE_ISBN, 'title': 'Dune'}), ('isbn as number', {'isbn': int(DUNE_ISBN)})]:
    print(f'{label:15} with pattern: {verdict(with_pattern, args)}')
    print(f'{"":15} bare string:  {verdict(bare, args)}')
schemas valid (Draft 2020-12): ['search_books', 'get_book_availability']
good ISBN       with pattern: PASS
                bare string:  PASS
isbn="Dune"     with pattern: FAIL 'Dune' does not match '^97[89][0-9]{10}$'
                bare string:  PASS
isbn missing    with pattern: FAIL 'isbn' is a required property
                bare string:  FAIL 'isbn' is a required property
extra key       with pattern: FAIL Additional properties are not allowed ('title' was unexpected)
                bare string:  FAIL Additional properties are not allowed ('title' was unexpected)
isbn as number  with pattern: FAIL 9780441172719 is not of type 'string'
                bare string:  FAIL 9780441172719 is not of type 'string'

A bare string accepts isbn="Dune"; the pattern rejects it. Keep ^ (start) and $ (end): without them, a pattern matches anywhere in the value.

Step 3: Build the loop for Claude

stop_reason says why Claude stopped: tool_use asks for a tool; anything else ends the loop. QUESTION is the question, execute (below) runs a tool, fail_tool makes it fail for a test. max_turns caps the rounds; is_error: true marks a failed call. “docs step” cites Anthropic’s rules for tool results:

def run_loop(client, fail_tool=None, max_turns=6):
    messages = [{'role': 'user', 'content': QUESTION}]
    for _ in range(max_turns):
        r = client.messages.create(model='claude-opus-5-5', max_tokens=1024, tools=anthropic_tools(), messages=messages)
        if r.stop_reason != 'tool_use':
            return r
        messages.append({'role': 'assistant', 'content': r.content})  # the response content, unchanged (docs step 2)
        results = []
        for b in (b for b in r.content if b.type == 'tool_use'):
            out, is_error = execute(b.name, b.input, down=(b.name == fail_tool))
            results.append({'type': 'tool_result', 'tool_use_id': b.id, 'content': out, **({'is_error': True} if is_error else {})})
        messages.append({'role': 'user', 'content': results})  # one tool_result per tool_use, first in the message (docs step 3)
    raise RuntimeError('too many turns')

The rules: the reply goes back unchanged as an assistant message, then ONE user message whose first blocks are the tool_result blocks, one per tool_use block (the call), each carrying its tool_use_id. Anthropic allows text after the results but warns against it; our code adds none.

Our script prints each request after the first. Without errors:

== happy: 3 requests, final: 'Yes: 2 copies of Dune are on the shelf.'
   request 2: roles ['user', 'assistant', 'user']; tool_use ids ['toolu_01'] -> tool_result ids ['toolu_01'] | is_error: [False] | ['[{"title": "Dune", "author": "Frank Herbert", "isbn": "97804']
   request 3: roles ['user', 'assistant', 'user', 'assistant', 'user']; tool_use ids ['toolu_02'] -> tool_result ids ['toolu_02'] | is_error: [False] | ['{"isbn": "9780441172719", "copies_on_shelf": 2}']

Step 4: Build the loop for OpenAI

OpenAI has Responses and the older Chat Completions:

ClaudeResponsesChat Completions
The calltool_usefunction_calltool_calls
Your resulttool_resultfunction_call_outputrole: "tool" message
Matched bytool_use_idcall_idtool_call_id
Error flagis_errornone (text only)none (text only)

In Responses, input and output are lists of items: messages, calls, results. Your results follow the reply’s items, as the OpenAI function calling guide shows:

def run_responses(client, fail_tool=None, max_turns=6):
    input_list = [{'role': 'user', 'content': QUESTION}]
    for _ in range(max_turns):
        r = client.responses.create(model=MODEL, tools=openai_responses_tools(), input=input_list)
        input_list += r.output  # docs: keep the model output items in the running input
        calls = [i for i in r.output if i.type == 'function_call']
        if not calls:
            return r.output_text
        for c in calls:
            out, _is_error = execute(c.name, json.loads(c.arguments), down=(c.name == fail_tool))
            # no is_error field exists on function_call_output: the docs say the string carries success or failure
            input_list.append({'type': 'function_call_output', 'call_id': c.call_id, 'output': out})
    raise RuntimeError('too many turns')
== responses / happy: 3 requests to https://api.openai.com/v1/responses, final: 'Yes: 2 copies of Dune are on the shelf.'
   request 2: items ['user', 'function_call', 'function_call_output']; answered ids ['call_1'] | ['[{"title": "Dune", "author": "Frank Herbert", "isbn": "97804']
   request 3: items ['user', 'function_call', 'function_call_output', 'function_call', 'function_call_output']; answered ids ['call_2'] | ['{"isbn": "9780441172719", "copies_on_shelf": 2}']

Chat Completions, with messages:

def run_chat(client, fail_tool=None, max_turns=6):
    messages = [{'role': 'user', 'content': QUESTION}]
    for _ in range(max_turns):
        m = client.chat.completions.create(model=MODEL, tools=openai_chat_tools(), messages=messages).choices[0].message
        if not m.tool_calls:
            return m.content
        messages.append(m.model_dump(exclude_none=True))  # the assistant message with its tool_calls
        for tc in m.tool_calls:
            out, _is_error = execute(tc.function.name, json.loads(tc.function.arguments), down=(tc.function.name == fail_tool))
            messages.append({'role': 'tool', 'tool_call_id': tc.id, 'content': out})
    raise RuntimeError('too many turns')

Recorded replies let run_chat use MODEL, GPT-6.2 Astra; real calls need a model with Chat Completions tool calling.

Step 5: Return errors

OpenAI’s Chat Completions reference says to validate the arguments in your code. execute does, and turns any failure into a result:

def execute(name, args, down=False):
    '''Returns (text, is_error). Validates the arguments first: the model may send values the schema forbids.'''
    if name not in BY_NAME:
        return f'Error: unknown tool {name!r}. Known tools: {sorted(BY_NAME)}', True
    errors = [e.message for e in jsonschema.Draft202012Validator(BY_NAME[name]['schema']).iter_errors(args)]
    if errors:
        return 'Error: invalid arguments: ' + '; '.join(errors) + '. Get the ISBN from search_books first.', True
    try:
        return json.dumps(library_service(name, args, down)), False
    except Exception as e:  # the tool itself failed
        return f'{type(e).__name__}: {e}', True

The first recorded reply asks for get_book_availability(isbn="Dune"); the pattern rejects it:

== wrong_isbn: 4 requests, final: 'Yes: 2 copies of Dune are on the shelf.'
   request 2: roles ['user', 'assistant', 'user']; tool_use ids ['toolu_01'] -> tool_result ids ['toolu_01'] | is_error: [True] | ["Error: invalid arguments: 'Dune' does not match '^97[89][0-9"]
   request 3: roles ['user', 'assistant', 'user', 'assistant', 'user']; tool_use ids ['toolu_02'] -> tool_result ids ['toolu_02'] | is_error: [False] | ['[{"title": "Dune", "author": "Frank Herbert", "isbn": "97804']
   request 4: roles ['user', 'assistant', 'user', 'assistant', 'user', 'assistant', 'user']; tool_use ids ['toolu_03'] -> tool_result ids ['toolu_03'] | is_error: [False] | ['{"isbn": "9780441172719", "copies_on_shelf": 2}']

The request carrying the error, with is_error=true:

  user      "Is Dune available at the city library?"
  assistant [tool_use id=toolu_01 name=get_book_availability input={isbn:"Dune"}]
  user      [tool_result tool_use_id=toolu_01 is_error=true content="Error: invalid arguments: 'Dune' does not match '^97[89][0-9]{10}$'. Get the ISBN from search_books first."]

The model may ask again. The ISBN is an Open Library example.

The error goes back as a result; the loop carries on.

Step 6: Test without a key

mock.py, the fake API:

'''A scripted fake API: returns the recorded responses in order and keeps every request body the SDK sent.'''
import json
import httpx2 as httpx  # anthropic 2.x and openai 3.x are built on httpx2, not httpx


class Recorded:
    def __init__(self, *responses):
        self.responses, self.requests = list(responses), []

    def handler(self, request):
        self.requests.append({'method': request.method, 'url': str(request.url), 'body': json.loads(request.content)})
        return httpx.Response(200, json=self.responses[len(self.requests) - 1])

    def http_client(self):
        return httpx.Client(transport=httpx.MockTransport(self.handler))

From loop_claude.py, the checks on every kept request:

            assert assistant['role'] == 'assistant' and user['role'] == 'user'
            assert [b['type'] for b in res] == ['tool_result'] * len(ids), 'tool_results must be the first and only blocks'
            assert [b['tool_use_id'] for b in res] == ids, 'ids and order must match'

mutate.py (at the end) breaks a copy of the loop in one place; its check must then fail. Every check failed:

BreakCheck failed
Claude: text before resultsyes
Claude: wrong tool_use_idyes
Responses: wrong call_idyes
Chat Completions: wrong tool_call_idyes

Our checklist. The run asserts the first three on every request; the other two it did not fully exercise:

  • one result per call, matched by id, in order (asserted);
  • the same tools every request (asserted);
  • at Claude, results first (asserted; our check allows none);
  • input validated before the tool runs (shown by the wrong-ISBN case only);
  • a cap on rounds: max_turns is in the code, but no scenario reached it.

Not checked: a real model, a real API.

Mistakes that break the loop

  • Text before results → Claude’s API rejects it → results first.
  • Wrong id → the result answers no call → copy the call’s id.
  • Error sent as success → at Claude only is_error marks it → set it.
  • Title where an ISBN belongs → a bare string takes it → add a pattern.

If you only wanted to build and test the loop, you can stop here.

Parallel calls in the run

In parallel tool calling, several calls arrive in one reply. Claude wants all results in ONE user message; OpenAI, one item or tool message per call:

== parallel: 2 requests, final: 'Dune is in the catalogue; Dune Messiah is not.'
   request 2: roles ['user', 'assistant', 'user']; tool_use ids ['toolu_01', 'toolu_02'] -> tool_result ids ['toolu_01', 'toolu_02'] | is_error: [False, False] | ['[{"title": "Dune", "author": "Frank Herbert", "isbn": "97804', '[]']
== responses / parallel: 2 requests to https://api.openai.com/v1/responses, final: 'Dune is in the catalogue; Dune Messiah is not.'
   request 2: items ['user', 'function_call', 'function_call', 'function_call_output', 'function_call_output']; answered ids ['call_1', 'call_2'] | ['[{"title": "Dune", "author": "Frank Herbert", "isbn": "97804', '[]']
== chat / parallel: 2 requests to https://api.openai.com/v1/chat/completions, final: 'Dune is in the catalogue; Dune Messiah is not.'
   request 2: items ['user', 'assistant', 'tool', 'tool']; answered ids ['call_1', 'call_2'] | ['[{"title": "Dune", "author": "Frank Herbert", "isbn": "97804', '[]']

Details behind the steps

Per the vendors’ documentation, read on 4 December 2026:

  • Python: both SDKs need 3.10 or newer.
  • Model ids in the code: from the vendors’ documentation examples, unchecked.
  • Definitions: Claude requires name and input_schema. At OpenAI, description and parameters are optional.
  • Descriptions: Anthropic asks for at least 3 to 4 sentences per tool, as advice, not a measurement. Name inputs so nobody can misread them (its engineering blog, September 2025: user_id, not user), and prefer fewer, broader tools.
  • Where the “when to call” text goes: Anthropic puts it in the description. OpenAI’s guide puts “when (and when not)” in the system prompt, the instructions you send before the user’s message; its field table also gives description as “Details on when and how to use the function”. Our tools put it in the description.
  • Claude results: Claude has no separate tool role, so results travel in a user message. Add no text right after them, or Claude may end its reply empty. A call you choose not to run still gets a result, with is_error: true and a short reason.
  • Error text: say what went wrong and what to try next.
  • OpenAI shape: OpenAI recommends Responses for all new projects. OpenAI’s guide says some GPT-6 models require Responses for tool calling (for example GPT-6.2 Astra, per its changelog of 17 November 2026).
  • Reasoning models, which reason before they answer, need their reasoning items (output items that hold that reasoning) passed back with the results; input_list += r.output keeps every output item, as the guide’s own example does. Our recorded replies held no reasoning item, so we did not exercise this.
  • OpenAI results: the output string’s format is up to you (“JSON, error codes, plain text, etc.”).
  • Chat Completions and reasoning: per OpenAI’s migration guide, since GPT-5.4 Chat Completions does not support tool calling with a reasoning_effort (how much the model reasons) other than none.

What strict adds, and what we did not try

strict asks the vendor to make the model’s tool call follow your schema. Per the vendors’ docs:

  • Anthropic: strict: true guarantees the tool input matches the schema, except after a refusal, a cut at max_tokens (the reply length limit you set), and for the capitalisation of enum values. It supports a subset of JSON Schema and of regular expressions (the ^…$ of our ISBN pattern is in it).
  • OpenAI recommends strict always. It needs additionalProperties: false on every object and every field listed in required; our schemas meet both. Responses tries strict when you omit it, Chat Completions stays non-strict, and string pattern is supported.

Our inference, from the validator and not from a model: strict cannot tell a title from an ISBN unless the pattern says so. We did not send strict with a pattern to either real API; the docs say both support it.

Making the model’s own text follow a schema, and what schemas cost, is structured output prompting.

Forcing a tool call and turning off parallel calls

Neither was in our run. tool_choice is the setting that tells the model whether it may, must or must not ask for a tool. Per the docs read on 4 December 2026:

  • Claude: auto (the default), any (ask for one of your tools), tool (ask for the named tool), none.
  • any and tool return a 400 error on the newest Claude models (the docs table “Model or setting” lists them) and give an error with manual extended thinking (thinking: {type: "enabled"}), the setting that makes Claude reason before it answers.
  • OpenAI: auto (the default), required, one forced function and none.
  • Parallel calls are on by default at both. Claude: disable_parallel_tool_use: true inside the tool_choice object ({"type": "auto", "disable_parallel_tool_use": true}), not at the top of the request. OpenAI: parallel_tool_calls: false, which allows zero or one call.

Where this code stops short of a production loop

This is a minimal loop. Our model replies were recorded, so no model chose anything here: run the loop against the real API before you ship.

  • Anthropic’s Python SDK has a tool runner, client.beta.messages.tool_runner, in beta, that runs the loop for you. The docs keep the manual loop for approvals and custom logging. We tried neither it nor streamed tool calls.
  • If a reply is cut at max_tokens inside a tool_use block, retry with a higher limit.
  • The SDK sets the anthropic-version header, which names the API version, for you; the current version is 2026-10-21.
  • Tool definitions are input tokens, paid on every request.
  • Tool results are untrusted input. Text from sources outside your control can carry instructions that try to redirect the model (indirect prompt injection). Who may use which tool is agent guardrails.
  • Measuring how well a real model picks tools is agent evaluation and testing, or BFCL scores.
  • Related topic pages: prompt optimization, prompt testing and evaluation.
  • Retries and recovery across a whole agent are agent error handling and recovery. How tool calling relates to MCP servers is Model Context Protocol.

The full scripts

requirements.txt (Step 1), check_schema.py (Step 2) and mock.py (Step 6) appear whole above. The four scripts below complete the folder. Put all of them there and run check_schema.py, loop_claude.py, loop_openai.py and mutate.py.

tools.py:

'''Two library tools, one definition, three wire shapes (Anthropic, OpenAI Responses, OpenAI Chat Completions).'''
import json
import jsonschema

# Dune, Ace Books. Open Library record https://openlibrary.org/isbn/9780441172719.json lists isbn_10 0441172717,
# which converts to this ISBN-13 (check digit 9 verified in the results file).
DUNE_ISBN = '9780441172719'

TOOLS = [
    {'name': 'search_books',
     'description': 'Call this when the user names a book by title or author. Returns matching books with their ISBN. '
                    'Do NOT use it to check availability.',
     'schema': {'type': 'object',
                'properties': {'query': {'type': 'string', 'description': 'Title or author words, e.g. "Dune"'}},
                'required': ['query'], 'additionalProperties': False}},
    {'name': 'get_book_availability',
     'description': 'Call this only with an ISBN from search_books. Returns whether the city library has a copy on the shelf.',
     'schema': {'type': 'object',
                'properties': {'isbn': {'type': 'string', 'pattern': '^97[89][0-9]{10}$', 'description': 'ISBN-13, digits only'}},
                'required': ['isbn'], 'additionalProperties': False}},
]
BY_NAME = {t['name']: t for t in TOOLS}


def anthropic_tools():
    return [{'name': t['name'], 'description': t['description'], 'input_schema': t['schema']} for t in TOOLS]


def openai_responses_tools():  # flat shape, strict as the docs recommend
    return [{'type': 'function', 'name': t['name'], 'description': t['description'], 'parameters': t['schema'], 'strict': True} for t in TOOLS]


def openai_chat_tools():  # nested shape: function.parameters
    return [{'type': 'function', 'function': {'name': t['name'], 'description': t['description'], 'parameters': t['schema']}} for t in TOOLS]


class LibraryDown(Exception):
    pass


def library_service(name, args, down=False):
    if down:
        raise LibraryDown('the city library service did not answer (HTTP 503)')
    if name == 'search_books':  # the fixture catalogue holds one book
        return [{'title': 'Dune', 'author': 'Frank Herbert', 'isbn': DUNE_ISBN}] if args['query'].strip().lower() == 'dune' else []
    return {'isbn': args['isbn'], 'copies_on_shelf': 2}


def execute(name, args, down=False):
    '''Returns (text, is_error). Validates the arguments first: the model may send values the schema forbids.'''
    if name not in BY_NAME:
        return f'Error: unknown tool {name!r}. Known tools: {sorted(BY_NAME)}', True
    errors = [e.message for e in jsonschema.Draft202012Validator(BY_NAME[name]['schema']).iter_errors(args)]
    if errors:
        return 'Error: invalid arguments: ' + '; '.join(errors) + '. Get the ISBN from search_books first.', True
    try:
        return json.dumps(library_service(name, args, down)), False
    except Exception as e:  # the tool itself failed
        return f'{type(e).__name__}: {e}', True

loop_claude.py:

'''The tool-calling loop on the real anthropic SDK, against recorded responses (no network, no key).
Shape of every recorded response: docs example "Example API response with a tool_use content block"
(https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls); the SDK also needs type/stop_sequence/usage, added by us.'''
import json
import pathlib
import anthropic
from mock import Recorded
from tools import DUNE_ISBN, anthropic_tools, execute

QUESTION = 'Is Dune available at the city library?'


def message(i, stop, *content):
    return {'id': f'msg_{i}', 'type': 'message', 'role': 'assistant', 'model': 'claude-opus-5-5', 'stop_reason': stop, 'stop_sequence': None,
            'usage': {'input_tokens': 10, 'output_tokens': 10}, 'content': list(content)}


def use(tid, name, **inp):
    return {'type': 'tool_use', 'id': tid, 'name': name, 'input': inp}


def text(t):
    return {'type': 'text', 'text': t}


def run_loop(client, fail_tool=None, max_turns=6):
    messages = [{'role': 'user', 'content': QUESTION}]
    for _ in range(max_turns):
        r = client.messages.create(model='claude-opus-5-5', max_tokens=1024, tools=anthropic_tools(), messages=messages)
        if r.stop_reason != 'tool_use':
            return r
        messages.append({'role': 'assistant', 'content': r.content})  # the response content, unchanged (docs step 2)
        results = []
        for b in (b for b in r.content if b.type == 'tool_use'):
            out, is_error = execute(b.name, b.input, down=(b.name == fail_tool))
            results.append({'type': 'tool_result', 'tool_use_id': b.id, 'content': out, **({'is_error': True} if is_error else {})})
        messages.append({'role': 'user', 'content': results})  # one tool_result per tool_use, first in the message (docs step 3)
    raise RuntimeError('too many turns')


SCENARIOS = {
    'happy': (None, [message(1, 'tool_use', text('I will look the book up.'), use('toolu_01', 'search_books', query='Dune')),
                     message(2, 'tool_use', use('toolu_02', 'get_book_availability', isbn=DUNE_ISBN)),
                     message(3, 'end_turn', text('Yes: 2 copies of Dune are on the shelf.'))]),
    'wrong_isbn': (None, [message(1, 'tool_use', use('toolu_01', 'get_book_availability', isbn='Dune')),
                          message(2, 'tool_use', use('toolu_02', 'search_books', query='Dune')),
                          message(3, 'tool_use', use('toolu_03', 'get_book_availability', isbn=DUNE_ISBN)),
                          message(4, 'end_turn', text('Yes: 2 copies of Dune are on the shelf.'))]),
    'tool_raises': ('get_book_availability', [message(1, 'tool_use', use('toolu_01', 'get_book_availability', isbn=DUNE_ISBN)),
                                              message(2, 'end_turn', text('The library service is down. Please try again later.'))]),
    'parallel': (None, [message(1, 'tool_use', text('I will search both titles.'), use('toolu_01', 'search_books', query='Dune'),
                                use('toolu_02', 'search_books', query='Dune Messiah')),
                        message(2, 'end_turn', text('Dune is in the catalogue; Dune Messiah is not.'))]),
}

if __name__ == '__main__':
    out = pathlib.Path('captured')
    out.mkdir(exist_ok=True)
    for name, (fail_tool, responses) in SCENARIOS.items():
        rec = Recorded(*responses)
        client = anthropic.Anthropic(api_key='not-a-key', http_client=rec.http_client())
        final = run_loop(client, fail_tool)
        (out / f'claude_{name}.json').write_text(json.dumps(rec.requests, indent=2, ensure_ascii=False))
        print(f'== {name}: {len(rec.requests)} requests, final: {final.content[0].text!r}')
        for n, req in enumerate(rec.requests[1:], 2):
            msgs = req['body']['messages']
            assistant, user = msgs[-2], msgs[-1]
            ids = [b['id'] for b in assistant['content'] if b['type'] == 'tool_use']
            res = user['content']
            assert assistant['role'] == 'assistant' and user['role'] == 'user'
            assert [b['type'] for b in res] == ['tool_result'] * len(ids), 'tool_results must be the first and only blocks'
            assert [b['tool_use_id'] for b in res] == ids, 'ids and order must match'
            print(f'   request {n}: roles {[m["role"] for m in msgs]}; tool_use ids {ids} -> tool_result ids {[b["tool_use_id"] for b in res]}',
                  '| is_error:', [b.get('is_error', False) for b in res], '|', [b['content'][:60] for b in res])
            assert req['body']['tools'] == rec.requests[0]['body']['tools'], 'same tools in every request'

loop_openai.py:

'''The tool-calling loop on the real openai SDK, against recorded responses (no network, no key). Two API shapes:
- Responses API (the shape the current docs lead with: https://developers.openai.com/api/docs/guides/function-calling)
- Chat Completions (older shape; the docs say GPT-6 models need Responses)
Recorded response shapes: Responses "Functions" example and the "multiple function calls" sample, Chat Completions "Response example"
(https://developers.openai.com/api/reference/resources/responses/methods/create and .../chat/subresources/completions/methods/create).'''
import json
import pathlib
import openai
from mock import Recorded
from tools import DUNE_ISBN, execute, openai_chat_tools, openai_responses_tools

QUESTION = 'Is Dune available at the city library?'
MODEL = 'gpt-6.2-astra'  # the model name the current docs use; nothing checks it here


# ---------- Responses API
def r_response(i, *output):
    return {'id': f'resp_{i}', 'object': 'response', 'created_at': 1741294021, 'status': 'completed', 'error': None, 'incomplete_details': None,
            'model': MODEL, 'output': list(output), 'parallel_tool_calls': True, 'tool_choice': 'auto', 'tools': [], 'metadata': {}}


def r_call(i, name, **args):
    return {'type': 'function_call', 'id': f'fc_{i}', 'call_id': f'call_{i}', 'name': name, 'arguments': json.dumps(args), 'status': 'completed'}


def r_text(t):
    return {'type': 'message', 'id': 'msg_1', 'status': 'completed', 'role': 'assistant', 'content': [{'type': 'output_text', 'text': t, 'annotations': []}]}


def run_responses(client, fail_tool=None, max_turns=6):
    input_list = [{'role': 'user', 'content': QUESTION}]
    for _ in range(max_turns):
        r = client.responses.create(model=MODEL, tools=openai_responses_tools(), input=input_list)
        input_list += r.output  # docs: keep the model output items in the running input
        calls = [i for i in r.output if i.type == 'function_call']
        if not calls:
            return r.output_text
        for c in calls:
            out, _is_error = execute(c.name, json.loads(c.arguments), down=(c.name == fail_tool))
            # no is_error field exists on function_call_output: the docs say the string carries success or failure
            input_list.append({'type': 'function_call_output', 'call_id': c.call_id, 'output': out})
    raise RuntimeError('too many turns')


# ---------- Chat Completions
def c_response(i, finish, **msg):
    return {'id': f'chatcmpl-{i}', 'object': 'chat.completion', 'created': 1699896916, 'model': MODEL,
            'choices': [{'index': 0, 'message': {'role': 'assistant', 'content': None, **msg}, 'logprobs': None, 'finish_reason': finish}]}


def c_call(i, name, **args):
    return {'id': f'call_{i}', 'type': 'function', 'function': {'name': name, 'arguments': json.dumps(args)}}


def run_chat(client, fail_tool=None, max_turns=6):
    messages = [{'role': 'user', 'content': QUESTION}]
    for _ in range(max_turns):
        m = client.chat.completions.create(model=MODEL, tools=openai_chat_tools(), messages=messages).choices[0].message
        if not m.tool_calls:
            return m.content
        messages.append(m.model_dump(exclude_none=True))  # the assistant message with its tool_calls
        for tc in m.tool_calls:
            out, _is_error = execute(tc.function.name, json.loads(tc.function.arguments), down=(tc.function.name == fail_tool))
            messages.append({'role': 'tool', 'tool_call_id': tc.id, 'content': out})
    raise RuntimeError('too many turns')


SCENARIOS = {
    'responses': (run_responses, {
        'happy': (None, [r_response(1, r_call(1, 'search_books', query='Dune')), r_response(2, r_call(2, 'get_book_availability', isbn=DUNE_ISBN)),
                         r_response(3, r_text('Yes: 2 copies of Dune are on the shelf.'))]),
        'wrong_isbn': (None, [r_response(1, r_call(1, 'get_book_availability', isbn='Dune')), r_response(2, r_call(2, 'search_books', query='Dune')),
                              r_response(3, r_call(3, 'get_book_availability', isbn=DUNE_ISBN)), r_response(4, r_text('Yes: 2 copies of Dune are on the shelf.'))]),
        'tool_raises': ('get_book_availability', [r_response(1, r_call(1, 'get_book_availability', isbn=DUNE_ISBN)),
                                                  r_response(2, r_text('The library service is down. Please try again later.'))]),
        'parallel': (None, [r_response(1, r_call(1, 'search_books', query='Dune'), r_call(2, 'search_books', query='Dune Messiah')),
                            r_response(2, r_text('Dune is in the catalogue; Dune Messiah is not.'))]),
    }),
    'chat': (run_chat, {
        'happy': (None, [c_response(1, 'tool_calls', tool_calls=[c_call(1, 'search_books', query='Dune')]),
                         c_response(2, 'tool_calls', tool_calls=[c_call(2, 'get_book_availability', isbn=DUNE_ISBN)]),
                         c_response(3, 'stop', content='Yes: 2 copies of Dune are on the shelf.')]),
        'wrong_isbn': (None, [c_response(1, 'tool_calls', tool_calls=[c_call(1, 'get_book_availability', isbn='Dune')]),
                              c_response(2, 'tool_calls', tool_calls=[c_call(2, 'search_books', query='Dune')]),
                              c_response(3, 'tool_calls', tool_calls=[c_call(3, 'get_book_availability', isbn=DUNE_ISBN)]),
                              c_response(4, 'stop', content='Yes: 2 copies of Dune are on the shelf.')]),
        'tool_raises': ('get_book_availability', [c_response(1, 'tool_calls', tool_calls=[c_call(1, 'get_book_availability', isbn=DUNE_ISBN)]),
                                                  c_response(2, 'stop', content='The library service is down. Please try again later.')]),
        'parallel': (None, [c_response(1, 'tool_calls', tool_calls=[c_call(1, 'search_books', query='Dune'), c_call(2, 'search_books', query='Dune Messiah')]),
                            c_response(2, 'stop', content='Dune is in the catalogue; Dune Messiah is not.')]),
    }),
}


def trailing(items, is_result):
    n = 0
    while n < len(items) and is_result(items[-1 - n]):
        n += 1
    return n


def check_responses(req, first):
    items = req['body']['input']
    n = trailing(items, lambda i: i.get('type') == 'function_call_output')  # the results of the latest turn
    outs, calls = items[-n:], items[-2 * n:-n]
    assert n and all(c['type'] == 'function_call' for c in calls), 'the function_call items come right before their outputs'
    assert [o['call_id'] for o in outs] == [c['call_id'] for c in calls], 'call_id must match, in order'
    assert req['body']['tools'] == first['body']['tools']
    return [i.get('type') or i['role'] for i in items], [o['call_id'] for o in outs], [o['output'][:60] for o in outs]


def check_chat(req, first):
    msgs = req['body']['messages']
    n = trailing(msgs, lambda m: m['role'] == 'tool')
    tool_msgs, assistant = msgs[-n:], msgs[-n - 1]
    assert n and assistant['role'] == 'assistant', 'the assistant message with tool_calls comes right before the tool messages'
    assert [t['id'] for t in assistant['tool_calls']] == [m['tool_call_id'] for m in tool_msgs], 'tool_call_id must match, in order'
    assert req['body']['tools'] == first['body']['tools']
    return [m['role'] for m in msgs], [m['tool_call_id'] for m in tool_msgs], [m['content'][:60] for m in tool_msgs]


if __name__ == '__main__':
    out = pathlib.Path('captured')
    out.mkdir(exist_ok=True)
    for api, (run, scenarios) in SCENARIOS.items():
        for name, (fail_tool, responses) in scenarios.items():
            rec = Recorded(*responses)
            client = openai.OpenAI(api_key='not-a-key', http_client=rec.http_client())
            final = run(client, fail_tool)
            (out / f'openai_{api}_{name}.json').write_text(json.dumps(rec.requests, indent=2, ensure_ascii=False))
            print(f'== {api} / {name}: {len(rec.requests)} requests to {rec.requests[0]["url"]}, final: {final!r}')
            for n, req in enumerate(rec.requests[1:], 2):
                shape, ids, outs = (check_responses if api == 'responses' else check_chat)(req, rec.requests[0])
                print(f'   request {n}: items {shape}; answered ids {ids} | {outs}')

mutate.py, which makes the table of breaks:

'''Mutation proof: break each loop in one place and show that the checks in the scripts redden. Works on copies in a temp dir.'''
import pathlib, shutil, subprocess, sys, tempfile

MUTANTS = [  # (script, exact text to replace, replacement, what the mutation does)
    ('loop_claude.py', "        messages.append({'role': 'user', 'content': results})",
     "        messages.append({'role': 'user', 'content': [{'type': 'text', 'text': 'Here are the results:'}] + results})", 'Claude: text BEFORE tool_result'),
    ('loop_claude.py', "'tool_use_id': b.id,", "'tool_use_id': b.id + 'x',", 'Claude: wrong tool_use_id'),
    ('loop_openai.py', "'call_id': c.call_id, 'output': out", "'call_id': c.call_id + 'x', 'output': out", 'OpenAI Responses: wrong call_id'),
    ('loop_openai.py', "'tool_call_id': tc.id,", "'tool_call_id': tc.id + 'x',", 'OpenAI Chat: wrong tool_call_id'),
]
here = pathlib.Path(__file__).parent
for script, old, new, label in MUTANTS:
    with tempfile.TemporaryDirectory() as d:
        for f in here.glob('*.py'):
            shutil.copy(f, d)
        p = pathlib.Path(d) / script
        src = p.read_text()
        assert src.count(old) == 1, (script, old, src.count(old))  # anchor must be unique
        p.write_text(src.replace(old, new))
        r = subprocess.run([sys.executable, script], cwd=d, capture_output=True, text=True)
        last = (r.stderr.strip().splitlines() or ['(no error)'])[-1]
        print(f'{label}: exit {r.returncode} | {last}')

Cheat sheet

The article on one page: open it full size, save it or share it.

Cheat sheet: pinned installs, two library tools, ISBN pattern, three loop rules, Claude and OpenAI result fields, loop test
PNG

AI-assisted content, human-reviewed. Images AI-generated. Editorial Standards · Our Editors