OpenAIAgentsSDK/multi_agent.ipynb (351 lines of code) (raw):

{ "cells": [ { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [], "source": [ "import os\n", "import asyncio\n", "from openai import AsyncAzureOpenAI\n", "from openai import OpenAIError\n", "from agents import Agent, Runner, OpenAIChatCompletionsModel, set_tracing_disabled, function_tool\n", "\n", "from azure.identity import DefaultAzureCredential, get_bearer_token_provider\n", "\n", "token_provider = get_bearer_token_provider(\n", " DefaultAzureCredential(), \"https://cognitiveservices.azure.com/.default\"\n", ")\n", "\n", "client = AsyncAzureOpenAI(\n", " api_version=\"2024-08-01-preview\",\n", " azure_endpoint=\"https://aihub6750316290.openai.azure.com/\",\n", " azure_ad_token_provider=token_provider, # Use DefaultAzureCredential for authentication\n", "\n", " )\n", "deployment = \"gpt-4o\"\n", "model = OpenAIChatCompletionsModel(\n", " model=deployment,\n", " openai_client=client,\n", " )" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [], "source": [ "from typing import List\n", "from pydantic import BaseModel\n", "from autogen_core.models import (\n", " AssistantMessage,\n", " ChatCompletionClient,\n", " LLMMessage,\n", " SystemMessage,\n", " UserMessage,\n", " FunctionExecutionResult\n", ")\n", "from typing import List, Literal, Optional, Union\n", "\n", "class GroupChatMessage(BaseModel):\n", " body: LLMMessage\n", " conversation_id: str\n", "\n", "class TransactionInfo(BaseModel):\n", " body: List[LLMMessage]\n", " conversation_id: str\n", " class Config:\n", " @staticmethod\n", " def schema_extra(schema: dict, model_class: type) -> None:\n", " # Remove defaults\n", " if \"properties\" in schema:\n", " for prop in schema[\"properties\"].values():\n", " prop.pop(\"default\", None)\n", " \n", "\n", "class AccountInfo(BaseModel):\n", " body: List[LLMMessage]\n", " conversation_id: str\n", " class Config:\n", " @staticmethod\n", " def schema_extra(schema: dict, model_class: type) -> None:\n", " # Remove defaults\n", " if \"properties\" in schema:\n", " for prop in schema[\"properties\"].values():\n", " prop.pop(\"default\", None)\n", "\n", "\n", "class NeedMoreInfo(BaseModel):\n", " body: List[LLMMessage]\n", " conversation_id: str\n", "\n", "\n", "\n", "class IntermediateResult(BaseModel):\n", " body: List[LLMMessage]\n", " conversation_id: str \n", "\n", "TransactionAccountInfo = Union[TransactionInfo, AccountInfo, NeedMoreInfo, IntermediateResult]\n", "\n", "FinalResponderAgentMessage = Union[IntermediateResult, NeedMoreInfo]\n", "\n", "class GroupChatMessages(BaseModel):\n", " body: List[LLMMessage]\n", " conversation_id: str" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "sample_data_path = os.path.join(\".\", \"sample_data\")\n", "@function_tool\n", "def get_account_info(account_id: str) -> str:\n", " \"\"\"Get account information for the given account ID.\"\"\"\n", " try:\n", " account_data_file = os.path.join(sample_data_path, f\"{account_id}.json\")\n", " with open(account_data_file, \"r\") as file:\n", " data = file.read()\n", " return data\n", " except FileNotFoundError:\n", " return \"Account not found.\"\n", "\n", "@function_tool\n", "def get_transaction_details(account_id: str) -> str:\n", " \"\"\"Get transaction details for the given account ID.\"\"\"\n", " try:\n", " txn_data_file = os.path.join(sample_data_path, f\"Txn_{account_id}.json\")\n", " with open(txn_data_file, \"r\") as file:\n", " data = file.read()\n", " return data\n", " except FileNotFoundError:\n", " return \"Transaction details not found.\"" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [], "source": [ "from agents import Agent, handoff, RunContextWrapper\n", "\n", "get_account_info_agent = Agent(name=\"GetAccountInfoAgent\",\n", " instructions=\"\"\"You are Transify Support Agent. Transify is an online payment platform.\n", " You can provide information about the account details. \n", " You need to know the 'account number' to provide the account details.\n", " If the 'account number' is provided use the get_account_info tool to get the account details.\n", " Format the response with 'Account Details:'.\n", " If the 'account number' is not provided, ask the user to provide the 'account number'. \n", " If the account number is already provided, don't ask for it again.\n", " Summarize and format your response in a clear and concise manner. \n", " Do not provide unnecessary information.\n", "\n", " Response Format as table:\n", " Account Balance: date | Balance Amount | account id\n", " \"\"\",\n", " tools=[get_account_info],\n", " model=model,\n", " #output_type=AccountInfo\n", " )\n", "\n", "\n", "get_transaction_info_agent = Agent(name=\"GetTransactionDetailsAgent\",\n", " instructions=\"\"\"You are Transify Support Agent. Transify is an online payment platform.\n", " You can provide information about the transaction details for the account.\n", " You need to know the 'account number' to provide the transaction details.\n", " If the 'account number' is provided use the get_transaction_details tool to get the transaction details.\n", " Format the response with 'Transaction Details:'.\n", " If the 'account number' is not provided, ask the user to provide the 'account number'. \n", " If the account number is already provided, don't ask for it again. \n", " Summarize and format your response in a clear and concise manner.\n", " Do not provide eunecessary information. \n", "\n", " Response Format as table:\n", " Transaction: date | amount | description | transaction id\n", " \"\"\",\n", " tools=[get_transaction_details],\n", " model=model,\n", " #output_type=TransactionInfo\n", " )" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [ "triage_agent = Agent(\n", " name=\"Triage agent\",\n", " instructions=(\n", " \"\"\"\n", " You are a Transify Support Agent Manager. Transify is an online payment platform.\n", " You can help users with their Transify related queries. \n", " You need to respond only to queries related to Transify and nothing else. \n", " If the question is not related to Transify, state that you only respond to Transify related queries and cannot answer this question. \n", " If this is Transify related question. you need to find the appropriate agent based on the question as below:\n", " Agent Types:\n", " \n", " 1. AccountInfo: If the question is about account details.\n", " 2. TransactionInfo: If the question is about transaction details.\n", " \"\"\"\n", " ),\n", " model=model,\n", " handoffs=[get_account_info_agent, get_transaction_info_agent],\n", ")" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Could you please provide your account number so I can retrieve your latest transaction details?\n" ] } ], "source": [ "result = await Runner.run(triage_agent, \"I want to know my latest transaction details. \")\n", "print(result.final_output)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "It seems no transaction details are found for account number **1255**. Please ensure the account number is correct or let me know if you need further assistance.\n" ] } ], "source": [ "user_follow_input = result.to_input_list() + [{\"role\": \"user\", \"content\": \"My account number is 1255.\"}]\n", "result = await Runner.run(triage_agent, user_follow_input)\n", "print(result.final_output)" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "### Transaction Details:\n", "\n", "| Transaction | Date | Amount | Description | Transaction ID |\n", "|-------------------|---------------------|----------|--------------------------------------------|-----------------------|\n", "| Latest Transaction| 29th September 2024 | $75.00 | Watercolor Paint Set & Brush Set | 9HX25435AB0123456 |\n", "\n", "Let me know if you need further details!\n" ] } ], "source": [ "user_follow_input = result.to_input_list() + [{\"role\": \"user\", \"content\": \"My account number is A1234567890.\"}]\n", "result = await Runner.run(triage_agent, user_follow_input)\n", "print(result.final_output)" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "**Transaction Details:**\n", "\n", "| Transaction | Date | Amount | Description | Transaction ID |\n", "|--------------------------|----------------------|---------|----------------------|---------------------|\n", "| Latest Transaction | 2024-09-29 | $75.00 | Watercolor Paint Set + Brush Set | 9HX25435AB0123456 |\n", "\n", "\n" ] } ], "source": [ "result = await Runner.run(triage_agent, \"I want to know my latest transaction details. My account number is A1234567890.\")\n", "print(result.final_output)" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "**Account Details:**\n", "\n", "| **Account Balance:** | Date | Balance Amount | Account ID |\n", "|-----------------------------|---------------------|----------------|----------------|\n", "| | 2024-10-09T10:20:15 | $150.00 | A1234567890 |\n" ] } ], "source": [ "result = await Runner.run(triage_agent, \"My account number is A1234567890.\")\n", "print(result.final_output)" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I only respond to Transify related queries and cannot answer this question. If you have any inquiries related to Transify, feel free to ask!\n" ] } ], "source": [ "result = await Runner.run(triage_agent, \"Plan a 3 day road trip to zion national park.\")\n", "print(result.final_output)" ] } ], "metadata": { "kernelspec": { "display_name": "venv", "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.11.5" } }, "nbformat": 4, "nbformat_minor": 2 }