Log In Sign Up
Michael Park July 5, 2026 15 min read

How to Build an AI Agent from Scratch: A Step-by-Step Guide

AI Agents LangChain Python Tutorial LLM
How to Build an AI Agent from Scratch: A Step-by-Step Guide

How to Build an AI Agent from Scratch

AI agents are the next frontier in artificial intelligence. Unlike simple chatbots, agents can plan, use tools, and accomplish complex tasks autonomously. In this guide, we’ll build a production-ready AI agent step by step.

What is an AI Agent?

An AI agent is a system that:

  • Perceives its environment
  • Plans and makes decisions
  • Uses tools to accomplish goals
  • Learns and adapts from feedback

Prerequisites

  • Python 3.10+
  • OpenAI API key (or compatible LLM)
  • Basic Python knowledge
  • Understanding of APIs

Step 1: Setting Up Your Environment

# Create a new project directory
mkdir ai-agent
cd ai-agent

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install dependencies
pip install langchain langchain-openai langchain-tools python-dotenv

Create a .env file:

OPENAI_API_KEY=your-api-key-here

Step 2: Building a Simple ReAct Agent

from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent
from langchain.tools import tool
from langchain import hub
import os
from dotenv import load_dotenv

load_dotenv()

# Define tools
@tool
def search_web(query: str) -> str:
    """Search the web for information."""
    # In production, use Tavily or Serper API
    return f"Search results for: {query}"

@tool
def calculate(expression: str) -> str:
    """Evaluate a mathematical expression."""
    try:
        result = eval(expression)
        return str(result)
    except:
        return "Error: Invalid expression"

@tool
def get_current_time() -> str:
    """Get the current date and time."""
    from datetime import datetime
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# Initialize LLM
llm = ChatOpenAI(model="gpt-4", temperature=0)

# Get the prompt to use
prompt = hub.pull("hwchase17/react")

# Create tools list
tools = [search_web, calculate, get_current_time]

# Create agent
agent = create_react_agent(llm, tools, prompt)

# Create agent executor
agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    max_iterations=10,
)

# Use the agent
result = agent_executor.invoke({
    "input": "What's the square root of 144 multiplied by the current hour?"
})

print(result["output"])

Step 3: Adding Memory

from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(
    memory_key="chat_history",
    return_messages=True
)

agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    memory=memory,
    verbose=True,
)

# Now the agent remembers previous conversations
agent_executor.invoke({"input": "My name is Alex"})
result = agent_executor.invoke({"input": "What's my name?"})
print(result["output"])  # Alex

Step 4: Building a Custom Tool

from langchain.tools import BaseTool
from pydantic import BaseModel, Field
from typing import Type

class WeatherInput(BaseModel):
    city: str = Field(description="The city name to get weather for")
    unit: str = Field(default="celsius", description="Temperature unit: celsius or fahrenheit")

class WeatherTool(BaseTool):
    name = "get_weather"
    description = "Get the current weather for a city"
    args_schema: Type[BaseModel] = WeatherInput

    def _run(self, city: str, unit: str = "celsius") -> str:
        """Use the tool."""
        # In production, call a weather API
        temp = 22 if unit == "celsius" else 72
        condition = "Partly cloudy"
        return f"Weather in {city}: {condition}, {temp}°{unit[0].upper()}"

# Add to tools
weather_tool = WeatherTool()
tools.append(weather_tool)

Step 5: Adding Multi-Step Planning

from langchain.agents import AgentType, initialize_agent

# Plan-and-execute agent for complex tasks
agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.OPENAI_FUNCTIONS,
    verbose=True,
    max_iterations=15,
)

# Complex multi-step task
result = agent.invoke({
    "input": """
    Plan a 7-day trip to Tokyo.
    Include:
    1. Daily itinerary with activities
    2. Estimated budget
    3. Best restaurants to try
    4. Transportation tips
    Format it as a structured travel plan.
    """
})

Step 6: Production Considerations

Error Handling

try:
    result = agent_executor.invoke({"input": task})
except Exception as e:
    print(f"Agent error: {e}")
    # Fallback to simpler approach
    result = llm.invoke(task)

Rate Limiting

import time
from functools import wraps

def rate_limit(max_calls: int, period: int):
    calls = []
    
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            now = time.time()
            calls[:] = [c for c in calls if now - c < period]
            
            if len(calls) >= max_calls:
                sleep_time = period - (now - calls[0])
                time.sleep(sleep_time)
            
            calls.append(time.time())
            return func(*args, **kwargs)
        
        return wrapper
    return decorator

Cost Tracking

import tiktoken

def count_tokens(text: str, model: str = "gpt-4") -> int:
    encoder = tiktoken.encoding_for_model(model)
    return len(encoder.encode(text))

# Track usage
total_input_tokens = 0
total_output_tokens = 0

def track_usage(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        global total_input_tokens, total_output_tokens
        # Track tokens before and after
        result = func(*args, **kwargs)
        return result
    return wrapper

Advanced Agent Architectures

1. Multi-Agent Systems

Planner Agent → Research Agent → Writing Agent → Review Agent → Final Output

2. RAG-Enhanced Agents

Combine agents with retrieval-augmented generation for knowledge-intensive tasks:

  • Vector store for knowledge base
  • Retrieval tool for agents to use
  • Grounded responses with sources

3. Human-in-the-Loop

For critical tasks, add human approval steps:

  • Agent proposes action
  • Human reviews and approves
  • Agent executes
  • Feedback loop for improvement

Best Practices

  1. Start simple: Begin with ReAct agent before moving to complex architectures
  2. Good tools are key: Invest time in building high-quality tools
  3. Monitor everything: Track cost, latency, success rate
  4. Add guardrails: Define what the agent can and cannot do
  5. Test thoroughly: Edge cases, error handling, security
  6. Iterate: Start small, gather feedback, improve

Common Pitfalls

  • ❌ Overcomplicating the architecture
  • ❌ Not handling errors gracefully
  • ❌ Ignoring cost and latency
  • ❌ Poor tool descriptions
  • ❌ No fallback mechanisms

Next Steps

  • Explore LangGraph for stateful multi-agent workflows
  • Add evaluation with LangSmith
  • Deploy as an API with FastAPI
  • Build a frontend interface
  • Add more specialized tools

Ready to build production AI agents? Check out our complete Build AI Agents from Scratch course with 12 hours of video, starter code, and real-world projects.

Related Posts

No related posts found.