AI agents are the biggest trend in software development right now. Unlike a standard chatbot that just answers questions, an AI agent can "think," make decisions, and use tools to complete complex tasks.

But most tutorials make building an agent sound incredibly complicated. They throw heavy frameworks like LangChain or AutoGen at you before explaining the basics.

You don't need a massive framework to build your first agent. You just need Python and a basic understanding of how the OpenAI API works. Here is exactly how to build a simple, functional AI agent from scratch.

Step 1: The Prerequisites

Before writing any code, you need two things:

  1. Python installed on your machine.
  2. An OpenAI API Key (you can get one from the OpenAI developer platform).

First, create a new project folder and install the official OpenAI Python library:

bash

pip install openai

Step 2: The Basic LLM Call

An AI agent is, at its core, a Large Language Model (LLM) running in a loop. Let's start by making a basic call to the model.

Create a file called agent.py and add this code:

python

import os
from openai import OpenAI

# Initialize the client
client = OpenAI(api_key="YOUR_API_KEY_HERE")

def get_ai_response(prompt):
    response = client.chat.completions.create(
        model="gpt-4-turbo", # Or gpt-3.5-turbo for lower cost
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message.content

# Test the basic call
print(get_ai_response("Hello! Who are you?"))

If you run this, you will get a standard response. But this is just a chatbot. It's not an agent yet.

Step 3: Giving the Agent "Tools"

The defining feature of an agent is its ability to use tools (also called function calling). A tool is just a standard Python function that the AI is allowed to execute.

Let's give our agent a simple tool to check the current time.

Update your agent.py file:

python

import datetime
import json

# 1. Define the tool
def get_current_time():
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# 2. Tell the AI the tool exists (The Schema)
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "Get the current date and time",
            "parameters": {
                "type": "object",
                "properties": {},
            },
        },
    }
]

Step 4: The Agent Loop (Thinking and Acting)

Now we need the agent to look at a user prompt, decide if it needs a tool, run the tool, and then give the final answer to the user.

Here is the complete "Agent Loop":

python

def run_agent(user_message):
    messages = [{"role": "user", "content": user_message}]
    
    # First API call: The AI decides if it needs a tool
    response = client.chat.completions.create(
        model="gpt-4-turbo",
        messages=messages,
        tools=tools
    )
    
    response_message = response.choices[0].message
    messages.append(response_message)

    # Check if the AI wants to call a tool
    if response_message.tool_calls:
        for tool_call in response_message.tool_calls:
            if tool_call.function.name == "get_current_time":
                # Execute the tool
                tool_result = get_current_time()
                
                # Send the result back to the AI
                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": tool_result
                })

        # Second API call: The AI uses the tool result to answer the user
        final_response = client.chat.completions.create(
            model="gpt-4-turbo",
            messages=messages
        )
        return final_response.choices[0].message.content
    
    # If no tool was needed, return the direct response
    return response_message.content

# Test the agent
print(run_agent("What time is it right now?"))

If you run this, the AI will realize it doesn't know the time, use the get_current_time function, read the result, and tell you the exact time.

Taking Your AI Agent to the Next Level

This is just the foundation. Once you master this loop, you can give your agent tools to search the web, read files, send emails, or execute complex code.

However, building a simple agent is easy. Building a production-ready, secure, and intelligent AI system that doesn't hallucinate or burn through your API budget is much harder.

If you are ready to take the next step, explore our complete AI Development Masterclass. It covers advanced agent architectures, memory management, deploying agents to production, and building custom LLM applications from scratch.