HomeBlogHow to Build an AI Agent...

Engineering Guide · 9 min read · October 8, 2026

How to Build an AI Agent from Scratch Using Python and FastAPI

Most tutorials stop at a 20-line wrapper around a chat completion API, which breaks as soon as an agent loops infinitely or mutates the wrong database record. Here is how to build a bounded, observable AI agent from scratch using Python, FastAPI, Pydantic schemas, and PostgreSQL.

Author
Smit Desai
Published
October 8, 2026
Read time
9 min read
Topic
AI & Agents
Services
Custom Web · Mobile Apps · All Services

Demo notebooks make AI agents look effortless: wire up a prompt, pass a list of Python functions, and watch the model pick tools on its own. Then you put that code behind an API for real startup users and hit reality on day one. The model invents JSON keys that do not exist, calls the same lookup tool six times in a row, hangs for 40 seconds while an external webhook stalls, or triggers a side effect twice when a client retries.

Shipping an agent that handles real customer workflows does not require a sprawling framework with twelve layers of abstraction. In practice, a small, explicit loop built with Python, FastAPI, Pydantic, and PostgreSQL is faster to debug, easier to secure, and far less likely to surprise you in production.

If you are mapping out where automation fits in your product lifecycle, pair this technical blueprint with our practical launch, growth, and AI agents roadmap. Below is the exact architecture I use when building custom agents from scratch.


Defining What an Agent Loop Actually Is

Strip away the marketing terminology and an AI agent is a bounded while loop wrapped around a model call and a tool dispatcher:

  1. Load conversation state, tenant permissions, and allowed tools.
  2. Send the message history and strict tool schemas to the LLM.
  3. Inspect the response: either return a final answer or validate requested tool calls.
  4. Execute permitted tools, append results to state, and check budget/step limits.
  5. Repeat until completion, escalation, or hard stop.

Separating Reasoning from Side Effects

The biggest architectural mistake startups make is giving the LLM direct access to raw database queries or unguarded write endpoints. Every tool exposed to the model should be an explicit domain action—such as lookup_invoice_status or draft_support_reply—with read-only actions separated from state-changing mutations. State-changing tools should require either deterministic policy checks or an explicit human approval gate before execution, aligned with the OWASP Top 10 for LLM Applications.


Designing the PostgreSQL State Schema First

Never hold multi-step agent memory solely in Python process RAM. If a FastAPI worker restarts mid-run or a client drops its connection, in-memory lists vanish and you lose the audit trail needed to explain why the agent made a decision.

Store every run and step in PostgreSQL so runs are resumable, inspectable, and billable per tenant:

CREATE TABLE agent_runs (
    id UUID PRIMARY KEY,
    tenant_id UUID NOT NULL,
    status VARCHAR(32) NOT NULL, -- queued, running, awaiting_approval, completed, failed
    step_count INTEGER NOT NULL DEFAULT 0,
    total_tokens INTEGER NOT NULL DEFAULT 0,
    cost_usd NUMERIC(10, 6) NOT NULL DEFAULT 0,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    finished_at TIMESTAMPTZ
);

CREATE TABLE agent_steps (
    id BIGSERIAL PRIMARY KEY,
    run_id UUID NOT NULL REFERENCES agent_runs(id) ON DELETE CASCADE,
    step_index INTEGER NOT NULL,
    role VARCHAR(24) NOT NULL, -- assistant, tool_call, tool_result
    tool_name VARCHAR(64),
    payload JSONB NOT NULL,
    latency_ms INTEGER,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_agent_steps_run ON agent_steps (run_id, step_index);

Recording latency_ms and total_tokens at the step level gives you immediate visibility into which tool or prompt is inflating run time and API spend.


Building Strict Tool Contracts with Pydantic

Tool calls fail silently when schemas are loose. Using Pydantic v2 models forces explicit parameter types, value bounds, and clear field descriptions that double as instructions for the model's function-calling layer described in the OpenAI API platform documentation.

from enum import Enum
from pydantic import BaseModel, Field, ConfigDict

class TicketPriority(str, Enum):
    LOW = "low"
    NORMAL = "normal"
    URGENT = "urgent"

class CreateEscalationInput(BaseModel):
    model_config = ConfigDict(extra="forbid")
    ticket_id: str = Field(..., min_length=4, max_length=32)
    priority: TicketPriority
    reason: str = Field(..., min_length=10, max_length=400)
    requires_refund: bool = False

Setting extra="forbid" rejects hallucinated fields before your application logic ever touches them. When validation fails, pass the concise validation error back to the model as the tool result so it can self-correct on the next iteration—up to your retry cap.


Implementing the FastAPI Agent Runner and Loop Guards

In FastAPI, keep route handlers thin and move the execution loop into an async service class. Every loop needs three non-negotiable circuit breakers: a maximum step cap, a repeated-call detector, and per-tool timeouts.

import hashlib
import json
import asyncio
from typing import Any, Callable, Awaitable


class AgentBudgetExceeded(Exception):
    pass


class BoundedAgentRunner:
    def __init__(
        self,
        llm_client: Any,
        tools: dict[str, Callable[[dict], Awaitable[dict]]],
        max_steps: int = 6,
        max_tokens: int = 24000,
    ) -> None:
        self.llm_client = llm_client
        self.tools = tools
        self.max_steps = max_steps
        self.max_tokens = max_tokens

    async def run(self, messages: list[dict], tenant_id: str) -> dict:
        seen_signatures: set[str] = set()
        tokens_used = 0

        for step in range(1, self.max_steps + 1):
            response = await asyncio.wait_for(
                self.llm_client.complete(messages=messages),
                timeout=20.0,
            )
            tokens_used += response.usage_tokens

            if tokens_used > self.max_tokens:
                raise AgentBudgetExceeded(f"Run exceeded {self.max_tokens} token cap")

            if not response.tool_calls:
                return {"status": "completed", "answer": response.text, "steps": step}

            for call in response.tool_calls:
                sig = hashlib.sha256(
                    f"{call.name}:{json.dumps(call.arguments, sort_keys=True)}".encode()
                ).hexdigest()

                if sig in seen_signatures:
                    return {
                        "status": "halted_repeat",
                        "answer": "Agent stopped after repeating an identical tool action.",
                        "steps": step,
                    }
                seen_signatures.add(sig)

                handler = self.tools.get(call.name)
                if handler is None:
                    result = {"error": f"Unknown tool: {call.name}"}
                else:
                    result = await asyncio.wait_for(
                        handler(call.arguments, tenant_id=tenant_id),
                        timeout=10.0,
                    )

                messages.append({"role": "tool", "name": call.name, "content": json.dumps(result)})

        return {"status": "halted_max_steps", "answer": "Escalated to human review.", "steps": self.max_steps}

Notice two subtle details that save real money in production:

  • tenant_id is injected server-side into every tool handler (handler(call.arguments, tenant_id=tenant_id)), never trusted from LLM arguments.
  • seen_signatures hashes the tool name and sorted JSON arguments so a confused model cannot loop forever querying the exact same endpoint.

Streaming Progress Over SSE Without Blocking Workers

Users abandon interfaces that spin silently for 12 seconds. FastAPI's StreamingResponse lets you emit typed Server-Sent Events as each step begins and finishes—showing "Checking order history..." before tokens even arrive.

Handling Client Disconnects Safely

Remember that if a browser closes a tab mid-stream, FastAPI raises asyncio.CancelledError or stops iterating the generator. If your agent is halfway through a multi-step job that must finish (for example, generating a compliance summary), decouple execution from the HTTP connection: push the run into an async worker (Celery, ARQ, or Dramatiq), publish step events to Redis Pub/Sub, and have the FastAPI SSE endpoint subscribe to that channel. That way, refreshing the browser reconnects cleanly to the live stream instead of killing or duplicating work.


Failure Modes and Production Guardrails Checklist

Before shipping any Python and FastAPI agent to users, verify every item in this table against your staging environment:

Failure Mode Symptom in Production Required Guardrail
Infinite tool loop Run hits 30+ calls and burns API credits max_steps cap (5–8) + argument hash deduplication
Cross-tenant data leak Model passes another customer's ID into tool args Inject tenant_id from verified JWT/session, never from prompt
Hallucinated JSON parameters KeyError or unexpected None inside tool handler Pydantic ConfigDict(extra="forbid") + schema validation
Upstream API hang FastAPI worker pool exhausted under low traffic asyncio.wait_for per LLM and tool call + circuit breaker
Unapproved state mutation Agent sends wrong email or issues duplicate refund Require awaiting_approval pause state before write tools execute
Unbounded prompt growth Latency spikes and context window overflows Summarize or truncate tool outputs older than 3 steps

Scoping and Shipping Your Agent Backend

Building an AI agent in Python and FastAPI is straightforward once you treat it like distributed systems engineering rather than prompt magic. At SmitDev, I work directly with startup founders and engineering teams—bringing experience from 170+ shipped case studies since 2017—to architect and deploy bounded, auditable AI backends without bloated middleware.

If you need a focused prototype or production service wired into your existing product, you can explore our AI agent consulting practice or engage directly through $55/day dedicated engineering sprints (8–9 hours/day) or $1,999/month continuous delivery. Ready to review your tool schemas, latency targets, and security boundaries? Send over your workflow requirements and we can map out the first sprint.

Written by Smit Desai · Principal Full-Stack & FDSE

8+ years shipping production systems · 171 case studies · 300+ WordPress servers managed for Finland partners.

Next Steps and Recommended Resources

Next Steps · Recommended Resources

Pillar 1 · Agentic Engineering

AI Agents & Automation Consulting

Deploy schema-validated AI agents, RAG pipelines, and CRM/support automation with predictable token and latency budgets.

Interactive Tool · Scope & Budget

SaaS & AI Cost Calculator

Estimate development timeline, MVP phases, and build costs across $55/day sprints or $1,999/month dedicated delivery.

01 — Frequently asked questions

ai & agents

Why build an AI agent in plain Python and FastAPI instead of a heavy agent framework?

Heavy orchestration frameworks hide retry logic, prompt formatting, and state transitions behind fragile abstractions. Writing the agent loop directly in Python and FastAPI keeps execution deterministic, simplifies debugging, and makes it straightforward to enforce strict timeouts, token budgets, and Pydantic validation.

How do you prevent an AI agent from getting stuck in an infinite tool-calling loop?

Enforce a hard max-iteration counter (typically 5 to 8 steps), track a cumulative token and dollar budget per run, and detect repeated identical tool-call signatures. When any threshold trips, terminate the loop gracefully and return a structured fallback or human escalation status.

Should an AI agent run inside a FastAPI request handler or a background worker?

Short read-only lookups can stream back over Server-Sent Events (SSE) inside an async FastAPI endpoint with strict timeouts. Multi-step workflows that call external APIs or update records should be dispatched to a queue worker and tracked via run IDs in PostgreSQL.

What does it cost to bring in senior engineering help to ship a production FastAPI agent?

SmitDev scopes and delivers custom agent backends via fixed milestones, $55/day senior engineering sprints (8–9 hours of daily work), or dedicated monthly delivery starting at $1,999/month.

03 — Have an engineering need?

hire the right expertise

Let's talk tech.

Deciding between an embedded forward deployed engineer or a senior full stack developer? Share your technical context and timeline.

Solitaire Corporate Park, Makarba, Ahmedabad, Gujarat 380015, India · IST (UTC+5:30) · --:-- IST · Mon–Fri 09:00–18:00 IST · US & EU overlap daily

No newsletter, no CRM. Just a reply.