|
| 1 | +--- |
| 2 | +title: 'How to use Azure AI Agent service with OpenAPI Specified Tools' |
| 3 | +titleSuffix: Azure OpenAI |
| 4 | +description: Learn how to use Azure AI Agents with OpenAPI Specified Tools. |
| 5 | +services: cognitive-services |
| 6 | +manager: nitinme |
| 7 | +ms.service: azure |
| 8 | +ms.topic: how-to |
| 9 | +ms.date: 12/16/2024 |
| 10 | +author: aahill |
| 11 | +ms.author: aahi |
| 12 | +zone_pivot_groups: selection-function-calling |
| 13 | +ms.custom: azure-ai-agents |
| 14 | +--- |
| 15 | +# How to use Azure AI Agent service with OpenAPI Specified Tools |
| 16 | + |
| 17 | +::: zone pivot="overview" |
| 18 | + |
| 19 | +You can now connect your Azure AI Agent to an external API using an OpenAPI 3.0 specified tool, |
| 20 | +allowing for scalable interoperability with various applications. Enable your custom tools |
| 21 | +to authenticate access and connections with managed identities (Microsoft Entra ID) for |
| 22 | +added security, making it ideal for integrating with existing infrastructure or web services. |
| 23 | + |
| 24 | +OpenAPI Specified tool improves your function calling experience by providing standardized, |
| 25 | +automated, and scalable API integrations that enhance the capabilities and efficiency of your agent. |
| 26 | +[OpenAPI specifications](https://spec.openapis.org/oas/latest.html) provide a formal standard for |
| 27 | +describing HTTP APIs. This allows people to understand how an API works, how a sequence of APIs |
| 28 | +work together, generate client code, create tests, apply design standards, and more. |
| 29 | + |
| 30 | +## Set up |
| 31 | +1. Ensure you've completed the prerequisites and setup steps in the [quickstart](../../quickstart.md). |
| 32 | + |
| 33 | +1. [optional]If your OpenAPI spec requires API key, you can store your API key in a `custom keys` connection and use `connection` authentication |
| 34 | + |
| 35 | + 1. Go to the [Azure AI Foundry portal](https://ai.azure.com/) and select the AI Project. Click **connected resources**. |
| 36 | + :::image type="content" source="../../media/tools/bing/project-settings-button.png" alt-text="A screenshot of the settings button for an AI project." lightbox="../../media/tools/bing/project-settings-button.png"::: |
| 37 | + |
| 38 | + 1. Select **+ new connection** in the settings page. |
| 39 | + >[!NOTE] |
| 40 | + > If you re-generate the API key at a later date, you need to update the connection with the new key. |
| 41 | + |
| 42 | + :::image type="content" source="../../media/tools/bing/project-connections.png" alt-text="A screenshot of the connections screen for the AI project." lightbox="../../media/tools/bing/project-connections.png"::: |
| 43 | + |
| 44 | + 1. Select **custom keys** in **other resource types**. |
| 45 | + |
| 46 | + :::image type="content" source="../../media/tools/bing/api-key-connection.png" alt-text="A screenshot of the custom keys selection for the AI project." lightbox="../../media/tools/bing/api-key-connection.png"::: |
| 47 | + |
| 48 | + 1. Enter the following information |
| 49 | + - `key`: "key" |
| 50 | + - value: YOUR_API_KEY |
| 51 | + - Connection name: `YOUR_CONNECTION_NAME` (You will use this connection name in the sample code below.) |
| 52 | + - Access: you can choose either *this project only* or *shared to all projects*. Just make sure in the sample code below, the project you entered connection string for has access to this connection. |
| 53 | + |
| 54 | + 1. Update your OpenAPI Spec with the following: |
| 55 | + ```json |
| 56 | + "components": { |
| 57 | + "securitySchemes": { |
| 58 | + "cosoLocationApiLambdaAuthorizer": { |
| 59 | + "type": "apiKey", |
| 60 | + "name": "key", |
| 61 | + "in": "query" |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | + ``` |
| 66 | +::: zone-end |
| 67 | + |
| 68 | +::: zone pivot="code-example" |
| 69 | +## Step 1: Create an agent with OpenAPI Spec tool |
| 70 | +Create a client object, which will contain the connection string for connecting to your AI project and other resources. |
| 71 | +# [Python](#tab/python) |
| 72 | + |
| 73 | +```python |
| 74 | +import os |
| 75 | +import jsonref |
| 76 | +from azure.ai.projects import AIProjectClient |
| 77 | +from azure.identity import DefaultAzureCredential |
| 78 | +from azure.ai.projects.models import OpenApiTool, OpenApiAnonymousAuthDetails |
| 79 | + |
| 80 | + |
| 81 | +# Create an Azure AI Client from a connection string, copied from your AI Studio project. |
| 82 | +# At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<HubName>" |
| 83 | +# Customer needs to login to Azure subscription via Azure CLI and set the environment variables |
| 84 | + |
| 85 | +project_client = AIProjectClient.from_connection_string( |
| 86 | + credential=DefaultAzureCredential(), |
| 87 | + conn_str=os.environ["PROJECT_CONNECTION_STRING"], |
| 88 | +) |
| 89 | +``` |
| 90 | +# [C#](#tab/csharp) |
| 91 | +```csharp |
| 92 | +using System; |
| 93 | +using System.Collections.Generic; |
| 94 | +using System.IO; |
| 95 | +using System.Runtime.CompilerServices; |
| 96 | +using System.Text.Json.Serialization; |
| 97 | +using System.Text.Json; |
| 98 | +using System.Threading.Tasks; |
| 99 | +using Azure.Core.TestFramework; |
| 100 | +using NUnit.Framework; |
| 101 | +using Newtonsoft.Json.Linq; |
| 102 | + |
| 103 | +namespace Azure.AI.Projects.Tests; |
| 104 | + |
| 105 | +public partial class Sample_Agent_OpenAPI : SamplesBase<AIProjectsTestEnvironment> |
| 106 | +{ |
| 107 | + private static string GetFile([CallerFilePath] string pth = "") |
| 108 | + { |
| 109 | + var dirName = Path.GetDirectoryName(pth) ?? ""; |
| 110 | + return Path.Combine(dirName, "weather_openapi.json"); |
| 111 | + } |
| 112 | + |
| 113 | + [Test] |
| 114 | + public async Task OpenAPICallingExample() |
| 115 | + { |
| 116 | + var connectionString = TestEnvironment.AzureAICONNECTIONSTRING; |
| 117 | + var storageQueueUri = TestEnvironment.STORAGE_QUEUE_URI; |
| 118 | + AgentsClient client = new(connectionString, new DefaultAzureCredential()); |
| 119 | + var file_path = GetFile(); |
| 120 | +``` |
| 121 | + |
| 122 | +--- |
| 123 | + |
| 124 | +## Step 2: Enable the OpenAPI Spec tool |
| 125 | +You might want to store the OpenAPI specification in another file and import the content to initialize the tool. Please note the sample code is using `anonymous` as authentication type. |
| 126 | + |
| 127 | +# [Python](#tab/python) |
| 128 | + |
| 129 | +```python |
| 130 | +with open('./weather_openapi.json', 'r') as f: |
| 131 | + openapi_spec = jsonref.loads(f.read()) |
| 132 | + |
| 133 | +# Create Auth object for the OpenApiTool (note that connection or managed identity auth setup requires additional setup in Azure) |
| 134 | +auth = OpenApiAnonymousAuthDetails() |
| 135 | + |
| 136 | +# Initialize agent OpenApi tool using the read in OpenAPI spec |
| 137 | +openapi = OpenApiTool(name="get_weather", spec=openapi_spec, description="Retrieve weather information for a location", auth=auth) |
| 138 | +``` |
| 139 | +If you want to use connection, which stores API key, for authentication, replace the line with |
| 140 | +```python |
| 141 | +auth = OpenApiConnectionAuthDetails(security_scheme=OpenApiConnectionSecurityScheme(connection_id="your_connection_id")) |
| 142 | +``` |
| 143 | +Your connection ID looks like `/subscriptions/{subscription ID}/resourceGroups/{resource group name}/providers/Microsoft.MachineLearningServices/workspaces/{project name}/connections/{connection name}`. |
| 144 | + |
| 145 | +If you want to use managed identity for authentication, replace the line with |
| 146 | +```python |
| 147 | +auth = OpenApiManagedAuthDetails(security_scheme=OpenApiManagedSecurityScheme(audience="https://your_identity_scope.com")) |
| 148 | +``` |
| 149 | +An example of the audience would be ```https://cognitiveservices.azure.com/```. |
| 150 | +
|
| 151 | +# [C#](#tab/csharp) |
| 152 | + |
| 153 | +```csharp |
| 154 | + #region Snippet:OpenAPIDefineFunctionTools |
| 155 | + OpenApiAnonymousAuthDetails oaiAuth = new(); |
| 156 | + OpenApiToolDefinition openapiTool = new( |
| 157 | + name: "get_weather", |
| 158 | + description: "Retrieve weather information for a location", |
| 159 | + spec: BinaryData.FromBytes(File.ReadAllBytes(file_path)), |
| 160 | + auth: oaiAuth |
| 161 | + ); |
| 162 | +``` |
| 163 | + |
| 164 | +--- |
| 165 | + |
| 166 | +## Step 3: Create a thread |
| 167 | + |
| 168 | +# [Python](#tab/python) |
| 169 | + |
| 170 | +```python |
| 171 | +# Create agent with OpenApi tool and process assistant run |
| 172 | +with project_client: |
| 173 | + agent = project_client.agents.create_agent( |
| 174 | + model="gpt-4o-mini", |
| 175 | + name="my-assistant", |
| 176 | + instructions="You are a helpful assistant", |
| 177 | + tools=openapi.definitions |
| 178 | + ) |
| 179 | + print(f"Created agent, ID: {agent.id}") |
| 180 | + |
| 181 | + # Create thread for communication |
| 182 | + thread = project_client.agents.create_thread() |
| 183 | + print(f"Created thread, ID: {thread.id}") |
| 184 | +``` |
| 185 | +# [C#](#tab/csharp) |
| 186 | +```csharp |
| 187 | +Response<Agent> agentResponse = await client.CreateAgentAsync( |
| 188 | + model: "gpt-4", |
| 189 | + name: "azure-function-agent-foo", |
| 190 | + instructions: "You are a helpful assistant.", |
| 191 | + tools: new List<ToolDefinition> { openapiTool } |
| 192 | + ); |
| 193 | +Agent agent = agentResponse.Value; |
| 194 | +#endregion |
| 195 | +Response<AgentThread> threadResponse = await client.CreateThreadAsync(); |
| 196 | +AgentThread thread = threadResponse.Value; |
| 197 | +``` |
| 198 | + |
| 199 | +--- |
| 200 | + |
| 201 | +## Step 4: Create a run and check the output |
| 202 | +Create a run and observe that the model uses the OpenAPI Spec tool to provide a response to the user's question. |
| 203 | + |
| 204 | +# [Python](#tab/python) |
| 205 | + |
| 206 | +```python |
| 207 | +# Create message to thread |
| 208 | + message = project_client.agents.create_message( |
| 209 | + thread_id=thread.id, |
| 210 | + role="user", |
| 211 | + content="What's the weather in Seattle?", |
| 212 | + ) |
| 213 | + print(f"Created message, ID: {message.id}") |
| 214 | + |
| 215 | + # Create and process agent run in thread with tools |
| 216 | + run = project_client.agents.create_and_process_run(thread_id=thread.id, assistant_id=agent.id) |
| 217 | + print(f"Run finished with status: {run.status}") |
| 218 | + |
| 219 | + if run.status == "failed": |
| 220 | + print(f"Run failed: {run.last_error}") |
| 221 | + |
| 222 | + # Delete the assistant when done |
| 223 | + project_client.agents.delete_agent(agent.id) |
| 224 | + print("Deleted agent") |
| 225 | + |
| 226 | + # Fetch and log all messages |
| 227 | + messages = project_client.agents.list_messages(thread_id=thread.id) |
| 228 | + print(f"Messages: {messages}") |
| 229 | +``` |
| 230 | + |
| 231 | +# [C#](#tab/csharp) |
| 232 | + |
| 233 | +```csharp |
| 234 | + #region Snippet:OpenAPIHandlePollingWithRequiredAction |
| 235 | + Response<ThreadMessage> messageResponse = await client.CreateMessageAsync( |
| 236 | + thread.Id, |
| 237 | + MessageRole.User, |
| 238 | + "What's the weather in Seattle?"); |
| 239 | + ThreadMessage message = messageResponse.Value; |
| 240 | + |
| 241 | + Response<ThreadRun> runResponse = await client.CreateRunAsync(thread, agent); |
| 242 | + |
| 243 | + do |
| 244 | + { |
| 245 | + await Task.Delay(TimeSpan.FromMilliseconds(500)); |
| 246 | + runResponse = await client.GetRunAsync(thread.Id, runResponse.Value.Id); |
| 247 | + } |
| 248 | + while (runResponse.Value.Status == RunStatus.Queued |
| 249 | + || runResponse.Value.Status == RunStatus.InProgress |
| 250 | + || runResponse.Value.Status == RunStatus.RequiresAction); |
| 251 | + #endregion |
| 252 | + |
| 253 | + Response<PageableList<ThreadMessage>> afterRunMessagesResponse |
| 254 | + = await client.GetMessagesAsync(thread.Id); |
| 255 | + IReadOnlyList<ThreadMessage> messages = afterRunMessagesResponse.Value.Data; |
| 256 | + |
| 257 | + // Note: messages iterate from newest to oldest, with the messages[0] being the most recent |
| 258 | + foreach (ThreadMessage threadMessage in messages) |
| 259 | + { |
| 260 | + Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: "); |
| 261 | + foreach (MessageContent contentItem in threadMessage.ContentItems) |
| 262 | + { |
| 263 | + if (contentItem is MessageTextContent textItem) |
| 264 | + { |
| 265 | + Console.Write(textItem.Text); |
| 266 | + } |
| 267 | + else if (contentItem is MessageImageFileContent imageFileItem) |
| 268 | + { |
| 269 | + Console.Write($"<image from ID: {imageFileItem.FileId}"); |
| 270 | + } |
| 271 | + Console.WriteLine(); |
| 272 | + } |
| 273 | + } |
| 274 | +``` |
| 275 | + |
| 276 | +--- |
| 277 | + |
| 278 | +::: zone-end |
0 commit comments