{ "cells": [ { "cell_type": "markdown", "id": "a6e34f84", "metadata": {}, "source": [ "# 🤝 Multi-Agent Workflow Systems with GitHub Models (Python)\n", "\n", "## 📋 Learning Objectives\n", "\n", "This notebook demonstrates how to build sophisticated multi-agent systems using the Microsoft Agent Framework with GitHub Models. You'll learn to orchestrate multiple specialized agents working together to solve complex problems through structured workflows.\n", "\n", "**Multi-Agent Capabilities You'll Build:**\n", "- 👥 **Agent Collaboration**: Multiple agents working together toward common goals\n", "- 🔄 **Workflow Orchestration**: Structured coordination of agent interactions\n", "- 🎭 **Role Specialization**: Agents with distinct personalities and expertise areas\n", "- 📋 **Quality Assurance**: Review and refinement through agent collaboration\n", "\n", "## 🎯 Multi-Agent Architecture Concepts\n", "\n", "### Core Multi-Agent Principles\n", "- **Division of Labor**: Each agent specializes in specific domain expertise\n", "- **Collaborative Decision Making**: Agents review and refine each other's work\n", "- **Workflow Coordination**: Structured handoffs and communication patterns\n", "- **Quality Enhancement**: Iterative improvement through multi-perspective analysis\n", "\n", "### Agent Interaction Patterns\n", "- **Sequential Processing**: Linear workflow with ordered agent participation\n", "- **Peer Review**: Agents validate and improve each other's outputs\n", "- **Hierarchical Structure**: Lead agents coordinating subordinate specialists\n", "- **Consensus Building**: Multiple agents contributing to final decisions\n", "\n", "## 🏗️ Technical Architecture\n", "\n", "### Workflow System Components\n", "- **Microsoft Agent Framework**: Python implementation with advanced workflow support\n", "- **WorkflowBuilder**: Declarative workflow definition and execution engine\n", "- **Agent Coordination**: Structured communication and handoff mechanisms\n", "- **Event-Driven Processing**: Reactive workflow execution based on agent outputs\n", "\n", "### Multi-Agent Process Flow\n", "```python\n", "User Request → Agent 1 (Specialist) → Agent 2 (Reviewer) → Quality Check\n", " ↓ ↓ ↓\n", " Initial Solution → Review & Feedback → Refined Output → Final Result\n", "```\n", "\n", "## 🎭 Agent Role Examples\n", "\n", "### Hotel Concierge System\n", "This notebook demonstrates a travel recommendation system with specialized roles:\n", "\n", "#### 🏨 **Front Desk Agent**\n", "- **Expertise**: Travel recommendations and local knowledge\n", "- **Personality**: Efficient, experienced, concise communication style\n", "- **Responsibilities**: Generate initial travel suggestions and activities\n", "\n", "#### 🎩 **Concierge Agent** \n", "- **Expertise**: Authentic local experiences and quality assessment\n", "- **Personality**: Discerning, focused on non-touristy recommendations\n", "- **Responsibilities**: Review and refine travel suggestions for authenticity\n", "\n", "## 🔧 Technical Implementation\n", "\n", "### Workflow Architecture\n", "- **Agent Definition**: Specialized instructions and personality configuration\n", "- **Workflow Builder**: Declarative workflow definition with event handling\n", "- **Communication Protocol**: Structured message passing between agents\n", "- **Result Aggregation**: Combining outputs from multiple agent perspectives\n", "\n", "### Event-Driven Coordination\n", "- **WorkflowEvent**: Trigger points for agent activation and handoffs\n", "- **OutputEvent**: Structured data exchange between agents\n", "- **Quality Gates**: Validation checkpoints in the workflow process\n", "- **Feedback Loops**: Iterative refinement through agent collaboration\n", "\n", "## ⚙️ Prerequisites & Setup\n", "\n", "\n", "**Required Dependencies:**\n", "```bash\n", "\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", "## 🎨 Multi-Agent Design Patterns\n", "\n", "### 1. **Producer-Consumer Pattern**\n", "- Specialized agents generate content for review by others\n", "- Clear handoff points and data exchange protocols\n", "- Quality assurance through independent review\n", "- Iterative refinement and improvement cycles\n", "\n", "### 2. **Committee Pattern**\n", "- Multiple agents contributing different perspectives\n", "- Consensus building through structured discussion\n", "- Democratic decision making with weighted opinions\n", "- Conflict resolution and tie-breaking mechanisms\n", "\n", "### 3. **Hierarchical Pattern**\n", "- Lead agents coordinating specialist subordinates \n", "- Clear authority structures and decision flow\n", "- Escalation paths for complex decisions\n", "- Performance monitoring and quality control\n", "\n", "### 4. **Pipeline Pattern**\n", "- Sequential processing with specialized stages\n", "- Each agent adds value in their domain of expertise\n", "- Efficient throughput through parallel processing\n", "- Error handling and recovery at each stage\n", "\n", "## 🚀 Advanced Multi-Agent Features\n", "\n", "### Workflow Orchestration\n", "- **Dynamic Routing**: Context-based agent selection and routing\n", "- **Parallel Processing**: Concurrent agent execution for efficiency\n", "- **Error Recovery**: Graceful handling of agent failures and retries\n", "- **Performance Monitoring**: Tracking workflow execution and optimization\n", "\n", "### Agent Communication\n", "- **Structured Messaging**: Type-safe communication protocols\n", "- **Context Preservation**: Maintaining conversation history across agents\n", "- **Metadata Passing**: Rich information exchange beyond text content\n", "- **Event Broadcasting**: Publish-subscribe patterns for coordination\n", "\n", "### Quality Assurance\n", "- **Multi-Perspective Review**: Different agents bringing unique viewpoints\n", "- **Iterative Refinement**: Progressive improvement through collaboration\n", "- **Validation Checkpoints**: Quality gates throughout the workflow\n", "- **Performance Metrics**: Measuring collaboration effectiveness\n", "\n", "## 📊 Use Cases & Applications\n", "\n", "### Business Process Automation\n", "- Document review and approval workflows\n", "- Customer service escalation systems\n", "- Quality assurance and compliance checking\n", "- Multi-stage content creation and editing\n", "\n", "### Research & Analysis\n", "- Peer review systems for research papers\n", "- Multi-analyst financial analysis\n", "- Collaborative report writing and fact-checking\n", "- Academic paper review and improvement\n", "\n", "### Creative Collaboration\n", "- Content creation with editors and reviewers\n", "- Multi-perspective creative brainstorming\n", "- Iterative design and feedback systems\n", "- Collaborative storytelling and world-building\n", "\n", "Ready to orchestrate intelligent multi-agent collaborations? Let's build systems where agents work together like a high-performing team! 🌟🤖" ] }, { "cell_type": "code", "execution_count": 1, "id": "9b42777d", "metadata": {}, "outputs": [], "source": [ "# ! pip install -r ../../../Installation/requirements.txt -U" ] }, { "cell_type": "code", "execution_count": 2, "id": "604f5e98", "metadata": { "language_info": { "name": "polyglot-notebook" }, "polyglot_notebook": { "kernelName": "csharp" } }, "outputs": [], "source": [ "# 🤖 Import Multi-Agent Workflow Components\n", "# OpenAIChatClient: GitHub Models integration for agent communication\n", "# WorkflowEvent, WorkflowBuilder: Core workflow orchestration classes\n", "# WorkflowOutputEvent: Structured event handling for agent coordination\n", "from agent_framework.openai import OpenAIChatCompletionClient\n", "from agent_framework import AgentResponse, WorkflowBuilder" ] }, { "cell_type": "code", "execution_count": 3, "id": "a7bbeb9f", "metadata": { "language_info": { "name": "polyglot-notebook" }, "polyglot_notebook": { "kernelName": "csharp" } }, "outputs": [], "source": [ "# 📦 Import Configuration and Environment Management\n", "import os # Environment variable access for secure configuration\n", "from typing import cast\n", "from dotenv import load_dotenv # Secure loading of API credentials and settings" ] }, { "cell_type": "markdown", "id": "64d8601b", "metadata": {}, "source": [ "## 📦 Import Environment Configuration\n", "\n", "Load secure configuration management for GitHub Models credentials." ] }, { "cell_type": "code", "execution_count": 4, "id": "a35f9a38", "metadata": { "language_info": { "name": "polyglot-notebook" }, "polyglot_notebook": { "kernelName": "csharp" } }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 🔧 Load Multi-Agent Workflow Configuration \n", "# Load environment variables for secure GitHub Models access\n", "# Required: GITHUB_ENDPOINT, GITHUB_TOKEN, GITHUB_MODEL_ID for agent communication\n", "load_dotenv()" ] }, { "cell_type": "markdown", "id": "eaa8d183", "metadata": {}, "source": [ "## 🔧 Load Environment Variables\n", "\n", "Initialize the environment configuration from the `.env` file." ] }, { "cell_type": "code", "execution_count": 5, "id": "763a7e8d", "metadata": { "language_info": { "name": "polyglot-notebook" }, "polyglot_notebook": { "kernelName": "csharp" } }, "outputs": [], "source": [ "# 🔗 Initialize Shared Chat Client for Multi-Agent Communication\n", "# Create a unified client that all agents in the workflow will use\n", "# This ensures consistent API access and efficient resource utilization\n", "chat_client = OpenAIChatCompletionClient(\n", " base_url=os.environ.get(\"GITHUB_ENDPOINT\"), # GitHub Models API endpoint\n", " api_key=os.environ.get(\"GITHUB_TOKEN\"), # Authentication token\n", " model=os.environ.get(\"GITHUB_MODEL_ID\") # Model for all agents in workflow\n", ")" ] }, { "cell_type": "markdown", "id": "bdecda11", "metadata": {}, "source": [ "## 🔗 Initialize Shared Chat Client\n", "\n", "Create a unified chat client that all agents in the workflow will share for efficient resource utilization." ] }, { "cell_type": "code", "execution_count": 6, "id": "ed07880b", "metadata": { "language_info": { "name": "polyglot-notebook" }, "polyglot_notebook": { "kernelName": "csharp" } }, "outputs": [], "source": [ "# 🎩 Agent 1: Hotel Concierge - Quality Reviewer Role\n", "# This agent specializes in evaluating travel recommendations for authenticity\n", "# Acts as the second stage in our multi-agent workflow for quality assurance\n", "REVIEWER_NAME = \"Concierge\"\n", "REVIEWER_INSTRUCTIONS = \"\"\"\n", " You are an experienced hotel concierge who has strong opinions about providing the most local and authentic experiences for travelers.\n", " \n", " Your role in this multi-agent workflow:\n", " - Review travel recommendations from the Front Desk agent\n", " - Assess whether suggestions provide authentic, non-touristy experiences\n", " - Approve recommendations that meet high standards for local authenticity\n", " - Provide constructive feedback for refinement without giving specific examples\n", " \n", " Always focus on the quality and authenticity of experiences rather than just popular tourist destinations.\n", " \"\"\"" ] }, { "cell_type": "markdown", "id": "00fffb69", "metadata": {}, "source": [ "## 🎩 Define Concierge Agent (Quality Reviewer)\n", "\n", "Configure the Concierge agent who specializes in evaluating travel recommendations for local authenticity and non-touristy experiences." ] }, { "cell_type": "code", "execution_count": 7, "id": "16ed7969", "metadata": { "language_info": { "name": "polyglot-notebook" }, "polyglot_notebook": { "kernelName": "csharp" } }, "outputs": [], "source": [ "FRONTDESK_NAME = \"FrontDesk\"\n", "FRONTDESK_INSTRUCTIONS = \"\"\"\n", " You are a Front Desk Travel Agent with ten years of experience and are known for brevity as you deal with many customers.\n", " The goal is to provide the best activities and locations for a traveler to visit.\n", " Only provide a single recommendation per response.\n", " You're laser focused on the goal at hand.\n", " Don't waste time with chit chat.\n", " Consider suggestions when refining an idea.\n", " \"\"\"" ] }, { "cell_type": "markdown", "id": "2f945e51", "metadata": {}, "source": [ "## 🏨 Define Front Desk Agent (Travel Specialist)\n", "\n", "Configure the Front Desk agent who provides expert travel recommendations with efficient, concise communication." ] }, { "cell_type": "code", "execution_count": 8, "id": "558221d3", "metadata": { "language_info": { "name": "polyglot-notebook" }, "polyglot_notebook": { "kernelName": "csharp" } }, "outputs": [], "source": [ "writer_agent = chat_client.as_agent(\n", " instructions=(\n", " REVIEWER_INSTRUCTIONS\n", " ),\n", " name=REVIEWER_NAME,\n", " )\n", "\n", "agent_reviewer = chat_client.as_agent(\n", " instructions=(\n", " FRONTDESK_INSTRUCTIONS\n", " ),\n", " name=FRONTDESK_NAME,\n", " )" ] }, { "cell_type": "markdown", "id": "c87382be", "metadata": {}, "source": [ "## 🤖 Create Agent Instances\n", "\n", "Instantiate both specialized agents with their configured instructions and personalities." ] }, { "cell_type": "code", "execution_count": 9, "id": "5de16a9c", "metadata": { "language_info": { "name": "polyglot-notebook" }, "polyglot_notebook": { "kernelName": "csharp" } }, "outputs": [], "source": [ "workflow = WorkflowBuilder(start_executor=writer_agent).add_edge(writer_agent, agent_reviewer).build()" ] }, { "cell_type": "markdown", "id": "9c0d9d9c", "metadata": {}, "source": [ "## 🔄 Build the Multi-Agent Workflow\n", "\n", "Create the workflow pipeline using `WorkflowBuilder`:\n", "1. **Start**: Concierge agent provides initial recommendation\n", "2. **Edge**: Front Desk agent reviews and refines the suggestion\n", "\n", "This creates a sequential workflow where each agent builds upon the previous one's output." ] }, { "cell_type": "code", "execution_count": 10, "id": "99988262", "metadata": {}, "outputs": [], "source": [ "\n", "# class DatabaseEvent(WorkflowEvent): ..." ] }, { "cell_type": "code", "execution_count": 11, "id": "dfbb0efa", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Concierge: That's wonderful! Paris offers many layers beyond the well-trodden sights. To ensure you have an authentically Parisian experience, could you share a bit about your interests? For example, are you drawn to art, cuisine, history, local neighborhoods, or perhaps unique cultural events? This will help tailor recommendations that truly immerse you in the local flavor.\n", "\n", "FrontDesk: Visit the Louvre Museum early in the morning to enjoy world-famous art with fewer crowds.\n", "\n", "Final state: WorkflowRunState.IDLE\n" ] } ], "source": [ "events = await workflow.run(\"I would like to go to Paris.\")\n", "\n", "outputs = events.get_outputs()\n", " # The outputs of the workflow are whatever the agents produce. So the outputs are expected to be a list\n", " # of `AgentResponse` from the agents in the workflow.\n", "outputs = cast(list[AgentResponse], outputs)\n", "for output in outputs:\n", " print(f\"{output.messages[0].author_name}: {output.text}\\n\")\n", "\n", " # Summarize the final run state (e.g., COMPLETED)\n", "print(\"Final state:\", events.get_final_state())\n" ] }, { "cell_type": "markdown", "id": "d72f84ce", "metadata": {}, "source": [ "## 🚀 Execute the Multi-Agent Workflow\n", "\n", "Run the workflow with a travel request. The agents will collaborate:\n", "1. First agent provides initial travel suggestion\n", "2. Second agent reviews and potentially refines the recommendation\n", "3. Results stream back showing each agent's contribution" ] } ], "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" }, "polyglot_notebook": { "kernelInfo": { "defaultKernelName": "csharp", "items": [ { "aliases": [], "name": "csharp" } ] } } }, "nbformat": 4, "nbformat_minor": 5 }