Skip to content
trending

Guides

AI Agents from Scratch: How They Work & How to Build One

A step-by-step guide to building AI agents: API basics, automation, and agents. 30-day plan, working Python code, 5 framework tests, and free courses.

By 11 min read
AI Agents from Scratch: How They Work & How to Build One

👁 126 reads

An AI agent is a program in which a language model runs in a loop, choosing a tool, examining the result, and deciding what to do next until it completes the task. To build your first agent and truly understand what’s happening, go through three stages: model APIs, automation, and agents. This page is a roadmap for that path, a 30-day learning plan, code I ran on my own computer on October 4, 2026, and a list of the best free courses and channels I checked the same day.

Status as of October 4, 2026

  • I ran all examples from this path on Windows 11 and Python 3.13: function calling, agent without a framework, the same agent in 4 frameworks, RAG on 3 Polish laws, custom MCP server, webhook from a form.
  • Total cost of all tests via OpenRouter: approximately 0.15 USD. Single agent task on a cheap model: approximately 0.001 USD.
  • Current versions: openai 3.24.0, openai-agents 0.23.1, langgraph 1.2.12, crewai 1.15.23, claude-agent-sdk 0.2.163, mcp 2.3.0 (in which FastMCP was renamed to MCPServer).
  • Ready-to-download code: ai-agents-starter package (zip, README in Polish).

Roadmap: From API to Your Own Agent

The most common mistake at the start is jumping straight into an agent framework. It works until something breaks, and then you don’t know where to look. That’s why the path has three stages, each building on the previous one:

Stage 1

Model APIs

Request, response, tokens, cost, key. AI API from scratch, tokens, OpenRouter.

Stage 2

Automation

Fixed steps, one of them done by AI. webhook, automation with AI, n8n, Make.

Stage 3

Agents

Model chooses steps itself. function calling, agent in Python, RAG, MCP, frameworks.

Stage 1 is covered by a separate guide, AI API. Here I focus on stages 2 and 3. If you prefer clicking to writing code, you can also go through stage 3 in Gumloop or in the AI Agent node in n8n, but understanding will come faster when you see the loop once in 76 lines of Python.

How an Agent Works: The Loop in Four Moves

Every agent, from my simplest one to Claude Code, does the same thing. The model doesn’t execute anything itself: it only requests a tool, and your program executes it and returns the result.

AI agent loop Task goes to model. Model makes decision: either requests tool or finishes with answer. Tool returns observation, which goes back to model. Step limit and log guard the loop. Taskfrom human 1. Modelreads task and entire history 2. Decisiontool or finish? 3. ToolYour code: file, API, calculator 4. Observationresult goes back to history request loop finish: answer safeguards: step limit, decision log,human approval for irreversible actions
Agent loop: model, decision, tool, observation. Diagram made in SVG based on my code from the article How to Build an AI Agent in Python.

In code it looks like this (fragment of my agent, full version in the article about building an agent):

    for step in range(1, MAX_STEPS + 1):
        r = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOLS)
        cost += getattr(r.usage, "cost", 0) or 0
        msg = r.choices[0].message
        messages.append(msg.model_dump(exclude_none=True))
        if not msg.tool_calls:
            print(f"--- finished after {step} steps, cost {cost:.5f} USD")
            return msg.content
        if msg.content: print(f"[step {step}] THOUGHT: {msg.content.strip()[:300]}")
        for call in msg.tool_calls:
            args = json.loads(call.function.arguments or "{}")
            try:
                obs = TOOLS_DICT[call.function.name](**args)
            except Exception as e:
                obs = f"ERROR: {e}"
            print(f"[step {step}] ACTION: {call.function.name}({json.dumps(args, ensure_ascii=False)})")
            print(f"[step {step}] OBSERVATION: {obs[:160]!r}")
            log.write(json.dumps({"t": time.strftime("%H:%M:%S"), "step": step, "tool": call.function.name,
                                  "args": args, "observation": obs[:500]}, ensure_ascii=False) + "n")
            messages.append({"role": "tool", "tool_call_id": call.id, "content": obs})
    return f"Stopped: limit of {MAX_STEPS} steps (cost {cost:.5f} USD)."

Three things worth remembering:

  • Tools are ordinary functions with a description in JSON Schema. The mechanism for requesting a function is function calling.
  • Each step sends the entire history, so cost grows faster than the number of steps. That’s why I trim tool results.
  • An agent without a step limit and log is asking for trouble. In my code the limit is 8 steps, and every decision goes to a JSONL file.

30-Day Learning Plan

The plan assumes one hour per day and Python basics (variables, functions, for loop). If you don’t have them, add a week for a free Python course before day 1.

Days Topic What you do Result
1-3 API and tokens You set up a key (e.g. OpenRouter with 2 USD limit), send first request from Python, count cost. AI API, tokens script that queries model and prints cost
4-6 Structured responses You make model return JSON, validate fields, handle errors message classifier
7-9 Webhook and automation FastAPI server receives data from form, model processes it, result goes to spreadsheet. Then same in Make or n8n. webhook working automation with AI
10-12 Function calling You give model 2-3 functions (weather, calculator, search) and handle rounds. function calling you understand tool_calls and tool_call_id
13-16 First agent Loop with step limit and log on your own files. agent in Python agent in about 80 lines
17-20 RAG and embeddings You index your own PDFs, measure search accuracy. embeddings, RAG step by step chat with documents with citations
21-23 MCP Your own server with 2-3 tools, test in Inspector and Claude Code. MCP server your tools in every MCP client
24-27 Framework You rewrite your agent to OpenAI Agents SDK or LangGraph. framework comparison you know what framework does for you
28-30 Your own project You choose one of 12 agent examples, add tests on known data and human confirmation for writes agent that saves you time every week

What I Built and How Much It Cost

Instead of describing theory, I ran each stage on my own computer. Model for everything except Claude Agent SDK: openai/gpt-5.6-luna via OpenRouter (0.20 USD per million input tokens). I computed embeddings locally in Ollama on RTX 4090.

Project What I tested Result Cost per run
Function calling weather, calculator, Wikipedia correct answers; once search returned garbage and model answered from memory 0.00008-0.00066 USD
Agent in Python invoices in PLN and EUR, NBP exchange rate, web page (we tested it in Polish) 3919.74 PLN, matching manual calculation 0.0008-0.0013 USD
5 frameworks same task, 3 repetitions each 15/15 correct 0.0006-0.0009 USD (Claude Agent SDK: 0.015 USD)
RAG Labor Code, tenant protection law, patient rights law (we tested it in Polish) 8 out of 10 good answers, 2 honest “not in documents”, 0 hallucinations about 0.00065 USD per question, embeddings locally at zero cost
MCP server NBP exchange rate, business days with holidays, notes; Inspector and Claude Code (we tested it in Polish) Claude calculated 14 business days deadline by itself about 0.06 USD (Claude Haiku 4.5)
Webhook 3 submissions from form, save to CSV 3/3 categories hit, 401 for wrong secret about 0.00016 USD

Frameworks and Tools: What to Choose

Tool Type Price When
Your own loop (openai library) code free learning, simple agents
OpenAI Agents SDK code free multiple agents, handoffs, guardrails
LangGraph code free (LangSmith paid) complex flows with branching
CrewAI code free (cloud paid) teams of agents with roles
Claude Agent SDK code free, Claude models only agent on files and in terminal
n8n no-code Community free self-hosted, cloud from 20 EUR/month (annual) many automations, data on your server
Make no-code free 1000 credits/month scenarios with branching
Zapier no-code free 100 tasks/month, two-step Zaps fastest start, most integrations
Gumloop no-code free plan and Pro agents clicked on canvas

Detailed measurement of five libraries (lines of code, time, cost, dependencies) is in the article AI Agent Frameworks. Hosted agents from OpenAI are described in Agents API from OpenAI, and ready-made coding agents in AI Agents for Code.

Testing in Polish

All my tests were in Polish: commands, tool descriptions, documents, and responses. Large models handle this without problems. Three places where Polish makes a difference:

  • Document search: embedding model must know Polish. On Polish laws bge-m3 found the right provision in top five in 8 out of 10 cases, and nomic-embed-text only in 4 (comparison).
  • Local knowledge: holidays, NBP exchange rates, regulations. Model probably doesn’t know them, so I provide them as tools.
  • Function names: without Polish characters, because APIs only allow Latin letters, digits, and underscores in them.

Where to Learn More: Free Courses and Channels (checked Oct 4, 2026)

This is the answer to a question I got from a reader: where do they explain step by step how APIs work, how to do automation and agents, so you really understand. I opened every address on October 4, 2026. For each I write who it’s for.

Official Courses and Documentation

Source Language Free For whom
Anthropic: Building effective agents English yes for everyone before choosing framework: how flow differs from agent, 6 patterns
Anthropic Academy: Building with the Claude API English yes, after registration you know Python basics: from API through tool use, RAG, MCP to agents
Anthropic Academy: Introduction to MCP English yes, after registration 14 lessons about MCP servers and clients in Python
OpenAI Agents SDK and Function calling guide English yes second step after your own loop; documentation with quickstart
Gemini API: function calling and Google ADK English yes (API with free tier) you want to start on Gemini free tier
Kaggle: 5-Day AI Agents Intensive (Google) English yes 5 days: agents, tools and MCP, memory, evaluation, production; code on ADK
DeepLearning.AI: Agentic AI (Andrew Ng) English video yes, exercises and certificate in Pro best “from principles”: each pattern first in pure Python
DeepLearning.AI: AI Agents in LangGraph and MCP with Anthropic English yes, during platform beta short courses (about 2 h), agent from scratch, then in framework
Hugging Face Agents Course and MCP Course English yes, with certificates theory of thought-action-observation loop and practice in smolagents, LangGraph, LlamaIndex
LangChain Academy: Intro to LangGraph English yes 6 modules, about 6 h; for those who chose LangGraph
Microsoft: Generative AI for Beginners English + Polish translation yes 21 lessons from basics, including function calling and agents; good introduction
Model Context Protocol documentation English yes “Build servers” and “Build clients” tutorials

In Polish

English Channels

  • freeCodeCamp: full, multi-hour courses for free, including “AI Agents For Beginners” (3 h, July 2026) and “Learn Python and Build Autonomous Agents” (6 h).
  • Dave Ebbelaar: building AI systems in Python from engineering side (RAG, FastAPI, automation).
  • LangChain: short concept explanations and LangGraph demos, new videos almost daily.
  • Sam Witteveen: quick, technical reviews of new models and agent frameworks with code.
  • Anthropic and OpenAI: official launches and conference recordings, fewer step-by-step courses.

My sequence for someone who wants to understand, not just click: Anthropic article on agents, then articles from this path with code, then Hugging Face Agents Course or Agentic AI by Andrew Ng, and finally course on chosen framework.

ai-agents-starter Package

All code from this path in one archive, with README in Polish and .env.example file without keys:

  • 01_function_calling.py: model calls weather, calculator, and Wikipedia;
  • 02_agent_bez_frameworka.py: agent in 76 lines with step limit and log;
  • 03_agent_openai_sdk.py: same agent on OpenAI Agents SDK;
  • 04_rag.py: chat with PDFs, embeddings in Ollama;
  • 05_serwer_mcp.py: MCP server with Polish tools;
  • 06_webhook.py: webhook from form with AI;
  • frameworki/: one agent in 5 versions;
  • dane/: fictional invoices and 3 laws from Official Journal of Laws.

Download ai-agents-starter.zip (2.1 MB, 25 files). MIT license. You enter OpenRouter key in your own .env file. Never paste it into code or screenshots.

Frequently Asked Questions

How to build an AI agent step by step?

  1. Master API request.
  2. Learn function calling.
  3. Close it in loop with step limit.
  4. Add read-only tools and log.
  5. Test on data whose result you know.

The whole process with code is in the article How to Build an AI Agent in Python.

Do I need to know programming to make an AI agent?

No, n8n, Make, and Gumloop let you click. But to understand what’s happening and why the agent makes mistakes, it’s worth reading a few dozen lines of loop code once. You can do this without prior experience.

How much does learning to build agents cost?

Courses from the list are free. For tokens: all my tests from this path cost about 0.15 USD. To start, 2-5 USD top-up with limit on key is enough.

How does an AI agent differ from automation?

In automation you set the steps. In an agent the model chooses the order of steps based on tool results. Most practical implementations are automation with one agent step.

Where to start: n8n or Python?

If you want working automation quickly, from n8n or Make. If you want to understand API and agent mechanics, from Python. Best both: same flow first in code, then in n8n.

What model to choose for first agent?

Cheap model with tool support (on OpenRouter filter “tools”). I used openai/gpt-5.6-luna at 0.20 USD per million input tokens. Take stronger model only when cheaper one clearly loses the plan.

What is MCP and do I need to know it?

MCP is a standard for connecting tools to AI applications. Not needed for first agent, but useful when you want to use your tools in Claude Code, Cursor, or other client. See Your Own MCP Server in 15 Minutes and introduction MCP: What It Is.

Can an AI agent run on my computer without internet?

Yes, with local model in Ollama, which has OpenAI-compatible API. Smaller local models more often confuse tool arguments, so start with simple tasks.

Google · Your sourcesQuantslant higher in your Google - one clickAdd to preferred sources →

Sources and Verification Date

Kinetyra

// read next

More on this from QUANTSLANT

Piotr Olszewski

Editor and publisher · Quantslant

I edit and publish Quantslant. AI tools help with research, drafts and translation; choosing topics, running the tests, checking facts and the decision to publish are mine, and so is the responsibility for what appears here.

read nextFunction Calling in AI: How Models Call Your FunctionsguidesFunction Calling in AI: How Models Call Your FunctionsFunction calling lets AI models request your functions instead of executing code themselves. Working Python example with weather, calculator, and Wikipedia.

Most read

  1. 1Best AI Video Generator Apps for Your Phone (2026)
  2. 2Claude Opus 5.5 Motion Graphics: 60s Showreel from One Prompt
  3. 3Wan 2.2 on RTX 4090: timings, VRAM and four test clips
// site map

This page in other languages6

Quantslant in numbers 1,423posts in archive22news from the last 7 days18video models in the observatory
🎬 AI Video Benchmarks: Higgsfield DoP vs OpenAI Sora • Higgsfield vs Runway Gen-3 • AI Video Credit Calculator
× ‹ enlarge ›