An agent is a language model in a loop: it decides which tool to call, your code runs the tool, the result goes back to the model, and the loop continues until the model gives a final answer. Frameworks add a lot on top, but the core fits on one screen.
The tools
Tools are ordinary functions plus a description the model can read.
import json, math, datetime
def calculator(expression: str) -> str:
allowed = {"sqrt": math.sqrt, "pi": math.pi}
return str(eval(expression, {"__builtins__": {}}, allowed)) # demo only — use a real parser in production
def today() -> str:
return datetime.date.today().isoformat()
TOOLS = {
"calculator": {"fn": calculator, "description": "Evaluate a math expression", "params": {"expression": "string"}},
"today": {"fn": today, "description": "Get today's date", "params": {}},
}The loop
Most model APIs support native tool calling. To keep this provider-neutral, we ask the model to reply in JSON.
SYSTEM = f"""You can use these tools: {json.dumps({k: {"description": v["description"], "params": v["params"]} for k, v in TOOLS.items()})}
Reply ONLY with JSON: {{"tool": name, "args": {{...}}}} to call a tool,
or {{"answer": "..."}} when you are done."""
def run_agent(question, llm, max_steps=6):
messages = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": question}]
for _ in range(max_steps):
reply = llm(messages) # returns the model's text
messages.append({"role": "assistant", "content": reply})
step = json.loads(reply)
if "answer" in step:
return step["answer"]
tool = TOOLS.get(step.get("tool"))
if tool is None:
result = f"Unknown tool {step.get('tool')!r}"
else:
try:
result = tool["fn"](**step.get("args", {}))
except Exception as e: # errors go back to the model so it can recover
result = f"Error: {e}"
messages.append({"role": "user", "content": f"Tool result: {result}"})
return "Stopped: too many steps."llm is any function that sends messages to a model and returns its text.
What makes agents reliable
- A step limit. Always cap the loop.
- Errors as observations. Return exceptions to the model instead of crashing; it can often fix its own call.
- Narrow, well-described tools. "search_orders(customer_id)" beats "run_sql(query)".
- Human approval for actions with consequences — sending emails, spending money, deleting data.
- Logs of every step, so you can see why it did what it did.
When you need more
Native tool-calling APIs replace the JSON parsing. Frameworks add memory, parallel tools, retries and tracing. But every one of them is this loop underneath.
Takeaways
- Agent = model + tools + loop + stop condition.
- Feed tool results and errors back as messages.
- Constrain tools and require approval for risky actions.