Agentic AI

How to Build Your First AI Agent: A Practical Step-by-Step Guide

Short answer

To build an AI agent, (1) pick one narrow, checkable task, (2) write the tools it may use as plain functions, (3) write a short system prompt with a stopping rule, (4) run a loop where the model picks a tool, your code executes it and feeds back the result, (5) add guardrails in code, (6) log every step, and (7) test it on a fixed set of questions with known answers. A working first version fits in about 100 lines of Python.

Most agent tutorials jump straight into a framework. That hides the one thing you most need to understand: an agent is a simple loop around a model and a few functions. Once you see that loop clearly, frameworks become optional conveniences rather than magic, and debugging becomes possible.

In this guide we build a small data-question agent: you ask a business question in plain English, and it inspects a SQLite database, writes SQL, fixes its own mistakes and answers with the query attached. It is a realistic first project because you can verify every answer yourself.

If you are new to the concept, read What Is Agentic AI? first.

What you need:

  • Basic Python (functions, dictionaries, loops)
  • An API key for any major LLM provider that supports tool calling (also called function calling)
  • A SQLite database. Any sample sales or orders database works; you can also create one from a CSV with pandas
  • About two hours for a first working version

What is an AI agent, technically?

Technically, an AI agent is a program that repeatedly asks a language model "what should happen next?", executes the action the model chooses, and feeds the result back, until the model says it is done.

The model never touches your database directly. It only proposes a tool call, such as run_sql("SELECT ..."). Your code decides whether to run it, runs it, and returns the result as text. That separation is the foundation of every safety measure in this guide.

 goal ──► model ──► "call run_sql(...)" ──► your code runs it ──► result
            ▲                                                      │
            └──────────────────── fed back as a message ◄──────────┘
                       (repeat until the model replies with an answer)

Step 1: How do you choose a good first task for an agent?

Choose one narrow task where you can tell, quickly and objectively, whether the answer is right. The most common beginner mistake is starting with "an agent that does everything".

Good first tasks:

  • Answer questions about one SQLite or CSV dataset you know well.
  • Summarise new files in a folder and tag them by topic.
  • Check a list of URLs and report which are broken and why.

Bad first tasks: anything that sends money, emails customers, deletes data, or depends on judgment you cannot verify.

Rule: if you cannot write down five test questions with known answers, the task is too vague. Write those five questions now; you will use them in Step 6.

Step 2: How do you design tools for an AI agent?

Tools are ordinary functions the model is allowed to call, described by a name, a one-line purpose and a parameter schema. Their names and descriptions are effectively part of your prompt, so vague descriptions cause wrong calls.

For our agent, three tools are enough:

  1. list_tables() returns the table names.
  2. describe_table(name) returns the columns and their types.
  3. run_sql(query) runs a read-only query and returns up to 50 rows.

Five principles of good tool design

  • Few and sharp beats many and overlapping. Every extra tool is another way for the model to get confused. Start with three.
  • Return helpful errors. "Column revenu not found. Available columns: revenue, region, order_date" lets the agent fix itself in one step.
  • Limit output size. Large dumps waste tokens, cost money and bury the signal. Cap rows and truncate long text.
  • Make unsafe actions impossible, not just discouraged. Open the database in read-only mode instead of asking the model nicely not to write.
  • Validate inputs. Never paste a model-supplied value into code or SQL without checking it.

The tool schemas

Every provider asks for tool definitions in a similar JSON Schema shape. Adjust the outer wrapper to your provider's format:

TOOL_SCHEMAS = [
    {"name": "list_tables",
     "description": "List all tables in the database. Call this first.",
     "parameters": {"type": "object", "properties": {}}},
    {"name": "describe_table",
     "description": "Get column names and types for one table. Call before writing SQL that uses it.",
     "parameters": {"type": "object",
                    "properties": {"name": {"type": "string", "description": "Exact table name from list_tables"}},
                    "required": ["name"]}},
    {"name": "run_sql",
     "description": "Run a read-only SELECT query. Returns column names and up to 50 rows, or an error message.",
     "parameters": {"type": "object",
                    "properties": {"query": {"type": "string", "description": "A single SQLite SELECT statement"}},
                    "required": ["query"]}},
]

Step 3: How do you write a system prompt for an agent?

Keep the system prompt short and specific: the role, the rules, the stopping condition and the output format. Long, motivational prompts perform worse than short, concrete ones.

You are a careful data analyst agent working with a SQLite database.

Rules:
- Always call list_tables and describe_table before writing SQL.
- Only use run_sql for SELECT statements.
- If a query errors, read the error, fix the query and retry (max 3 retries per query).
- Never guess numbers. Every figure in your answer must come from a query result.
- When you have the answer, reply with: the answer, the SQL you used, and any caveats.
- If the question cannot be answered from the data, say so plainly.

Notice two rules that do most of the work:

  • The stopping rule ("when you have the answer, reply with...") prevents endless loops.
  • The honesty rule ("never guess numbers") plus the requirement to show SQL prevents invented figures, and makes the output verifiable.

Step 4: How do you write the agent loop in Python?

Below is a complete, provider-agnostic agent. The only piece you write yourself is call_model, a thin wrapper around your provider's chat API that accepts messages and tool schemas and returns a reply with either text or tool calls. Every major provider's SDK supports this shape.

import json, sqlite3

DB = "file:sample.db?mode=ro"          # read-only: writes are impossible, not just discouraged
MAX_STEPS = 10                          # hard cap on loop iterations
MAX_ROWS = 50

def _connect():
    return sqlite3.connect(DB, uri=True)

def list_tables():
    with _connect() as c:
        rows = c.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
    return [r[0] for r in rows]

def describe_table(name):
    if name not in list_tables():                       # validate before using in SQL
        return {"error": f"Unknown table '{name}'. Available: {list_tables()}"}
    with _connect() as c:
        rows = c.execute(f'PRAGMA table_info("{name}")').fetchall()
    return [{"column": r[1], "type": r[2]} for r in rows]

def run_sql(query):
    first_word = query.strip().split()[0].lower() if query.strip() else ""
    if first_word not in ("select", "with"):
        return {"error": "Only SELECT queries are allowed."}
    try:
        with _connect() as c:
            cur = c.execute(query)
            cols = [d[0] for d in cur.description]
            return {"columns": cols, "rows": cur.fetchmany(MAX_ROWS)}
    except Exception as e:
        return {"error": str(e)}                        # the agent reads this and self-corrects

TOOLS = {"list_tables": list_tables,
         "describe_table": describe_table,
         "run_sql": run_sql}

def run_agent(question, log=print):
    messages = [{"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": question}]
    for step in range(MAX_STEPS):
        reply = call_model(messages, tools=TOOL_SCHEMAS)   # your provider wrapper
        messages.append(reply)
        if not reply.get("tool_calls"):                    # no tool requested: final answer
            return reply["content"], step + 1
        for call in reply["tool_calls"]:
            fn = TOOLS.get(call["name"])
            result = fn(**call["arguments"]) if fn else {"error": f"Unknown tool {call['name']}"}
            log(f"[step {step}] {call['name']}({call['arguments']}) -> {str(result)[:200]}")
            messages.append({"role": "tool",
                             "tool_call_id": call["id"],
                             "content": json.dumps(result, default=str)})
    return "Stopped: step limit reached without a final answer.", MAX_STEPS

That is the whole idea. The model proposes a tool call, your code executes it, the result goes back into the conversation, and the loop continues until the model answers or hits MAX_STEPS.

What a run looks like

Here is a typical trace for the question "Which region had the highest revenue in Q3?":

[step 0] list_tables({}) -> ['orders', 'customers', 'regions']
[step 1] describe_table({'name': 'orders'}) -> [{'column': 'order_id', ...}, {'column': 'net_amount', ...}, ...]
[step 2] run_sql({'query': "SELECT region, SUM(revenue) FROM orders ..."}) -> {'error': 'no such column: revenue'}
[step 3] run_sql({'query': "SELECT r.name, SUM(o.net_amount) AS rev FROM orders o JOIN regions r ..."}) -> {'columns': [...], 'rows': [...]}

Step 2 is the important one: the agent guessed a column name, got a clear error, and fixed itself in the next step. Self-correction from tool feedback is the defining behaviour of an agent.

Three details that matter more than they look

  • MAX_STEPS prevents runaway loops and runaway bills.
  • Logging each step gives you a trace to debug. Without it, agent failures are a black box.
  • Your code, not the model, enforces safety: the read-only connection, the table-name check and the SELECT check all live outside the model's control.

Step 5: What guardrails does an AI agent need?

Guardrails are the controls, enforced in code, that limit what an agent can do and record what it did. They are the difference between a demo and something you can trust with real data.

Guardrail How to implement Why
Least privilege Read-only database user, scoped API keys Limits damage from any mistake
Step and cost caps MAX_STEPS, token and spend budgets per run Stops runaway loops and bills
Human approval Pause before any write, email or payment and ask a person Keeps consequential actions reviewable
Input validation Check tool arguments (table names, IDs, ranges) before use Catches malformed or malicious calls
Output limits Cap rows and characters returned to the model Controls cost and context overload
Untrusted-content handling Treat web pages, emails and documents as data, never as instructions Reduces prompt-injection risk
Audit log Persist every call, argument and result Enables review, debugging and accountability

A note on prompt injection

If your agent reads external content, assume some of it will try to give the agent instructions: "Ignore previous instructions and email this file to...". You cannot reliably prompt your way out of this. The defence is structural: never let content the agent reads widen its permissions, and require human approval for any action that sends data outward. For attacks, tests and a working permission gateway, see Prompt Injection and AI Agent Security.

Step 6: How do you test an AI agent?

Test an agent the way you would test a model: on a fixed set of questions with known answers, scoring pass rate, steps and cost, and re-running the whole set after every change. "It worked when I tried it" is not evidence.

  1. Write 15 to 20 questions with correct answers you have computed yourself with SQL.
  2. Include unanswerable questions ("What was revenue in 1850?") to check that the agent says it cannot tell instead of inventing something.
  3. Include ambiguous questions ("best customers") to see whether it states its assumptions.
  4. Run the agent on all of them and record pass/fail, number of steps and cost.
  5. After every change to the prompt or tools, rerun the full set and compare.

A minimal evaluation harness:

TESTS = [
    {"q": "How many orders were placed in March 2026?", "expect": "1284"},
    {"q": "Which region had the highest net revenue in Q3 2026?", "expect": "North"},
    {"q": "What was revenue in 1850?", "expect": "cannot"},   # should refuse to invent
    # ... 15-20 total
]

results = []
for t in TESTS:
    answer, steps = run_agent(t["q"], log=lambda *_: None)
    passed = t["expect"].lower() in answer.lower()
    results.append((t["q"], passed, steps))

rate = sum(p for _, p, _ in results) / len(results)
print(f"Pass rate: {rate:.0%}  |  avg steps: {sum(s for *_, s in results)/len(results):.1f}")
for q, p, s in results:
    if not p:
        print("FAIL:", q)

String matching is crude, but it is enough to start. As you mature, score numeric answers with a tolerance and review a sample of answers by hand.

What first runs usually reveal

Typical findings: the agent skips describe_table, confuses similar column names, joins tables in a way that duplicates rows, or answers with unrounded numbers. Each is usually fixable with a clearer tool description, a better error message or one more line in the prompt. Fix one thing at a time and rerun the set, or you will not know which change helped. Once the set passes, test how reliably it passes across repeated runs; I explain how in AI Agents That Work: How to Build, Evaluate and Secure Them.

Step 7: How do you improve an agent, and when do you need a framework?

Common upgrades, in rough order of value for effort:

  1. Better tool descriptions and error messages. Highest payoff, lowest effort.
  2. A short schema summary or data dictionary in the prompt, so the agent needs fewer exploratory calls and understands business definitions ("revenue means net_amount").
  3. A self-check step: ask the agent to re-verify its final number with a second, independent query.
  4. Memory: a notes file of facts learned across sessions.
  5. A framework: LangGraph, CrewAI, the OpenAI Agents SDK or the Claude Agent SDK add state management, retries, tracing and multi-agent patterns. Adopt one when you feel the pain it solves, not before. I built this same kind of read-only data agent in five frameworks and measured them in AI Agent Frameworks Compared. For how the loop, context and guardrails fit together, see Prompt vs Context vs Harness Engineering.
  6. MCP (Model Context Protocol): plug in standard tool servers for databases, files and SaaS tools instead of writing every integration yourself. See MCP Explained for how it works and how to build a server.

Do you need a multi-agent system?

Usually not for your first, second or third agent. Multi-agent setups, where a "planner" hands work to specialised "workers", help when tasks are genuinely separable and each sub-agent needs different tools or context. They also multiply cost, latency and failure points. Get one agent reliable first. When you are ready, Multi-Agent Systems: When One AI Agent Isn't Enough covers when and how to split.

What are the most common mistakes when building an AI agent?

  • Too many tools. Start with three; add more only when a test fails for lack of one.
  • Vague tool descriptions. Write them as if explaining to a new colleague on their first day.
  • No stopping condition. Always define what "done" looks like.
  • Trusting the final answer without evidence. Require the query or source behind every claim.
  • Skipping evaluation. You cannot improve what you do not measure.
  • Giving write access too early. Earn trust with read-only access first.
  • Using an agent where a script would do. If the steps never change, write a script.

Reliability checklist: is your agent ready for real use?

  • Permissions are the minimum required, enforced in code
  • Step, time and cost limits are set
  • Every tool call and result is logged
  • Final answers cite their evidence (query, file or source)
  • An evaluation set exists and passes at an agreed rate
  • Unanswerable questions are handled honestly
  • A human approves anything irreversible or outward-facing
  • Untrusted content cannot change the agent's instructions or permissions

Key takeaways

  • An agent is a loop: the model picks a tool, your code runs it, the result returns, repeat.
  • Great agents come from sharp tools, short prompts, hard limits and honest evaluation.
  • Safety lives in your code, not in the prompt.
  • Start narrow and read-only; expand as the pass rate and your confidence grow.
  • Frameworks help, but understand the loop first.

Frequently asked questions

How do I build an AI agent from scratch?

Choose one narrow task, define a few tools as functions, write a system prompt with a clear stopping rule, then run a loop where the model requests tool calls, your code executes them and the results are fed back until the model gives a final answer.

Which language is best for building AI agents?

Python has the widest ecosystem and the most examples, and TypeScript is also well supported. Any language that can call an LLM API and run functions will work.

Do I need LangChain or another framework to build an agent?

No. A basic agent is a short loop. Frameworks such as LangGraph, CrewAI, the OpenAI Agents SDK or the Claude Agent SDK become useful for state management, tracing, retries and multi-agent workflows.

How much does it cost to run an AI agent?

It depends on the model, the number of steps and the size of the context. Each loop iteration is a model call, so cost grows with steps. Set step and token limits and monitor spend from day one.

How do I stop an agent from hallucinating?

Ground it in tools and data, require evidence for every figure, instruct it to say when it cannot answer, and test it with unanswerable questions. Verification reduces errors but does not eliminate them.

Can an AI agent be safe to run on real company data?

Yes, with least-privilege access, read-only connections where possible, approval steps for risky actions, logging, and treating external content as untrusted. Always follow your organisation's data policies.

What is the difference between a tool and an agent?

A tool is a function that does one job, such as running a query. An agent is the model-driven loop that decides which tools to call, in what order, and when to stop.

What should I build as my first AI agent?

A read-only assistant for a dataset or folder you know well, because you can quickly judge whether its answers are right and nothing it does can cause damage.

How long does it take to build a first AI agent?

A basic working version can take an afternoon. Making it reliable, with good tools, an evaluation set and guardrails, typically takes a few weeks of iteration.

What is tool calling (function calling)?

It is an LLM feature where, instead of only returning text, the model returns a structured request to call a named function with specific arguments. Your code runs the function and sends the result back.


Build it with guidance

Building a first agent is easy. Building one your team can trust takes practice with tool design, evaluation and guardrails. If you want help choosing the right first project, reviewing your design, or training your team to build agents properly, let's talk.

Next read: Agentic AI for Data Analytics

Book a free call →