A raw OpenAI agent loop built from first principles β no frameworks, no LangChain, just the OpenAI API and Python.
Most AI agent courses use LangChain or the OpenAI Agents SDK which hide the agent loop behind abstractions. This project implements that loop manually to show exactly what's happening underneath every framework.
The agent solves a multi-step crypto price calculation by:
- Breaking the problem into steps using a todo list
- Carrying out each calculation step using tool calls
- Returning a formatted final answer in the terminal
Send messages to GPT
β
GPT wants to call a tool? β run the tool, add result to messages, loop again
β
GPT is done? β return the final answer
The key is finish_reason. When GPT returns "tool_calls" it wants to run a function. When it returns "stop" it's done. That's the entire loop.
create_todos(descriptions: list[str])
Creates a list of calculation steps for the agent to work through. Returns the full todo list.
mark_complete(index: int, completion_notes: str)
Marks a step as done and records the result. Returns the updated list.
A crypto trader buys Bitcoin at $42,000.
It drops 15% the first week, then rises 22% the second week.
What is the current price and the net percentage gain or loss?
The agent plans its own steps, calculates each one, and returns the final answer β no hardcoded logic, just GPT reasoning with tools.
- Python
- OpenAI API
gpt-5.2 - Rich β terminal formatting
- python-dotenv β API key management
Requires uv. Install it if you don't have it:
pip install uvClone the repo and install dependencies:
git clone https://github.com/agenticmohit/agent-loop-from-scratch
cd agent-loop-from-scratch
uv syncCreate a .env file:
OPENAI_API_KEY=your_key_here
Run:
uv run main.pyThe agent creates todo steps β calculate price after week 1 drop, calculate price after week 2 rise, calculate net change β marks each complete with the result, then returns a formatted terminal summary.
Understanding what happens inside agent.invoke() or Runner.run() makes you a better AI engineer. This is the raw loop β the internals every framework is built on top of.
Part of my AI engineering learning path. See also: