Build a working tool-calling AI agent in under 50 lines of Python — the same plan-act-observe loop behind Dots, Muse and Grok Bot. Run it free in your browser.
Published 2026-10-14
TL;DR
An AI agent is a loop: ask the model for the next action, run the matching tool, feed the result back, and stop when the model returns a final answer or you hit a step limit. The example below does exactly that in about 40 lines and runs in your browser with no API key.
Key takeaways
Agents = model + tools + loop + stop condition.
Have the model return structured JSON ({"tool", "input"} or {"final"}) so your code can act on it.
Always cap steps and reject unknown tools — that prevents runaway agents.
Start with a stub model, then swap in a real API once the loop works.
The whole idea: one loop
Products like OpenAI Dots, Meta Muse and Grok Bot look magical, but each step they take is the same: the model picks an action, your code runs it, the result goes back to the model. Repeat until done.
The 40-line agent
How it works
Tools are plain functions in a dictionary. The model (stubbed as fake_llm) returns either {"tool", "input"} or {"final"}. The loop runs the tool, stores the result in history, and asks again. The guard rails — max_steps and the unknown-tool check — keep it from looping forever or calling something it shouldn’t.
Extend it
Open it in the editor and ask the AI assistant: "add a tool that reverses a string" or "add memory so the agent remembers past goals." Then follow the LLM API guide to replace the stub with a real model. If it breaks, check the 7 most common agent bugs.
Frequently asked questions
Do I need LangChain to build an agent?
No. For simple agents, a plain loop like the one here is easier to read and debug. Frameworks help once you need memory, many tools or multiple agents.
How do I connect a real model?
Replace fake_llm() with a call to any chat API that supports JSON output or tool calling, and parse its reply into the same dict shape. See our LLM API guide for Groq, OpenRouter and Gemini examples.
Is eval() safe in the calculator tool?
Only for demos. In a real agent, use a proper math parser — model output should never be run as code without sandboxing.