Back to Blog
EnglishTutorial

GPT Agent Workflows: A Bounded Tool Loop with a Tested Stop Condition

A GPT-5-mini stock lookup completes a model-tool-model loop. Six local executor cases and a three-turn cap make the application boundary explicit without claiming ChatGPT agent-mode parity.

S
Sophie M
February 27, 2026 / 1700 views
Share:
GPT Agent Workflows: A Bounded Tool Loop with a Tested Stop Condition

An API agent workflow is an application loop: receive a tool proposal, validate it, run an allowed operation and return its result to the model. This example completes that loop with synthetic stock data and stops after a final answer or a three-turn limit.

Crazyrouter was the gateway for this 1-case experiment: 1 cases met the declared complete-output criterion; the results below retain the failures and their limits.

By Sophie M · Tested November 3, 2026

How do I build a bounded GPT agent tool loop?#

ChatGPT agent experiences and a developer-built tool loop are different products and interfaces. This article tests Chat Completions with gpt-5-mini and one custom stock_lookup function. It does not claim that adding an “agent mode” flag activates browser use, computer control or every ChatGPT capability.

The model receives the tool schema and a request about DEMO-7. The application accepts one tool call, validates its arguments, returns a synthetic quantity of seven and checks the final JSON. The recorded run completed those steps.

November 3 experiment and observed results#

The scripts ran on Windows with Python 3.10.2 and synthetic inputs. Gateway generation and catalog requests use https://api.crazyrouter.com; paths and complete payloads appear in the code. Each result describes this run only. A test program exiting successfully means its observations were recorded, not that every model response passed.

Requested model IDVisible to this credential
gpt-5-miniYes
Route / caseHTTP or turnsFinish / outcomeAcceptedObserved output or error
gpt-5-mini / stock tool loop200, 200finalYes{"sku":"DEMO-7","available":7}

Observed successful-envelope response IDs (failed acceptance can still have an ID):

text
resp_000b61dc0dbe3994016ae9ebba17b8819486a52c3a8039e87f
resp_01d72d7a24b6cd84016ae9ebbb966081978ae20a6fb415bea0
Executed local caseExpected behavior met
validYes
duplicateYes
unknownYes
bad JSONYes
extra fieldYes
wrong SKUYes

Full application contract: Tool execution plus exact final JSON is required

Bound both execution and generation#

The executor permits only stock_lookup and exactly one sku field with the expected synthetic value. It rejects unknown functions, malformed JSON, extra arguments, another SKU and repeated tool-call IDs. Six local fixtures exercise these decisions before any live request.

The loop accepts at most three model turns and requires the correct tool_calls finish state before executing. The final result needs stop, one actual lookup and the expected JSON. A final answer that guessed seven without a lookup would fail. A repeated semantic operation under a new call ID is not covered by the ID set, so external writes need a stronger business idempotency design.

Use a read-only tool before adding side effects#

This tool reads a local synthetic dictionary; it does not contact a warehouse or change a record. Real inventory operations need trusted identity, authorization and current-state checks. Keep those checks inside the application, not in model-generated arguments.

Network errors, invalid tool turns and turn-limit exhaustion produce explicit failed outcomes. No retry is hidden in the loop. If you add retries, decide which operations are safe to replay and preserve the corresponding result IDs.

Reproduce the experiment#

Install requests, set CRAZYROUTER_API_KEY in the process environment, save this complete script and run it with Python 3.10 or later. Requests use your authorized credential and can consume usage. Authorization headers are not printed.

python
import json
import os
import time
import requests

BASE = "https://api.crazyrouter.com/v1"

def catalog(models):
    with requests.Session() as s:
        s.trust_env=False
        r=s.get(BASE+"/models",headers={"Authorization":"Bearer "+os.environ["CRAZYROUTER_API_KEY"]},timeout=(10,40),allow_redirects=False)
        r.raise_for_status();names={x["id"] for x in r.json()["data"]}
    return {m:m in names for m in models}

def chat(model,prompt,**options):
    payload={"model":model,"messages":[{"role":"user","content":prompt}],**options}
    record={"model":model,"request":payload};start=time.perf_counter()
    try:
        with requests.Session() as s:
            s.trust_env=False
            r=s.post(BASE+"/chat/completions",headers={"Authorization":"Bearer "+os.environ["CRAZYROUTER_API_KEY"]},json=payload,timeout=(10,65),allow_redirects=False)
        record["http"]=r.status_code
        if r.status_code==200:
            d=r.json();c=d["choices"][0];record.update(response_id=d.get("id"),output=c["message"].get("content"),finish=c.get("finish_reason"),usage=d.get("usage",{}))
        else:record["error"]="HTTP_"+str(r.status_code)
    except (requests.RequestException,ValueError,KeyError,IndexError) as e:record["error"]=type(e).__name__
    record["seconds"]=round(time.perf_counter()-start,3)
    return record

def parsed(row):
    if row.get("finish")!="stop":return None
    try:return json.loads(row.get("output") or "null")
    except (ValueError,TypeError):return None

def emit(**data):print(json.dumps(data,ensure_ascii=False))

def execute(call,seen):
    if call.get("id") in seen:return {"error":"duplicate"}
    if call.get("function",{}).get("name")!="stock_lookup":return {"error":"unknown_tool"}
    try:args=json.loads(call["function"]["arguments"])
    except (ValueError,KeyError,TypeError):return {"error":"invalid_json"}
    if type(args) is not dict or set(args)!={"sku"} or args["sku"]!="DEMO-7":return {"error":"invalid_arguments"}
    seen.add(call["id"])
    return {"sku":"DEMO-7","available":7}

def loop(model):
    messages=[{"role":"user","content":'Use stock_lookup for SKU DEMO-7, then return only JSON {"sku":"DEMO-7","available":7}. The tool is the source of stock data.'}]
    tool={"type":"function","function":{"name":"stock_lookup","description":"Read synthetic stock, no external operation","parameters":{"type":"object","properties":{"sku":{"type":"string"}},"required":["sku"],"additionalProperties":False}}}
    seen=set();turns=[];outcome="turn_limit";output=None
    with requests.Session() as s:
        s.trust_env=False
        for turn in range(3):
            payload={"model":model,"messages":messages,"tools":[tool],"tool_choice":"auto"}
            if model.startswith("gpt-5"):payload.update(max_completion_tokens=1024,reasoning_effort="none" if model=="gpt-5.5" else "minimal")
            else:payload["max_tokens"]=1024
            started=time.perf_counter()
            try:
                response=s.post(BASE+"/chat/completions",headers={"Authorization":"Bearer "+os.environ["CRAZYROUTER_API_KEY"]},json=payload,timeout=(10,65),allow_redirects=False)
                row={"turn":turn+1,"http":response.status_code,"request":json.loads(json.dumps(payload))}
                if response.status_code!=200:outcome="http_failure";turns.append(row);break
                data=response.json();choice=data["choices"][0];msg=choice["message"]
                row.update(response_id=data.get("id"),finish=choice.get("finish_reason"),output=msg.get("content"),usage=data.get("usage",{}),seconds=round(time.perf_counter()-started,3));turns.append(row)
                calls=msg.get("tool_calls") or []
                if calls:
                    if choice.get("finish_reason")!="tool_calls" or len(calls)!=1:outcome="invalid_tool_turn";break
                    result=execute(calls[0],seen);row["tool_result"]=result
                    if "error" in result:outcome="executor_rejected";break
                    messages.append({"role":"assistant","content":msg.get("content"),"tool_calls":calls})
                    messages.append({"role":"tool","tool_call_id":calls[0]["id"],"content":json.dumps(result)})
                else:
                    output=msg.get("content");outcome="final" if choice.get("finish_reason")=="stop" else "incomplete";break
            except (requests.RequestException,ValueError,KeyError,IndexError) as e:
                outcome=type(e).__name__;turns.append({"turn":turn+1,"error":outcome});break
    try:answer=json.loads(output or "null")
    except ValueError:answer=None
    return {"model":model,"case":"stock tool loop","turns":turns,"outcome":outcome,"output":output,"passed":outcome=="final" and len(seen)==1 and answer=={"sku":"DEMO-7","available":7}}

valid={"id":"call-test","function":{"name":"stock_lookup","arguments":'{"sku":"DEMO-7"}'}}
tests=[]
cases=[("valid",valid,set(),None),("duplicate",valid,{"call-test"},"duplicate"),("unknown",{"id":"x","function":{"name":"delete"}},set(),"unknown_tool"),("bad JSON",{"id":"x","function":{"name":"stock_lookup","arguments":"{"}},set(),"invalid_json"),("extra field",{"id":"x","function":{"name":"stock_lookup","arguments":'{"sku":"DEMO-7","tenant":"other"}'}},set(),"invalid_arguments"),("wrong SKU",{"id":"x","function":{"name":"stock_lookup","arguments":'{"sku":"OTHER"}'}},set(),"invalid_arguments")]
for name,call,seen,error in cases:
    result=execute(call,seen);assert result.get("error")==error;tests.append({"case":name,"passed":True})
models=['gpt-5-mini'];available=catalog(models)
emit(catalog=available,requests=[loop(m) for m in models if available[m]],local_tests=tests,scope="At most three model turns; read-only synthetic dictionary, no external side effect")

Model turns observed: HTTP failures are retained; at most three turns per route

Sources checked November 3, 2026: OpenAI function calling. Official descriptions and gateway observations are separate evidence.

FAQ#

Is this the ChatGPT agent product?#

No. It is an application-built Chat Completions tool loop.

How many model turns are allowed?#

At most three, including the final response.

What proves the tool was used?#

The receipt contains the tool turn, local result and completed final response; the criterion also requires one executed call.

Can the model call any function?#

No. Only the exact stock_lookup schema and synthetic SKU are accepted.

Does duplicate-ID detection guarantee exactly-once writes?#

No. This read-only example does not implement business-level idempotency.

Were real inventory records touched?#

No. All tool data was synthetic and local.

Last actually tested: November 3, 2026. This API-dependent article is due for review December 3, 2026.

Implementation Guides

Podcast

AI Dev Tools: The Crazyrouter Podcast

Short episodes for developers on AI APIs, gateways, cost control and coding tools.

Latest episodes

  • EP196 · Oct 29, 2026 · 6:53

    AI API Security Posture — Turn Controls Into Continuous Evidence

    A practical guide to AI API security posture: inventory exposure, verify controls continuously, protect keys and data, constrain tools, and turn security assumptions into evidence that operators can act on.

  • EP195 · Oct 28, 2026 · 7:21

    AI API Policy Drift — Detect When Production Rules Stop Matching Intent

    A practical guide to policy drift in AI APIs: version routing and safety rules, detect stale enforcement, compare intended and observed behavior, and restore control before small gaps become incidents.

Episodes with written show notes →

Related Articles

How to Get a Claude API Key: Test the Gateway Credential FirstTutorial

How to Get a Claude API Key: Test the Gateway Credential First

A safe setup guide that distinguishes an Anthropic-issued key from a Crazyrouter gateway key. Two live Claude Sonnet requests and six local destination checks show what was actually verified.

Mar 19
OpenClaw Architecture: How OpenClaw Works Under the Hood in 2026Tutorial

OpenClaw Architecture: How OpenClaw Works Under the Hood in 2026

A technical deep dive into OpenClaw architecture exploring the Gateway layer, Agent Runtime, Markdown-based memory system, plugin slots, and complete message lifecycle. Learn how OpenClaw processes AI assistant requests from send to reply.

Mar 7
Ghibli Style Photo Transformation with GPT-image-2 — Turn Any Photo Into Anime ArtTutorial

Ghibli Style Photo Transformation with GPT-image-2 — Turn Any Photo Into Anime Art

Transform photos into Studio Ghibli anime style using GPT-image-2 via Crazyrouter API. Multiple anime styles covered with full code examples.

May 1
Pika 2.2 API Integration Guide: Build Video Generation Pipelines in 2026Tutorial

Pika 2.2 API Integration Guide: Build Video Generation Pipelines in 2026

"Step-by-step guide to integrating Pika 2.2's API into production video pipelines. Covers text-to-video, image-to-video, effects, pricing, and multi-model fallback strategies."

Apr 13
AI Content Creation Tools 2026: Complete Guide for CreatorsTutorial

AI Content Creation Tools 2026: Complete Guide for Creators

AI has revolutionized content creation. From writing blog posts to generating images, music, and videos, creators now have powerful tools at their fingertips. This guide covers the best AI content cre...

Jan 26
How to Get a Claude API Key in 2026: Secure Setup for Teams, CI, and AlternativesTutorial

How to Get a Claude API Key in 2026: Secure Setup for Teams, CI, and Alternatives

If you searched for **how to get claude api key**, you probably do not need another shallow feature list. You need to know what Claude API is, how it compares with alternatives, how to use it in a dev...

May 26