Sub topic 4
Reading tool-call items in the response
When the provider runs a built-in tool, the tool activity is recorded in the response itself. This chapter shows how to read that record so you can debug a request, audit what the model did, and pull out the parts you need.
This chapter assumes you can call the OpenAI Responses API with the Python SDK, read JSON bodies, and know roughly what tool calling is. You should also know how to declare a built-in tool in a request, which the previous chapter covers.
The output is a list of items
A Responses API result has an output field. It is a list of typed items, in the order the model produced them. response.output_text is only a convenience property that joins the text of the message items. If you read only that property, you lose everything else.
A single request that uses web search typically returns items like these:
- A
web_search_callitem, which records that the provider searched. - A
messageitem, which holds the final answer text and its annotations.
A request with code execution returns a code_interpreter_call item before the message. File search returns a file_search_call item. With a reasoning model, you may also see reasoning items. Do not assume a fixed length or position. Always branch on item.type.
Each tool-call item carries an id, a status, and fields specific to the tool. The message item holds a content list. Each part of type output_text has text and an annotations list.
Item types and their fields
| Item type | Produced by | Useful fields |
|---|---|---|
| `web_search_call` | Web search | `id`, `status`, `action` (the query, when present) |
| `code_interpreter_call` | Code execution | `id`, `status`, `code`, `container_id`, `outputs` |
| `file_search_call` | File search | `id`, `status`, `queries`, `results` |
| `message` | Any request | `role`, `content` (text parts with `annotations`) |
| `reasoning` | Reasoning models | `id`, `summary` |
The status field tells you how the call ended. Typical values are in_progress, searching, interpreting, completed, and failed. The exact set depends on the tool, so check the API reference for yours.
Two fields are empty unless you ask for them. file_search_call.results and code_interpreter_call.outputs come back as null by default. Add them with the include parameter, for example include=["file_search_call.results"] or include=["code_interpreter_call.outputs"]. Web search sources can be requested with include=["web_search_call.action.sources"]. This keeps ordinary responses small. Request these fields only when you are debugging or auditing, because they add many tokens and bytes.
A generic walker
The following function prints a one-line summary of every item. It uses getattr because the available fields differ by item type and by SDK version.
from openai import OpenAI
client = OpenAI()
def summarize_output(response):
for item in response.output:
kind = item.type
if kind == "web_search_call":
action = getattr(item, "action", None)
query = getattr(action, "query", None)
print(f"[web_search_call] status={item.status} query={query!r}")
elif kind == "code_interpreter_call":
code = getattr(item, "code", None) or ""
print(f"[code_interpreter_call] status={item.status} "
f"container={getattr(item, 'container_id', None)}")
print(" code:", code.strip().replace("\n", "\n "))
elif kind == "file_search_call":
queries = getattr(item, "queries", None)
results = getattr(item, "results", None)
count = len(results) if results is not None else "not requested"
print(f"[file_search_call] status={item.status} "
f"queries={queries} results={count}")
elif kind == "message":
chars = sum(len(p.text) for p in item.content if p.type == "output_text")
print(f"[message] {chars} characters of answer text")
else:
print(f"[{kind}] (not handled)")
response = client.responses.create(
model="gpt-4.1",
tools=[{"type": "code_interpreter", "container": {"type": "auto"}}],
instructions="When a question involves arithmetic, write and run code to answer it.",
input="What is the sum of the squares of the integers from 1 to 1000?",
)
summarize_output(response)
print(response.output_text)Run this and you see the code_interpreter_call first, with the Python the model wrote, then the message. The correct sum is 333833500. If the model answers without calling the tool, no code_interpreter_call item appears. That tells you the model computed the number itself, which is a good reason to check the items instead of trusting the text alone.
Reading annotations from the message
Annotations tie ranges of the answer text to sources. Each output_text part has an annotations list. The annotation type tells you which tool the source came from.
| Annotation type | Fields |
|---|---|
| `url_citation` | `url`, `title`, `start_index`, `end_index` |
| `file_citation` | `file_id`, `filename`, `index` |
| `container_file_citation` | `container_id`, `file_id`, `filename`, `start_index`, `end_index` |
def collect_sources(response):
sources = []
for item in response.output:
if item.type != "message":
continue
for part in item.content:
if part.type != "output_text":
continue
for ann in part.annotations or []:
if ann.type == "url_citation":
span = part.text[ann.start_index:ann.end_index]
sources.append(("web", ann.title, ann.url, span))
elif ann.type == "file_citation":
sources.append(("file", ann.filename, ann.file_id, None))
elif ann.type == "container_file_citation":
sources.append(("generated", ann.filename, ann.file_id, None))
return sources
for source in collect_sources(response):
print(source)The start_index and end_index values are character offsets into that part's text. They are useful for rendering inline links. If you edit or reformat the text before displaying it, recompute the offsets, because the original ones no longer line up.
Gotchas
- Missing annotations are normal. A model may search and then answer without citing anything. Treat
annotationsas possibly empty, and decide in your application whether an uncited answer is acceptable. - A tool-call item does not prove the answer used it. The item shows the call happened. Only annotations, or the code and results you inspect, show what the answer relied on.
- Several calls per request are possible. The model can search more than once or run code more than once. Loop over all items rather than taking the first match.
- Failed calls can still yield a message. If a
web_search_callhas statusfailed, the model may still write an answer from its own knowledge. Checkstatusbefore you treat the answer as grounded. - Do not index by position.
response.output[0]may be areasoningitem or a tool call. Filter bytype.
The same idea with another provider
Anthropic uses the same pattern with different names. The message.content list holds blocks. A server_tool_use block records the call, and its input holds the query. A web_search_tool_result block holds the results. text blocks carry a citations list.
import anthropic
client = anthropic.Anthropic()
message = client.messages.create(
model="claude-sonnet-4-20250514",
max_tokens=1024,
tools=[{"type": "web_search_20250305", "name": "web_search", "max_uses": 3}],
messages=[{"role": "user", "content": "What changed in the latest Python release?"}],
)
for block in message.content:
if block.type == "server_tool_use":
print("search query:", block.input.get("query"))
elif block.type == "web_search_tool_result":
results = block.content if isinstance(block.content, list) else []
print("results returned:", len(results))
elif block.type == "text":
for cite in getattr(block, "citations", None) or []:
print("cited:", cite.title, cite.url)If the search fails, block.content is an error object instead of a list. The code above handles that by printing zero results. The usage field also reports how many searches ran, in usage.server_tool_use.web_search_requests.
Exercise
A request enables file_search, and the response contains a file_search_call item whose results is null. Did the search return nothing? What should you do to see what was retrieved?
Show answer
Not necessarily. results is null by default because the provider omits it to keep responses small. Re-run the request with include=["file_search_call.results"] to get the retrieved chunks, then check queries and the file_citation annotations on the message.
Exercise
Your code reads response.output[0].content[0].text and sometimes raises an AttributeError when web search is enabled. Why, and how do you fix it?
Show answer
The first output item is often a web_search_call, which has no content. Loop over response.output, keep items where item.type == "message", and then read the parts of type output_text.