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.

Image of AssemblyAI tool

Transforming Interviews into Publishable Stories with AssemblyAI

Insightview is a modern web application that streamlines the interview workflow for journalists. By leveraging AssemblyAI's LeMUR and Universal-2 technology, it transforms raw interview recordings into structured, actionable content, dramatically reducing the time from recording to publication.

Key Features:
🎥 Audio/video file upload with real-time preview
🗣️ Advanced transcription with speaker identification
⭐ Automatic highlight extraction of key moments
✍️ AI-powered article draft generation
📤 Export interview's subtitles in VTT format

Read full post

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay