AI Agents: Theory and Implementation with FastMCP

Session 1: Introduction to AI Agents: Theory & Architecture

March 16, 2024 | Instructor: Benjamin Coder

View on GitHub

This session covers the fundamentals of AI agents, including their design principles, architecture patterns, decision-making frameworks, and operating environments.

1. Introduction to AI Agents

AI agents are autonomous systems that can perceive their environment, make decisions, and take actions to achieve specific goals. Unlike traditional software, agents operate with varying degrees of autonomy and can adapt to changing circumstances.

Key Characteristics of AI Agents

Agent Architectures

Different agent architectures organize these capabilities in various ways:

Architecture Description Suitable Applications
Reactive Simple stimulus-response mechanisms without state Time-critical applications, robotics
Deliberative Planning-based approaches with world models Complex problem-solving, strategy
Hybrid Combines reactive and deliberative elements Multi-objective tasks, flexible responses
Learning Adapts behavior based on experience Dynamic environments, personalization
FastMCP Multi-context planning with rapid cycles Knowledge work, reasoning tasks, LLM integration

For more detailed information on agent architectures, see the project documentation at theory/concepts/agent_architectures.md.

Agent Environments

Agents operate within specific environments, which can be characterized by several properties:

Agent Decision-Making Frameworks

Agents use various decision-making frameworks to determine their actions:

Session 2: Building AI Agents: FastMCP with Claude Integration

March 30, 2024 | Instructor: Benjamin Coder

View on GitHub

This session focuses on implementing AI agents using the FastMCP (Fast Multi-Context Planning) architecture with Claude integration, covering practical implementation techniques and hands-on development.

2. Understanding FastMCP Architecture

FastMCP (Fast Multi-Context Planning) is an agent architecture methodology designed to enable AI systems to plan and execute tasks across multiple domains or contexts. It emphasizes:

Core Components of FastMCP

The FastMCP architecture consists of five main components that work together to create an effective agent system.

Context Manager

Manages different domains of knowledge and expertise:


# Example of creating contexts in FastMCP
research = Context("research", "Gathering information and analyzing data")
planning = Context("planning", "Creating step-by-step plans to achieve goals")
decision = Context("decision", "Making choices based on criteria and consequences")
        

Planning System

Generates structured plans for achieving goals:


# Creating a plan in FastMCP
plan = planner.create_plan("Research and summarize advances in AI agent architectures")
        

Reasoning Engine

Provides cognitive capabilities for planning and analysis, often implemented using LLMs like Claude.

Execution Framework

Manages the implementation of plans by translating steps into concrete actions.

Reflection Module

Evaluates performance and drives improvement through analysis of results.

3. Claude AI Integration

Claude is an AI assistant developed by Anthropic that excels at complex reasoning tasks, making it an ideal foundation for the reasoning component of FastMCP agents.

Setting Up Claude API Access

To use Claude with your FastMCP implementation:

  1. Obtain an API key from Anthropic
  2. Set up your environment with the API key

# Set up environment variable
export ANTHROPIC_API_KEY=your_claude_api_key_here

# Or add to .env file
ANTHROPIC_API_KEY=your_claude_api_key_here
        

Basic Claude API Integration


# Simple example of Claude API usage
import anthropic

client = anthropic.Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
response = client.messages.create(
    model="claude-3-opus-20240229",
    system="You are a planning assistant.",
    max_tokens=1000,
    messages=[{"role": "user", "content": "Create a plan for writing a research paper"}]
)
print(response.content[0].text)
        
Remember to keep your API key secure. Never commit it directly to your code repository.

4. Implementation Walkthrough

The repository includes a complete implementation of the FastMCP architecture with Claude integration. Let's walk through the key components:

Project Structure


/theory                  # Theoretical concepts and documentation
  /concepts              # Detailed explanations of key concepts
  /diagrams              # Visual representations of the architecture
/implementation          # Core implementation code
  /fastmcp_core          # FastMCP framework implementation
  /claude_integration    # Claude AI integration components
  /demos                 # Example implementations and demonstrations
/examples                # Simpler standalone examples
/resources               # Additional resources and references
        

Core FastMCP Implementation

The core implementation in implementation/fastmcp_core/fastmcp.py provides the following classes:

Claude Integration

The Claude integration in implementation/claude_integration/claude_reasoning.py provides:

5. Building Your First Agent

Let's walk through the process of creating a basic agent using the FastMCP framework with Claude integration.

Step 1: Set Up Dependencies


# Install required packages
pip install -r requirements.txt
        

Step 2: Create a Basic Agent

We'll start with the example in examples/basic_agent.py:


import os
import json
from dotenv import load_dotenv
import anthropic

# Load environment variables
load_dotenv()

class FastMCPAgent:
    def __init__(self, api_key: str = None):
        self.api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
        if not self.api_key:
            raise ValueError("No API key provided")
        
        self.client = anthropic.Anthropic(api_key=self.api_key)
        self.model = "claude-3-opus-20240229"
    
    # ... [methods for thinking, executing, reflecting]
    
    def run(self, task: str):
        print(f"🤖 Agent received task: {task}")
        
        # Planning phase
        plan = self.think(task)
        
        # Execution phase
        results = self.execute(plan)
        
        # Reflection phase
        reflection = self.reflect(task, plan, results)
        
        return {
            "task": task,
            "plan": plan,
            "execution_results": results,
            "reflection": reflection
        }
        

Step 3: Running Your Agent


# Create and run the agent
agent = FastMCPAgent()
task = "Research and summarize the three most promising applications of AI agents in healthcare"
result = agent.run(task)
        

6. Running the FastMCP Demo

For a more comprehensive example, you can run the demo in implementation/demos/fastmcp_claude_demo.py:


python implementation/demos/fastmcp_claude_demo.py
        

This demo shows a complete FastMCP agent that:

  1. Initializes the FastMCP framework with multiple contexts
  2. Sets up the Claude reasoning engine
  3. Creates a plan for a complex goal
  4. Executes the plan step by step
  5. Analyzes the results to provide insights

The demo simulates execution for educational purposes. In a real-world implementation, the execution engine would perform actual actions.

7. Advanced Concepts

Multi-Context Planning

FastMCP excels at tasks that span multiple domains. For example, creating a workshop might involve:

Customizing Contexts

You can create custom contexts to represent specific domains of expertise:


# Creating a custom context
healthcare_context = Context("healthcare", "Medical knowledge and healthcare applications")
healthcare_context.add_rule({"name": "patient_privacy", "description": "Ensure patient privacy is protected"})
healthcare_context.add_heuristic({"name": "evidence_based", "description": "Prioritize evidence-based approaches"})
planner.register_context(healthcare_context)
        

Extending the Agent

To extend your agent with new capabilities:

  1. Add new methods to the FastMCPAgent class
  2. Create new contexts for specialized domains
  3. Implement custom execution methods for specific actions
  4. Enhance the reflection process for better learning

8. Exercises and Projects

Exercise 1: Create a Research Agent

Extend the basic agent to perform research on a specific topic, summarize findings, and provide recommendations.

Exercise 2: Implement a Project Planning Agent

Build an agent that can create detailed project plans, estimate timelines, identify risks, and suggest mitigation strategies.

Exercise 3: Develop a Content Creation Agent

Create an agent that can generate various types of content (articles, social media posts, educational materials) based on specific requirements.

Challenge Project: Multi-Agent System

Implement a system of multiple FastMCP agents that can collaborate to solve complex problems requiring diverse expertise.