次の方法で共有


Bing検索で Grounding を使用する方法

この記事を使用して、Bing検索を使用した Grounding の詳細な手順とコード サンプルを見つけます。

[前提条件]

  • 接続された Bing Custom Search を使用した典拠リソース
  • 接続 ID は次の形式である必要があります。 /subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/Microsoft.CognitiveServices/accounts/<ai_service_name>/projects/<project_name>/connections/<connection_name>

Von Bedeutung

Bing検索結果で Grounding を表示するための要件があります。 詳細については、 概要に 関する記事を参照してください。

  1. Azure AI Foundry ポータルエージェント画面に移動し、右側の[セットアップ]ペインを下にスクロールして知識へ移動します。 その後、追加を選択します。

    Azure AI Foundry ポータルで使用できるツール カテゴリを示すスクリーンショット。

  2. [Bing Search を使用したグラウンディング] を選択し、プロンプトに従ってツールを追加します。 エージェントごとに追加できるのは 1 つのみであることに注意してください。

    Azure AI Foundry ポータルで使用できるナレッジ ツールを示すスクリーンショット。

  3. クリックして新しい接続を追加します。 接続を追加したら、既存の一覧から直接選択できます。

    新しい接続を作成するためのボタンを示すスクリーンショット。

  4. 使用する Bing Search を使用したグラウンディング リソースを選択し、クリックして接続を追加します。

    Grounding with Bing Search の使用可能な接続を示すスクリーンショット。

プロジェクト クライアントを作成する

クライアント オブジェクトを作成します。このオブジェクトには、AI プロジェクトやその他のリソースに接続するためのエンドポイントが含まれます。

import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from azure.ai.agents.models import BingGroundingTool

# Create an Azure AI Client from an endpoint, copied from your Azure AI Foundry project.
# You need to login to Azure subscription via Azure CLI and set the environment variables
project_endpoint = os.environ["PROJECT_ENDPOINT"]  # Ensure the PROJECT_ENDPOINT environment variable is set

# Create an AIProjectClient instance
project_client = AIProjectClient(
    endpoint=project_endpoint,
    credential=DefaultAzureCredential(),  # Use Azure Default Credential for authentication
    api_version="latest",
)

Bing検索ツールを有効にして Grounding を使用してエージェントを作成する

Bing 検索を使用したグラウンディング ツールをエージェントに利用できるようにするには、接続を使用してツールを初期化し、エージェントにアタッチします。 接続は、Azure AI Foundry ポータルのプロジェクトの接続済みリソース セクションで確認できます。

conn_id = os.environ["BING_CONNECTION_NAME"]  # Ensure the BING_CONNECTION_NAME environment variable is set

# Initialize the Bing Grounding tool
bing = BingGroundingTool(connection_id=conn_id)

with project_client:
    # Create an agent with the Bing Grounding tool
    agent = project_client.agents.create_agent(
        model=os.environ["MODEL_DEPLOYMENT_NAME"],  # Model deployment name
        name="my-agent",  # Name of the agent
        instructions="You are a helpful agent",  # Instructions for the agent
        tools=bing.definitions,  # Attach the Bing Grounding tool
    )
    print(f"Created agent, ID: {agent.id}")

スレッドを作成する

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

# Add a message to the thread
message = project_client.agents.messages.create(
    thread_id=thread.id,
    role="user",  # Role of the message sender
    content="What is the weather in Seattle today?",  # Message content
)
print(f"Created message, ID: {message['id']}")

実行を作成して出力を確認する

実行を作成し、モデルが Grounding with Bing Search ツールを使用してユーザーの質問に応答することを確認します。

# Create and process an agent run
run = project_client.agents.runs.create_and_process(
    thread_id=thread.id,
    agent_id=agent.id,
    # tool_choice={"type": "bing_grounding"}  # optional, you can force the model to use Grounding with Bing Search tool
)
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
messages = project_client.agents.messages.list(thread_id=thread.id)
for message in messages:
    print(f"Role: {message.role}, Content: {message.content}")

必要に応じて、エージェントで使用される実行手順を出力します

run_steps = project_client.agents.run_steps.list(thread_id=thread.id, run_id=run.id)
for step in run_steps:
    print(f"Step {step['id']} status: {step['status']}")

    # Check if there are tool calls in the step details
    step_details = step.get("step_details", {})
    tool_calls = step_details.get("tool_calls", [])

    if tool_calls:
        print("  Tool calls:")
        for call in tool_calls:
            print(f"    Tool Call ID: {call.get('id')}")
            print(f"    Type: {call.get('type')}")

            function_details = call.get("function", {})
            if function_details:
                print(f"    Function name: {function_details.get('name')}")
    print()  # add an extra newline between steps

完了したらエージェントを削除する

project_client.agents.delete_agent(agent.id)
print("Deleted agent")

プロジェクト クライアントを作成する

クライアント オブジェクトを作成します。このオブジェクトには、AI プロジェクトやその他のリソースに接続するためのプロジェクト エンドポイントが含まれます。

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 bingConnectionId = configuration["BingConnectionId"];

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

Bing検索ツールを有効にして Grounding を使用してエージェントを作成する

Bing 検索を使用したグラウンディング ツールをエージェントに利用できるようにするには、接続を使用してツールを初期化し、エージェントにアタッチします。 接続は、Azure AI Foundry ポータルのプロジェクトの接続済みリソース セクションで確認できます。

BingGroundingSearchConfiguration searchConfig = new BingGroundingSearchConfiguration(bingConnectionId)
{ 
    Count = 5,
    Freshness = "Week"
};

// Create the BingGroundingToolDefinition object used when creating the agent
BingGroundingToolDefinition bingGroundingTool = new BingGroundingToolDefinition(
    new BingGroundingSearchToolParameters(
        [
            searchConfig
        ]
    )
);

// Create the Agent
PersistentAgent agent = agentClient.Administration.CreateAgent(
    model: modelDeploymentName,
    name: "my-agent",
    instructions: "Use the bing grounding tool to answer questions.",
    tools: [bingGroundingTool]
);

スレッドを作成して実行する

PersistentAgentThread thread = agentClient.Threads.CreateThread();

// Create message and run the agent
PersistentThreadMessage message = agentClient.Messages.CreateMessage(
    thread.Id,
    MessageRole.User,
    "How does wikipedia explain Euler's Identity?");
ThreadRun run = agentClient.Runs.CreateRun(thread, agent);

エージェントが完了するのを待ち、出力を出力します

まず、エージェントの状態をポーリングして実行が完了するまで待ちます。 モデルがユーザーの質問に対する回答を提供するために [Grounding with Bing Search] ツールを使用していることを観察してください。

// 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 all 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)
        {
            string response = textItem.Text;

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

必要に応じて、エージェントで使用される実行手順を出力します

// 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 Bing Grounding tool, so we can cast it directly
        foreach (RunStepBingGroundingToolCall toolCall in toolCallDetails.ToolCalls)
        {
            Console.WriteLine($"   Tool Call Details: {toolCall.GetType()}");

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

リソースをクリーンアップする

このサンプルのリソースをクリーンアップします。

// Delete thread and agent
agentClient.Threads.DeleteThread(threadId: thread.Id);
agentClient.Administration.DeleteAgent(agentId: agent.Id);

プロジェクト クライアントを作成する

クライアント オブジェクトを作成します。このオブジェクトには、AI プロジェクトやその他のリソースに接続するためのエンドポイントが含まれます。

const { AgentsClient, ToolUtility, isOutputOfType } = require("@azure/ai-agents");
const { delay } = require("@azure/core-util");
const { DefaultAzureCredential } = require("@azure/identity");

require("dotenv/config");

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

// Create an Azure AI Client
const client = new AgentsClient(projectEndpoint, new DefaultAzureCredential());

Bing検索ツールを有効にして Grounding を使用してエージェントを作成する

Bing 検索を使用したグラウンディング ツールをエージェントに利用できるようにするには、接続を使用してツールを初期化し、エージェントにアタッチします。 接続は、Azure AI Foundry ポータルのプロジェクトの接続済みリソース セクションで確認できます。


const connectionId = process.env["AZURE_BING_CONNECTION_ID"] || "<connection-name>";
// Initialize agent bing tool with the connection id
const bingTool = ToolUtility.createBingGroundingTool([{ connectionId: connectionId }]);

// Create agent with the bing tool and process assistant run
const agent = await client.createAgent("gpt-4o", {
  name: "my-agent",
  instructions: "You are a helpful agent",
  tools: [bingTool.definition],
});
console.log(`Created agent, agent ID : ${agent.id}`);

スレッドを作成する

// 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",
  "How does wikipedia explain Euler's Identity?",
);
console.log(`Created message, message ID : ${message.id}`);

実行を作成して出力を確認する

実行を作成し、モデルが Grounding with Bing Search ツールを使用してユーザーの質問に応答することを確認します。


// 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: ${run.lastError?.message}`);
}
console.log(`Run finished with status: ${run.status}`);

// 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
const firstMessage = await messagesIterator.next();
if (!firstMessage.done && firstMessage.value) {
  const agentMessage = firstMessage.value.content[0];
  if (isOutputOfType(agentMessage, "text")) {
    const textContent = agentMessage;
    console.log(`Text Message Content - ${textContent.text.value}`);
  }
}

Von Bedeutung

  1. この REST API を使用すると、開発者は Azure AI Foundry Agent サービスを使用して Bing Search ツールを使用して Grounding を呼び出すことができます。 Bing Search API を使用した Grounding への呼び出しは直接送信されません。

REST API クイック スタートに従って、環境変数のAGENT_TOKENAZURE_AI_FOUNDRY_PROJECT_ENDPOINTAPI_VERSIONに適切な値を設定します。

Bing検索ツールを有効にして Grounding を使用してエージェントを作成する

Bing 検索を使用したグラウンディング ツールをエージェントに利用できるようにするには、接続を使用してツールを初期化し、エージェントにアタッチします。 接続は、Azure AI Foundry ポータルのプロジェクトの接続済みリソース セクションで確認できます。

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",
        "model": "gpt-4o",
        "tools": [
          {
            "type": "bing_grounding",
            "bing_grounding": {
                "search_configurations": [
                    {
                        "connection_id": "<your_connection_id>",
                        "count": 7, 
                        "market": "en-US", 
                        "set_lang": "en", 
                        "freshness": "7d",
                    }
                ]
            }
          }
        ]
      }'

スレッドを作成する

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 ''

ユーザーの質問をスレッドに追加する

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 is the weather in Seattle?"
    }'

実行を作成して出力を確認する

実行を作成し、モデルが Grounding with Bing Search ツールを使用してユーザーの質問に応答することを確認します。

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",
  }'

実行の状態を取得する

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

エージェントの応答を取得する

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

次のステップ

Bing 検索を使用したグラウンディングの完全なサンプルを参照してください。