├── .devcontainer
├── Dockerfile
└── devcontainer.json
├── .env.example
├── .gitignore
├── CODE_OF_CONDUCT.md
├── LICENSE
├── README.md
├── SECURITY.md
├── SUPPORT.md
├── requirements.txt
└── session-delivery-resources
├── README.md
├── demo-1
└── demo-1-codeintrepreter.ipynb
├── demo-2
├── __pycache__
│ └── user_functions.cpython-311.pyc
├── demo-2-functioncalling.ipynb
└── user_functions.py
└── requirements.txt
/.devcontainer/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM mcr.microsoft.com/devcontainers/python:3.11-bullseye
2 |
3 | # Install pip for Python 3.11
4 | RUN python -m pip install --upgrade pip
5 |
6 | # Copy requirements.txt and install the packages
7 | COPY requirements.txt .
8 | RUN pip install -r requirements.txt
9 |
--------------------------------------------------------------------------------
/.devcontainer/devcontainer.json:
--------------------------------------------------------------------------------
1 | // README at: https://github.com/devcontainers/templates/tree/main/src/python
2 | {
3 | "name": "Python 3.11",
4 | "build": {
5 | "dockerfile": "Dockerfile",
6 | "context": ".."
7 | },
8 | "features": {
9 | "ghcr.io/devcontainers/features/azure-cli:1": {
10 | "extensions": "ml"
11 | }
12 | },
13 | "customizations": {
14 | "vscode": {
15 | "extensions": [
16 | "ms-azuretools.vscode-docker",
17 | "ms-python.python",
18 | "ms-toolsai.jupyter",
19 | "ms-python.black-formatter"
20 | ]
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/.env.example:
--------------------------------------------------------------------------------
1 | PROJECT_CONNECTION_STRING=""
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .env
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Microsoft Open Source Code of Conduct
2 |
3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
4 |
5 | Resources:
6 |
7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Microsoft Corporation.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Getting Started with AI Agents
2 | [](https://discord.com/invite/ByRwuEEgH4?WT.mc_id=academic-105485-koreyst)
4 |
5 | This repo is a companion to this session at Microsoft AI Tour, a worldwide tour of events.
6 |
7 | > Learn more about Microsoft AI Tour on the official website.
8 |
9 | ## Session Description
10 |
11 | Explore the fascinating world of AI agents with Azure! Dive into the innovative Azure AI Agent Service, where you’ll discover how these intelligent agents can transform processes and products. Learn about the diverse use cases, from automating customer support to enhancing decision-making processes. Understand why AI agents are essential for modern businesses, offering efficiency, scalability, and advanced problem-solving capabilities.
12 |
13 |
14 | ## Learning Outcomes
15 | 1. Gain a fundamental understanding of what AI agents are and how they function.
16 |
17 | 2. Discover various use cases for AI agents across different industries.
18 |
19 | 3. Learn about the features and capabilities of the Azure AI Agent Service.
20 |
21 | 4. Understand how to implement AI agents using the Azure AI Agent Service in your projects.
22 |
23 | ## Technology Used
24 | 1. Azure OpenAI Service
25 |
26 | 2. Azure AI Foundry
27 |
28 | 3. Azure AI Agent Service
29 |
30 | ## Additional Resources and Continued Learning
31 |
32 | | Resources | Links | Description |
33 | |:-------------------|:----------------------------------|:-------------------|
34 | | AI Foundry | [AI Foundry](https://ai.azure.com/) | Azure AI Foundry is a platform for building, evaluating, and deploying generative AI solutions and custom copilots. |
35 | | AI Agent Service | [AI Agent Service](https://learn.microsoft.com/en-us/azure/ai-services/agents/) | Azure AI Agent Service is a fully managed service designed to empower developers to securely build, deploy, and scale high-quality, and extensible AI agents without needing to manage the underlying compute and storage resources |
36 | | Semantic Kernel Agent Framework | [Semantic Kernel Agent Framework](https://learn.microsoft.com/en-us/semantic-kernel/frameworks/agent/?pivots=programming-language-csharp) | The Semantic Kernel Agent Framework provides a platform within the Semantic Kernel eco-system that allow for the creation of AI agents and the ability to incorporate agentic patterns into any application based on the same patterns and features that exist in the core Semantic Kernel framework. |
37 | | AutoGen Agent Framework | [AutoGen Agent Framework](https://microsoft.github.io/autogen/stable/) | AutoGen core offers an easy way to quickly build event-driven, distributed, scalable, resilient AI agent systems. Agents are developed by using the Actor model. |
38 |
39 | ## Content Owners
40 |
41 |
42 |
43 |
51 |
52 |
53 |
54 | ## Responsible AI
55 |
56 | Microsoft is committed to helping our customers use our AI products responsibly, sharing our learnings, and building trust-based partnerships through tools like Transparency Notes and Impact Assessments. Many of these resources can be found at [https://aka.ms/RAI](https://aka.ms/RAI).
57 | Microsoft’s approach to responsible AI is grounded in our AI principles of fairness, reliability and safety, privacy and security, inclusiveness, transparency, and accountability.
58 |
59 | Large-scale natural language, image, and speech models - like the ones used in this sample - can potentially behave in ways that are unfair, unreliable, or offensive, in turn causing harms. Please consult the [Azure OpenAI service Transparency note](https://learn.microsoft.com/legal/cognitive-services/openai/transparency-note?tabs=text) to be informed about risks and limitations.
60 |
61 | The recommended approach to mitigating these risks is to include a safety system in your architecture that can detect and prevent harmful behavior. [Azure AI Content Safety](https://learn.microsoft.com/azure/ai-services/content-safety/overview) provides an independent layer of protection, able to detect harmful user-generated and AI-generated content in applications and services. Azure AI Content Safety includes text and image APIs that allow you to detect material that is harmful. Within Azure AI Foundry, the Content Safety service allows you to view, explore and try out sample code for detecting harmful content across different modalities. The following [quickstart documentation](https://learn.microsoft.com/azure/ai-services/content-safety/quickstart-text?tabs=visual-studio%2Clinux&pivots=programming-language-rest) guides you through making requests to the service.
62 |
63 | Another aspect to take into account is the overall application performance. With multi-modal and multi-models applications, we consider performance to mean that the system performs as you and your users expect, including not generating harmful outputs. It's important to assess the performance of your overall application using [Performance and Quality and Risk and Safety evaluators](https://learn.microsoft.com/azure/ai-studio/concepts/evaluation-metrics-built-in). You also have the ability to create and evaluate with [custom evaluators](https://learn.microsoft.com/azure/ai-studio/how-to/develop/evaluate-sdk#custom-evaluators).
64 |
65 | You can evaluate your AI application in your development environment using the Azure AI Evaluation SDK. Given either a test dataset or a target, your generative AI application generations are quantitatively measured with built-in evaluators or custom evaluators of your choice. To get started with the azure ai evaluation sdk to evaluate your system, you can follow the [quickstart guide](https://learn.microsoft.com/azure/ai-studio/how-to/develop/flow-evaluate-sdk). Once you execute an evaluation run, you can [visualize the results in Azure AI Foundry](https://learn.microsoft.com/azure/ai-studio/how-to/evaluate-flow-results).
66 |
67 |
68 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | ## Security
4 |
5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet) and [Xamarin](https://github.com/xamarin).
6 |
7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/security.md/definition), please report it to us as described below.
8 |
9 | ## Reporting Security Issues
10 |
11 | **Please do not report security vulnerabilities through public GitHub issues.**
12 |
13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report).
14 |
15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/security.md/msrc/pgp).
16 |
17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
18 |
19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
20 |
21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.)
22 | * Full paths of source file(s) related to the manifestation of the issue
23 | * The location of the affected source code (tag/branch/commit or direct URL)
24 | * Any special configuration required to reproduce the issue
25 | * Step-by-step instructions to reproduce the issue
26 | * Proof-of-concept or exploit code (if possible)
27 | * Impact of the issue, including how an attacker might exploit the issue
28 |
29 | This information will help us triage your report more quickly.
30 |
31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/security.md/msrc/bounty) page for more details about our active programs.
32 |
33 | ## Preferred Languages
34 |
35 | We prefer all communications to be in English.
36 |
37 | ## Policy
38 |
39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/security.md/cvd).
40 |
41 |
42 |
--------------------------------------------------------------------------------
/SUPPORT.md:
--------------------------------------------------------------------------------
1 | # TODO: The maintainer of this repo has not yet edited this file
2 |
3 | **REPO OWNER**: Do you want Customer Service & Support (CSS) support for this product/project?
4 |
5 | - **No CSS support:** Fill out this template with information about how to file issues and get help.
6 | - **Yes CSS support:** Fill out an intake form at [aka.ms/onboardsupport](https://aka.ms/onboardsupport). CSS will work with/help you to determine next steps.
7 | - **Not sure?** Fill out an intake as though the answer were "Yes". CSS will help you decide.
8 |
9 | *Then remove this first heading from this SUPPORT.MD file before publishing your repo.*
10 |
11 | # Support
12 |
13 | ## How to file issues and get help
14 |
15 | This project uses GitHub Issues to track bugs and feature requests. Please search the existing
16 | issues before filing new issues to avoid duplicates. For new issues, file your bug or
17 | feature request as a new Issue.
18 |
19 | For help and questions about using this project, please **REPO MAINTAINER: INSERT INSTRUCTIONS HERE
20 | FOR HOW TO ENGAGE REPO OWNERS OR COMMUNITY FOR HELP. COULD BE A STACK OVERFLOW TAG OR OTHER
21 | CHANNEL. WHERE WILL YOU HELP PEOPLE?**.
22 |
23 | ## Microsoft Support Policy
24 |
25 | Support for this **PROJECT or PRODUCT** is limited to the resources listed above.
26 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | azure-identity
2 | azure-ai-projects
3 | ipython
4 | jupyter
5 | tabulate
6 | pathlib
7 | typing
8 | datetime
--------------------------------------------------------------------------------
/session-delivery-resources/README.md:
--------------------------------------------------------------------------------
1 | # Session delivery resources
2 |
3 | The following resources are intended for a presenter to learn and deliver the session.
4 |
5 | ## How To Use
6 |
7 | Welcome,
8 |
9 | We're glad you are here and look forward to your delivery of this amazing content. As an experienced presenter, we know you know HOW to present so this guide will focus on WHAT you need to present. It will provide you a full run-through of the presentation created by the presentation design team.
10 |
11 | Along with the video of the presentation, this document will link to all the assets you need to successfully present including PowerPoint slides and demo instructions &
12 | code.
13 |
14 | 1. Read document in its entirety.
15 | 2. Watch the video presentation
16 | 3. Ask questions of the Lead Presenter
17 |
18 | ## File Summary
19 | | Resources | Links | Description |
20 | |-------------------|----------------------------------|-------------------|
21 | | PowerPoint | - [Presentation](https://aka.ms/AAu3mh5) | Slides |
22 | | PPT Recording | - [Presentation](https://aka.ms/AAv5pzs) | Presentation Recording |
23 | | Videos | - [Video](https://aka.ms/AAv5pzh) | |
24 | | Demo 1 -Code Intepreter | - [Demo 1 - Code Intepreter](demo-1/demo-1-codeintrepreter.ipynb) | Code Sample using Code Inrepreter to create Data Visualizations |
25 | | Demo 2 - Function Calling | - [Demo 2 - Code Intepreter](demo-2/demo-2-functioncalling.ipynb) | Code Sample using Function Calling and Custom Defined Functions |
26 | | Session delivery recording | [Microsoft Reactor session](https://www.youtube.com/watch?v=seOJn-1omek)| Session delivery recording|
27 |
28 |
29 | ## Get Started
30 |
31 | This training repository is divided in to the following sections:
32 |
33 | | [Slides](#slides) | [Demos](demos/README.md) | [Deployment](deployment/README.md) |
34 | |-------------------|---------------------------|--------------------------------------
35 | | 30 slides - 30 minutes| 2 demos - 15 minutes | Demo setup
36 |
37 | ## Slides
38 |
39 | The [slides](presentations.md) have presenter notes in each part of the session
40 |
41 | ### Timing
42 |
43 | | Time | Description
44 | --------------|-------------
45 | 0:00 - 10:00 | Understanding Agents
46 | 10:00 - 15:00 | AI Agent Use Cases
47 | 15:00 - 20:00 | Building Agents
48 | 20:00 - 35:00 | Azure AI Agent Service + 2 Demos
49 | 35:00 - 40:00 | Exploring AI Agent Frameworks
50 | 40:00 - 45:00 | Session review - Takeaways
51 |
52 | ## Deployment / Preparation
53 |
54 | >**What's Here?** Deploying the demo environment on Azure - including the prerequisites.
55 |
56 | 1. Follow the manual deployment steps in the [AI Agents Quick Start](https://github.com/Azure/azure-ai-agents) repo and deploy using the **basic-agent-keys.bicep** file to create an Azure AI Project.
57 | 2. At the time of writing the bicep deploys a **gpt-4o-mini** model. If you would like to work with another model supported by the Azure AI Agent service, you need to manually deployfrom the [Azure AI Foundry portal](https://ai.azure.com) into the newly created project.
58 | 3. Follow the instructions to create to [Create an Agent connection string](https://github.com/Azure/azure-ai-agents/blob/main/quickstart.md#create-an-agent)
59 | 5. Set up the .env file variable **PROJECT_CONNECTION_STRING** to the connection string you just created.
60 |
61 |
62 |
63 | ## Demos
64 |
65 | | Demo | Minutes | Video |
66 | -------------------------------------------------------------------------------------------------------|---------|----------------- |
67 | | [1 - Using Code Interpreter with Azure AI Agent Service](demo-1/demo-1-codeintrepreter.ipynb) | 5 | [Coming Soon](https://globaleventcdn.blob.core.windows.net/assets/data/data10/Data10-Demo-NoAudio.mp4) |
68 | | [2 - Using Function Calling with Azure AI Agent Service](demo-1/demo-1-codeintrepreter.ipynb) | 10 | [Coming Soon](https://globaleventcdn.blob.core.windows.net/assets/data/data10/Data10-Demo-NoAudio.mp4) |
69 |
70 |
--------------------------------------------------------------------------------
/session-delivery-resources/demo-1/demo-1-codeintrepreter.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Code Interpreter with Azure AI Agent Service "
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "!pip install -r ../requirements.txt"
17 | ]
18 | },
19 | {
20 | "cell_type": "markdown",
21 | "metadata": {},
22 | "source": [
23 | "## Import Packages "
24 | ]
25 | },
26 | {
27 | "cell_type": "code",
28 | "execution_count": null,
29 | "metadata": {},
30 | "outputs": [],
31 | "source": [
32 | "import os\n",
33 | "from azure.ai.projects import AIProjectClient\n",
34 | "from azure.ai.projects.models import CodeInterpreterTool\n",
35 | "from azure.identity import DefaultAzureCredential\n",
36 | "from typing import Any\n",
37 | "from pathlib import Path\n",
38 | "from pprint import pformat\n",
39 | "from datetime import datetime\n",
40 | "\n",
41 | "from tabulate import tabulate"
42 | ]
43 | },
44 | {
45 | "cell_type": "markdown",
46 | "metadata": {},
47 | "source": [
48 | "## Connecct to AI Foundry Project "
49 | ]
50 | },
51 | {
52 | "cell_type": "code",
53 | "execution_count": null,
54 | "metadata": {},
55 | "outputs": [],
56 | "source": [
57 | "project_client = AIProjectClient.from_connection_string(\n",
58 | " credential=DefaultAzureCredential(), conn_str=os.environ[\"PROJECT_CONNECTION_STRING\"]\n",
59 | ")"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": null,
65 | "metadata": {},
66 | "outputs": [],
67 | "source": [
68 | "with project_client:\n",
69 | " # Create an instance of the CodeInterpreterTool\n",
70 | " code_interpreter = CodeInterpreterTool()\n",
71 | "\n",
72 | " # The CodeInterpreterTool needs to be included in creation of the agent\n",
73 | " agent = project_client.agents.create_agent(\n",
74 | " model=\"gpt-4o-mini\",\n",
75 | " name=\"my-agent\",\n",
76 | " instructions=\"You are helpful agent\",\n",
77 | " tools=code_interpreter.definitions,\n",
78 | " tool_resources=code_interpreter.resources,\n",
79 | " )\n",
80 | " print(f\"Created agent, agent ID: {agent.id}\")\n",
81 | "\n",
82 | " # Create a thread\n",
83 | " thread = project_client.agents.create_thread()\n",
84 | " print(f\"Created thread, thread ID: {thread.id}\")\n",
85 | "\n",
86 | " # Create a message\n",
87 | " message = project_client.agents.create_message(\n",
88 | " thread_id=thread.id,\n",
89 | " role=\"user\",\n",
90 | " content=\"Could you please create a bar chart for the operating profit using the following data and provide the file to me? Company A: $1.2 million, Company B: $2.5 million, Company C: $3.0 million, Company D: $1.8 million\",\n",
91 | " )\n",
92 | " print(f\"Created message, message ID: {message.id}\")\n",
93 | "\n",
94 | " # Run the agent\n",
95 | " run = project_client.agents.create_and_process_run(\n",
96 | " thread_id=thread.id, agent_id=agent.id)\n",
97 | " print(f\"Run finished with status: {run.status}\")\n",
98 | "\n",
99 | " if run.status == \"failed\":\n",
100 | " # Check if you got \"Rate limit is exceeded.\", then you want to get more quota\n",
101 | " print(f\"Run failed: {run.last_error}\")\n",
102 | "\n",
103 | " # Get messages from the thread\n",
104 | " messages = project_client.agents.list_messages(thread_id=thread.id)\n",
105 | " print(\"\\n=== Thread Messages ===\")\n",
106 | " print(pformat(messages.__dict__, indent=2, width=80))\n",
107 | "\n",
108 | " # Get the last message from the sender\n",
109 | " # last_msg = messages.get_last_text_message_by_sender(\"assistant\")\n",
110 | " # if last_msg:\n",
111 | " # print(f\"Last Message: {last_msg.text.value}\")\n",
112 | "\n",
113 | "\n",
114 | "\n",
115 | "\n",
116 | " # Generate an image file for the bar chart\n",
117 | " for image_content in messages.image_contents:\n",
118 | " print(f\"Image File ID: {image_content.image_file.file_id}\")\n",
119 | " file_name = f\"{image_content.image_file.file_id}_image_file.png\"\n",
120 | " project_client.agents.save_file(\n",
121 | " file_id=image_content.image_file.file_id, file_name=file_name)\n",
122 | " print(f\"Saved image file to: {Path.cwd() / file_name}\")\n",
123 | "\n",
124 | " # Print the file path(s) from the messages\n",
125 | " for file_path_annotation in messages.file_path_annotations:\n",
126 | " print(f\"File Paths:\")\n",
127 | " print(f\"Type: {file_path_annotation.type}\")\n",
128 | " print(f\"Text: {file_path_annotation.text}\")\n",
129 | " print(f\"File ID: {file_path_annotation.file_path.file_id}\")\n",
130 | " print(f\"Start Index: {file_path_annotation.start_index}\")\n",
131 | " print(f\"End Index: {file_path_annotation.end_index}\")\n",
132 | " project_client.agents.save_file(\n",
133 | " file_id=file_path_annotation.file_path.file_id, file_name=Path(file_path_annotation.text).name)\n",
134 | "\n",
135 | " # Delete the agent once done\n",
136 | " project_client.agents.delete_agent(agent.id)\n",
137 | " print(\"Deleted agent\")"
138 | ]
139 | }
140 | ],
141 | "metadata": {
142 | "kernelspec": {
143 | "display_name": "recycling",
144 | "language": "python",
145 | "name": "python3"
146 | },
147 | "language_info": {
148 | "codemirror_mode": {
149 | "name": "ipython",
150 | "version": 3
151 | },
152 | "file_extension": ".py",
153 | "mimetype": "text/x-python",
154 | "name": "python",
155 | "nbconvert_exporter": "python",
156 | "pygments_lexer": "ipython3",
157 | "version": "3.10.15"
158 | }
159 | },
160 | "nbformat": 4,
161 | "nbformat_minor": 2
162 | }
163 |
--------------------------------------------------------------------------------
/session-delivery-resources/demo-2/__pycache__/user_functions.cpython-311.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/microsoft/aitour-getting-started-with-ai-agents/340684affcb4ac9ee701ff056ed2a1167e7cdde1/session-delivery-resources/demo-2/__pycache__/user_functions.cpython-311.pyc
--------------------------------------------------------------------------------
/session-delivery-resources/demo-2/demo-2-functioncalling.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "metadata": {},
6 | "source": [
7 | "# Function Calling with the Azure AI Agent Service "
8 | ]
9 | },
10 | {
11 | "cell_type": "code",
12 | "execution_count": null,
13 | "metadata": {},
14 | "outputs": [],
15 | "source": [
16 | "import os\n",
17 | "from azure.ai.projects import AIProjectClient\n",
18 | "from azure.identity import DefaultAzureCredential\n",
19 | "from azure.ai.projects.models import FunctionTool, ToolSet, CodeInterpreterTool\n",
20 | "from user_functions import user_functions\n",
21 | "from pprint import pformat\n",
22 | "\n",
23 | "\n",
24 | "\n",
25 | "project_client = AIProjectClient.from_connection_string(\n",
26 | " credential=DefaultAzureCredential(),\n",
27 | " conn_str=os.environ[\"PROJECT_CONNECTION_STRING\"],\n",
28 | ")"
29 | ]
30 | },
31 | {
32 | "cell_type": "code",
33 | "execution_count": null,
34 | "metadata": {},
35 | "outputs": [],
36 | "source": [
37 | "with project_client:\n",
38 | " # Initialize agent toolset with user functions and code interpreter\n",
39 | " # [START create_agent_toolset]\n",
40 | " functions = FunctionTool(user_functions)\n",
41 | " code_interpreter = CodeInterpreterTool()\n",
42 | "\n",
43 | " toolset = ToolSet()\n",
44 | " toolset.add(functions)\n",
45 | " toolset.add(code_interpreter)\n",
46 | "\n",
47 | " agent = project_client.agents.create_agent(\n",
48 | " model=\"gpt-4o-mini\",\n",
49 | " name=\"my-assistant\",\n",
50 | " instructions=\"You are a helpful assistant\",\n",
51 | " toolset=toolset,\n",
52 | " )\n",
53 | " # [END create_agent_toolset]\n",
54 | " print(f\"Created agent, ID: {agent.id}\")\n",
55 | "\n",
56 | " # Create thread for communication\n",
57 | " thread = project_client.agents.create_thread()\n",
58 | " print(f\"Created thread, ID: {thread.id}\")\n",
59 | "\n",
60 | " # Create message to thread\n",
61 | " message = project_client.agents.create_message(\n",
62 | " thread_id=thread.id,\n",
63 | " role=\"user\",\n",
64 | " content=\"Hello, send an email with the datetime and weather information in New York?\",\n",
65 | " )\n",
66 | " print(f\"Created message, ID: {message.id}\")\n",
67 | "\n",
68 | " # Create and process agent run in thread with tools\n",
69 | " # [START create_and_process_run]\n",
70 | " run = project_client.agents.create_and_process_run(\n",
71 | " thread_id=thread.id, agent_id=agent.id)\n",
72 | " # [END create_and_process_run]\n",
73 | " print(f\"Run finished with status: {run.status}\")\n",
74 | "\n",
75 | " if run.status == \"failed\":\n",
76 | " print(f\"Run failed: {run.last_error}\")\n",
77 | "\n",
78 | " # Delete the assistant when done\n",
79 | " project_client.agents.delete_agent(agent.id)\n",
80 | " print(\"Deleted agent\")\n",
81 | "\n",
82 | " # Fetch and log all messages\n",
83 | " messages = project_client.agents.list_messages(thread_id=thread.id)\n",
84 | " print(\"\\n=== Thread Messages ===\")\n",
85 | " print(pformat(messages.__dict__, indent=2, width=80))"
86 | ]
87 | },
88 | {
89 | "cell_type": "code",
90 | "execution_count": null,
91 | "metadata": {},
92 | "outputs": [],
93 | "source": []
94 | }
95 | ],
96 | "metadata": {
97 | "kernelspec": {
98 | "display_name": "pydev",
99 | "language": "python",
100 | "name": "python3"
101 | },
102 | "language_info": {
103 | "codemirror_mode": {
104 | "name": "ipython",
105 | "version": 3
106 | },
107 | "file_extension": ".py",
108 | "mimetype": "text/x-python",
109 | "name": "python",
110 | "nbconvert_exporter": "python",
111 | "pygments_lexer": "ipython3",
112 | "version": "3.11.8"
113 | }
114 | },
115 | "nbformat": 4,
116 | "nbformat_minor": 2
117 | }
118 |
--------------------------------------------------------------------------------
/session-delivery-resources/demo-2/user_functions.py:
--------------------------------------------------------------------------------
1 | import json
2 | import datetime
3 | from typing import Any, Callable, Set, Dict, List, Optional
4 |
5 | # These are the user-defined functions that can be called by the agent.
6 |
7 |
8 | def fetch_current_datetime(format: Optional[str] = None) -> str:
9 | """
10 | Get the current time as a JSON string, optionally formatted.
11 |
12 | :param format (Optional[str]): The format in which to return the current time. Defaults to None, which uses a standard format.
13 | :return: The current time in JSON format.
14 | :rtype: str
15 | """
16 | current_time = datetime.datetime.now()
17 |
18 | # Use the provided format if available, else use a default format
19 | if format:
20 | time_format = format
21 | else:
22 | time_format = "%Y-%m-%d %H:%M:%S"
23 |
24 | time_json = json.dumps(
25 | {"current_time": current_time.strftime(time_format)})
26 | return time_json
27 |
28 |
29 | def fetch_weather(location: str) -> str:
30 | """
31 | Fetches the weather information for the specified location.
32 |
33 | :param location (str): The location to fetch weather for.
34 | :return: Weather information as a JSON string.
35 | :rtype: str
36 | """
37 | # In a real-world scenario, you'd integrate with a weather API.
38 | # Here, we'll mock the response.
39 | mock_weather_data = {"New York": "Sunny, 25°C",
40 | "London": "Cloudy, 18°C", "Tokyo": "Rainy, 22°C"}
41 | weather = mock_weather_data.get(
42 | location, "Weather data not available for this location.")
43 | weather_json = json.dumps({"weather": weather})
44 | return weather_json
45 |
46 |
47 | def send_email(recipient: str, subject: str, body: str) -> str:
48 | """
49 | Sends an email with the specified subject and body to the recipient.
50 |
51 | :param recipient (str): Email address of the recipient.
52 | :param subject (str): Subject of the email.
53 | :param body (str): Body content of the email.
54 | :return: Confirmation message.
55 | :rtype: str
56 | """
57 | # In a real-world scenario, you'd use an SMTP server or an email service API.
58 | # Here, we'll mock the email sending.
59 | print(f"Sending email to {recipient}...")
60 | print(f"Subject: {subject}")
61 | print(f"Body:\n{body}")
62 |
63 | message_json = json.dumps(
64 | {"message": f"Email successfully sent to {recipient}."})
65 | return message_json
66 |
67 |
68 | def calculate_sum(a: int, b: int) -> str:
69 | """Calculates the sum of two integers.
70 |
71 | :param a (int): First integer.
72 | :rtype: int
73 | :param b (int): Second integer.
74 | :rtype: int
75 |
76 | :return: The sum of the two integers.
77 | :rtype: str
78 | """
79 | result = a + b
80 | return json.dumps({"result": result})
81 |
82 |
83 | def convert_temperature(celsius: float) -> str:
84 | """Converts temperature from Celsius to Fahrenheit.
85 |
86 | :param celsius (float): Temperature in Celsius.
87 | :rtype: float
88 |
89 | :return: Temperature in Fahrenheit.
90 | :rtype: str
91 | """
92 | fahrenheit = (celsius * 9 / 5) + 32
93 | return json.dumps({"fahrenheit": fahrenheit})
94 |
95 |
96 | def toggle_flag(flag: bool) -> str:
97 | """Toggles a boolean flag.
98 |
99 | :param flag (bool): The flag to toggle.
100 | :rtype: bool
101 |
102 | :return: The toggled flag.
103 | :rtype: str
104 | """
105 | toggled = not flag
106 | return json.dumps({"toggled_flag": toggled})
107 |
108 |
109 | def merge_dicts(dict1: Dict[str, Any], dict2: Dict[str, Any]) -> str:
110 | """Merges two dictionaries.
111 |
112 | :param dict1 (Dict[str, Any]): First dictionary.
113 | :rtype: dict
114 | :param dict2 (Dict[str, Any]): Second dictionary.
115 | :rtype: dict
116 |
117 | :return: The merged dictionary.
118 | :rtype: str
119 | """
120 | merged = dict1.copy()
121 | merged.update(dict2)
122 | return json.dumps({"merged_dict": merged})
123 |
124 |
125 | def get_user_info(user_id: int) -> str:
126 | """Retrieves user information based on user ID.
127 |
128 | :param user_id (int): ID of the user.
129 | :rtype: int
130 |
131 | :return: User information as a JSON string.
132 | :rtype: str
133 | """
134 | mock_users = {
135 | 1: {"name": "Alice", "email": "alice@example.com"},
136 | 2: {"name": "Bob", "email": "bob@example.com"},
137 | 3: {"name": "Charlie", "email": "charlie@example.com"},
138 | }
139 | user_info = mock_users.get(user_id, {"error": "User not found."})
140 | return json.dumps({"user_info": user_info})
141 |
142 |
143 | def longest_word_in_sentences(sentences: List[str]) -> str:
144 | """Finds the longest word in each sentence.
145 |
146 | :param sentences (List[str]): A list of sentences.
147 | :return: A JSON string mapping each sentence to its longest word.
148 | :rtype: str
149 | """
150 | if not sentences:
151 | return json.dumps({"error": "The list of sentences is empty"})
152 |
153 | longest_words = {}
154 | for sentence in sentences:
155 | # Split sentence into words
156 | words = sentence.split()
157 | if words:
158 | # Find the longest word
159 | longest_word = max(words, key=len)
160 | longest_words[sentence] = longest_word
161 | else:
162 | longest_words[sentence] = ""
163 |
164 | return json.dumps({"longest_words": longest_words})
165 |
166 |
167 | def process_records(records: List[Dict[str, int]]) -> str:
168 | """
169 | Process a list of records, where each record is a dictionary with string keys and integer values.
170 |
171 | :param records: A list containing dictionaries that map strings to integers.
172 | :return: A list of sums of the integer values in each record.
173 | """
174 | sums = []
175 | for record in records:
176 | # Sum up all the values in each dictionary and append the result to the sums list
177 | total = sum(record.values())
178 | sums.append(total)
179 | return json.dumps({"sums": sums})
180 |
181 |
182 | # Example User Input for Each Function
183 | # 1. Fetch Current DateTime
184 | # User Input: "What is the current date and time?"
185 | # User Input: "What is the current date and time in '%Y-%m-%d %H:%M:%S' format?"
186 |
187 | # 2. Fetch Weather
188 | # User Input: "Can you provide the weather information for New York?"
189 |
190 | # 3. Send Email
191 | # User Input: "Send an email to john.doe@example.com with the subject 'Meeting Reminder' and body 'Don't forget our meeting at 3 PM.'"
192 |
193 | # 4. Calculate Sum
194 | # User Input: "What is the sum of 45 and 55?"
195 |
196 | # 5. Convert Temperature
197 | # User Input: "Convert 25 degrees Celsius to Fahrenheit."
198 |
199 | # 6. Toggle Flag
200 | # User Input: "Toggle the flag True."
201 |
202 | # 7. Merge Dictionaries
203 | # User Input: "Merge these two dictionaries: {'name': 'Alice'} and {'age': 30}."
204 |
205 | # 8. Get User Info
206 | # User Input: "Retrieve user information for user ID 1."
207 |
208 | # 9. Longest Word in Sentences
209 | # User Input: "Find the longest word in each of these sentences: ['The quick brown fox jumps over the lazy dog', 'Python is an amazing programming language', 'Azure AI capabilities are impressive']."
210 |
211 | # 10. Process Records
212 | # User Input: "Process the following records: [{'a': 10, 'b': 20}, {'x': 5, 'y': 15, 'z': 25}, {'m': 30}]."
213 |
214 | # Statically defined user functions for fast reference
215 | user_functions: Set[Callable[..., Any]] = {
216 | fetch_current_datetime,
217 | fetch_weather,
218 | send_email,
219 | calculate_sum,
220 | convert_temperature,
221 | toggle_flag,
222 | merge_dicts,
223 | get_user_info,
224 | longest_word_in_sentences,
225 | process_records,
226 | }
227 |
--------------------------------------------------------------------------------
/session-delivery-resources/requirements.txt:
--------------------------------------------------------------------------------
1 | azure-identity
2 | azure-ai-projects
3 | ipython
4 | jupyter
5 | tabulate
6 | pathlib
7 | typing
8 | datetime
--------------------------------------------------------------------------------