DEV Community

Bartolomeo Hart
Bartolomeo Hart

Posted on

Building an AI Agent Is Easy! Here’s Proof..

AI Agent Banner
I’ve created a simple AI agent that shows how anyone with minimal Python knowledge can get started. Let me show you how straightforward it can be!

(Note: Full code example provided below)

4 Core Components🎯

The Brain (AI Model Connection)

At its core, an AI agent just needs to talk to a language model. Here’s how you establish a connection using the Anthropic API:

def __init__(self, anthropic_api_key):
    self.anthropic_client = anthropic.Client(api_key=anthropic_api_key)
    self.models = {
        "haiku": "claude-3-haiku-20240307",
        "sonnet": "claude-3-sonnet-20240229",
    }
Enter fullscreen mode Exit fullscreen mode

The Memory (Action Management)

Register all possible actions that are available for your agent to use. No rocket science here:

# Register single actions
self.actions = {
    "search_wikipedia": self.search_wikipedia,
    "calculate": self.calculate,
    "get_weather": self.get_weather,
    "get_crypto": self.get_crypto_data,
}

# Register automated actions
self.automated_actions = {
    "crypto_tracking": self.start_crypto_scheduler
}
Enter fullscreen mode Exit fullscreen mode

The Instructions (System Prompt)

Here’s where the magic happens. Just tell your AI what it can do:

self.system_prompt = """You are an AI assistant that can perform both automated and one-time actions.
Response Format:
- For automation: 'AUTOMATE: action_name'
- For one-time actions: 'ACTION: action_name: parameter'
- For general queries: Respond naturally
"""
Enter fullscreen mode Exit fullscreen mode

The Executor (Command Processing)

Simply watch for commands and execute them:

# Check for automation command
automate_match = re.search(r'AUTOMATE: (\w+)', assistant_message)
if automate_match:
    action_name = automate_match.group(1)
    result = self.automated_actions[action_name]()
Enter fullscreen mode Exit fullscreen mode

Piecing It All Together 🔄

Let’s see what this could look like:

# Init Anthropic
self.anthropic_client = anthropic.Client(api_key=anthropic_api_key)
self.models = {
    "haiku": "claude-3-haiku-20240307",
    "sonnet": "claude-3-sonnet-20240229",
}

# Create system prompt
self.system_prompt = """You are an AI assistant that ...more"""

# Create automated action
def start_crypto_scheduler(self):
    if not self.scheduler_running:
        self.scheduler_running = True

        # Schedule task for every 10 seconds
        schedule.every(10).seconds.do(self.save_crypto_data)

        # Initial run
        self.save_crypto_data()

        # Start scheduler in separate thread
        scheduler_thread = threading.Thread(target=self.run_scheduler)
        scheduler_thread.daemon = True
        scheduler_thread.start()

# Register action
self.automated_actions = {
    "crypto_tracking": self.start_crypto_scheduler
}

# Excute
def execute(self, user_input):

    # User input : "Can you monitor crypto prices?"
    self.messages.append({"role": "user", "content": user_input})
    conversation_history = [msg for msg in self.messages if msg['role'] != 'system']

    selected_model = self.models.get(model_choice, self.models["haiku"])

    # Get AI response
    response = self.anthropic_client.messages.create(
        model=selected_model,
        messages=conversation_history,
        system=self.system_prompt,
        max_tokens=1000,
        temperature=0.2,
        top_p=1.0,
    )

    assistant_message = response.content[0].text
    self.messages.append({"role": "assistant", "content": assistant_message})

    # Check for automation command
    automate_match = re.search(r'AUTOMATE: (\w+)', assistant_message)
    if automate_match:
        action_name = automate_match.group(1)
        if action_name in self.automated_actions:
            result = self.automated_actions[action_name]()
            return f"Automated task started: {result}"
        return f"Error: Unknown automated action {action_name}"
Enter fullscreen mode Exit fullscreen mode

That’s it! A few simple steps to go from user input to automated task execution.

Real-World Example🚀

Want to try it yourself? Check out the full project code and get started within minutes: https://github.com/unameit10000000/reallysimpleagent

Takeaway 💡

Building an AI agent does not need to be complex. With just basic Python knowledge and a clear structure, you can start building your own agents incrementally and create something powerfull.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 👀

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay