Sub topic 2
Designing Tools a Model Can Use Well
Assume you know Python, JSON, web APIs, and the basic prompt–response pattern of a large language model. This chapter focuses on the parts that make an agent reliable after the model chooses a tool.
Design a clear tool contract
A tool is a program function that an agent can call. Give each tool one narrow job, a specific name, and argument descriptions that remove ambiguity. Validate arguments before performing side effects. Return structured results, including errors that the model can understand.
Prefer tools that are safe to repeat, or make repeated calls detectable with an idempotency key.
import json
def get_weather(city: str) -> str:
if not city.strip():
return json.dumps({"error": "city must not be empty"})
return json.dumps({"city": city, "temp_c": 18})
TOOLS = {"get_weather": get_weather}
def run_tool(name: str, arguments: dict) -> str:
tool = TOOLS.get(name)
if tool is None:
return json.dumps({"error": f"unknown tool: {name}"})
try:
return tool(**arguments)
except TypeError as exc:
return json.dumps({"error": f"invalid arguments: {exc}"})
except Exception:
return json.dumps({"error": "tool failed"})Run the agent loop
The agent loop alternates between asking the model for an action and executing that action. The tool result becomes an observation in the conversation history. The model then decides whether to act again or answer.
Handle errors, retries, and stopping
Treat tool errors as data, not as permission to crash or invent a result. A model may correct invalid arguments after seeing an error. Retry only transient failures, such as a timeout, and use a small limit with backoff. Always set a maximum number of steps. Also stop when the model returns an answer, requests an unavailable tool, or repeats the same failing action.
Manage memory and context
Conversation history is the agent's working memory, but the context window has a fixed token limit. Keep the current goal, recent tool results, and important constraints. Summarize older turns and remove duplicate observations. Store durable facts separately from the prompt, and retrieve only facts relevant to the current task.
Ground responses with retrieval
Retrieval finds relevant documents or records before the model answers. Split documents into searchable chunks, retrieve the best matches, and include their contents with source identifiers. Instruct the model to distinguish retrieved evidence from its own assumptions. Retrieval improves grounding, but stale or irrelevant documents can still produce wrong answers.
Choose a planning pattern
Use direct tool calling for short tasks. Add an explicit plan when the task has several dependent steps. Use retrieval when the main uncertainty is missing knowledge. Use multiple agents only when separate roles genuinely reduce complexity; otherwise, coordination adds latency and failure points.
Exercise
Why should an agent receive a tool error as a structured observation instead of an exception that ends the program?
Show answer
The model can inspect the error, correct its arguments, choose another tool, or report failure without losing the conversation state.