Build a Function-Calling Agent in Python
Build a small tool-using agent in Python with the OpenAI SDK: define tools, run the loop, handle tool errors, cap steps and track tokens. Runs on a free model.
An "agent" sounds like a big piece of software. At its core it is a loop: ask the model, run any tools it requests, give it the results, ask again — until it answers in plain text. This post builds one in about 80 lines of Python, using the official openai package pointed at FreeModel.
Our agent answers questions about a folder of text files. It gets two tools — list the files and read a file — and has to decide on its own which files to open.
How the loop works
- Send the conversation plus the tool definitions to
/v1/chat/completions. - If the reply has
tool_calls(andfinish_reasonistool_calls), run each one. - Append the assistant message and one
toolmessage per call, each with itstool_call_id. - Go back to step 1. When the reply has no tool calls, that text is the answer.
The message format is described in the tool calling docs. Everything below is that format plus guardrails.
Step 1: set up the client
pip install openai
export FREEMODEL_API_KEY=fm_your_key_here
We use gpt-6-luna, a free model with the tools capability. Any model with that capability on the models page works with the same code; Claude models such as claude-sonnet-5 need a paid plan.
Step 2: define the tools
Each tool is a JSON Schema description the model reads, plus a Python function you run. Good descriptions matter more than clever code: the model decides when to call a tool purely from its name and description.
import json
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI(api_key=os.environ["FREEMODEL_API_KEY"],
base_url="https://freemodel.in/v1")
MODEL = "gpt-6-luna"
ROOT = Path("./notes").resolve() # the only folder the agent may read
def _safe(rel_path):
p = (ROOT / rel_path).resolve()
if not p.is_relative_to(ROOT):
raise ValueError("path is outside the notes folder")
return p
def list_files(subdir="."):
folder = _safe(subdir)
return sorted(str(p.relative_to(ROOT)) for p in folder.rglob("*") if p.is_file())
def read_file(path, max_chars=4000):
text = _safe(path).read_text(encoding="utf-8", errors="replace")
return {"path": path, "content": text[:max_chars],
"truncated": len(text) > max_chars}
HANDLERS = {"list_files": list_files, "read_file": read_file}
TOOLS = [
{"type": "function", "function": {
"name": "list_files",
"description": "List all text files in the notes folder (paths relative to it).",
"parameters": {"type": "object",
"properties": {"subdir": {"type": "string",
"description": "Optional sub-folder"}}},
}},
{"type": "function", "function": {
"name": "read_file",
"description": "Read one file from the notes folder. Use a path from list_files.",
"parameters": {"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"]},
}},
]
_safe is not decoration. The model chooses the arguments, so treat them like user input: never let a tool read or write outside a folder you chose.
Step 3: write the loop
def run_tool(call):
try:
args = json.loads(call.function.arguments or "{}")
result = HANDLERS[call.function.name](**args)
except Exception as e: # bad JSON, unknown tool, bad path...
result = {"error": f"{type(e).__name__}: {e}"}
return json.dumps(result)
def run_agent(question, max_steps=8):
messages = [
{"role": "system", "content":
"Answer questions using the notes folder. List files first, read only "
"what you need, and cite file names in your answer."},
{"role": "user", "content": question},
]
used = 0
for step in range(1, max_steps + 1):
resp = client.chat.completions.create(
model=MODEL, messages=messages, tools=TOOLS, max_tokens=4096)
used += resp.usage.total_tokens
msg = resp.choices[0].message
if not msg.tool_calls:
print(f"[{step} steps, {used:,} tokens]")
return msg.content
messages.append(msg.model_dump(exclude_none=True))
for call in msg.tool_calls:
print(f" -> {call.function.name}({call.function.arguments})")
messages.append({"role": "tool", "tool_call_id": call.id,
"content": run_tool(call)})
return "Stopped: step limit reached without a final answer."
if __name__ == "__main__":
print(run_agent("Which notes mention the billing migration, and what was decided?"))
Step 4: run it
Create a notes/ folder with a few .md or .txt files and run the script. A typical trace looks like this: one list_files call, then one or more read_file calls — sometimes in parallel in a single response — then the answer. The loop already handles parallel calls, because it answers every entry in tool_calls before asking again.
Guardrails that matter
| Guardrail | In the code | Why |
|---|---|---|
| Step limit | max_steps=8 | A confused model can loop for ever; every step costs tokens |
| Errors become results | run_tool returns {"error": ...} | The model reads the error and corrects itself instead of the program crashing |
| Path sandbox | _safe() | Arguments come from the model, not from you |
| Output truncation | max_chars=4000 | Big tool results are resent on every later step |
| Token tracking | used += resp.usage.total_tokens | Lets you log or stop on a budget |
Add a confirmation step before any tool that changes something — writes a file, sends a message, spends money. Read-only tools can run freely; write tools should ask a human first.
What an agent costs
The chat API is stateless, so each step sends the whole conversation again: system prompt, question, every earlier tool call and every tool result. Input tokens and output tokens both count toward your plan. A run with five steps that each carry 6,000 tokens of history uses roughly 30,000 input tokens, not 6,000.
On a model with a multiplier the plan cost scales too: on a 3× model such as claude-sonnet-5, those 30,000 tokens use 90,000 plan tokens. Truncating tool output and keeping the step limit low are the two biggest savings. For more, see long-context best practices.
When it goes wrong
- The model never calls a tool. Make the descriptions more specific, or set
tool_choice="required"on the first step. json.JSONDecodeErroron arguments. Handled — it becomes an error result. If it happens often, try another model with the tools capability.- 403
upgrade_required. You picked a paid model with a free key. Switch back togpt-6-lunaor upgrade. - Empty final answer. A reasoning model used the whole
max_tokensbudget thinking. Raise it.
FAQ
Do I need a framework to build an agent?
No. An agent is a loop around the chat completions endpoint. A framework can help later, but the loop in this post is about 40 lines and easy to debug.
Which models can I use for this agent?
Any model with the tools capability. gpt-6-luna and claude-haiku-5.5 work on the free plan. Other Claude models such as claude-sonnet-5 work with the same code on a paid plan.
Why does my agent get more expensive with every step?
Each step sends the whole conversation again, including earlier tool results. Truncate tool output, cap the number of steps and keep the system prompt short.
What happens if the model calls a tool that does not exist?
In this loop the call returns an error object as the tool result. The model reads it and usually corrects itself on the next step.
Grab a free API key — 1M tokens on 8 free models after a one-time Telegram verification, no card. Every model from $1.20.