How to Build an AI Agent: A Step-by-Step Guide With Python and Examples

By Rahul Singh

Updated on Dec 3, 2026

Share:

Quick Overview:

  • To create an AI agent, start with defining a goal, choose a language model, connect tools, give instructions, and implement an execution loop.

  • Key elements in creating an AI agent are the model, instructions, tools, memory, orchestration, guardrails, and evaluation.

  • Examples of how you can build AI agents are by using Python, ChatGPT, Claude, and frameworks like LangGraph, CrewAI, and OpenAI Agents SDK.

  • It is possible to build AI agents for free by using open source models, execution tools like Ollama, and free API tiers.

  • This blog covers how to build an AI agent step by step, with Python code examples, architecture, development approaches, and framework comparisons.

Building reliable AI agents requires practical knowledge of LLMs, tool calling, memory management, and agent orchestration. IIT Kharagpur's Generative AI & Agentic AI Course - Executive Post Graduate Certificate helps you develop these skills through hands-on projects involving RAG, AI agents, and multi-agent systems.

Prerequisites for Building an AI Agent

Before you learn how to build an AI agent in code, get a few basics in place. None of this is exotic, and most developers already have half of it.

  • Python 3.10 or later: You should be comfortable with functions, dictionaries, loops and installing packages with pip.

  • API basics: Know how to send a request, read JSON and handle errors, since your agent will do this constantly.

  • An API key or a local model: You can use a hosted provider such as OpenAI or Anthropic, or run an open model on your own machine.

  • A clear use case: "Answer order-status questions from our database" is a good first agent. "Run my business" is not.

  • Prompting skills: You will write instructions for the model, so clear, specific wording matters.

  • A safe test setup: Use a virtual environment, keep keys out of your code and begin with read-only data.

If you can write a small Python script that calls a web API, you are ready. Experience with machine learning is helpful, but it is not required.

How to Build an AI Agent: Step-by-Step Process

Whether coding from scratch or using a framework, the process retains the same pattern. This is how an AI agent can be created in seven steps.

Seven steps to build an AI agent, including defining a goal, choosing a model, building tools, writing instructions, running agent loops, adding memory and guardrails, and testing performance.
  1. Define one narrow goal: Write down what the agent should do, what counts as success and what it must never do. A narrow goal makes every later choice easier.

  2. Choose a model: Start with a capable model so you can see what is possible. Once it works, try a smaller, cheaper model and check whether quality holds.

  3. Build the tools: A tool is a plain function the agent can call, such as searching a database, sending an email or reading a file. Give each tool a clear name and description, because the model picks tools based on those words.

  4. Write the instructions: This is the system prompt. State the agent's role, the steps to follow, what to do when information is missing and when to stop.

  5. Run it in a loop: The agent calls the model, runs any tool the model asks for, feeds the result back and repeats until the model gives a final answer. Always set a maximum number of steps.

  6. Add memory and guardrails: Keep conversation history for short-term memory. Add input checks, output checks and human approval for risky actions such as payments or deletions.

  7. Test, measure and monitor: Build a small set of test questions with known answers, run it after every change and log every tool call in production.

How to Build an AI Agent With Python?

Here is a complete agent in plain Python, with no framework. It uses Anthropic's SDK, but the same loop works with any provider that supports tool calling. Install it with pip install anthropic and set your ANTHROPIC_API_KEY first.

import anthropic

client = anthropic.Anthropic()  # reads the API key from your environment

MODEL = "claude-sonnet-5-5"     # pick a current model from the provider docs

MAX_STEPS = 6

def get_order_status(order_id: str) -> str:

    orders = {"A101": "Shipped, arriving Friday", "A102": "Processing"}

    return orders.get(order_id, "Order not found")

TOOLS = [{

    "name": "get_order_status",

    "description": "Look up the delivery status of an order by its ID.",

    "input_schema": {

        "type": "object",

        "properties": {"order_id": {"type": "string", "description": "For example, A101"}},

        "required": ["order_id"],

    },

}]

TOOL_FUNCTIONS = {"get_order_status": get_order_status}

SYSTEM = "You are a support agent. Use tools for order facts. If a tool finds nothing, say so."

def run_agent(question: str) -> str:

    messages = [{"role": "user", "content": question}]

    for in range(MAXSTEPS):

        response = client.messages.create(

            model=MODEL, max_tokens=1024, system=SYSTEM,

            tools=TOOLS, messages=messages,

        )

        if response.stop_reason != "tool_use":

            return "".join(b.text for b in response.content if b.type == "text")

        messages.append({"role": "assistant", "content": response.content})

        results = []

        for block in response.content:

            if block.type == "tool_use":

                output = TOOL_FUNCTIONS[block.name](**block.input)

                results.append({"type": "tool_result",

                                "tool_use_id": block.id, "content": output})

        messages.append({"role": "user", "content": results})

    return "Stopped: step limit reached."

print(run_agent("Where is order A101?"))

Read it top to bottom and you will see every idea from the steps above. The for loop is the agent. The model decides whether to answer or call get_order_status, your code runs the tool, and the result goes back into the conversation. The MAX_STEPS cap stops runaway loops.

To extend it, add more tools to the TOOLS list and the TOOL_FUNCTIONS dictionary. Keep each tool small and give it a precise description.

Core Components of an AI Agent Architecture

Every agent, from a weekend project to a production system, is built from the same few parts which are the core components of agentic AI architecture. Knowing them is half of how to build an AI agent that you can actually debug, because each failure usually traces back to one component.

Component

What It Does

Example

Model

Reads the goal, reasons and decides the next action

A hosted LLM or a local open model

Instructions

Define the role, steps, limits and tone

A system prompt with numbered rules

Tools

Let the agent fetch data or act in other systems

Database query, web search, email sender

Memory

Keeps context within and across sessions

Chat history, a vector database, saved user notes

Control loop

Runs model and tool calls until the task ends

A for loop with a step limit

Orchestration

Coordinates several agents or workflow branches

A manager agent that delegates to specialists

LLM Guardrails

Block unsafe inputs, outputs and actions

Input filters, PII checks, human approval

Evaluation and logging

Measure quality and expose failures

Test question sets, tracing dashboards

A common mistake is to spend all the effort on the model and none on the last two rows. In practice, guardrails and evaluation decide whether anyone trusts the agent.

Different Approaches to Building AI Agents

There is no single right way to approach how to build an AI agent. Your best approach depends on your skills, your timeline and how much control you need.

  • No-code builders: You can build an agent using visual tools without writing any code. It is fast but you lose control over it.

  • Low-code and workflow tools: Tools like n8n allow you to integrate models with applications using drag-and-drop workflows, while allowing some coding.

  • Agentic AI Frameworks: Frameworks like LangGraph, CrewAI or OpenAI Agents SDK take care of everything for you.

  • Plain code: Writing the loop yourself, as above, gives the most control and the clearest understanding of what is happening.

There is also a design choice about autonomy. A workflow follows steps you define in code, and the model fills in the details. A fully autonomous agent chooses its own steps. Workflows are more predictable, so they suit most business tasks. Reach for full autonomy only when the path truly cannot be planned in advance.

How to Build an AI Agent With ChatGPT?

There are two main routes, depending on whether you want to code.

The no-code route is a custom GPT. Inside ChatGPT, you write instructions, upload reference files and connect actions to outside services. It is the fastest way to a working assistant, though availability of GPT creation depends on your plan.

The code route is OpenAI's Agents SDK, a lightweight Python library. Install it with pip install openai-agents, then define an agent with instructions and tools.

from agents import Agent, Runner, function_tool

@function_tool

def get_weather(city: str) -> str:

    return f"It is sunny in {city}."

agent = Agent(

    name="Weather agent",

    instructions="Answer weather questions using the tool.",

    tools=[get_weather],

)

result = Runner.run_sync(agent, "What is the weather in Pune?")

print(result.final_output)

The SDK also supports handoffs between agents and built-in guardrails, which is handy once your project grows.

How to Build an AI Agent With Claude?

You can build with Claude in two ways as well. 

  • The first is the Messages API with tool use, which is exactly what the Python example above does. You define tools with a JSON schema, Claude asks for a tool call when it needs one, and your code returns the result.

  • The second is Anthropic's Claude Agent SDK, which gives you a ready-made agent loop and built-in tools for working with files and commands. It suits coding and automation tasks where you would rather not write the loop yourself. For connecting an agent to outside systems, the Model Context Protocol (MCP) offers one standard way to plug in tools and data sources. Check the current documentation for setup details, since these SDKs change quickly.

How to Create Your Own AI Agent for Free?

You can build a useful agent without paying anything, with a few trade-offs.

  • Run an open model locally: Tools like Ollama let you run models such as Llama or Qwen on your own computer. There are no per-token fees, but you need decent hardware.

  • Use free API tiers: Several providers offer limited free usage. Rate limits and terms vary, so read them before you build around one.

  • Pick open-source frameworks: LangGraph, CrewAI and similar libraries cost nothing to use.

  • Start with a small task: A free setup works best for learning projects and personal tools.

Free routes usually mean slower responses or weaker tool calling with smaller models. That is fine for learning. For a customer-facing agent, you will likely want a stronger hosted model.

Tools and Frameworks for Building AI Agents

A framework saves you from rewriting the same loop, state handling and logging. Here is how the popular options compare.

Framework

Best For

Key Strength

LangGraph

Complex, stateful workflows

Explicit graphs with branching, loops and human approval

CrewAI

Teams of role-based agents

Simple setup for multi-agent collaboration

OpenAI Agents SDK

Lightweight agents with handoffs

Clean API, guardrails and tracing built in

Claude Agent SDK

Coding and automation agents

Ready-made loop with file and command tools

Google ADK

Agents on Google Cloud

Multi-agent design with cloud integration

LlamaIndex

Agents over documents and data

Strong retrieval and data connectors

AutoGen

Conversational multi-agent research

Agents that talk to one another to solve tasks

n8n

Low-code automation

Visual flows that connect models to many apps

Frameworks change fast, so check each project's documentation before you commit. For tracing and debugging, tools such as LangSmith and Langfuse record every model and tool call, which makes problems far easier to find. 

If you are just starting out on how to build an AI agent, my advice is to build the plain Python version first. Once you understand the loop, every framework makes more sense.

Conclusion

How to build an AI agent is less mysterious than it looks. Strip away the hype and you have a model, a few tools, clear instructions and a loop that knows when to stop. 

Start with one narrow task, get it working in plain Python, and test it against questions you already know the answers to. Then add tools, memory and guardrails one at a time. The agents that earn trust are rarely the cleverest. They are the ones built carefully, tested often and kept on a short leash until they prove themselves.


Rahul Singh

Rahul Singh

49+ of articles published


Current role in the industry :

Associate - Content Marketing

Education Qualification :

B.Tech in Computer Science & Engineering

Expertise :

Artificial intelligenceMachine Learning (ML)Data ScienceFull-Stack DevelopmentData Structures & Algorithms

Tools & Technologies :

PythonReact.js & Next.jsJavaScript (ES6+)SQLTailwind CSSNode.js & MongoDBGit & GitHubSEO Tools (SEMRush)Google Search ConsoleTableau / Power BIFigma

About

Rahul Singh is an Associate Content Writer, with a strong interest in Generative AI, Agentic AI and AI-Native Software Engineering. He combines technical development skills with data-driven strategies to build scalable applications and optimize digital content. Rahul specializes in simplifying complex concepts across AI, ML and software development into practical, easy-to-understand insights, helping learners understand how AI products, systems and services are built and applied. He focuses on real world applications and explains advanced topics in a clear, step by step manner so you can follow along without confusion. His work connects theory with hands-on examples, covering AI-assisted development, intelligent automation and AI integration in software applications. He aims to help you learn faster, create better projects, and apply your knowledge confidently in real scenarios.

Follow me on :

Frequently Asked Questions

FAQ

Ready to Take the Next Step? Enroll Today!