Files
microsoft--ai-agents-for-be…/02-explore-agentic-frameworks/code_samples/02-python-agent-framework-azure-openai.ipynb
T
2026-07-13 12:59:43 +08:00

213 lines
6.9 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Microsoft Agent Framework — Azure OpenAI (Responses API)\n",
"\n",
"In this code sample, you will use the **Microsoft Agent Framework (MAF)** to create a simple agent backed by **Azure OpenAI** using the **Responses API**.\n",
"\n",
"> **Migration note:** This sample previously used Semantic Kernel with GitHub Models. It has been migrated to the Microsoft Agent Framework, and GitHub Models (deprecated, retiring July 2026) has been replaced with Azure OpenAI, which supports the Responses API. The `OpenAIChatClient` in MAF targets Azure OpenAI's stable `/openai/v1/` endpoint and uses the Responses API by default.\n",
"\n",
"The purpose of this sample is to demonstrate the steps that will later be applied in additional code samples when implementing various agentic patterns.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"%pip install agent-framework agent-framework-openai azure-identity -q\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Import the Needed Python Packages\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import random\n",
"\n",
"from dotenv import load_dotenv\n",
"from IPython.display import display, HTML\n",
"\n",
"from agent_framework import tool\n",
"from agent_framework.openai import OpenAIChatClient\n",
"from azure.identity import AzureCliCredential\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Defining a Tool\n",
"\n",
"In the Microsoft Agent Framework, a **tool** is a plain Python function decorated with `@tool` that the agent can call. Below we define a tool that returns a random vacation destination and avoids repeating the previous one.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# A list of vacation destinations the tool can choose from.\n",
"_DESTINATIONS = [\n",
" \"Barcelona, Spain\",\n",
" \"Paris, France\",\n",
" \"Berlin, Germany\",\n",
" \"Tokyo, Japan\",\n",
" \"Sydney, Australia\",\n",
" \"New York, USA\",\n",
" \"Cairo, Egypt\",\n",
" \"Cape Town, South Africa\",\n",
" \"Rio de Janeiro, Brazil\",\n",
" \"Bali, Indonesia\",\n",
"]\n",
"\n",
"# Track the last destination so repeated calls avoid immediate repeats.\n",
"_last_destination: str | None = None\n",
"\n",
"\n",
"@tool(approval_mode=\"never_require\")\n",
"def get_random_destination() -> str:\n",
" \"\"\"Provides a random vacation destination.\"\"\"\n",
" global _last_destination\n",
" available = _DESTINATIONS.copy()\n",
" if _last_destination and len(available) > 1:\n",
" available.remove(_last_destination)\n",
" destination = random.choice(available)\n",
" _last_destination = destination\n",
" return destination\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"load_dotenv()\n",
"\n",
"endpoint = os.environ[\"AZURE_OPENAI_ENDPOINT\"]\n",
"deployment = os.environ.get(\"AZURE_OPENAI_DEPLOYMENT\", \"gpt-4o-mini\")\n",
"\n",
"# OpenAIChatClient targets Azure OpenAI's v1 endpoint and uses the Responses API.\n",
"# Sign in with `az login` first so AzureCliCredential can authenticate.\n",
"chat_client = OpenAIChatClient(\n",
" model=deployment,\n",
" azure_endpoint=endpoint,\n",
" credential=AzureCliCredential(),\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Creating the Agent\n",
"\n",
"Here, we create the Agent named `TravelAgent`.\n",
"\n",
"In this example, we use very basic instructions. Feel free to modify these instructions to observe how the agent's behavior changes.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"agent = chat_client.as_agent(\n",
" name=\"TravelAgent\",\n",
" instructions=\"You are a helpful AI Agent that can help plan vacations for customers at random destinations\",\n",
" tools=[get_random_destination],\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Running the Agent\n",
"\n",
"Now we can run the agent. We create an `AgentSession` so the agent remembers the conversation across turns, then send two `user_inputs`. The first asks for a trip; the second says the user didn't like the suggestion and asks for another — the agent uses the session history plus the `get_random_destination` tool to respond.\n",
"\n",
"You can modify these messages to observe how the agent reacts differently. Responses are **streamed** token-by-token.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"user_inputs = [\n",
" \"Plan me a day trip.\",\n",
" \"I don't like that destination. Plan me another vacation.\",\n",
"]\n",
"\n",
"\n",
"async def main():\n",
" # A session keeps conversation history across turns.\n",
" session = agent.create_session()\n",
"\n",
" for user_input in user_inputs:\n",
" html_output = (\n",
" f\"<div style='margin-bottom:10px'>\"\n",
" f\"<div style='font-weight:bold'>User:</div>\"\n",
" f\"<div style='margin-left:20px'>{user_input}</div></div>\"\n",
" )\n",
"\n",
" full_response: list[str] = []\n",
" # Stream the agent's response token-by-token. The agent will call the\n",
" # get_random_destination tool automatically when it needs a destination.\n",
" async for chunk in agent.run(user_input, session=session, stream=True):\n",
" full_response.append(str(chunk))\n",
"\n",
" html_output += (\n",
" \"<div style='margin-bottom:20px'>\"\n",
" f\"<div style='font-weight:bold'>TravelAgent:</div>\"\n",
" f\"<div style='margin-left:20px; white-space:pre-wrap'>{''.join(full_response)}</div></div><hr>\"\n",
" )\n",
"\n",
" display(HTML(html_output))\n",
"\n",
"\n",
"await main()\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}