How To Build AI Agents From Scratch

You do not need a heavy framework like LangChain to build your first AI agent. An AI agent is just a short Python loop that connects a language model to local functions on your computer until a task finishes.

A regular chatbot answers one prompt and stops. An agent looks at the tools you gave it, asks your code to run one, reads the output, and picks the next step on its own.

What You Need to Get Started

You only need four small pieces to build a working agent:

  • An API key from OpenAI, Anthropic, or Google Gemini that supports function calling.
  • Two or three plain Python functions, such as reading a log file or checking free disk space.
  • A Python list that stores the conversation, every tool request, and each tool result.
  • A hard step limit like max_steps = 10 so a stuck model cannot loop forever and waste your money.

Write Your Tools Before Prompts

Suppose your website crashed last night and you want an agent to check the server logs. Write two simple functions first: read_log_tail(path, lines) and get_disk_usage(mount).

Give each function clear argument names and a one-line description. The AI reads those descriptions to decide which function fits the user's question.

Always return plain text from your tools, even when something breaks. If read_log_tail cannot find a file, catch the error and return "Error: file not found" instead of letting Python crash.

Models read error text well and often check the parent folder on the next turn to find the right file. Also cut off any output past 4,000 characters so huge files do not inflate your API bill on every loop turn.

Connect the Loop Safely

Your AI model cannot touch your hard drive directly. You pass a JSON Schema list of your functions to the API, and the model replies with a JSON request asking your script to run one.

Put the API call inside a for loop that stops after 10 rounds. Each round, run whatever function the model asked for, save the text output to your history list, and send the updated list back. When the model replies with plain English instead of a function request, print the answer and stop.

Never let an agent delete files, run database writes, or send emails without asking you first, a risk security teams call OWASP LLM06. Put an input("Approve? y/n: ") check inside any tool that changes data, and lock file reads to one safe folder with Path.resolve().

Test Before You Trust It

Try breaking your agent with fake file paths and impossible questions before using it on real work. For more practical AI tutorials and crypto tech guides, check out 3verse TV at https://www.3versetv.com/.