Skip to content

Commit 4326d10

Browse files
authored
Merge pull request #1873 from lindazqli/patch-7
Create openapi-spec.md
2 parents 5caba5f + 7663496 commit 4326d10

File tree

2 files changed

+145
-0
lines changed

2 files changed

+145
-0
lines changed
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
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/06/2024
10+
author: aahill
11+
ms.author: aahi
12+
zone_pivot_groups: selection-function-calling
13+
recommendations: false
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 much, much 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+
![image](https://github.com/user-attachments/assets/2e6e8efe-1a31-4097-a859-58ac5ee17a96)
46+
47+
1. Enter the following information
48+
- `key`: "key"
49+
- value: YOUR_API_KEY
50+
- Connection name: `YOUR_CONNECTION_NAME` (You will use this connection name in the sample code below.)
51+
- 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.
52+
53+
::: zone-end
54+
55+
::: zone pivot="code-example"
56+
## Step 1: Create an agent with OpenAPI Spec tool
57+
Create a client object, which will contain the connection string for connecting to your AI project and other resources.
58+
```python
59+
import os
60+
import jsonref
61+
from azure.ai.projects import AIProjectClient
62+
from azure.identity import DefaultAzureCredential
63+
from azure.ai.projects.models import OpenApiTool, OpenApiAnonymousAuthDetails
64+
65+
66+
# Create an Azure AI Client from a connection string, copied from your AI Studio project.
67+
# At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<HubName>"
68+
# Customer needs to login to Azure subscription via Azure CLI and set the environment variables
69+
70+
project_client = AIProjectClient.from_connection_string(
71+
credential=DefaultAzureCredential(),
72+
conn_str=os.environ["PROJECT_CONNECTION_STRING"],
73+
)
74+
```
75+
76+
## Step 2: Enable the OpenAPI Spec tool
77+
You may 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.
78+
```python
79+
with open('./weather_openapi.json', 'r') as f:
80+
openapi_spec = jsonref.loads(f.read())
81+
82+
# Create Auth object for the OpenApiTool (note that connection or managed identity auth setup requires additional setup in Azure)
83+
auth = OpenApiAnonymousAuthDetails()
84+
85+
# Initialize agent OpenApi tool using the read in OpenAPI spec
86+
openapi = OpenApiTool(name="get_weather", spec=openapi_spec, description="Retrieve weather information for a location", auth=auth)
87+
```
88+
If you want to use connection, which stores API key, for authentication, replace the line with
89+
```python
90+
auth = OpenApiConnectionAuthDetails(security_scheme=OpenApiConnectionSecurityScheme(connection_id="your_connection_id"))
91+
```
92+
Your connection ID looks like `/subscriptions/{subscription ID}/resourceGroups/{resource group name}/providers/Microsoft.MachineLearningServices/workspaces/{project name}/connections/{connection name}`.
93+
94+
If you want to use managed identity for authentication, replace the line with
95+
```python
96+
auth = OpenApiManagedAuthDetails(security_scheme=OpenApiManagedSecurityScheme(audience="https://your_identity_scope.com"))
97+
```
98+
An example of the audience would be ```https://cognitiveservices.azure.com/```.
99+
100+
## Step 3: Create a thread
101+
```python
102+
# Create agent with OpenApi tool and process assistant run
103+
with project_client:
104+
agent = project_client.agents.create_agent(
105+
model="gpt-4o-mini",
106+
name="my-assistant",
107+
instructions="You are a helpful assistant",
108+
tools=openapi.definitions
109+
)
110+
print(f"Created agent, ID: {agent.id}")
111+
112+
# Create thread for communication
113+
thread = project_client.agents.create_thread()
114+
print(f"Created thread, ID: {thread.id}")
115+
```
116+
117+
## Step 4: Create a run and check the output
118+
Create a run and observe that the model uses the OpenAPI Spec tool to provide a response to the user's question.
119+
```python
120+
# Create message to thread
121+
message = project_client.agents.create_message(
122+
thread_id=thread.id,
123+
role="user",
124+
content="What's the weather in Seattle?",
125+
)
126+
print(f"Created message, ID: {message.id}")
127+
128+
# Create and process agent run in thread with tools
129+
run = project_client.agents.create_and_process_run(thread_id=thread.id, assistant_id=agent.id)
130+
print(f"Run finished with status: {run.status}")
131+
132+
if run.status == "failed":
133+
print(f"Run failed: {run.last_error}")
134+
135+
# Delete the assistant when done
136+
project_client.agents.delete_agent(agent.id)
137+
print("Deleted agent")
138+
139+
# Fetch and log all messages
140+
messages = project_client.agents.list_messages(thread_id=thread.id)
141+
print(f"Messages: {messages}")
142+
```
143+
::: zone-end

articles/ai-services/agents/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ items:
3636
href: how-to/tools/file-search.md
3737
- name: Action tools
3838
items:
39+
- name: OpenAPI specified tools
40+
href: how-to/tools/openapi-spec.md
3941
- name: Agent function calling
4042
href: how-to/tools/function-calling.md
4143
- name: Code interpreter

0 commit comments

Comments
 (0)