Sub topic 12
Operating Tool-Using and Agentic Workflows
Prerequisites and the operating model
This chapter assumes you understand Python, API-based model calls, basic logging, and the difference between a prompt and a model. It also assumes you know that a tool is a controlled function an LLM application can call, such as looking up an order or creating a calendar event.
A tool-using workflow has a model choose from available functions. An agentic workflow repeats this process until it reaches a stopping condition. The application, not the model, must own the control loop:
- Send the user request and tool descriptions to the model.
- Inspect the model's response.
- If it requests a tool, validate the arguments.
- Apply authorization and safety checks.
- Run the tool with a timeout.
- Return the result to the model.
- Stop when the model produces a final answer or the workflow reaches a limit.
The model proposes an action. Your application decides whether that action is allowed.
A bounded tool loop
The following example uses a fake order lookup. It demonstrates the important operational boundary without requiring an external model API. A production adapter would replace choose_action with an SDK call.
from dataclasses import dataclass
from typing import Any
@dataclass
class ToolCall:
name: str
arguments: dict[str, Any]
ORDERS = {
"A-100": {"status": "shipped", "eta": "2026-12-03"},
"A-101": {"status": "processing", "eta": "2026-12-05"},
}
def get_order(order_id: str) -> dict[str, str]:
if order_id not in ORDERS:
return {"error": "order not found"}
return ORDERS[order_id]
def choose_action(messages: list[dict[str, str]]) -> ToolCall | None:
"""A stand-in for a model response."""
user_text = messages[0]["content"]
if "A-100" in user_text and not any(
message["role"] == "tool" for message in messages
):
return ToolCall("get_order", {"order_id": "A-100"})
return None
def run_agent(user_text: str, max_steps: int = 3) -> str:
messages = [{"role": "user", "content": user_text}]
tools = {"get_order": get_order}
for step in range(max_steps):
call = choose_action(messages)
if call is None:
return "I could not find a tool action to take."
if call.name not in tools:
return f"Blocked unknown tool: {call.name}"
if set(call.arguments) != {"order_id"}:
return "Blocked invalid tool arguments."
result = tools[call.name](**call.arguments)
messages.append({"role": "tool", "content": str(result)})
if result.get("error"):
return f"Lookup failed: {result['error']}"
return f"Order {call.arguments['order_id']} is {result['status']}."
return "Stopped: maximum steps reached."
print(run_agent("Where is order A-100?"))The step limit prevents an infinite loop. Real systems should also enforce a total time limit, a maximum number of tool calls, and limits on returned data. Validate types, ranges, and ownership before executing a tool. Never let a model-supplied identifier bypass the application's authorization checks.
Reliability and observability
Treat every tool as a production dependency. Give each call a timeout, retry only operations that are safe to repeat, and use idempotency keys for actions such as payments or account changes. Separate read tools from write tools. Require explicit approval before high-impact writes.
Record a trace for the user request, every model turn, every tool name, arguments after sensitive values are redacted, result status, latency, and token usage. This trace helps distinguish model errors from tool failures and slow downstream services. Store the prompt and tool-schema versions with the trace so a later investigation can reproduce the workflow.
Exercise
Why should the application, rather than the model, enforce the maximum number of tool calls?
Show answer
The application controls execution and can reliably stop loops, contain cost, and protect downstream systems even when the model keeps requesting actions.