{ "cells": [ { "cell_type": "markdown", "id": "04b696ee", "metadata": {}, "source": [ "# 🎯 Planning & Design Patterns with GitHub Models (Python)\n", "\n", "## πŸ“‹ Learning Objectives\n", "\n", "This notebook demonstrates advanced planning and design patterns for building intelligent agents using the Microsoft Agent Framework with GitHub Models. You'll learn how to create agents that can decompose complex problems, plan multi-step solutions, and coordinate sophisticated workflows.\n", "\n", "**Advanced Capabilities You'll Master:**\n", "- 🧠 **Strategic Planning**: Breaking complex tasks into manageable subtasks\n", "- πŸ—ΊοΈ **Multi-Step Reasoning**: Sequential and parallel task execution patterns\n", "- 🎯 **Goal-Oriented Design**: Agents that work toward specific objectives\n", "- πŸ”„ **Adaptive Planning**: Dynamic strategy adjustment based on context\n", "\n", "## 🎯 Planning Architecture Concepts\n", "\n", "### Core Planning Components\n", "- **Task Decomposition**: Breaking complex problems into smaller, manageable pieces\n", "- **Execution Planning**: Determining optimal order and dependencies for subtasks\n", "- **Resource Management**: Efficiently allocating tools and capabilities\n", "- **Progress Monitoring**: Tracking completion and adapting to changes\n", "\n", "### Design Patterns for Planning\n", "- **Strategy Pattern**: Multiple planning approaches for different scenarios\n", "- **Chain of Responsibility**: Sequential processing with fallback options\n", "- **Command Pattern**: Encapsulated task execution with undo/redo capabilities\n", "- **Observer Pattern**: Progress tracking and event-driven updates\n", "\n", "## πŸ—οΈ Technical Architecture\n", "\n", "### Planning System Components\n", "- **Microsoft Agent Framework**: Python implementation with advanced planning support\n", "- **GitHub Models Integration**: High-performance reasoning and decision-making\n", "- **Task Orchestration**: Coordinated execution of complex workflows \n", "- **State Management**: Persistent tracking of planning progress and results\n", "\n", "### Planning Process Flow\n", "```python\n", "Complex Goal β†’ Task Analysis β†’ Subtask Decomposition β†’ Execution Planning\n", " ↓ ↓ ↓\n", " Priority Assessment β†’ Resource Allocation β†’ Sequential Execution\n", " ↓ ↓ ↓\n", " Progress Monitoring β†’ Adaptive Replanning β†’ Goal Achievement\n", "```\n", "\n", "## 🧠 Planning Methodologies\n", "\n", "### 1. **Hierarchical Task Planning**\n", "- Top-down decomposition of complex objectives\n", "- Nested goal structures with dependencies\n", "- Recursive planning for sub-objectives\n", "- Efficient resource allocation across levels\n", "\n", "### 2. **Sequential Planning**\n", "- Step-by-step task execution with clear dependencies\n", "- Error handling and recovery at each stage\n", "- Progress checkpoints and validation\n", "- Rollback capabilities for failed steps\n", "\n", "### 3. **Parallel Planning**\n", "- Concurrent execution of independent tasks\n", "- Resource synchronization and conflict resolution\n", "- Performance optimization through parallelization\n", "- Coordinated completion and result aggregation\n", "\n", "## βš™οΈ Prerequisites & Setup\n", "\n", "\n", "**Required Dependencies:**\n", "```bash\n", "\n", "pip install agent-framework-core -U\n", "```\n", "\n", "**Environment Configuration (.env file):**\n", "```env\n", "GITHUB_TOKEN=your_github_personal_access_token\n", "GITHUB_ENDPOINT=https://models.inference.ai.azure.com\n", "GITHUB_MODEL_ID=gpt-4o-mini\n", "```\n", "\n", "## 🎨 Planning Design Patterns\n", "\n", "### Goal-Oriented Planning\n", "- **SMART Goals**: Specific, Measurable, Achievable, Relevant, Time-bound objectives\n", "- **Milestone Tracking**: Progress measurement and validation checkpoints\n", "- **Success Criteria**: Clear definitions of task completion\n", "- **Adaptive Strategies**: Dynamic planning adjustment based on feedback\n", "\n", "### Resource-Aware Planning\n", "- **Capability Assessment**: Understanding available tools and their limitations\n", "- **Load Balancing**: Optimal distribution of tasks across available resources\n", "- **Constraint Management**: Working within system and API limitations\n", "- **Performance Optimization**: Maximizing efficiency and minimizing latency\n", "\n", "### Error-Resilient Planning\n", "- **Failure Detection**: Early identification of planning or execution issues\n", "- **Recovery Strategies**: Automatic fallback and alternative approaches\n", "- **State Preservation**: Maintaining progress during error recovery\n", "- **Graceful Degradation**: Partial success when full completion isn't possible\n", "\n", "## πŸš€ Advanced Planning Features\n", "\n", "- **Meta-Planning**: Agents that plan how to plan\n", "- **Collaborative Planning**: Multi-agent coordination for complex projects\n", "- **Learning from Experience**: Improving planning strategies over time\n", "- **Real-Time Adaptation**: Dynamic replanning based on changing conditions\n", "\n", "## πŸ“Š Use Cases & Applications\n", "\n", "### Business Process Automation\n", "- Project management and task scheduling\n", "- Workflow optimization and resource allocation\n", "- Strategic planning and decision support\n", "- Process improvement and automation\n", "\n", "### Research & Analysis\n", "- Literature review and synthesis\n", "- Data analysis pipeline planning\n", "- Experimental design and execution\n", "- Report generation and formatting\n", "\n", "### Creative Projects\n", "- Content creation workflows\n", "- Multi-media project coordination\n", "- Campaign planning and execution\n", "- Event organization and management\n", "\n", "Ready to build intelligent planning agents that can tackle complex, multi-step challenges? Let's architect some sophisticated problem-solving capabilities! 🧠✨" ] }, { "cell_type": "code", "execution_count": 15, "id": "7d9d6188", "metadata": {}, "outputs": [], "source": [ "# ! pip install -r ../../../Installation/requirements.txt -U" ] }, { "cell_type": "code", "execution_count": 16, "id": "b6280fda", "metadata": {}, "outputs": [], "source": [ "# πŸ“¦ Import Standard Libraries\n", "# os: For environment variable access\n", "# dotenv: For loading environment variables from .env file\n", "import os\n", "\n", "from dotenv import load_dotenv" ] }, { "cell_type": "code", "execution_count": 17, "id": "3bd855d5", "metadata": {}, "outputs": [], "source": [ "# πŸ“ Import Data Modeling Libraries\n", "# Pydantic: For data validation and structured outputs\n", "# BaseModel: Base class for creating data models\n", "# Field: For adding metadata and validation to model fields\n", "# List: Type hint for list collections\n", "from pydantic import BaseModel, Field\n", "from typing import List" ] }, { "cell_type": "code", "execution_count": 18, "id": "b63147e1", "metadata": {}, "outputs": [], "source": [ "# πŸ€– Import Microsoft Agent Framework Components\n", "# ChatMessage: For creating structured chat messages\n", "# Role: Enum for message roles (user, assistant, system)\n", "# ChatOptions: Configuration options for chat interactions\n", "# OpenAIChatClient: Client for OpenAI-compatible APIs (GitHub Models)\n", "from agent_framework import Message, Role, ChatOptions\n", "from agent_framework.openai import OpenAIChatCompletionClient" ] }, { "cell_type": "markdown", "id": "6ebba89d", "metadata": {}, "source": [ "## πŸ“¦ Import Agent Framework Components\n", "\n", "Import the core Agent Framework classes for building planning agents:\n", "- `ChatMessage` & `Role`: For structured message creation\n", "- `ChatOptions`: Configuration for chat interactions with response formatting\n", "- `OpenAIChatClient`: GitHub Models integration" ] }, { "cell_type": "code", "execution_count": 19, "id": "d95ec338", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# πŸ”§ Load Environment Variables\n", "# Load configuration from .env file\n", "# Required: GITHUB_ENDPOINT, GITHUB_TOKEN, GITHUB_MODEL_ID\n", "load_dotenv()" ] }, { "cell_type": "markdown", "id": "f39f3488", "metadata": {}, "source": [ "## πŸ”§ Load Environment Configuration\n", "\n", "Initialize environment variables for GitHub Models API access." ] }, { "cell_type": "code", "execution_count": 20, "id": "baeb5915", "metadata": {}, "outputs": [], "source": [ "# 🎯 Agent Configuration\n", "# Define the agent's name and role\n", "\n", "AGENT_NAME = \"TravelAgent\"\n", "\n", "# πŸ“‹ System Instructions for Planning Agent\n", "# This agent acts as a coordinator that decides which specialized agents to use\n", "AGENT_INSTRUCTIONS = \"\"\"You are a planner agent.\n", " Your job is to decide which agents to run based on the user's request.\n", " Below are the available agents specialized in different tasks:\n", " - FlightBooking: For booking flights and providing flight information\n", " - HotelBooking: For booking hotels and providing hotel information\n", " - CarRental: For booking cars and providing car rental information\n", " - ActivitiesBooking: For booking activities and providing activity information\n", "\"\"\"\n" ] }, { "cell_type": "markdown", "id": "3c1c9217", "metadata": {}, "source": [ "## 🎯 Define Planning Agent Configuration\n", "\n", "Configure the planner agent that coordinates multiple specialized sub-agents:\n", "- **FlightBooking**: Handles flight reservations\n", "- **HotelBooking**: Manages hotel accommodations \n", "- **CarRental**: Books rental vehicles\n", "- **ActivitiesBooking**: Organizes activities and tours\n", "\n", "The planner decomposes complex travel requests into subtasks assigned to appropriate specialists." ] }, { "cell_type": "code", "execution_count": 21, "id": "556b40c1", "metadata": {}, "outputs": [], "source": [ "class SubTask(BaseModel):\n", " assigned_agent: str = Field(\n", " description=\"The specific agent assigned to handle this subtask\")\n", " task_details: str = Field(\n", " description=\"Detailed description of what needs to be done for this subtask\")\n", "\n", "\n", "class TravelPlan(BaseModel):\n", " main_task: str = Field(\n", " description=\"The overall travel request from the user\")\n", " subtasks: List[SubTask] = Field(\n", " description=\"List of subtasks broken down from the main task, each assigned to a specialized agent\")" ] }, { "cell_type": "markdown", "id": "89419727", "metadata": {}, "source": [ "## πŸ“‹ Define Structured Output Models\n", "\n", "Use Pydantic models to define the expected output structure:\n", "- **SubTask**: Individual task with assigned agent and description\n", "- **TravelPlan**: Complete plan with main task and list of subtasks\n", "\n", "This enables **structured output** where the AI returns data in a predictable, typed format." ] }, { "cell_type": "code", "execution_count": 22, "id": "3c16e0df", "metadata": {}, "outputs": [], "source": [ "options = ChatOptions(response_format=TravelPlan)" ] }, { "cell_type": "markdown", "id": "77efd5ea", "metadata": {}, "source": [ "## βš™οΈ Configure Chat Options for Structured Response\n", "\n", "Set up chat options to request the TravelPlan structured output format." ] }, { "cell_type": "code", "execution_count": 23, "id": "a312a074", "metadata": {}, "outputs": [], "source": [ "client = OpenAIChatCompletionClient(base_url=os.environ.get(\"GITHUB_ENDPOINT\"), api_key=os.environ.get(\"GITHUB_TOKEN\"), model=os.environ.get(\"GITHUB_MODEL_ID\"))" ] }, { "cell_type": "markdown", "id": "1bef0dbf", "metadata": {}, "source": [ "## πŸ”— Initialize GitHub Models Chat Client\n", "\n", "Create the OpenAI-compatible client for GitHub Models API communication." ] }, { "cell_type": "code", "execution_count": 24, "id": "374e70ee", "metadata": {}, "outputs": [], "source": [ "agent = client.as_agent(name= AGENT_NAME , instructions=AGENT_INSTRUCTIONS)" ] }, { "cell_type": "markdown", "id": "838b94f6", "metadata": {}, "source": [ "## πŸ€– Create the Planning Agent\n", "\n", "Convert the chat client to an agent with the planner configuration." ] }, { "cell_type": "code", "execution_count": 25, "id": "cde85093", "metadata": {}, "outputs": [], "source": [ "messages = [\n", " Message(role=\"user\", contents=\"Create a travel plan for a family of 4, with 2 kids, from Singapore to Melbourne\")\n", " ]" ] }, { "cell_type": "markdown", "id": "3c6a730f", "metadata": {}, "source": [ "## πŸ’¬ Prepare User Message\n", "\n", "Create the travel planning request message for the agent." ] }, { "cell_type": "code", "execution_count": 26, "id": "781c7c2a", "metadata": {}, "outputs": [], "source": [ "response = await agent.run(messages, options=options)" ] }, { "cell_type": "markdown", "id": "8b58f1ea", "metadata": {}, "source": [ "## πŸš€ Execute Planning Agent\n", "\n", "Run the agent with the travel request. The agent will:\n", "1. Analyze the complex travel requirement\n", "2. Decompose it into manageable subtasks\n", "3. Assign each subtask to the appropriate specialist agent\n", "4. Return a structured TravelPlan with all assignments" ] }, { "cell_type": "code", "execution_count": 27, "id": "25b44f81", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'{\"main_task\":\"Create a travel plan for a family of 4, with 2 kids, traveling from Singapore to Melbourne.\",\"subtasks\":[{\"assigned_agent\":\"FlightBooking\",\"task_details\":\"Book flights for 4 family members, including 2 kids, from Singapore to Melbourne.\"},{\"assigned_agent\":\"HotelBooking\",\"task_details\":\"Find and book family-friendly accommodation in Melbourne suitable for 4 people including 2 kids.\"},{\"assigned_agent\":\"CarRental\",\"task_details\":\"Arrange for a suitable car rental in Melbourne for a family of 4, including 2 kids.\"},{\"assigned_agent\":\"ActivitiesBooking\",\"task_details\":\"Plan and book family-friendly activities and attractions in Melbourne suitable for 2 adults and 2 kids.\"}]}'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "response.messages[0].text" ] }, { "cell_type": "markdown", "id": "fdfed881", "metadata": {}, "source": [ "## πŸ“– Display the Generated Travel Plan\n", "\n", "View the structured travel plan with agent assignments and task details." ] } ], "metadata": { "kernelspec": { "display_name": "agentdev", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.10" } }, "nbformat": 4, "nbformat_minor": 5 }