Lab 5 of 8 · Tools and agents
Give the assistant tools
Let Claude search the documents and calculate exact refunds with two tools, in a loop with a step limit.
- Time
- 60 minutes
- Cost
- About a cent of API credit.
What you learn
Models are bad at exact arithmetic and cannot look things up on their own. Tools let a model ask your code to do those jobs; an agent is a loop that keeps calling tools until the task is done.
- Describing a tool with a JSON schema
- The tool-use loop: ask, run, return the result
- Limiting steps so an agent cannot run forever
- When an agent is the right design, and when it is not
In the AI era: Agents are what most companies mean by "AI that does work". The engineering is in the guard rails: few, well-described tools, step limits, and never letting the model take risky actions alone.
Before you start
Finish lab 4.
Step by step
1 Write the tools and the loop
The model decides when to call
search_docsorrefund_amount. Your code runs the tool and sends back the result, until the model gives a final answer or reaches 5 steps.import json import sys from llm import MODEL, client, text_of from rag import search TOOLS = [ { "name": "search_docs", "description": "Search Northwind Coffee's policy documents. Returns the most relevant paragraphs.", "input_schema": { "type": "object", "properties": {"query": {"type": "string", "description": "What to look for"}}, "required": ["query"], }, }, { "name": "refund_amount", "description": "Exact refund for an order under the refund policy.", "input_schema": { "type": "object", "properties": { "price": {"type": "number", "description": "Order price in dollars"}, "days_since_delivery": {"type": "integer"}, "opened": {"type": "boolean"}, }, "required": ["price", "days_since_delivery", "opened"], }, }, ] def refund_amount(price: float, days_since_delivery: int, opened: bool) -> dict: if not opened and days_since_delivery <= 30: return {"refund_to_card": price, "store_credit": 0} if opened and days_since_delivery <= 14: return {"refund_to_card": 0, "store_credit": price} return {"refund_to_card": 0, "store_credit": 0, "reason": "outside the return window"} def run_tool(name: str, arguments: dict) -> str: if name == "search_docs": return json.dumps(search(arguments["query"])) if name == "refund_amount": return json.dumps(refund_amount(**arguments)) return json.dumps({"error": f"unknown tool {name}"}) def ask(question: str, max_steps: int = 5) -> str: messages = [{"role": "user", "content": question}] for _ in range(max_steps): message = client().messages.create( model=MODEL, max_tokens=600, system="You help Northwind Coffee customers. Use the tools for policies and numbers.", tools=TOOLS, messages=messages, ) if message.stop_reason != "tool_use": return text_of(message) messages.append({"role": "assistant", "content": message.content}) results = [] for block in message.content: if block.type == "tool_use": print(f" [tool] {block.name}({block.input})") results.append( {"type": "tool_result", "tool_use_id": block.id, "content": run_tool(block.name, block.input)} ) messages.append({"role": "user", "content": results}) return "I could not finish this within the step limit." if __name__ == "__main__": print(ask(" ".join(sys.argv[1:]) or "I opened a $27.50 bag 10 days ago. What do I get back?"))2 Watch it use the tools
The
[tool]lines show each decision the model made.python agent.py "I opened a $27.50 bag 10 days ago. What do I get back?" python agent.py "Is support open on Saturday?"You should see:A
refund_amountcall and an answer of $27.50 in store credit; then asearch_docscall and an answer that support is closed on Saturdays.3 Test the tool logic
The money calculation is plain code, so test it like plain code.
from agent import refund_amount def test_unopened_within_30_days_is_a_full_refund() -> None: assert refund_amount(20, 10, opened=False) == {"refund_to_card": 20, "store_credit": 0} def test_opened_within_14_days_is_store_credit() -> None: assert refund_amount(20, 10, opened=True) == {"refund_to_card": 0, "store_credit": 20} def test_late_returns_get_nothing() -> None: assert refund_amount(20, 40, opened=False)["reason"] == "outside the return window"4 Run the tests and push
All tests so far should pass.
python -m pytest -q git add agent.py tests git commit -m "Add a tool-using agent with a step limit" git pushYou should see:5 passed.
You are done when
The agent calls the right tool for each question.
Refund numbers come from your code, not from the model's arithmetic.
The loop stops after at most 5 steps.
We check your public GitHub repository and give you a page to share with recruiters, and can add the project to your resume.