{ "cells": [ { "cell_type": "markdown", "id": "8744544f", "metadata": {}, "source": [ "# ๐Ÿ› ๏ธ Advanced Tool Use with GitHub Models (Python)\n", "\n", "## ๐Ÿ“‹ Learning Objectives\n", "\n", "This notebook demonstrates advanced tool integration patterns using the Microsoft Agent Framework with GitHub Models. You'll learn how to create, manage, and orchestrate multiple tools to build sophisticated agent capabilities.\n", "\n", "**What You'll Master:**\n", "- ๐Ÿ”ง **Multi-Tool Architecture**: Building agents with multiple specialized tools\n", "- ๐ŸŽฏ **Tool Selection Logic**: How agents choose the right tool for each task\n", "- ๐Ÿ“Š **Data Processing Tools**: Creating tools that handle different data types\n", "- ๐Ÿ”— **Tool Composition**: Combining tools for complex workflows\n", "\n", "## ๐ŸŽฏ Key Tool Patterns\n", "\n", "### Tool Design Principles\n", "- **Single Responsibility**: Each tool has a clear, focused purpose\n", "- **Type Safety**: Strong typing for reliable tool execution\n", "- **Error Handling**: Graceful failure and recovery patterns\n", "- **Composability**: Tools that work well together\n", "\n", "### Advanced Tool Features\n", "- **Context Awareness**: Tools that understand conversation context\n", "- **Data Validation**: Input sanitization and output validation\n", "- **Performance Optimization**: efficient tool execution patterns\n", "- **Extensibility**: Easy addition of new tool capabilities\n", "\n", "## ๐Ÿ”ง Technical Architecture\n", "\n", "### Core Components\n", "- **Microsoft Agent Framework**: Python implementation with advanced tool support\n", "- **GitHub Models Integration**: High-performance language model access\n", "- **Tool Registry System**: Organized management of agent capabilities\n", "- **Error Recovery Patterns**: Robust handling of tool execution failures\n", "\n", "### Tool Integration Flow\n", "```python\n", "User Request โ†’ Agent Analysis โ†’ Tool Selection โ†’ Tool Execution โ†’ Response Synthesis\n", "```\n", "\n", "## ๐Ÿ› ๏ธ Tool Categories Demonstrated\n", "\n", "### 1. **Data Generation Tools**\n", "- Random destination generator\n", "- Weather information provider \n", "- Travel cost calculator\n", "- Activity recommendation engine\n", "\n", "### 2. **Processing Tools**\n", "- Text formatting and validation\n", "- Data transformation utilities\n", "- Content analysis functions\n", "- Response enhancement tools\n", "\n", "### 3. **Integration Tools**\n", "- External API connectors\n", "- File system operations\n", "- Database query interfaces\n", "- Web scraping utilities\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", "**Optional APIs:**\n", "- Weather service API key (for weather tools)\n", "- Currency conversion API access\n", "- Travel information service credentials\n", "\n", "## ๐ŸŽจ Design Patterns\n", "\n", "### Tool Factory Pattern\n", "- Centralized tool creation and configuration\n", "- Consistent tool interface design\n", "- Easy tool registration and discovery\n", "\n", "### Command Pattern\n", "- Encapsulated tool execution logic\n", "- Undo/redo functionality for complex operations\n", "- Audit logging for tool usage\n", "\n", "### Observer Pattern\n", "- Tool execution monitoring\n", "- Performance metrics collection\n", "- Error reporting and alerting\n", "\n", "## ๐Ÿš€ Best Practices\n", "\n", "- **Tool Documentation**: Clear descriptions for agent understanding\n", "- **Input Validation**: Robust parameter checking and sanitization\n", "- **Output Formatting**: Consistent, parseable tool responses\n", "- **Error Messages**: Helpful error information for debugging\n", "- **Performance**: Optimized tool execution for responsiveness\n", "\n", "Ready to build agents with powerful tool capabilities? Let's create something amazing! โšก" ] }, { "cell_type": "code", "execution_count": 1, "id": "59c0feeb", "metadata": {}, "outputs": [], "source": [ "# ! pip install -r ../../../Installation/requirements.txt -U" ] }, { "cell_type": "code", "execution_count": 2, "id": "c0df8a52", "metadata": {}, "outputs": [], "source": [ "# ๏ฟฝ Import core dependencies for Agent Framework and tool integration\n", "# This sets up the essential libraries for building intelligent agents with tool capabilities\n", "\n", "import asyncio\n", "import os\n", "import json\n", "\n", "from dotenv import load_dotenv # For loading environment variables securely\n", "from random import randint\n", "\n", "# These are the core components for building tool-enabled agents\n", "from agent_framework import Agent # Main agent class\n", "from agent_framework.openai import OpenAIChatCompletionClient # OpenAI-compatible client" ] }, { "cell_type": "code", "execution_count": 3, "id": "24c10eb0", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "load_dotenv()" ] }, { "cell_type": "code", "execution_count": 4, "id": "151e0314", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "GITHUB_ENDPOINT: https://models.github.ai/inference\n", "GITHUB_TOKEN: ***\n", "GITHUB_MODEL_ID: openai/gpt-4.1-mini\n" ] } ], "source": [ "# ๐Ÿ”‘ Environment variables verification\n", "# Ensure all required GitHub Models credentials are properly configured\n", "print(\"GITHUB_ENDPOINT:\", os.environ.get(\"GITHUB_ENDPOINT\"))\n", "print(\"GITHUB_TOKEN:\", \"***\" if os.environ.get(\"GITHUB_TOKEN\") else \"Not set\")\n", "print(\"GITHUB_MODEL_ID:\", os.environ.get(\"GITHUB_MODEL_ID\"))" ] }, { "cell_type": "markdown", "id": "89029823", "metadata": {}, "source": [ "## ๐Ÿ”‘ Verify Environment Configuration\n", "\n", "Display the loaded configuration to verify GitHub Models credentials are properly set up." ] }, { "cell_type": "code", "execution_count": 5, "id": "a6141584", "metadata": {}, "outputs": [], "source": [ "# ๐Ÿงช Test GitHub Models connectivity\n", "openai_chat_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": "a9a083ff", "metadata": {}, "source": [ "## ๐Ÿงช Test GitHub Models Connectivity\n", "\n", "Verify the connection to GitHub Models API before building the agent." ] }, { "cell_type": "code", "execution_count": 6, "id": "a6507f83", "metadata": {}, "outputs": [], "source": [ "# ๐Ÿ› ๏ธ Define travel planning tools for agent integration\n", "# These functions provide specific capabilities that the agent can invoke dynamically\n", "\n", "def get_random_destination() -> str:\n", " \"\"\"\n", " ๐ŸŽฒ Random destination generator tool\n", " Returns a randomly selected travel destination from curated list\n", " Useful when customers need inspiration for their next vacation\n", " \"\"\"\n", " destinations = [\n", " \"Paris, France\",\n", " \"Tokyo, Japan\", \n", " \"New York City, USA\",\n", " \"London, England\",\n", " \"Rome, Italy\",\n", " \"Sydney, Australia\",\n", " \"Dubai, UAE\",\n", " \"Barcelona, Spain\",\n", " \"Bangkok, Thailand\",\n", " \"Amsterdam, Netherlands\",\n", " \"Istanbul, Turkey\",\n", " \"Prague, Czech Republic\",\n", " \"Santorini, Greece\",\n", " \"Reykjavik, Iceland\",\n", " \"Marrakech, Morocco\",\n", " \"Cape Town, South Africa\",\n", " \"Rio de Janeiro, Brazil\",\n", " \"Bali, Indonesia\"\n", " ]\n", " # ๐ŸŽฏ Return random selection from the curated destination list\n", " return destinations[randint(0, len(destinations) - 1)]" ] }, { "cell_type": "markdown", "id": "c1dc87ad", "metadata": {}, "source": [ "## ๐Ÿ› ๏ธ Define Tool Functions\n", "\n", "Create tool functions that extend the agent's capabilities. Tools allow the agent to perform actions beyond text generation.\n", "\n", "### Random Destination Generator\n", "This tool returns a random vacation destination from a curated list. The agent can invoke this tool when users need travel inspiration." ] }, { "cell_type": "code", "execution_count": 7, "id": "5d4f0568", "metadata": {}, "outputs": [], "source": [ "# ๐Ÿ”— Initialize GitHub Models chat client for agent communication\n", "# Creates the primary interface between the agent and the language model\n", "openai_chat_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": "b779ffef", "metadata": {}, "source": [ "## ๐Ÿ”— Initialize Chat Client for Tool-Enabled Agent\n", "\n", "Create the OpenAI-compatible chat client that will power our tool-enabled agent." ] }, { "cell_type": "code", "execution_count": 8, "id": "751668c5", "metadata": {}, "outputs": [], "source": [ "# ๐Ÿค– Configure travel agent identity and behavioral instructions\n", "# Define the agent's personality, capabilities, and operational guidelines\n", "\n", "AGENT_NAME = \"TravelAgent\"\n", "\n", "AGENT_INSTRUCTIONS = \"\"\"You are a helpful AI Agent that can help plan vacations for customers at random destinations\n", "\"\"\"" ] }, { "cell_type": "markdown", "id": "570cfa00", "metadata": {}, "source": [ "## ๐Ÿค– Configure Agent Identity and Instructions\n", "\n", "Define the agent's name and behavioral guidelines for how it should interact with users." ] }, { "cell_type": "code", "execution_count": 9, "id": "be18ac4f", "metadata": {}, "outputs": [], "source": [ "agent = Agent(\n", " name = AGENT_NAME,\n", " client=openai_chat_client,\n", " instructions=AGENT_INSTRUCTIONS,\n", " tools=[get_random_destination]\n", ")" ] }, { "cell_type": "markdown", "id": "b6b125fc", "metadata": {}, "source": [ "## ๐Ÿญ Create the Tool-Enabled Agent\n", "\n", "Instantiate the ChatAgent with the configured client, instructions, and registered tools.\n", "The agent will automatically decide when to use the `get_random_destination` tool based on user requests." ] }, { "cell_type": "code", "execution_count": 10, "id": "772e9481", "metadata": {}, "outputs": [], "source": [ "session = agent.create_session()" ] }, { "cell_type": "markdown", "id": "43c844c3", "metadata": {}, "source": [ "## ๐Ÿงต Create Conversation Thread\n", "\n", "Initialize a new thread to maintain conversation context and tool execution history." ] }, { "cell_type": "code", "execution_count": 11, "id": "a731b547", "metadata": {}, "outputs": [], "source": [ "response1 = await agent.run(\"Plan me a day trip\",session= session)" ] }, { "cell_type": "markdown", "id": "79e2bd2a", "metadata": {}, "source": [ "## ๐Ÿš€ Execute Agent with Tool Call\n", "\n", "Send a travel planning request to the agent. The agent will:\n", "1. Recognize the need for a destination\n", "2. Call the `get_random_destination` tool\n", "3. Use the returned destination to create an itinerary" ] }, { "cell_type": "code", "execution_count": 12, "id": "7d3fe00a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Travel plan:\n", "I have chosen Istanbul, Turkey as your day trip destination. Here's a suggested itinerary for a day in Istanbul:\n", "\n", "Morning:\n", "- Start your day with a visit to the iconic Hagia Sophia, an architectural marvel with a rich history.\n", "- Walk to the nearby Blue Mosque to admire its stunning blue tiles and grand design.\n", "- Explore the historic Hippodrome area, home to the Obelisk of Theodosius and other ancient monuments.\n", "\n", "Lunch:\n", "- Enjoy a traditional Turkish lunch at a local restaurant, savoring dishes like kebabs, mezes, and baklava.\n", "\n", "Afternoon:\n", "- Visit the Topkapi Palace, the former residence of Ottoman sultans, and explore its opulent rooms and beautiful gardens.\n", "- Take a stroll through the colorful Grand Bazaar, where you can shop for souvenirs, spices, and handmade crafts.\n", "\n", "Evening:\n", "- End your day with a relaxing Bosphorus cruise to see Istanbul's skyline, bridges, and palaces from the water.\n", "- Have dinner at a waterfront restaurant, enjoying fresh seafood and Turkish cuisine.\n", "\n", "Would you like me to help you with booking tickets or finding specific restaurants and transport options in Istanbul?\n" ] } ], "source": [ "\n", "last_message = response1.messages[-1]\n", "text_content = last_message.contents[0].text\n", "print(\"Travel plan:\")\n", "print(text_content)" ] }, { "cell_type": "markdown", "id": "88f99e51", "metadata": {}, "source": [ "## ๐Ÿ“– Display the Generated Travel Plan\n", "\n", "Extract and display the agent's response with the tool-generated travel recommendation." ] } ], "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 }