Exchange
The loop in 50 lines of Python
1 file3 KB
A look inside
The first lines of agent-loop.zip. The whole file is in your library once you get it.
# ABOUTME: The agent loop on one page: a model asks for tools, this code runs them, results go back.
# ABOUTME: Needs `pip install anthropic` and ANTHROPIC_API_KEY. It can only list and read files here.
import os
MODEL = "claude-haiku-5-5" # the cheapest current Claude model (read 27 Oct 2026)
MAX_LAPS = 10 # a stopping condition of our own
tools = [
{"name": "list_files", "description": "List the files in the current folder.",
"input_schema": {"type": "object", "properties": {}}},
{"name": "read_file", "description": "Read a text file in the current folder.",
"input_schema": {"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"]}},
]
def run_tool(name, args, folder="."):
here = os.path.realpath(folder)
if name == "list_files":
return "\n".join(sorted(f for f in os.listdir(here)
if os.path.isfile(os.path.join(here, f))))
if name == "read_file":
path = os.path.realpath(os.path.join(here, args.get("path", "")))
…and 32 more lines.What is inside
- agent-loop.zip3 KB
How to use it
The whole agent loop on one page: a model asks for a tool, this code runs it, and the result goes back, until the task is done.
Put it in a folder of text files, run pip install anthropic, set ANTHROPIC_API_KEY, then run python3 agent_loop.py. It can only list and read the files in the folder it runs in. The tests beside it need no key: python3 -I -m unittest.
Run before it was listed
Tested 2026-11-27: python3 -I -m unittest: 6 tests passed with a stub client and no key. A live run with a real API key is still owed.