DEV Community

Anna lilith
Anna lilith

Posted on

How to Build an AI Agent in Python That Actually Works

How to Build an AI Agent in Python That Actually Works

Last updated: July 2026

AI agents are the future of automation. This guide shows you how to build one that's reliable, useful, and doesn't require a PhD in machine learning.

What is an AI Agent?

An AI agent is a program that:

  • Perceives its environment (reads data, receives inputs)
  • Makes decisions (using rules, ML, or LLMs)
  • Takes actions (API calls, file operations, communications)
  • Learns from results (improves over time)

Simple Rule-Based Agent

Start with a rule-based agent:

class SimpleAgent:
    def __init__(self):
        self.rules = {
            "error": self.handle_error,
            "warning": self.handle_warning,
            "success": self.handle_success,
        }

    def perceive(self, input_data):
        """Parse input and determine type."""
        if "error" in input_data.lower():
            return "error"
        elif "warning" in input_data.lower():
            return "warning"
        return "success"

    def act(self, perception):
        """Execute action based on perception."""
        handler = self.rules.get(perception, self.default_handler)
        return handler()

    def handle_error(self):
        return "Alerting admin and logging error"

    def handle_warning(self):
        return "Logging warning for review"

    def handle_success(self):
        return "No action needed"

    def default_handler(self):
        return "Unknown input, logging for analysis"
Enter fullscreen mode Exit fullscreen mode

LLM-Powered Agent

Use an LLM for more sophisticated decisions:

import requests

class LLMAgent:
    def __init__(self, api_key):
        self.api_key = api_key
        self.history = []

    def decide(self, context):
        """Use LLM to decide what action to take."""
        prompt = f"""Given this context: {context}

What action should I take? Options:
1. send_email
2. create_task
3. update_database
4. notify_user
5. no_action

Respond with just the action name."""

        response = requests.post(
            "https://text.pollinations.ai/",
            json={
                "messages": [{"role": "user", "content": prompt}],
                "model": "openai"
            }
        )

        action = response.text.strip().lower()
        self.history.append({"context": context, "action": action})
        return action

    def execute(self, action, params):
        """Execute the chosen action."""
        actions = {
            "send_email": self.send_email,
            "create_task": self.create_task,
            "update_database": self.update_db,
            "notify_user": self.notify_user,
        }

        handler = actions.get(action)
        if handler:
            return handler(params)
        return "No action taken"
Enter fullscreen mode Exit fullscreen mode

Agent with Memory

Add memory for context retention:

import json
from pathlib import Path

class MemoryAgent:
    def __init__(self, memory_file="agent_memory.json"):
        self.memory_file = Path(memory_file)
        self.memory = self.load_memory()

    def load_memory(self):
        if self.memory_file.exists():
            return json.loads(self.memory_file.read_text())
        return {"short_term": [], "long_term": {}}

    def save_memory(self):
        self.memory_file.write_text(json.dumps(self.memory, indent=2))

    def remember(self, key, value, long_term=False):
        if long_term:
            self.memory["long_term"][key] = value
        else:
            self.memory["short_term"].append({key: value})
            # Keep only last 10 items
            self.memory["short_term"] = self.memory["short_term"][-10:]
        self.save_memory()

    def recall(self, key):
        # Check short-term first
        for item in reversed(self.memory["short_term"]):
            if key in item:
                return item[key]
        # Then long-term
        return self.memory["long_term"].get(key)
Enter fullscreen mode Exit fullscreen mode

Agent with Tools

Give your agent tools to use:

class ToolAgent:
    def __init__(self):
        self.tools = {
            "search": self.search_web,
            "calculate": self.calculate,
            "read_file": self.read_file,
            "write_file": self.write_file,
        }

    def use_tool(self, tool_name, **kwargs):
        if tool_name in self.tools:
            return self.tools[tool_name](**kwargs)
        return f"Unknown tool: {tool_name}"

    def search_web(self, query):
        # Implement web search
        return f"Search results for: {query}"

    def calculate(self, expression):
        try:
            return str(eval(expression))
        except:
            return "Invalid calculation"

    def read_file(self, path):
        try:
            return Path(path).read_text()
        except:
            return "File not found"

    def write_file(self, path, content):
        Path(path).write_text(content)
        return "File written successfully"
Enter fullscreen mode Exit fullscreen mode

Production Considerations

  1. Error Handling: Always wrap actions in try/except
  2. Rate Limiting: Don't overwhelm APIs or services
  3. Logging: Track all decisions and actions
  4. Testing: Test each tool and decision path
  5. Security: Validate inputs, sandbox execution

Get the Production-Ready Version

We have a complete AI agent framework at our store.

What's included:

  • Multiple agent types (rule-based, LLM, hybrid)
  • Memory system
  • Tool integration
  • Decision logging
  • Easy customization

Browse the collection →

Top comments (0)