az ml connection create --file {connection.yml} --resource-group {my_resource_group} --workspace-name {my_project_name}
将占位符 my_connection_name、my_endpoint 和 my_key(可选)替换为 Azure AI 搜索连接详细信息,并运行以下代码来创建与 Azure AI 搜索资源的项目连接。
from azure.ai.ml.entities import AzureAISearchConnection
# create an Azure AI Search project connection
my_connection_name = "my-connection-name"
my_endpoint = "my-endpoint" # this could also be called target
my_api_keys = None # leave blank for Authentication type = AAD
my_connection = AzureAISearchConnection(name=my_connection_name,
endpoint=my_endpoint,
api_key= my_api_keys)
# Create the connection
ml_client.connections.create_or_update(my_connection)
在 Azure AI Foundry 中,导航到在代理设置中创建的项目。 单击“在管理中心”中打开。
单击“连接”选项卡,然后选择“添加连接”。
选择“Azure AI 搜索”。
提供要使用的 Azure AI 搜索资源所需的连接详细信息。 同时支持托管标识和基于密钥的身份验证。 填充所有字段后,单击“添加连接”。
验证连接是否已成功创建,现在显示在项目的“连接”选项卡中。
创建与 Azure AI 搜索资源的项目连接后,可以配置并开始使用 SDK 的 Azure AI 搜索工具。 请参阅代码示例选项卡以开始使用。
将 Azure AI 搜索工具添加到代理
可以使用本文顶部列出的代码示例或 Azure AI Foundry 门户以编程方式将 Azure AI 搜索工具添加到代理。 如果要使用门户:
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from azure.ai.projects.models import AzureAISearchTool
# Create an Azure AI Client from a connection string, copied from your Azure AI Foundry project.
# At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>"
# HostName can be found by navigating to your discovery_url and removing the leading "https://" and trailing "/discovery"
# To find your discovery_url, run the CLI command: az ml workspace show -n {project_name} --resource-group {resource_group_name} --query discovery_url
# Project Connection example: eastus.api.azureml.ms;my-subscription-id;my-resource-group;my-hub-name
connection_string = os.environ["PROJECT_CONNECTION_STRING"]
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(),
conn_str=connection_string,
)
using System;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.TestFramework;
using NUnit.Framework;
using System.Collections.Generic;
// Create an Azure AI Client from a connection string, copied from your Azure AI Foundry project.
// At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>"
// Customer needs to login to Azure subscription via Azure CLI and set the environment variables
var connectionString = TestEnvironment.AzureAICONNECTIONSTRING;
var clientOptions = new AIProjectClientOptions();
// Adding the custom headers policy
clientOptions.AddPolicy(new CustomHeadersPolicy(), HttpPipelinePosition.PerCall);
var projectClient = new AIProjectClient(connectionString, new DefaultAzureCredential(), clientOptions);
const connectionString =
process.env["AZURE_AI_PROJECTS_CONNECTION_STRING"] || "<project connection string>";
if (!connectionString) {
throw new Error("AZURE_AI_PROJECTS_CONNECTION_STRING must be set in the environment variables");
}
const client = AIProjectsClient.fromConnectionString(
connectionString || "",
new DefaultAzureCredential(),
);
按照 REST API 快速入门设置环境变量 AZURE_AI_AGENTS_TOKEN 和 AZURE_AI_AGENTS_ENDPOINT 的正确值。
步骤 2:获取 Azure AI 搜索资源的连接 ID
获取项目中 Azure AI 搜索连接的连接 ID。 可以使用代码片段打印项目中所有 Azure AI 搜索连接的连接 ID。
# AI Search resource connection ID
# This code looks for the AI Search Connection ID and saves it as variable conn_id
# If you have more than one AI search connection, try to establish the value in your .env file.
# Extract the connection list.
conn_list = project_client.connections._list_connections()["value"]
conn_id = ""
# Search in the metadata field of each connection in the list for the azure_ai_search type and get the id value to establish the variable
for conn in conn_list:
metadata = conn["properties"].get("metadata", {})
if metadata.get("type", "").upper() == "AZURE_AI_SEARCH":
conn_id = conn["id"]
break
ListConnectionsResponse connections = await projectClient.GetConnectionsClient().GetConnectionsAsync(ConnectionType.AzureAISearch).ConfigureAwait(false);
if (connections?.Value == null || connections.Value.Count == 0)
{
throw new InvalidOperationException("No connections found for the Azure AI Search.");
}
# TO DO: replace this value with the connection ID of the search index
conn_id = "/subscriptions/<your-subscription-id>/resourceGroups/<your-resource-group>/providers/Microsoft.MachineLearningServices/workspaces/<your-project-name>/connections/<your-azure-ai-search-connection-name>"
# Initialize agent AI search tool and add the search index connection ID and index name
# TO DO: replace <your-index-name> with the name of the index you want to use
ai_search = AzureAISearchTool(index_connection_id=conn_id, index_name="<your-index-name>")
// TO DO: replace this value with the connection ID of the search index
ConnectionResponse connection = connections.Value[0];
// Initialize agent Azure AI search tool and add the search index connection ID and index name
// TO DO: replace <your-index-name> with the name of the index you want to use
ToolResources searchResource = new ToolResources
{
AzureAISearch = new AzureAISearchResource
{
IndexList = { new IndexResource(connection.Id, "<your-index-name>") }
}
};
const azureAISearchTool = ToolUtility.createAzureAISearchTool(
cognitiveServicesConnection.id,
cognitiveServicesConnection.name,
);
// Create agent with the Azure AI search tool
const agent = await client.agents.createAgent("gpt-4o-mini", {
name: "my-agent",
instructions: "You are a helpful agent",
tools: [azureAISearchTool.definition],
toolResources: azureAISearchTool.resources,
});
console.log(`Created agent, agent ID : ${agent.id}`);
不适用
步骤 4:创建启用了 Azure AI 搜索工具的代理
将模型更改为项目中部署的模型。 可以在“模型”选项卡下的 Azure AI Foundry 中找到模型名称。还可以更改代理的名称和说明,以满足你的需求。
# Create a thread
thread = project_client.agents.create_thread()
print(f"Created thread, thread ID: {thread.id}")
# Create a message
message = project_client.agents.create_message(
thread_id=thread.id,
role="user",
content="what are my health insurance plan coverage types?",
)
print(f"Created message, message ID: {message.id}")
# Run the agent
run = project_client.agents.create_and_process_run(thread_id=thread.id, assistant_id=agent.id)
print(f"Run finished with status: {run.status}")
if run.status == "failed":
# Check if you got "Rate limit is exceeded.", then you want to get more quota
print(f"Run failed: {run.last_error}")
# Get messages from the thread
messages = project_client.agents.list_messages(thread_id=thread.id)
print(f"Messages: {messages}")
assistant_message = ""
for message in messages.data:
if message["role"] == "assistant":
assistant_message = message["content"][0]["text"]["value"]
# Get the last message from the sender
print(f"Assistant response: {assistant_message}")
// Create thread for communication
Response<AgentThread> threadResponse = await agentClient.CreateThreadAsync();
AgentThread thread = threadResponse.Value;
// Create message to thread
Response<ThreadMessage> messageResponse = await agentClient.CreateMessageAsync(
thread.Id,
MessageRole.User,
"what are my health insurance plan coverage types?");
ThreadMessage message = messageResponse.Value;
// Run the agent
Response<ThreadRun> runResponse = await agentClient.CreateRunAsync(thread, agent);
do
{
await Task.Delay(TimeSpan.FromMilliseconds(500));
runResponse = await agentClient.GetRunAsync(thread.Id, runResponse.Value.Id);
}
while (runResponse.Value.Status == RunStatus.Queued
|| runResponse.Value.Status == RunStatus.InProgress);
Response<PageableList<ThreadMessage>> afterRunMessagesResponse
= await agentClient.GetMessagesAsync(thread.Id);
IReadOnlyList<ThreadMessage> messages = afterRunMessagesResponse.Value.Data;
// Note: messages iterate from newest to oldest, with the messages[0] being the most recent
foreach (ThreadMessage threadMessage in messages)
{
Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
foreach (MessageContent contentItem in threadMessage.ContentItems)
{
if (contentItem is MessageTextContent textItem)
{
Console.Write(textItem.Text);
}
else if (contentItem is MessageImageFileContent imageFileItem)
{
Console.Write($"<image from ID: {imageFileItem.FileId}");
}
Console.WriteLine();
}
}
// create a thread
const thread = await client.agents.createThread();
// add a message to thread
await client.agents.createMessage(
thread.id, {
role: "user",
content: "what are my health insurance plan coverage types?",
});
// Intermission is now correlated with thread
// Intermission messages will retrieve the message just added
// create a run
const streamEventMessages = await client.agents.createRun(thread.id, agent.id).stream();
for await (const eventMessage of streamEventMessages) {
switch (eventMessage.event) {
case RunStreamEvent.ThreadRunCreated:
break;
case MessageStreamEvent.ThreadMessageDelta:
{
const messageDelta = eventMessage.data;
messageDelta.delta.content.forEach((contentPart) => {
if (contentPart.type === "text") {
const textContent = contentPart;
const textValue = textContent.text?.value || "No text";
}
});
}
break;
case RunStreamEvent.ThreadRunCompleted:
break;
case ErrorEvent.Error:
console.log(`An error occurred. Data ${eventMessage.data}`);
break;
case DoneEvent.Done:
break;
}
}
// Print the messages from the agent
const messages = await client.agents.listMessages(thread.id);
// Messages iterate from oldest to newest
// messages[0] is the most recent
for (let i = messages.data.length - 1; i >= 0; i--) {
const m = messages.data[i];
if (isOutputOfType<MessageTextContentOutput>(m.content[0], "text")) {
const textContent = m.content[0];
console.log(`${textContent.text.value}`);
console.log(`---------------------------------`);
}
}