Sub topic 2
Sending Tool Results Back to the Model
Assume you know Python, JSON, and chat APIs that use role-tagged messages. The model does not execute a function. Your application executes it, then sends the result back in a tool message.
Sending the result back
A tool result must include the same call ID that the model generated. This lets the model match each result with its request. Append the assistant's tool-call message before appending the result.
import json
def get_weather(city, unit="celsius"):
return {"city": city, "temperature": 7, "unit": unit}
def validate_args(arguments):
if not isinstance(arguments, dict):
raise ValueError("arguments must be an object")
if not isinstance(arguments.get("city"), str):
raise ValueError("city must be a string")
unknown = set(arguments) - {"city", "unit"}
if unknown:
raise ValueError("unknown arguments: " + ", ".join(unknown))
def run_tool_call(call):
try:
validate_args(call["arguments"])
result = get_weather(**call["arguments"])
return {"is_error": False, "content": json.dumps(result)}
except (KeyError, TypeError, ValueError) as exc:
return {"is_error": True, "content": "Invalid tool call: " + str(exc)}
except Exception:
return {"is_error": True, "content": "The weather service failed."}
def call_model(messages):
if messages[-1]["role"] == "user":
return {
"role": "assistant",
"tool_calls": [{
"id": "call_1",
"name": "get_weather",
"arguments": {"city": "Oslo"}
}]
}
return {"role": "assistant", "content": "Oslo is 7 degrees Celsius."}
def run_agent(messages, max_steps=4):
for _ in range(max_steps):
reply = call_model(messages)
messages.append(reply)
calls = reply.get("tool_calls", [])
if not calls:
return reply["content"]
for call in calls:
outcome = run_tool_call(call)
messages.append({
"role": "tool",
"tool_call_id": call["id"],
"content": outcome["content"]
})
raise RuntimeError("Tool loop exceeded its step limit")
print(run_agent([{"role": "user", "content": "What is the weather in Oslo?"}]))Reporting errors so the model can recover
Return tool failures as ordinary tool results with an error marker in the content. The model can then ask for clarification, retry with corrected arguments, or explain that the operation failed. Do not expose passwords, stack traces, or internal paths.
Several calls and loop limits
A model can return several calls in one response. Execute each allowed call, append every result with its matching ID, and call the model again only after all results are available. Always set a step limit to control infinite loops, latency, and cost.
Exercise
Why must a tool result contain the model's original call ID?
Show answer
The ID lets the model associate each result with the correct request, especially when several tools are called together.