Skip to content

Commit d6bbdbf

Browse files
committed
using includes to fix tab groups
1 parent 65bb287 commit d6bbdbf

File tree

3 files changed

+313
-307
lines changed

3 files changed

+313
-307
lines changed

articles/ai-services/agents/how-to/tools/azure-ai-search.md

Lines changed: 2 additions & 307 deletions
Original file line numberDiff line numberDiff line change
@@ -36,318 +36,13 @@ Use an existing Azure AI Search index with the agent's Azure AI Search tool.
3636
::: zone-end
3737

3838
::: zone pivot="setup"
39-
## Setup: Create an agent that can use an existing Azure AI Search index
40-
#### 1. Prerequisite: Have an existing Azure AI Search index
41-
A prerequisite of using the Azure AI Search tool is to have an existing Azure AI Search index. If you don't have an existing index, you can create one in the Azure portal or via REST API.
42-
- [Quickstart: Create a vector index using the Azure portal](../../../../search/search-get-started-portal-import-vectors.md)
43-
- [Quickstart: Create a vector index using REST API](../../../../search/search-get-started-vector.md)
44-
#### 2. Complete the agent setup
45-
- **Option 1: Standard Agent Setup using existing AI Search resource** If you want your agent to use an existing AI Search resource to create new indexes or bring existing ones you should use the [standard agent setup and add your AI Search resource ID](../../quickstart.md).
46-
- You can provide your Azure AI Search resource ID in the bicep file. Your resource ID should be in the format: `/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}`.
47-
- **Option 2: Standard Agent Setup** If you want to create a new Azure AI Search resource for your agents to use when creating new indexes follow the [standard agent setup](../../quickstart.md).
48-
49-
#### 3. Create a project connection to the Azure AI Search resource with the index you want to use
50-
If you already connected the AI Search resource that contains the index you want to use to your project, skip this step.
51-
52-
##### Get your Azure AI Search resource connection key and endpoint
53-
- Access your Azure AI Search resource.
54-
- In the Azure portal, navigate to the AI Search resource that contains the index you want to use.
55-
- Copy the connection endpoint.
56-
- In the Overview tab, copy the URL of your resource. The URL should be in the format `https://<your-resource-name>.search.windows.net/`.
57-
:::image type="content" source="../../media/tools/ai-search/connection-endpoint.png" alt-text="A screenshot of an AI Search resource Overview tab in the Azure portal." lightbox="../../media/tools/ai-search/connection-endpoint.png":::
58-
59-
- Verify API Acccess control is set to **Both** and copy one of the keys under **Manage admin keys**.
60-
- From the left-hand navigation bar, scroll down to the Settings section and select **Keys**.
61-
- Under the **API Access Control** section, ensure the option **Both** API key and Role-based access control is selected.
62-
- If you want the connection to use API Keys for authentication, copy one of the keys under **Manage admin keys**.
63-
:::image type="content" source="../../media/tools/ai-search/acs-azure-portal.png" alt-text="A screenshot of an AI Search resource Keys tab in the Azure portal." lightbox="../../media/tools/ai-search/acs-azure-portal.png":::
64-
65-
##### Create an Azure AI Search project connection
66-
67-
**Azure CLI**
68-
```azurecli
69-
az ml connection create --file {connection.yml} --resource-group {my_resource_group} --workspace-name {my_hub_name}
70-
```
71-
72-
You can use either an API key or credential-less YAML configuration file. For more information on the YAML configuration file, see the [Azure AI Search connection YAML schema](../../../../machine-learning/reference-yaml-connection-ai-search.md):
73-
- API Key example:
74-
75-
```yml
76-
name: myazaics_apk
77-
type: azure_ai_search
78-
endpoint: https://contoso.search.windows.net/
79-
api_key: XXXXXXXXXXXXXXX
80-
```
81-
82-
- Credential-less
83-
84-
```yml
85-
name: myazaics_ei
86-
type: azure_ai_search
87-
endpoint: https://contoso.search.windows.net/
88-
```
89-
90-
**Python**
91-
```python
92-
from azure.ai.ml.entities import AzureAISearchConnection
93-
94-
# constrict an Azure AI Search connection
95-
my_connection_name = "myaiservivce"
96-
my_endpoint = "demo.endpoint" # this could also be called target
97-
my_api_keys = None # leave blank for Authentication type = AAD
98-
99-
my_connection = AzureAISearchConnection(name=my_connection_name,
100-
endpoint=my_endpoint,
101-
api_key= my_api_keys)
102-
103-
# Create the connection
104-
ml_client.connections.create_or_update(my_connection)
105-
```
106-
107-
**Azure AI Foundry**
108-
1. In Azure AI Foundry, navigate to the project you created in the agent setup. Click on **Open in management center**.
109-
:::image type="content" source="../../media/tools/ai-search/project-studio.png" alt-text="A screenshot of a project in Azure AI Foundry." lightbox="../../media/tools/ai-search/project-studio.png":::
110-
111-
2. Click on the **Connections** tab and select **Add Connection**.
112-
:::image type="content" source="../../media/tools/ai-search/project-connections-page.png" alt-text="A screenshot of the project connections page." lightbox="../../media/tools/ai-search/project-connections-page.png":::
113-
114-
3. Select **Azure AI Search**.
115-
:::image type="content" source="../../media/tools/ai-search/select-acs.png" alt-text="A screenshot of the Azure AI Search connection type the user should select." lightbox="../../media/tools/ai-search/select-acs.png":::
116-
117-
4. Provide the required connection details for the Azure AI Search resource you want to use. Both Managed Identity and Key-based authentication are supported. Once all the fields are filled in, click **Add connection**.
118-
:::image type="content" source="../../media/tools/ai-search/acs-connection-2.png" alt-text="A screenshot the required fields to add a new Azure AI Search connection." lightbox="../../media/tools/ai-search/acs-connection-2.png":::
119-
120-
5. Verify that the connection was successfully created and now appears in the project's Connections tab.
121-
:::image type="content" source="../../media/tools/ai-search/success-acs-connection.png" alt-text="A screenshot of the project connections page with a new Azure AI Search connection added." lightbox="../../media/tools/ai-search/success-acs-connection.png":::
122-
12339

40+
[!INCLUDE [acs-setup](../../includes/acs/acs-setup.md)]
12441

12542
::: zone-end
12643

12744
::: zone pivot="code-examples"
12845

129-
## Quickstart – Use an existing Azure AI Search index with the Azure AI Search tool
130-
131-
This quickstart shows how to use an existing Azure AI Search index with the Azure AI Search tool.
132-
133-
### Prerequisites
134-
Complete the [Azure AI Search tool setup](?pivot=setup).
135-
136-
### Step 1: Create an Azure AI Client
137-
First, create an Azure AI Client using the connection string of your project.
138-
# [Python](#tab/python)
139-
```python
140-
import os
141-
from azure.ai.projects import AIProjectClient
142-
from azure.identity import DefaultAzureCredential
143-
from azure.ai.projects.models import AzureAISearchTool
144-
145-
# Create an Azure AI Client from a connection string, copied from your AI Studio project.
146-
# At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>"
147-
# HostName can be found by navigating to your discovery_url and removing the leading "https://" and trailing "/discovery"
148-
# To find your discovery_url, run the CLI command: az ml workspace show -n {project_name} --resource-group {resource_group_name} --query discovery_url
149-
# Project Connection example: eastus.api.azureml.ms;my-subscription-id;my-resource-group;my-hub-name
150-
151-
connection_string = os.environ["PROJECT_CONNECTION_STRING"]
152-
153-
project_client = AIProjectClient.from_connection_string(
154-
credential=DefaultAzureCredential(),
155-
conn_str=connection_string,
156-
)
157-
```
158-
159-
# [C#](#tab/csharp)
160-
```csharp
161-
using System;
162-
using System.Threading.Tasks;
163-
using Azure.Core;
164-
using Azure.Core.TestFramework;
165-
using NUnit.Framework;
166-
using System.Collections.Generic;
167-
168-
// Create an Azure AI Client from a connection string, copied from your AI Studio project.
169-
// At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>"
170-
// Customer needs to login to Azure subscription via Azure CLI and set the environment variables
171-
var connectionString = TestEnvironment.AzureAICONNECTIONSTRING;
172-
var clientOptions = new AIProjectClientOptions();
173-
174-
// Adding the custom headers policy
175-
clientOptions.AddPolicy(new CustomHeadersPolicy(), HttpPipelinePosition.PerCall);
176-
var projectClient = new AIProjectClient(connectionString, new DefaultAzureCredential(), clientOptions);
177-
```
178-
---
179-
### Step 2: Get the connection ID for the Azure AI Search resource
180-
181-
Get the connection ID of the Azure AI Search connection in the project. You can use the code snippet to print the connection ID of all the Azure AI Search connections in the project.
182-
183-
# [Python](#tab/python)
184-
185-
```python
186-
# AI Search resource connection ID
187-
# This code prints out the connection ID of all the Azure AI Search connections in the project
188-
# If you have more than one AI search connection, make sure to select the correct one that contains the index you want to use.
189-
conn_list = project_client.connections.list()
190-
conn_id = ""
191-
for conn in conn_list:
192-
if conn.connection_type == "CognitiveSearch":
193-
print(f"Connection ID: {conn.id}")
194-
```
195-
# [C#](#tab/csharp)
196-
```csharp
197-
ListConnectionsResponse connections = await projectClient.GetConnectionsClient().GetConnectionsAsync(ConnectionType.AzureAISearch).ConfigureAwait(false);
198-
199-
if (connections?.Value == null || connections.Value.Count == 0)
200-
{
201-
throw new InvalidOperationException("No connections found for the Azure AI Search.");
202-
}
203-
204-
```
205-
---
206-
The second way to get the connection ID is to navigate to the project in the Azure AI Foundry and click on the **Connected resources** tab and then select your Azure AI Search resource.
207-
:::image type="content" source="../../media/tools/ai-search/success-acs-connection.png" alt-text="A screenshot of an AI Search resource connection page in Azure AI Foundry." lightbox="../../media/tools/ai-search/success-acs-connection.png":::
208-
In the URL, you see the wsid=/subscription/your-subscription-id..., this is the connection ID you need to use. Copy everything that comes after wsid=.
209-
:::image type="content" source="../../media/tools/ai-search/connection-id.png" alt-text="A screenshot of an AI Search resource connection and how to copy the connection ID." lightbox="../../media/tools/ai-search/connection-id.png":::
210-
211-
### Step 3: Configure the Azure AI Search tool
212-
Using the connection ID you got in the previous step, you can now configure the Azure AI Search tool to use your Azure AI Search index.
213-
# [Python](#tab/python)
214-
```python
215-
# TO DO: replace this value with the connection ID of the search index
216-
conn_id = "/subscriptions/<your-subscription-id>/resourceGroups/<your-resource-group>/providers/Microsoft.MachineLearningServices/workspaces/<your-project-name>/connections/<your-azure-ai-search-connection-name>"
217-
218-
# Initialize agent AI search tool and add the search index connection ID and index name
219-
# TO DO: replace <your-index-name> with the name of the index you want to use
220-
ai_search = AzureAISearchTool()
221-
ai_search.add_index(conn_id, "<your-index-name>")
222-
```
223-
# [C#](#tab/csharp)
224-
```csharp
225-
// TO DO: replace this value with the connection ID of the search index
226-
ConnectionResponse connection = connections.Value[0];
227-
228-
// Initialize agent Azure AI search tool and add the search index connection ID and index name
229-
// TO DO: replace <your-index-name> with the name of the index you want to use
230-
ToolResources searchResource = new ToolResources
231-
{
232-
AzureAISearch = new AzureAISearchResource
233-
{
234-
IndexList = { new IndexResource(connection.Id, "<your-index-name>") }
235-
}
236-
};
237-
```
238-
---
239-
240-
### Step 4: Create an agent with the Azure AI Search tool enabled
241-
Change the model to the one deployed in your project. You can find the model name in the Azure AI Foundry under the **Models** tab. You can also change the name and instructions of the agent to suit your needs.
242-
# [Python](#tab/python)
243-
```python
244-
agent = project_client.agents.create_agent(
245-
model="gpt-4o-mini",
246-
name="my-assistant",
247-
instructions="You are a helpful assistant",
248-
tools=ai_search.definitions,
249-
tool_resources = ai_search.resources,
250-
headers={"x-ms-enable-preview": "true"},
251-
)
252-
print(f"Created agent, ID: {agent.id}")
253-
```
254-
# [C#](#tab/csharp)
255-
```csharp
256-
AgentsClient agentClient = projectClient.GetAgentsClient();
257-
258-
Response<Agent> agentResponse = await agentClient.CreateAgentAsync(
259-
model: "gpt-4o-mini",
260-
name: "my-assistant",
261-
instructions: "You are a helpful assistant.",
262-
tools: new List<ToolDefinition> { new AzureAISearchToolDefinition() },
263-
toolResources: searchResource);
264-
Agent agent = agentResponse.Value;
265-
```
266-
---
267-
268-
### Step 5: Ask the agent questions about data in the index
269-
Now that the agent is created, ask it questions about the data in your Azure AI Search index. The example assumes your Azure AI Search index contains information about health care plans.
270-
# [Python](#tab/python)
271-
```python
272-
# Create a thread
273-
thread = project_client.agents.create_thread()
274-
print(f"Created thread, thread ID: {thread.id}")
275-
276-
# Create a message
277-
message = project_client.agents.create_message(
278-
thread_id=thread.id,
279-
role="user",
280-
content="what are my health insurance plan coverage types?",
281-
)
282-
print(f"Created message, message ID: {message.id}")
283-
284-
# Run the agent
285-
run = project_client.agents.create_and_process_run(thread_id=thread.id, assistant_id=agent.id)
286-
print(f"Run finished with status: {run.status}")
287-
288-
if run.status == "failed":
289-
# Check if you got "Rate limit is exceeded.", then you want to get more quota
290-
print(f"Run failed: {run.last_error}")
291-
292-
# Get messages from the thread
293-
messages = project_client.agents.list_messages(thread_id=thread.id)
294-
print(f"Messages: {messages}")
295-
296-
assistant_message = ""
297-
for message in messages.data:
298-
if message["role"] == "assistant":
299-
assistant_message = message["content"][0]["text"]["value"]
300-
301-
# Get the last message from the sender
302-
print(f"Assistant response: {assistant_message}")
303-
```
304-
# [C#](#tab/csharp)
305-
```csharp
306-
307-
// Create thread for communication
308-
Response<AgentThread> threadResponse = await agentClient.CreateThreadAsync();
309-
AgentThread thread = threadResponse.Value;
310-
311-
// Create message to thread
312-
Response<ThreadMessage> messageResponse = await agentClient.CreateMessageAsync(
313-
thread.Id,
314-
MessageRole.User,
315-
"Hello, send an email with the datetime and weather information in New York?");
316-
ThreadMessage message = messageResponse.Value;
317-
318-
// Run the agent
319-
Response<ThreadRun> runResponse = await agentClient.CreateRunAsync(thread, agent);
320-
321-
do
322-
{
323-
await Task.Delay(TimeSpan.FromMilliseconds(500));
324-
runResponse = await agentClient.GetRunAsync(thread.Id, runResponse.Value.Id);
325-
}
326-
while (runResponse.Value.Status == RunStatus.Queued
327-
|| runResponse.Value.Status == RunStatus.InProgress);
328-
329-
Response<PageableList<ThreadMessage>> afterRunMessagesResponse
330-
= await agentClient.GetMessagesAsync(thread.Id);
331-
IReadOnlyList<ThreadMessage> messages = afterRunMessagesResponse.Value.Data;
332-
333-
// Note: messages iterate from newest to oldest, with the messages[0] being the most recent
334-
foreach (ThreadMessage threadMessage in messages)
335-
{
336-
Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
337-
foreach (MessageContent contentItem in threadMessage.ContentItems)
338-
{
339-
if (contentItem is MessageTextContent textItem)
340-
{
341-
Console.Write(textItem.Text);
342-
}
343-
else if (contentItem is MessageImageFileContent imageFileItem)
344-
{
345-
Console.Write($"<image from ID: {imageFileItem.FileId}");
346-
}
347-
Console.WriteLine();
348-
}
349-
}
350-
```
351-
---
46+
[!INCLUDE [acs-code-examples](../../includes/acs/acs-code-examples.md)]
35247

35348
::: zone-end

0 commit comments

Comments
 (0)