How to Build an Autonomous AI Agent from Scratch in Python
You can build an autonomous AI agent in plain Python with a short loop, a few tools and a memory file. Here is how the parts fit and a six-step build.
On this page
Short answer
An autonomous AI agent built from scratch in Python is a program that takes a goal, plans its own steps, calls tools to act, and checks its results in a loop until the goal is done. You build it with plain Python: a loop that sends the goal and the conversation so far to a language model, runs the tool it picks, and feeds the result back in.
What is an autonomous AI agent built from scratch in Python?
An autonomous AI agent built from scratch in Python is a program that works toward a goal on its own, choosing its next step each time instead of following a fixed script. You write it with plain Python and the standard library, plus calls to a language model, rather than installing an agent framework.
The agent runs a loop. It looks at the goal and what has happened so far, asks the model what to do next, runs the tool the model picks, and feeds the result back into the next round. The loop keeps going until the goal is met, the agent asks a person for help, or it hits a limit you set.
Building from scratch means you own every part: the prompt, the tool list, the memory, the limits and the logs. That is more work than using a framework, but it leaves nothing hidden. When the agent does something odd, you can read the exact code that decided it, which makes debugging far easier.
What parts does a from-scratch agent need?
A from-scratch agent needs five parts, and each one is a small piece of Python you can write and test on its own. If one part is missing, the agent either cannot act or cannot be trusted.
| Part | What it does | Plain Python form |
|---|---|---|
| Goal | States what done looks like | A short string and a check function |
| Loop | Runs observe, think, act, check | A while loop with a step limit |
| Tools | Let the agent act on the world | Named functions with a short description |
| Memory | Keeps facts and past results | A list of messages plus a notes file |
| Limits | Stop runaway work | Max steps, max cost, allowed tools |
The model is the reasoning part, but it is not the agent. The agent is the loop, the tools and the memory around the model. You can swap the model later without rewriting the rest, because the rest is your code.
How does the agent loop work?
The agent loop works in four steps that repeat: observe, think, act and check. Each round starts with the current state, which is the goal plus the messages and tool results so far.
In the think step, your code sends the state to the language model with a list of the tools it may use. The model replies with either a tool call or a final answer.
In the act step, your code runs the named tool with the arguments the model gave, and records the result. In the check step, your code asks whether the goal is met, whether the step limit is reached, or whether the agent asked for help.
Keep each round small. One tool call per round is easier to log and to roll back than several at once. If a tool fails, feed the error message back to the model in the next round so it can try a different approach instead of repeating the same call.
How do you give the agent tools?
You give the agent tools by writing ordinary Python functions and describing each one in a short text the model can read. Each description states the tool name, what it does, and what inputs it needs.
A good tool does one job and returns a short text result. A search tool returns a few lines of matches, a file tool returns the lines it read, and a send-message tool returns a confirmation. Long results waste the model's reading budget and hide the useful part, so trim results before they go back into the loop.
Tools are where the risk lives, so guard them. A tool that sends mail or moves money should check its inputs, refuse anything outside its allowed list, and ask a person to confirm before it acts. The agent should never call a tool you would not run by hand, and every call should be written to a log you can read later.
How do you add memory without a framework?
You add memory without a framework by keeping two things: the running list of messages in the loop, and a short notes file the agent updates as it learns facts. The message list is short-term memory; the notes file is long-term memory.
The message list grows with every round, so it needs trimming. Keep the goal, the latest tool results and a short summary of earlier rounds, and drop the oldest detail. A simple rule is to summarise the list when it passes a size you choose, and keep the summary as the first message.
The notes file holds facts the agent should remember across runs, such as a customer's preferred format or a supplier's account number. Let the agent add a line only when it has confirmed the fact from a tool result, never from a guess. Read the notes file yourself from time to time, because bad facts in memory become bad decisions in every later run.
How to build it in six steps
Build your first from-scratch agent in six steps, testing each one before moving on. A working loop with one tool beats a large agent that has never run.
- Pick one narrow goal. Choose a task with a clear end, such as triaging a support inbox or checking a price list, not a vague job like handling customers.
- Write the loop first. Build the observe, think, act and check cycle with a fake model reply, so the loop works before any model call is made.
- Add one tool. Give the agent a single safe tool, such as reading a file or searching a list, and watch it use the tool correctly.
- Add the model call. Connect the loop to a language model, pass the goal and the tool list, and log every reply and tool call.
- Add memory and limits. Add the notes file, message trimming, a step limit and a cost limit, then run the agent on real inputs.
- Test with hard cases. Feed it missing data, a broken tool and a goal it cannot meet, and check that it stops cleanly and asks for help.
Ship the agent behind a switch you can turn off. Run it on a small share of real work first, read its logs daily, and only widen its scope once its mistakes are rare and cheap.
Example (hypothetical): an invoice-triage agent
Example (hypothetical): a small finance team gets 200 supplier invoices a day and wants an agent to sort them before a person reviews them. The goal is simple: for each invoice, decide whether it matches a purchase order, and put the rest in a review pile.
The agent reads each invoice with a file tool, checks the amount and supplier against the order list with a lookup tool, and writes its decision to a results file. On a test day it sorts 140 invoices as matching, sends 40 to review because the amounts differ, and stops on 20 where the supplier is missing from the order list.
The arithmetic is easy to check. The team spends 140 times 1 minute, or about 2 hours and 20 minutes, reviewing the 140 sorted invoices in a quick pass, plus 40 times 5 minutes, or 3 hours and 20 minutes, on the review pile.
That is 5 hours and 40 minutes against the 200 times 5 minutes, or 16 hours and 40 minutes, the manual sort used to take. The 20 stopped invoices go to a person the same day, so nothing is silently dropped.
What are the common mistakes?
The most common mistakes are giving the agent too much freedom, letting its memory grow without limit, and trusting tool results it never checked.
- No step limit. An agent without a maximum step count can loop for hours on a goal it cannot meet. Set a limit and stop cleanly.
- Tools that do too much. A tool that both reads and writes is harder to test and easier to misuse. Split tools into small, single jobs.
- Unbounded memory. Feeding the whole history into every round slows the agent and confuses the model. Summarise and trim.
- Silent failures. If a tool fails and the agent carries on as if it worked, the result looks finished but is wrong. Log every failure.
- No human checkpoint. Letting an agent send mail or spend money without a confirmation step is how small bugs become real losses.
- Testing only the happy path. Test missing data, bad inputs and broken tools, because those are the cases that reach production.
Key takeaways
- The agent is the loop, the tools and the memory, not the model alone
- One tool call per round is easier to log, test and roll back
- Guard every tool that writes, sends or spends, and log every call
- Trim memory with summaries and keep confirmed facts in a notes file
- Set step and cost limits, and test the cases where the agent must stop
Frequently asked questions
Do I need a framework to build an AI agent in Python?
No. A framework adds ready-made loops, tool handling and memory, but you can write those parts yourself in plain Python. Building from scratch takes more code, yet it leaves every decision visible, which makes debugging and testing simpler for a first agent.
How much Python do I need to know?
You need the basics: functions, loops, lists, dictionaries and file handling, plus how to call a web API with a library such as requests. You do not need advanced Python or any machine learning knowledge, because the language model does the reasoning.
How do I stop the agent looping forever?
Set a maximum step count, such as 20 rounds, and a maximum cost or time budget, and check both after every round. Also give the agent a way to say it is stuck, so it asks a person for help instead of trying the same failing tool again.
Which tools should an agent have first?
Start with one safe read-only tool, such as searching a list or reading a file, and add tools one at a time. Add a write tool only after the read tools work well, and guard it with input checks and a confirmation step.
How do I test an agent before it touches real work?
Run it on past cases where you know the right answer, and compare its results. Then feed it missing data, a broken tool and an impossible goal, and check that it stops cleanly, logs the problem and asks for help.
Can a from-scratch agent use more than one model?
Yes. The loop is separate from the model, so you can call one model for planning and a cheaper one for simple steps, or swap models later. Keep the model choice in one place in your code so changing it is a single edit.