Build an Agent From Scratch: The Tool Loop Without a Framework
Hand-roll a tool-using agent on the chat completions API and nothing else: parse the model's tool calls, dispatch them to plain Python functions, close the loop with correctly threaded tool results, add stop conditions and budgets, turn every failure into a tool result the model can read, put an approval guardrail in front of a side-effecting refund tool, control context with truncation and a trace, and finish with an evaluation run that scores the agent on a fixed question set.
Hands-on labs require Pro · $29.99/mo · cancel anytime
What you'll learn
- 1One round trip: what the model actually sends backAn agent is a loop around one API call. Before writing the loop, look at
- 2The dispatcher: from a tool name to a running functionThe model returns a name and some arguments. Something has to turn that
- 3Close the loopSend the conversation with the tools. If the assistant message carries tool
- 4Stop conditions: budgets for steps, tool calls and tokensThe loop script in fake_client.py is a real transcript. A small model
- 5Errors as information: nothing raises out of the loopTwo more recordings. In malformed, the model's arguments string is two
- 6A guardrail in front of the tool that moves moneyFive of the six tools read or compute. refund writes a line to the refunds
- 7Control the context and trace every stepEvery tool result is appended to the conversation and sent back on every
- 8Evaluate the agent on a fixed question setEverything so far makes the agent robust. Nothing so far says whether it
Prerequisites
- Python: functions, dicts, json, try/except, a while loop
- The chat completions message format: system, user, assistant, tool roles
- Read the module's tool-calling lecture first: the model emits intent, your code executes
Exam domains covered
Skills & technologies you'll practice
This intermediate-level ai/ml lab gives you real-world reps across:
Why build the agent loop yourself
Every agent framework hides the same forty lines: send the conversation with a tools array, read the tool calls off the assistant message, run the matching functions, append one tool message per call with its id, send the conversation back, and repeat until the model answers in text. Building that loop once by hand is the fastest way to understand what the frameworks do, to debug them when they misbehave, and to decide whether you need one at all. The lab goes past the happy path. A scripted model replays real failure transcripts captured from a small model: an endless loop on an unknown order, arguments that are not valid JSON, and an API response with no choices. You add stop conditions and budgets, turn every failure into information the model can act on, put an approval guardrail in front of the refund tool with an audit log, truncate oversized tool results, trace each step, and score the finished agent against a fixed question set with an exit code a CI job can use.