Skip to content

XueyanZhang/AgenticAI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Agentic AI Design Patterns

This repository contains hands-on labs and assignments from the Agentic AI course by DeepLearning.AI.

GREAT COURSE! EVERYONE HERE SHOULD CHECK IT OUT!

Course Overview

Learn to build intelligent AI agents using established design patterns for autonomous systems. The course covers reflection, tool use, planning, and multi-agent collaboration patterns through practical implementations with modern LLMs.

Repository Structure

M2: Reflection Design Pattern

AI systems that critique and improve their own outputs through iterative self-evaluation.

Key Activities:

  • flashcards_agent - Generate and refine study flashcards using LLM-based reflection
  • pii_removal - Protect sensitive information using defensive reflection techniques
  • sql_agent - Convert natural language to SQL queries with reflection-based improvement
  • visualization_agent - Create and enhance data visualizations through iterative critique

Learning Focus:

  • Implementing reflection loops where AI evaluates its own work
  • Using one model to critique another's output
  • Iterative refinement based on pedagogical and quality best practices
  • Defensive strategies to prevent prompt injection attacks

M3: Tool Use Design Pattern

Agents that extend their capabilities by calling external tools and APIs.

Key Activities:

  • email_agent - LLM tool implementation with aisuite for email operations (send, search, read, mark)
  • research_agent - External API tools for web search (Tavily) and academic research (arXiv, Wikipedia)
  • sql-agent - Database interaction comparing OpenAI function calling vs AISuite approaches

Learning Focus:

  • Converting Python functions into LLM-callable tools
  • Function calling with OpenAI and AISuite syntaxes
  • Tool definition using Pydantic schemas
  • Dynamic tool registration and execution loops
  • Safe database operations with schema exploration

M4: Multi-agent Collaboration

Sequential agent pipelines where specialized agents work together to solve complex problems.

Key Activities:

  • customer-service - Four-agent pipeline (Planner → Coder → Executor → Reflector) for processing customer requests in a sunglasses store context

Learning Focus:

  • Modular task decomposition across specialized agents
  • Sequential orchestration patterns
  • Error recovery through agent communication
  • Self-correction capabilities in multi-agent systems

M5: Advanced Multi-agent Patterns

Building on M4 concepts with more sophisticated multi-agent architectures.

Key Activities:

  • research-agent - Advanced research workflows with tool integration
  • inventory management - Multi-agent systems for e-commerce operations

Learning Focus:

  • Complex agent communication patterns
  • State management across agents
  • Tool use in multi-agent contexts
  • Production-ready agent architectures

Getting Started

Prerequisites

  • Python 3.8+
  • Jupyter Notebook
  • API keys for:
    • OpenAI
    • Anthropic (Claude)
    • Google AI Studio
    • Tavily (web search)

Installation

  1. Clone this repository:
git clone <repository-url>
cd AgenticAi
  1. Create a virtual environment:
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies (per module):
pip install -r M2/assignment/autograder/requirements.txt
  1. Create a .env file in the root directory:
OPENAI_API_KEY=your_openai_key_here
ANTHROPIC_API_KEY=your_anthropic_key_here
GOOGLE_API_KEY=your_google_key_here
TAVILY_API_KEY=your_tavily_key_here
DLAI_TAVILY_BASE_URL=optional_custom_endpoint
  1. Launch Jupyter:
jupyter notebook

AI Client Usage

OpenAI Client (Primary)

Most exercises use the OpenAI client for LLM interactions:

from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()
client = OpenAI()  # Automatically reads OPENAI_API_KEY from environment

# Basic completion
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
    ],
    temperature=0.7
)

# Access response
answer = response.choices[0].message.content

Tool Calling Pattern

# Define tools
tools = [
    {
        "type": "function",
        "function": {
            "name": "search_arxiv",
            "description": "Search academic papers on arXiv",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "Search query"}
                },
                "required": ["query"]
            }
        }
    }
]

# Call with tools
response = client.chat.completions.create(
    model="gpt-4o",
    messages=messages,
    tools=tools,
    tool_choice="auto"  # Let model decide when to use tools
)

# Handle tool calls
msg = response.choices[0].message
if msg.tool_calls:
    for call in msg.tool_calls:
        function_name = call.function.name
        arguments = json.loads(call.function.arguments)
        # Execute the tool and append result to messages

AISuite (Multi-Provider)

Some exercises use aisuite for provider-agnostic LLM calls:

import aisuite

client = aisuite.Client()

# Specify provider:model format
response = client.chat.completions.create(
    model="openai:gpt-4o",  # or "anthropic:claude-3-5-sonnet-20241022"
    messages=[
        {"role": "user", "content": "Hello!"}
    ]
)

Agentic Loop Pattern

messages = [{"role": "user", "content": "Your task here"}]
max_turns = 10

for _ in range(max_turns):
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        tools=tools,
        tool_choice="auto"
    )

    msg = response.choices[0].message
    messages.append(msg)

    # Break if no tool calls (final answer)
    if not msg.tool_calls:
        break

    # Execute each tool call
    for call in msg.tool_calls:
        result = execute_tool(call)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "name": call.function.name,
            "content": json.dumps(result)
        })

final_answer = messages[-1].content

Working with Assignments

Each module contains graded assignments with specific structure:

  • Code must be written only between ### START CODE HERE ### and ### END CODE HERE ### markers
  • Global variables (e.g., CLIENT, TOOL_MAPPING) are provided in UPPERCASE
  • Test your code with included unit tests: unittests.test_function_name(your_function)
  • Cells outside markers are frozen and should not be modified

Key Libraries

  • openai - OpenAI API client for GPT models
  • aisuite - Unified interface for multiple LLM providers
  • tavily - Web search API client
  • wikipedia - Wikipedia API wrapper
  • requests - HTTP library for API calls
  • python-dotenv - Environment variable management
  • pydantic - Data validation and tool schema definitions
  • pandas - Data manipulation (multi-agent exercises)

Common Patterns

Reflection Pattern

# 1. Generate initial output
initial_output = generate_content(prompt)

# 2. Reflect on output
reflection = critique_output(initial_output)

# 3. Revise based on reflection
improved_output = revise_content(initial_output, reflection)

Tool Definition Pattern

def my_tool(param: str) -> dict:
    """Tool implementation"""
    return {"result": "..."}

tool_def = {
    "type": "function",
    "function": {
        "name": "my_tool",
        "description": "What it does",
        "parameters": {...}
    }
}

tool_mapping = {"my_tool": my_tool}

Multi-Agent Pattern

# Specialized agents with distinct roles
planner_response = planner_agent(user_request)
code = coder_agent(planner_response)
result = executor_agent(code)
final_output = reflector_agent(result)

Resources

License

Educational materials from DeepLearning.AI

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors