Sub topic 2
How the Provider Runs the Tool Loop for You
This chapter assumes you have called a chat or responses API with an API key and read JSON request and response bodies. It also assumes you know the basic idea of function calling. The examples use the OpenAI Responses API, with notes on Anthropic's Messages API where behavior differs.
The loop you normally write
With a function tool, the model never runs anything. It returns a request such as "call get_weather with {"city": "Oslo"}". Your code runs the function, sends the result back, and calls the API again. That repeats until the model answers in plain text.
import json
from openai import OpenAI
client = OpenAI()
def get_weather(city: str) -> str:
return json.dumps({"city": city, "temp_c": 18})
tools = [
{
"type": "function",
"name": "get_weather",
"description": "Get the current weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
"additionalProperties": False,
},
"strict": True,
}
]
response = client.responses.create(
model="gpt-4.1",
tools=tools,
input="What is the weather in Oslo?",
)
while True:
calls = [item for item in response.output if item.type == "function_call"]
if not calls:
break
results = []
for call in calls:
args = json.loads(call.arguments)
results.append(
{
"type": "function_call_output",
"call_id": call.call_id,
"output": get_weather(**args),
}
)
response = client.responses.create(
model="gpt-4.1",
tools=tools,
previous_response_id=response.id,
input=results,
)
print(response.output_text)Each trip around the while loop is a separate HTTP request. Your process sits between the model and the tool every time.
What changes with built-in tools
A built-in tool moves that loop onto the provider's servers. You declare the tool, send one request, and wait. Inside that request the provider:
- Lets the model decide whether to use a tool.
- Runs the tool itself (a search, a Python process, a vector lookup).
- Feeds the result back to the model.
- Repeats until the model produces a final answer or a limit is reached.
You get one response back. It contains the final text and a record of the intermediate steps.
The benefits are fewer network round trips, no tool-execution code to write, and no results for you to serialize and return. The cost is control. Your code cannot see or change the individual steps while they happen.
What you receive
The response output is a list of items in the order the model produced them. A built-in tool run typically looks like this:
| Item type | What it means |
|---|---|
| `web_search_call` | The provider performed a search. It has a `status`. |
| `code_interpreter_call` | The model ran code. It carries the code and its outputs. |
| `file_search_call` | The provider queried a vector store. |
| `message` | The assistant's text, possibly with annotations such as citations. |
You do not reply to these items. They are a log. Only items that need action from you, such as function_call, require a follow-up request.
This snippet counts the item types in any response, which is a quick way to confirm which tools actually ran:
from collections import Counter
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-4.1",
tools=[{"type": "web_search"}],
input="What is the latest stable release of Python?",
)
counts = Counter(item.type for item in response.output)
print(dict(counts))
print(response.output_text)A result like {'web_search_call': 1, 'message': 1} means one search ran. Two search calls mean the model ran two searches inside the same request.
Mixing built-in and function tools
You can declare both kinds in one request. The provider runs its own tools internally. When the model asks for a function tool, the provider stops and returns a function_call item, because only your code can run it.
The loop from the first example works unchanged. It filters for function_call items and ignores web_search_call items. Add {"type": "web_search"} to tools and the same loop handles both.
tools_mixed = tools + [{"type": "web_search"}]Pass tools_mixed in both create calls. One user question can then trigger several provider-side searches, followed by a hand-off to your function, followed by more provider-side work after you return the result.
Where the provider stops the loop
The provider-side loop is bounded. Know the limits, because they decide what you see when a task is hard.
- Usage caps. Anthropic's
max_useson the web search tool limits searches per request. If the model wants more, it stops searching and answers with what it has, and the result carries an error entry for the tool. - Turn limits. Anthropic can end a long server-side turn early with
stop_reason == "pause_turn". The response is incomplete. You continue it by sending the conversation back with that assistant content appended. - Incomplete responses. OpenAI responses carry a
status. Check forincompleteand readincomplete_detailsbefore assuming the text is final. - Tool failures. A search or code run can fail. The model usually sees the failure and works around it, so a failed step may be visible only in the item log and not in the final text.
Here is the Anthropic continuation pattern:
import anthropic
client = anthropic.Anthropic()
tools = [{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}]
messages = [
{"role": "user", "content": "Compare the three most recent Python releases."}
]
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
tools=tools,
messages=messages,
)
while message.stop_reason == "pause_turn":
messages.append({"role": "assistant", "content": message.content})
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=2048,
tools=tools,
messages=messages,
)
for block in message.content:
if block.type == "text":
print(block.text)Anthropic logs the steps as server_tool_use blocks and result blocks such as web_search_tool_result. The idea matches OpenAI's call items, but the names differ.
Consequences to plan for
- No approval step. With function tools you can inspect, log, or refuse a call before running it. With built-in tools the call has already happened when you see it. Use tool configuration (allowed domains, usage caps) to limit exposure in advance.
- Hidden tokens. Search results and code output are fed back to the model as input tokens. A single request can use far more tokens than your prompt and answer suggest. Check
response.usage. - Latency. One request may take many seconds because several tool steps run in sequence. Set client timeouts accordingly, and consider streaming.
- Debugging. When an answer looks wrong, read the output items first. They show whether a tool ran, how many times, and how it ended.
Exercise
You declare websearch and a function tool named lookuporder in one request. The first response contains one websearchcall item and one function_call item. What must your code do next, and what should it not do?
Show answer
Run lookuporder with the arguments in the functioncall item, then send a new request containing a functioncalloutput item with the matching callid (using previousresponseid to continue the conversation). It should not try to run or answer the websearch_call, because the provider already performed that search and the item is only a log entry.
Exercise
A request with web search returns normally, but the output list shows three websearchcall items although your code made only one API call. How is that possible?
Show answer
The provider runs the tool loop inside a single request. The model decided on its own to search three times before writing its answer, and each search is recorded as its own item.