3/17
Part 1 of 7 · The loopLearn and do
The model asks for a tool, your code runs it, and the result goes back
Anthropic's tool use docs put the whole idea in one line: every tool call is a round trip, where the model asks, you execute, you report back, and the model continues. The API says the model wants a tool by returning a stop reason of tool_use with one or more tool_use blocks. Your code runs the tool and sends a new request with all the earlier messages plus the results.
The model in the code below is a stand-in, a short script that plays the LLM's part, so the run is the same every time. The loop around it is the real thing.
def look_up_order(order_id: str) -> str:
"""The shop's order record, as text."""
return {"A17": "A17: 2-person tent, delivered Nov 10, $189.00, unused"}.get(order_id, "no such order")
def return_window(item: str) -> str:
"""The return policy for one kind of item."""
return "unused gear: 30 days from delivery"
# what the payment system did
refunds = []
def issue_refund(order_id: str, amount: float) -> str:
"""Pays the money back. This one has consequences."""
refunds.append((order_id, amount))
return f"refunded ${amount:.2f} on {order_id}"
TOOLS = {"look_up_order": look_up_order, "return_window": return_window, "issue_refund": issue_refund}
def scripted_model(transcript: list[dict]) -> dict:
"""Stands in for the LLM: the next move, given what's happened so far."""
done = [m["tool"] for m in transcript if m["role"] == "result"]
if "look_up_order" not in done:
return {"tool": "look_up_order", "args": {"order_id": "A17"}}
if "return_window" not in done:
return {"tool": "return_window", "args": {"item": "tent"}}
if "issue_refund" not in done:
return {"tool": "issue_refund", "args": {"order_id": "A17", "amount": 189.0}}
return {"answer": "Your refund of $189.00 is on its way."}
for m in run_agent(scripted_model, TOOLS, "I want to return my tent, order A17", 10):
print(m["role"], "|", m.get("tool", ""), m.get("args", m.get("content", m.get("text", ""))))
How many times does run_agent call the model before it gets an answer?
Pick one to see what it prints.
Pick an answer above to see the rest