Projects · Advanced · 4–6 hours
A tool-using agent
Build the agent loop yourself: tools, a step limit, a trace of every action, and tests that don't need an API.
A small support agent that looks up orders and does arithmetic, stops safely, and leaves a readable trace of everything it did.
Python 3 and NumPy where the code imports it. None needed: the tools use a small built-in order table.
Steps
Tick each step off as you finish it. Your progress is saved on this device, and to your account when you sign in.
Write the tools
Tools are plain functions with clear inputs and plain-text results. The calculator refuses anything except numbers and operators, so the model can't run code through it.
Python ORDERS = {"A-1042": {"status": "shipped", "total": 1499}, "A-1043": {"status": "processing", "total": 650}} def get_order(order_id: str) -> str: order = ORDERS.get(order_id.strip().upper()) return f"{order_id}: {order['status']}, total ₹{order['total']}" if order else f"error: no order {order_id}" def calculator(expression: str) -> str: if not set(expression) <= set("0123456789+-*/(). ") or "**" in expression: return "error: only numbers and + - * / ( ) are allowed" try: return str(round(eval(expression, {"__builtins__": {}}), 4)) except Exception as e: return f"error: {e}" TOOLS = {"get_order": get_order, "calculator": calculator}Check: calculator('9**9**9') returns an error instead of freezing your computer.
Write the loop
Ask the model for the next action, run the tool, feed the result back, and repeat until it answers or hits the step limit. Errors go back to the model as text so it can recover.
Python import json def run_agent(goal, model, tools=TOOLS, max_steps=6): """model(messages) returns {"tool": name, "args": {...}} or {"answer": text}.""" messages = [{"role": "user", "content": goal}] trace = [] for step in range(max_steps): reply = model(messages) if "answer" in reply: return reply["answer"], trace name, args = reply.get("tool"), reply.get("args", {}) try: result = tools[name](**args) if name in tools else f"error: unknown tool {name}" except TypeError as e: result = f"error: bad arguments ({e})" trace.append({"step": step, "tool": name, "args": args, "result": result}) messages.append({"role": "assistant", "content": json.dumps(reply)}) messages.append({"role": "user", "content": f"Tool result: {result}"}) return "Stopped: step limit reached.", traceTest with a fake model
Before paying for API calls, drive the loop with scripted replies.
Python def scripted(replies): """A fake model that returns fixed replies in order, for testing the loop without an API.""" queue = list(replies) return lambda messages: queue.pop(0) if queue else {"answer": "(out of script)"}Check: A script that looks up orders A-1042 and A-1043 and adds their totals ends with ₹2,149.
Connect a real model
Describe each tool with a JSON schema and let the provider's tool calling pick one. This turns the model's reply into the shape run_agent expects. It reuses chat() from the document-chat project, with the same LLM_API_KEY.
Python import json SYSTEM = "You are a support agent for an online store. Use the tools to look up orders and to do any arithmetic, one call at a time. Then answer the customer in one or two sentences." TOOL_SPECS = [ {"type": "function", "function": {"name": "get_order", "description": "Look up an order's status and total in rupees", "parameters": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}}}, {"type": "function", "function": {"name": "calculator", "description": "Arithmetic with + - * / and brackets", "parameters": {"type": "object", "properties": {"expression": {"type": "string"}}, "required": ["expression"]}}}, ] def llm_model(messages): """Turns the model's reply into the shape run_agent expects: a tool call or a final answer.""" msg = chat([{"role": "system", "content": SYSTEM}] + messages, tools=TOOL_SPECS) if msg.get("tool_calls"): call = msg["tool_calls"][0]["function"] try: args = json.loads(call.get("arguments") or "{}") except json.JSONDecodeError: args = {} return {"tool": call["name"], "args": args} return {"answer": (msg.get("content") or "").strip()}Check: Asked 'What do my orders A-1042 and A-1043 cost together?', it calls get_order twice and the calculator, then answers ₹2,149.
Add guardrails
Detect an agent stuck repeating the same call, keep the step limit, and save every trace.
Python def repeated_call(trace, times=3): """Spot an agent stuck calling the same tool with the same arguments.""" calls = [(t["tool"], json.dumps(t["args"], sort_keys=True)) for t in trace] return any(calls.count(c) >= times for c in calls)Check: A model that keeps calling the same tool is stopped and flagged.
- Answers questions that need two or more tool calls
- Stops cleanly at the step limit
- Every run leaves a readable trace
Go further
- Add a refund tool that needs approval above ₹1,000
- Add a cost budget per run
- Write 15 test tasks and measure the success rate over 3 runs each
This project is part of Pro
The first two projects are free. Pro opens every lesson and every project.
See Pro plansFrom ₹119 a month. No auto-renewal.