你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
按照本文查找“使用必应搜索提供事实依据”的分步说明和代码示例。
先决条件
- 一个已连接的“使用必应搜索提供事实依据”资源。
- 连接 ID 需要采用以下格式:
/subscriptions/<subscription_id>/resourceGroups/<resource_group_name>/providers/Microsoft.CognitiveServices/accounts/<ai_service_name>/projects/<project_name>/connections/<connection_name>
重要
需要满足一定的要求才能显示“使用必应搜索提供事实依据”结果。 有关详细信息,请参阅 概述文章 。
在 Azure AI Foundry 门户中,导航到代理的“代理”屏幕,向下滚动“知识”右侧的“设置”窗格。 然后选择“添加”。
选择“使用必应搜索查找事实依据”,然后按照提示添加该工具。 请注意,每个代理只能添加一个。
单击可添加新连接。 添加连接后,可以直接从现有列表中选择。
选择要使用的“使用必应搜索查找事实依据”资源,然后单击以添加连接。
创建项目客户端
创建一个客户端对象,该对象将包含用于连接到 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",
)
创建已启用“使用必应搜索提供事实依据”工具的代理
要使“使用必应搜索查找事实依据”工具可供代理使用,请使用连接来初始化该工具并将其附加到代理。 可以在 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']}")
创建运行并检查输出
创建运行并观察模型是否使用“使用必应搜索查找事实依据”工具来响应用户的问题。
# 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());
创建已启用“使用必应搜索提供事实依据”工具的代理
要使“使用必应搜索查找事实依据”工具可供代理使用,请使用连接来初始化该工具并将其附加到代理。 可以在 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);
等待代理完成并打印输出
首先,通过轮询代理的状态,等待代理完成运行。 观察模型是否使用“使用必应搜索提供事实依据”工具来响应用户的问题。
// 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());
创建已启用“使用必应搜索提供事实依据”工具的代理
要使“使用必应搜索查找事实依据”工具可供代理使用,请使用连接来初始化该工具并将其附加到代理。 可以在 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}`);
创建运行并检查输出
创建运行并观察模型是否使用“使用必应搜索查找事实依据”工具来响应用户的问题。
// 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}`);
}
}
重要
- 此 REST API 允许开发人员通过 Azure AI Foundry 代理服务调用必应搜索工具中的 Grounding 功能。 它不会直接通过必应搜索 API 向 Grounding 发送请求。
请按照 REST API 快速入门 为环境变量 AGENT_TOKEN
、AZURE_AI_FOUNDRY_PROJECT_ENDPOINT
和 API_VERSION
设置正确的值。
创建已启用“使用必应搜索提供事实依据”工具的代理
要使“使用必应搜索查找事实依据”工具可供代理使用,请使用连接来初始化该工具并将其附加到代理。 可以在 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?"
}'
创建运行并检查输出
创建运行并观察模型是否使用“使用必应搜索查找事实依据”工具来响应用户的问题。
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"