Bagikan melalui


Cara menggunakan indeks Pencarian Azure AI yang sudah ada dengan alat Pencarian Azure AI

Artikel ini memperlihatkan cara menggunakan indeks Pencarian Azure AI yang sudah ada dengan alat Pencarian Azure AI.

Prasyarat

Selesaikan penyiapan alat Pencarian Azure AI.

  1. Buka portal Azure AI Foundry, dan navigasikan ke layar Agen untuk agen Anda, gulir ke bawah panel Penyiapan di sebelah kanan ke pengetahuan. Kemudian pilih Tambahkan.

    Cuplikan layar memperlihatkan kategori alat yang tersedia di portal Azure AI Foundry.

  2. Pilih Azure AI Search dan ikuti perintah untuk menambahkan alat.

    Cuplikan layar memperlihatkan alat pengetahuan yang tersedia di portal Azure AI Foundry.

Membuat Klien Azure AI

Pertama, buat Klien Azure AI menggunakan titik akhir proyek Anda.

import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential

# Retrieve the endpoint from environment variables
project_endpoint = os.environ["PROJECT_ENDPOINT"]

# Initialize the AIProjectClient
project_client = AIProjectClient(
    endpoint=project_endpoint,
    credential=DefaultAzureCredential(exclude_interactive_browser_credential=False)
)

Mengonfigurasi alat Pencarian Azure AI

Dengan menggunakan ID koneksi sumber daya Azure AI Search Anda, konfigurasikan alat Azure AI Search untuk menggunakan indeks Azure AI Search Anda.

from azure.ai.agents.models import AzureAISearchTool, AzureAISearchQueryType
from azure.ai.projects.models import ConnectionType

# Define the Azure AI Search connection ID and index name
azure_ai_conn_id = project_client.connections.get_default(ConnectionType.AZURE_AI_SEARCH).id

# find the index name in your AI Search Azure resource page under Search Management -> Indexes
index_name = "sample_index"

# Initialize the Azure AI Search tool
ai_search = AzureAISearchTool(
    index_connection_id=azure_ai_conn_id,
    index_name=index_name,
    query_type=AzureAISearchQueryType.SIMPLE,  # Use SIMPLE query type
    top_k=3,  # Retrieve the top 3 results
    filter="",  # Optional filter for search results
)

Membuat agen dengan alat Pencarian Azure AI diaktifkan

Buat agen dengan alat Pencarian Azure AI terlampir. Ubah model ke yang di-deploy dalam proyek Anda.

# Define the model deployment name
model_deployment_name = os.environ["MODEL_DEPLOYMENT_NAME"]

# Create an agent with the Azure AI Search tool
agent = project_client.agents.create_agent(
    model=model_deployment_name,
    name="my-agent",
    instructions="You are a helpful agent",
    tools=ai_search.definitions,
    tool_resources=ai_search.resources,
)
print(f"Created agent, ID: {agent.id}")

Ajukan pertanyaan agen tentang data dalam indeks

Sekarang setelah agen dibuat, ajukan pertanyaan tentang data di indeks Azure AI Search Anda.

from azure.ai.agents.models import MessageRole, ListSortOrder

# Create a thread for communication
thread = project_client.agents.threads.create()
print(f"Created thread, ID: {thread.id}")

# Send a message to the thread
message = project_client.agents.messages.create(
    thread_id=thread.id,
    role=MessageRole.USER,
    content="What is the temperature rating of the cozynights sleeping bag?",
)
print(f"Created message, ID: {message['id']}")

# Create and process a run with the specified thread and agent
run = project_client.agents.runs.create_and_process(thread_id=thread.id, agent_id=agent.id)
print(f"Run finished with status: {run.status}")

# Check if the run failed
if run.status == "failed":
    print(f"Run failed: {run.last_error}")

# Fetch and log all messages in the thread
messages = project_client.agents.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING)
for message in messages.data:
    print(f"Role: {message.role}, Content: {message.content}")

Membersihkan sumber daya

Setelah menyelesaikan operasi, hapus agen untuk membersihkan sumber daya.

# Delete the agent
project_client.agents.delete_agent(agent.id)
print("Deleted agent")

Membuat klien proyek

Buat objek klien, yang akan berisi titik akhir proyek untuk menyambungkan ke proyek AI Anda dan sumber daya lainnya.

using Azure;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading;

// Get Connection information from app configuration
IConfigurationRoot configuration = new ConfigurationBuilder()
    .SetBasePath(AppContext.BaseDirectory)
    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
    .Build();

var projectEndpoint = configuration["ProjectEndpoint"];
var modelDeploymentName = configuration["ModelDeploymentName"];
var azureAiSearchConnectionId = configuration["AzureAiSearchConnectionId"];

// Create the Agent Client
PersistentAgentsClient agentClient = new(projectEndpoint, new DefaultAzureCredential());

Mengonfigurasi alat Pencarian Azure AI

Menggunakan ID Koneksi Pencarian AI, konfigurasikan alat Pencarian Azure AI untuk menggunakan indeks Pencarian Azure AI Anda.

AzureAISearchToolResource searchResource = new(
    indexConnectionId: azureAiSearchConnectionId,
    indexName: "sample_index",
    topK: 5,
    filter: "category eq 'sleeping bag'",
    queryType: AzureAISearchQueryType.Simple
);

ToolResources toolResource = new() { AzureAISearch = searchResource };

Membuat agen dengan alat Pencarian Azure AI diaktifkan

Ubah model ke yang di-deploy dalam proyek Anda. Anda dapat menemukan nama model di Azure AI Foundry di bawah tab Model . Anda juga dapat mengubah nama dan instruksi agen agar sesuai dengan kebutuhan Anda.

// Create an agent with Tools and Tool Resources
PersistentAgent agent = agentClient.Administration.CreateAgent(
    model: modelDeploymentName,
    name: "my-agent",
    instructions: "Use the index provided to answer questions.",
    tools: [new AzureAISearchToolDefinition()],
    toolResources: toolResource
);

Ajukan pertanyaan agen tentang data dalam indeks

Sekarang setelah agen dibuat, ajukan pertanyaan tentang data di indeks Azure AI Search Anda.

// Create thread for communication
PersistentAgentThread thread = agentClient.Threads.CreateThread();

// Create message and run the agent
PersistentThreadMessage message = agentClient.Messages.CreateMessage(
    thread.Id,
    MessageRole.User,
    "What is the temperature rating of the cozynights sleeping bag?");
ThreadRun run = agentClient.Runs.CreateRun(thread, agent);

Tunggu hingga agen selesai dan cetak output

Tunggu hingga agen menyelesaikan proses dan mencetak output ke konsol.

// Wait for the agent to finish running
do
{
    Thread.Sleep(TimeSpan.FromMilliseconds(500));
    run = agentClient.Runs.GetRun(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued
    || run.Status == RunStatus.InProgress);

// Confirm that the run completed successfully
if (run.Status != RunStatus.Completed)
{
    throw new Exception("Run did not complete successfully, error: " + run.LastError?.Message);
}

// Retrieve the messages from the agent client
Pageable<PersistentThreadMessage> messages = agentClient.Messages.GetMessages(
    threadId: thread.Id,
    order: ListSortOrder.Ascending
);

// Process messages in order
foreach (PersistentThreadMessage 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)
        {
            // We need to annotate only Agent messages.
            if (threadMessage.Role == MessageRole.Agent && textItem.Annotations.Count > 0)
            {
                string annotatedText = textItem.Text;

                // If we have Text URL citation annotations, reformat the response to show title & URL for citations
                foreach (MessageTextAnnotation annotation in textItem.Annotations)
                {
                    if (annotation is MessageTextUriCitationAnnotation urlAnnotation)
                    {
                        annotatedText = annotatedText.Replace(
                            urlAnnotation.Text,
                            $" [see {urlAnnotation.UriCitation.Title}] ({urlAnnotation.UriCitation.Uri})");
                    }
                }
                Console.Write(annotatedText);
            }
            else
            {
                Console.Write(textItem.Text);
            }
        }
        else if (contentItem is MessageImageFileContent imageFileItem)
        {
            Console.Write($"<image from ID: {imageFileItem.FileId}");
        }
        Console.WriteLine();
    }
}

Secara opsional menghasilkan langkah-langkah eksekusi yang digunakan oleh agen

// Retrieve the run steps used by the agent and print those to the console
Console.WriteLine("Run Steps used by Agent:");
Pageable<RunStep> runSteps = agentClient.Runs.GetRunSteps(run);

foreach (var step in runSteps)
{
    Console.WriteLine($"Step ID: {step.Id}, Total Tokens: {step.Usage.TotalTokens}, Status: {step.Status}, Type: {step.Type}");

    if (step.StepDetails is RunStepMessageCreationDetails messageCreationDetails)
    {
        Console.WriteLine($"   Message Creation Id: {messageCreationDetails.MessageCreation.MessageId}");
    }
    else if (step.StepDetails is RunStepToolCallDetails toolCallDetails)
    {
        // We know this agent only has the AI Search tool, so we can cast it directly
        foreach (RunStepAzureAISearchToolCall toolCall in toolCallDetails.ToolCalls)
        {
            Console.WriteLine($"   Tool Call Details: {toolCall.GetType()}");

            foreach (var result in toolCall.AzureAISearch)
            { 
                Console.WriteLine($"      {result.Key}: {result.Value}");
            }
        }
    }
}

Membersihkan sumber daya

Bersihkan sumber daya dari sampel ini.

// Clean up resources
agentClient.Threads.DeleteThread(thread.Id);
agentClient.Administration.DeleteAgent(agent.Id);

Membuat Klien Azure AI

Pertama, buat Klien Azure AI menggunakan titik akhir proyek Anda.

const projectEndpoint = process.env["PROJECT_ENDPOINT"];

if (!projectString) {
  throw new Error("AZURE_AI_PROJECTS_CONNECTION_STRING must be set in the environment variables");
}

const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());

Mengonfigurasi alat Pencarian Azure AI

Dengan menggunakan ID koneksi sumber daya Azure AI Search, konfigurasikan alat Azure AI Search untuk menggunakan indeks Azure AI Search Anda.

const connectionId = process.env["AZURE_AI_CONNECTION_ID"] || "<connection-name>";

const azureAISearchTool = ToolUtility.createAzureAISearchTool(connectionId, "ai-search-sample", {
    queryType: "simple",
    topK: 3,
    filter: "",
    indexConnectionId: "",
    indexName: "",
  });

Membuat agen dengan alat Pencarian Azure AI diaktifkan

Ubah model ke yang di-deploy dalam proyek Anda. Anda dapat menemukan nama model di Azure AI Foundry di bawah tab Model . Anda juga dapat mengubah nama dan instruksi agen agar sesuai dengan kebutuhan Anda.


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}`);

Ajukan pertanyaan agen tentang data dalam indeks

Sekarang setelah agen dibuat, ajukan pertanyaan tentang data di indeks Azure AI Search Anda.

// Create thread for communication
  const thread = await client.threads.create();
  console.log(`Created thread, thread ID: ${thread.id}`);

// Create message to thread
const message = await client.messages.create(
  thread.id,
  "user",
  "What is the temperature rating of the cozynights sleeping bag?",
);
console.log(`Created message, message ID : ${message.id}`);

// Create and process agent run in thread with tools
let run = await client.runs.create(thread.id, agent.id);
while (run.status === "queued" || run.status === "in_progress") {
  await delay(1000);
  run = await client.runs.get(thread.id, run.id);
}
if (run.status === "failed") {
  console.log(`Run failed:`, JSON.stringify(run, null, 2));
}
console.log(`Run finished with status: ${run.status}`);

// Fetch run steps to get the details of agent run
const runSteps = await client.runSteps.list(thread.id, run.id);

for await (const step of runSteps) {
  console.log(`Step ID: ${step.id}, Status: ${step.status}`);
  const stepDetails = step.stepDetails;
  if (isOutputOfType(stepDetails, "tool_calls")) {
    const toolCalls = stepDetails.toolCalls;
    for (const toolCall of toolCalls) {
      console.log(`Tool Call ID: ${toolCall.id}, Tool type: ${toolCall.type}`);
      if (isOutputOfType(toolCall, "azure_ai_search")) {
        {
          const azureAISearch = toolCall.azureAISearch;
          if (azureAISearch) {
            console.log(`Azure AI Search Tool Call input: ${azureAISearch.input}`);
            console.log(`Azure AI Search Tool Call output: ${azureAISearch.output}`);
          }
        }
      }
    }
  }
}
// Delete the assistant when done
await client.deleteAgent(agent.id);
console.log(`Deleted agent, agent ID: ${agent.id}`);

// Fetch and log all messages
const messagesIterator = client.messages.list(thread.id);
console.log(`Messages:`);

// Get the first message
for await (const m of messagesIterator) {
  if (m.content.length > 0) {
    const agentMessage = m.content[0];
    if (isOutputOfType(agentMessage, "text")) {
      const textContent = agentMessage;
      console.log(`Text Message Content - ${textContent.text.value}`);
    }
  }
  break; // Just process the first message
}

Ikuti Mulai Cepat REST API untuk mengatur nilai yang tepat untuk AGENT_TOKEN variabel lingkungan, AZURE_AI_FOUNDRY_PROJECT_ENDPOINT, dan API_VERSION.

Mendapatkan ID koneksi untuk sumber daya Pencarian Azure AI

Untuk mendapatkan ID koneksi, navigasikan ke proyek di Azure AI Foundry dan klik tab Sumber daya tersambung lalu pilih sumber daya Azure AI Search Anda.

Cuplikan layar halaman koneksi sumber daya Pencarian AI di Azure AI Foundry.

Di URL, Anda melihat wsid=/subscription/your-subscription-id..., ini adalah ID koneksi yang perlu Anda gunakan. Salin semua yang muncul setelah wsid=.

Cuplikan layar koneksi sumber daya Pencarian AI dan cara menyalin ID koneksi.

Mengonfigurasi alat Pencarian Azure AI

Dengan menggunakan ID koneksi yang Anda dapatkan di langkah sebelumnya, Anda sekarang dapat mengonfigurasi alat Pencarian Azure AI untuk menggunakan indeks Pencarian Azure AI Anda.

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/assistants?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
        "instructions": "You are a helpful agent.",
        "name": "my-agent",
        "tools": [
          {"type": "azure_ai_search"}
        ],
        "model": "gpt-4o-mini",
        "tool_resources": {
            "azure_ai_search": {
              "indexes": [
                  {
                      "index_connection_id": "/subscriptions/<your-subscription-id>/resourceGroups/<your-resource-group>/providers/Microsoft.MachineLearningServices/workspaces/<your-project-name>/connections/<your-azure-ai-search-connection-name>",
                      "index_name": "<your-index-name>",
                      "query_type": "semantic"
                  }
              ]
            }
        }
      }'

Ajukan pertanyaan agen tentang data dalam indeks

Sekarang setelah agen dibuat, ajukan pertanyaan tentang data di indeks Azure AI Search Anda.

Buat utas

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d ''

Tambahkan pertanyaan pengguna ke topik

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/messages?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
      "role": "user",
      "content": "what are my health insurance plan coverage types?"
    }'

Jalankan thread

curl --request POST \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/runs?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "assistant_id": "asst_abc123",
  }'

Mengambil status proses

curl --request GET \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/runs/run_abc123?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN"

Dapatkan respons agen

curl --request GET \
  --url $AZURE_AI_FOUNDRY_PROJECT_ENDPOINT/threads/thread_abc123/messages?api-version=$API_VERSION \
  -H "Authorization: Bearer $AGENT_TOKEN"