Understand the tool-calling loop with a weather lookup
Follow a weather lookup through tool selection, argument validation, execution, and response correlation while keeping application authority explicit.

If you are adding a tool to an LLM application, the model proposes a tool invocation and the application decides whether and how to execute it. The tool result can then return to the model so it can answer the user. A model-generated tool name is a request for an operation; it is not evidence that the operation has already happened.
A read-only weather lookup is a useful first example because the expected effect is small and observable. Suppose the user asks, “What is the weather in Da Nang?” The application offers a weather tool that accepts a location identifier and a unit. It should be possible to inspect every transition from that question to the displayed answer.
Describe the tool’s contract
The application defines the allowed tool name, its purpose, and a schema for arguments. The schema below is a simplified application contract rather than a complete request body for any particular vendor API:
{
"name": "get_current_weather",
"description": "Read current observed weather for one supported location.",
"parameters": {
"type": "object",
"properties": {
"location_id": {"type": "string"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location_id", "unit"],
"additionalProperties": false
}
}
The description says “current observed weather” so that the tool is not mistaken for a forecast service. A location identifier avoids relying on a free-text city name that may be ambiguous. In a real application, the model may need a separate location search or a clarification before it can supply a valid identifier.
The OpenAI function calling guide, retrieved on September 20, 2026, describes a multi-step flow in which the application executes the requested function and returns its result. Request envelopes vary across APIs and versions. The separation between a proposed call and application execution remains the design point to preserve.
Follow a concrete trace
Imagine the model returns a call with identifier call-17, tool name get_current_weather, and arguments for the supported location vn-da-nang. The application parses the arguments and validates the schema. It also checks that this tool is allowed for the current request and that the location identifier exists.
Only after those checks does the application invoke the weather service. Suppose the service returns a hypothetical observation of 29 degrees Celsius with an observation timestamp. The application wraps that result with the same call identifier. The model can now explain the observation and its age to the user.
The temperature in the figure is illustrative. It is not a report of current weather. The call identifier matters when a response contains multiple proposed calls: each result must be associated with the call that requested it. Attaching one city’s weather to another city’s call would produce a plausible but incorrect answer.
The application should keep transport success separate from tool success. An HTTP response can arrive successfully while reporting that the location was unknown or that no observation is available. The model needs a truthful result such as no_observation, not an empty success object that encourages it to fill the gap.
Validate beyond JSON shape
A schema can reject an unexpected unit, missing field, or extra property. It does not prove that a location belongs to the user’s organization or that a requested operation is permitted. Those are application checks. For a weather tool they may be simple; for an internal customer-search tool they can determine whether sensitive records are exposed.
Tool descriptions should also be treated according to their origin. The MCP tools specification for revision 2025-06-18 defines discovery and invocation messages for tools. Protocol compatibility does not turn every connected server into a trusted authority. A server’s description is data that the host needs to evaluate within its security policy.
Likewise, a tool result may contain untrusted text. A weather provider’s description field should not gain permission to request a file upload merely because the model can read it. The executor should permit only operations within the task’s allowed capabilities, regardless of text encountered in a result.
Execute one call before building the loop
A small executor can make the boundary observable. This Python function accepts an already parsed call envelope with a nonempty, unique string id, a string name, and an arguments field. The surrounding application owns envelope validation and uniqueness. The function validates this tool’s arguments before invoking an injected service adapter; it does not dynamically resolve arbitrary function names.
def execute_weather(call, read_weather, allowed_locations):
def reply(status, **fields):
return {"call_id": call["id"], "status": status, **fields}
if call["name"] != "get_current_weather":
return reply("unsupported_tool")
args = call["arguments"]
if (type(args) is not dict
or set(args) != {"location_id", "unit"}
or type(args["location_id"]) is not str
or type(args["unit"]) is not str
or args["unit"] not in {"celsius", "fahrenheit"}):
return reply("invalid_arguments")
if args["location_id"] not in allowed_locations:
return reply("unsupported_location")
try:
observation = read_weather(args["location_id"], args["unit"])
except TimeoutError:
return reply("unavailable")
if observation is None:
return reply("no_observation")
return reply("observed", observation=observation)
calls = []
def stub(location, unit):
calls.append((location, unit))
return {"value": 29, "unit": "celsius", "observed_at": "2026-09-21T01:00:00Z"}
call = {"id": "call-17", "name": "get_current_weather",
"arguments": {"location_id": "vn-da-nang", "unit": "celsius"}}
print(execute_weather(call, stub, {"vn-da-nang"}))
print(len(calls))
This literal fixture returns status observed, preserves call-17, and calls the stub once. Its timestamp and temperature are fabricated test data. Change the unit to kelvin or add a user_id argument: the status becomes invalid_arguments, and the service receives no additional call. An allowed location comes from application configuration or authenticated scope, not from a list supplied by the model.
The adapter contract matters too. The minimal stub only supplies the demonstrated Celsius response. A real adapter must validate the provider’s payload and return the requested unit, a finite measurement and a usable timestamp, or an explicit failure. This executor assumes that adapter contract; it does not verify arbitrary response dictionaries. Test a Fahrenheit adapter separately so a correct argument does not yield a Celsius value mislabeled as Fahrenheit. Unexpected adapter exceptions should reach controlled application error handling rather than being disguised as a valid empty observation.
Replace the stub with one returning None, then one raising TimeoutError: each is invoked once, but the statuses differ. Next execute calls call-17 and call-18 for two supported locations and retain the identifiers even if later asynchronous execution completes them in reverse order. The caller must reject duplicate IDs before dispatch; this one-call function alone cannot establish uniqueness across requests.
Ken Aizawa’s Anthropic engineering article, published September 11, 2025, recommends reading raw tool transcripts alongside task outcomes and error counts. That practice helps distinguish a bad selection from a failed execution. Its evaluation guidance concerns realistic tasks; our deterministic weather stub checks only executor behavior and provides no evidence that a model understands real users’ weather questions.
Bound the loop
Some requests need another call after the first result. If the location is ambiguous, the assistant may search locations and then fetch weather. If a provider fails briefly, the application might retry. Define a maximum number of calls and an overall deadline so that these paths cannot continue indefinitely.
A useful terminal result is explicit: completed with an observation, needs clarification, temporarily unavailable, or rejected because the request is unsupported. The final answer should reflect that state. “I checked the weather” is false if the service timed out before returning an observation.
For the first test, use a stub service with known responses. Verify that valid arguments invoke the service once, invalid units invoke it zero times, and a timeout produces an unavailable answer. Add a two-call case to check correlation identifiers. These tests inspect the application loop; they do not require a live weather provider or a claim about model quality.
Once the loop behaves correctly, evaluate whether the model selects the right tool and arguments for actual user wording. Keep that evaluation separate from executor correctness. A perfect executor cannot repair every misunderstood question, and an accurate model should not be asked to compensate for missing authorization or ambiguous result handling.