Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Lo strumento di ricerca Web nel servizio agenti di Foundry consente al modello Foundry dell'agente di recuperare e integrare le risposte con informazioni in tempo reale dal Web pubblico prima di generare l'output. Se abilitato, il modello può restituire up-to-date risposte con citazioni inline, consentendo di creare agenti che forniscono informazioni attuali e effettive agli utenti.
Importante
- Ricerca Web usa il Grounding con Ricerca Bing e/o il Grounding con Ricerca personalizzata Bing, entrambi servizi a consumo proprietari regolamentati dalle Condizioni per l'utilizzo del Grounding con Bing e dall'Informativa sulla privacy di Microsoft.
- Il Microsoft Data Protection Addendum non si applica ai dati inviati a Grounding con Ricerca Bing e Grounding con Ricerca personalizzata Bing. Quando si usa Grounding con Bing Search e Grounding con Bing Custom Search; i trasferimenti di dati si verificano al di fuori della conformità e dei limiti geografici.
- L'uso di Grounding con Ricerca Bing e di Grounding con Ricerca personalizzata Bing comporta dei costi. Per informazioni dettagliate, vedere i prezzi .
- Vedere la sezione management per informazioni su come gli amministratori Azure possono gestire l'accesso all'uso della ricerca Web.
Tip
Prendere in considerazione l'aggiunta di questo strumento usando una casella degli strumenti. Usando una casella degli strumenti, è possibile riutilizzare lo strumento tra agenti e runtime, nonché centralizzare la gestione delle credenziali, il controllo delle versioni e l'imposizione dei criteri tramite un endpoint MCP gestito. Consulta la guida introduttiva di Toolbox.
Supporto per l'utilizzo
La tabella seguente illustra il supporto dell'SDK e della configurazione.
| Supporto Foundry di Microsoft | PYTHON SDK | SDK di C# | JavaScript SDK | JAVA SDK | REST API | Configurazione dell'agente di base | Configurazione dell'agente standard |
|---|---|---|---|---|---|---|---|
| ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ | ✔️ |
Prerequisiti
Pacchetto SDK più recente. L'SDK di .NET è attualmente in anteprima. Per informazioni dettagliate, vedere la guida introduttiva .
ruolo Foundry User nel progetto Foundry per creare ed eseguire agenti.
Importante
I ruoli di Controllo degli accessi in base al ruolo di Foundry sono stati recentemente rinominati. Foundry User, Foundry Owner, Foundry Account Owner e Foundry Project Manager erano precedentemente denominati Azure AI User, Azure AI Owner, Azure AI Account Owner e Azure AI Project Manager. È possibile che i nomi precedenti vengano visualizzati in alcune posizioni durante l'esecuzione della ridenominazione. Gli ID ruolo e le autorizzazioni di base sono invariati dalla ridenominazione.
Ruolo Project Manager Foundry nel progetto Foundry se si crea la connessione del progetto remote-tool per la ricerca con restrizioni di dominio.
Azure credenziali configurate per l'autenticazione, ad esempio
DefaultAzureCredential.URL dell'endpoint del progetto Foundry e nome dell'implementazione del modello.
Scegli uno scenario di grounding web
| Scenario | Da scegliere per | Iniziare da qui |
|---|---|---|
| Ricerca Web generale | L'agente necessita di informazioni aggiornate dal Web pubblico senza una risorsa o una connessione di progetto Bing separata. | Aggiungere la ricerca Web direttamente a un agente di prompt. |
| Ricerca personalizzata Bing con restrizioni di dominio | I risultati della ricerca devono provenire da domini pubblici configurati nell'istanza di Ricerca personalizzata Bing. | Configurare la ricerca con restrizioni di dominio. |
| Ricerca approfondita | Il tuo agente o3-deep-research ha bisogno di ricerca e sintesi in più fasi. |
Usare la ricerca web diretta per una ricerca approfondita. |
| Strumenti di base Bing | È necessario il tipo di strumento esplicito bing_grounding o bing_custom_search_preview per una connessione a un progetto Bing. |
Usare gli strumenti Grounding con Ricerca Bing. |
Aggiungere la ricerca Web direttamente a un agente
Inizia con la scheda Prompt Agents. Questa scheda aggiunge WebSearchTool direttamente a un agente lato server e non richiede un toolbox né una connessione separata a un progetto Bing. Questo percorso offre il modo più rapido per ottenere una risposta fondata corredata di citazioni.
La scheda Agenti ospitati usa WebSearchToolboxTool per aggiungere la ricerca Web a una casella degli strumenti, quindi si connette all'endpoint MCP della casella degli strumenti. Mantieni separati i tipi direct-agent e toolbox perché si applicano a diverse interfacce API.
Nota
Per informazioni sull'ottimizzazione dell'utilizzo degli strumenti, vedere Procedure consigliate.
Ricerca Web generale
Nell'esempio seguente viene illustrato come concedere a un agente l'accesso alla ricerca Web. Selezionare Prompt Agents per usare Azure AI Projects SDK per creare un agente prompt sul lato server o Hosted Agents per usare Agent Framework FoundryChatClient per creare un agente temporaneo in-process.
Agenti rapidi
Creare l'agente ed eseguire una ricerca
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
PromptAgentDefinition,
WebSearchTool,
WebSearchApproximateLocation,
)
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Create an agent with the web search tool
agent = project.agents.create_version(
agent_name="MyAgent",
definition=PromptAgentDefinition(
model="gpt-5-mini",
instructions="You are a helpful assistant that can search the web",
tools=[
WebSearchTool(
user_location=WebSearchApproximateLocation(
country="GB", city="London", region="London"
)
)
],
),
description="Agent for web search.",
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
# Send a query and stream the response
stream_response = openai.responses.create(
stream=True,
tool_choice="required",
input="What is today's date and weather in Seattle?",
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
# Process streaming events
for event in stream_response:
if event.type == "response.created":
print(f"Follow-up response created with ID: {event.response.id}")
elif event.type == "response.output_text.delta":
print(f"Delta: {event.delta}")
elif event.type == "response.output_text.done":
print(f"\nFollow-up response done!")
elif event.type == "response.output_item.done":
if event.item.type == "message":
item = event.item
if item.content[-1].type == "output_text":
text_content = item.content[-1]
for annotation in text_content.annotations:
if annotation.type == "url_citation":
print(f"URL Citation: {annotation.url}")
elif event.type == "response.completed":
print(f"\nFollow-up completed!")
print(f"Full response: {event.response.output_text}")
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Agent deleted")
Output previsto
Agent created: <agent-name> (version 1)
Response: The latest trends in renewable energy include ...
URL Citation: https://example.com/source
Follow-up completed!
Full response: Based on current data ...
Agent deleted
Agenti ospitati
Questo esempio usa FoundryChatClient da Microsoft Agent Framework e si connette all'endpoint MCP della casella degli strumenti usando FoundryToolbox. Installare il pacchetto con pip install agent-framework-foundry, impostare le FOUNDRY_PROJECT_ENDPOINT variabili di ambiente e FOUNDRY_MODEL e accedere con az login. Per il modello completo della casella degli strumenti dell'agente ospitato, vedere l'esempio completo.
Creare una casella degli strumenti ed eseguire un agente ospitato
import asyncio
from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient, FoundryToolbox
from azure.identity import AzureCliCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import WebSearchToolboxTool, WebSearchApproximateLocation
PROJECT_ENDPOINT = "https://<account>.services.ai.azure.com/api/projects/<project>"
async def main() -> None:
credential = AzureCliCredential()
# 1. Create the web search tool and add it to a toolbox. Using a toolbox is the
# recommended way to give agents tools: curate tools once and reuse the
# toolbox across agents. See /azure/foundry/agents/concepts/toolbox-overview
project = AIProjectClient(endpoint=PROJECT_ENDPOINT, credential=credential)
toolbox = project.toolboxes.create_version(
name="web-search-toolbox",
description="Toolbox with the web search tool",
tools=[
WebSearchToolboxTool(
user_location=WebSearchApproximateLocation(
country="GB", city="London", region="London"
)
)
],
)
# 2. The toolbox exposes an MCP-compatible endpoint.
TOOLBOX_MCP_URL = (
f"{PROJECT_ENDPOINT}/toolboxes/{toolbox.name}"
f"/versions/{toolbox.version}/mcp?api-version=v1"
)
# 3. Attach the toolbox to the hosted agent as an MCP tool.
, timeout=120.0)
toolbox_tool = FoundryToolbox(credential, url=TOOLBOX_MCP_URL)
agent = Agent(
client=FoundryChatClient(credential=credential),
instructions="You are a research assistant. Use web search to find current information.",
tools=[toolbox_tool],
)
result = await agent.run("What are the latest updates to Microsoft Foundry?")
print(f"Agent: {result.text}")
# Print any URL citations returned by the web search tool.
for message in result.messages:
for content in message.contents:
for annotation in getattr(content, "annotations", None) or []:
url = getattr(annotation, "url", None)
if url:
title = getattr(annotation, "title", None) or ""
print(f"URL Citation: [{title}]({url})")
if __name__ == "__main__":
asyncio.run(main())
Output previsto
L'agente risponde usando informazioni aggiornate dal Web e stampa tutte le citazioni URL restituite dallo strumento. L'output varia in base alle modifiche apportate al contenuto sul Web:
Agent: The latest updates to Microsoft Foundry include ...
URL Citation: [Microsoft Foundry documentation](https://learn.microsoft.com/azure/ai-foundry/)
Lo strumento di ricerca web viene eseguito sul lato server nella Foundry Responses API. È possibile combinarlo con gli strumenti di funzione locali aggiungendo voci aggiuntive (ad esempio, una @toolfunzione decorata) all'elenco tools . Per ulteriori informazioni, vedere Avvio rapido: Usa l'API Responses di Foundry.
Ricerca con restrizioni di dominio con Ricerca personalizzata Bing
L'esempio seguente illustra come limitare la ricerca Web a domini specifici usando un'istanza di Ricerca personalizzata Bing. Questo approccio consente di controllare i siti Web che l'agente può cercare.
Creare la casella degli strumenti e l'agente con restrizioni di dominio
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import (
PromptAgentDefinition,
WebSearchToolboxTool,
WebSearchConfiguration,
MCPTool,
)
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
BING_CUSTOM_SEARCH_CONNECTION_ID = "your_bing_custom_search_connection_id"
BING_CUSTOM_SEARCH_INSTANCE_NAME = "your_bing_custom_search_instance_name"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# 1. Add the web search tool and custom search configuration to a toolbox.
toolbox = project.toolboxes.create_version(
name="web-search-toolbox",
description="Toolbox with the web search tool",
tools=[
WebSearchToolboxTool(
custom_search_configuration=WebSearchConfiguration(
project_connection_id=BING_CUSTOM_SEARCH_CONNECTION_ID,
instance_name=BING_CUSTOM_SEARCH_INSTANCE_NAME,
)
)
],
)
# 2. The toolbox exposes an MCP-compatible endpoint.
TOOLBOX_MCP_URL = (
f"{PROJECT_ENDPOINT}/toolboxes/{toolbox.name}"
f"/versions/{toolbox.version}/mcp?api-version=v1"
)
# 3. Create a remote-tool project connection that points at the toolbox endpoint.
# Use a user Entra token so the caller's identity is passed through
# (audience https://ai.azure.com). Create the connection once, for example with
# the Azure Developer CLI:
#
# azd ai connection create web-search-toolbox-conn \
# --kind remote-tool \
# --target "<TOOLBOX_MCP_URL>" \
# --auth-type user-entra-token \
# --audience https://ai.azure.com
TOOLBOX_CONNECTION_NAME = "web-search-toolbox-conn"
# 4. Attach the toolbox to a prompt agent as an MCP tool.
agent = project.agents.create_version(
agent_name="MyAgent",
definition=PromptAgentDefinition(
model="gpt-5-mini",
instructions="You are a helpful assistant that can search the web",
tools=[
MCPTool(
server_label="toolbox",
server_url=TOOLBOX_MCP_URL,
require_approval="never",
project_connection_id=TOOLBOX_CONNECTION_NAME,
)
],
),
description="Agent for domain-restricted web search.",
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
# Send a query and stream the response
stream_response = openai.responses.create(
stream=True,
tool_choice="required",
input="What are the latest updates from Microsoft Learn?",
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
# Process streaming events
for event in stream_response:
if event.type == "response.created":
print(f"Response created with ID: {event.response.id}")
elif event.type == "response.output_text.delta":
print(f"Delta: {event.delta}")
elif event.type == "response.output_text.done":
print(f"\nResponse done!")
elif event.type == "response.output_item.done":
if event.item.type == "message":
item = event.item
if item.content[-1].type == "output_text":
text_content = item.content[-1]
for annotation in text_content.annotations:
if annotation.type == "url_citation":
print(f"URL Citation: {annotation.url}")
elif event.type == "response.completed":
print(f"\nResponse completed!")
print(f"Full response: {event.response.output_text}")
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Agent deleted")
Output previsto
Agent created (id: abc123, name: MyAgent, version: 1)
Response created with ID: resp_456
Delta: Based on your custom search ...
Response done!
URL Citation: https://your-allowed-domain.com/article
Response completed!
Full response: Based on your custom search ...
Agent deleted
Suggerimenti per la ricerca con restrizioni di dominio
Grounding con Ricerca personalizzata Bing è uno strumento potente che è possibile utilizzare per selezionare un sottospazio del Web per limitare le conoscenze di base dell'agente. Ecco alcuni suggerimenti per sfruttare al meglio questa funzionalità:
- Se si è proprietari di un sito pubblico che si vuole includere nella ricerca, ma che Bing non ha indicizzato, consultare le Linee guida per i Webmaster di Bing per informazioni dettagliate su come ottenere l'indicizzazione del sito. La documentazione per i webmaster fornisce anche informazioni dettagliate su come fare in modo che Bing esegua la scansione del tuo sito se l'indice non è aggiornato.
- Per creare una configurazione, attivare appena in tempo il ruolo Collaboratore nella risorsa Bing Custom Search tramite Microsoft Entra PIM. Disattivare il ruolo dopo la configurazione. Gli sviluppatori dell'agente quotidiano e gli utenti di runtime non hanno bisogno di questo ruolo.
- È possibile bloccare determinati domini ed eseguire una ricerca sul resto del Web (ad esempio il sito di un concorrente).
- Grounding con Ricerca personalizzata Bing restituisce solo risultati per domini e pagine Web pubblici e indicizzati da Bing.
- È possibile specificare diversi livelli di granularità:
- Dominio (ad esempio,
https://www.microsoft.com) - Dominio e percorso (ad esempio,
https://www.microsoft.com/surface) - Pagina Web (ad esempio,
https://www.microsoft.com/en-us/p/surface-earbuds/8r9cpq146064)
- Dominio (ad esempio,
Ricerca approfondita con la ricerca Web
Nell'esempio seguente viene illustrato come usare il o3-deep-research modello con lo strumento di anteprima della ricerca Web diretta. Questo approccio sostituisce lo strumento Deep Research deprecato. Non indirizzare la ricerca Web tramite una casella degli strumenti di ricerca approfondita perché il modello richiede lo strumento di ricerca Web di risposte dirette.
Creare l'agente di ricerca approfondita
from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient
from azure.ai.projects.models import PromptAgentDefinition, WebSearchPreviewTool
# Format: "https://resource_name.ai.azure.com/api/projects/project_name"
PROJECT_ENDPOINT = "your_project_endpoint"
# Create clients to call Foundry API
project = AIProjectClient(
endpoint=PROJECT_ENDPOINT,
credential=DefaultAzureCredential(),
)
openai = project.get_openai_client()
# Create a prompt agent with the direct web search preview tool.
agent = project.agents.create_version(
agent_name="MyDeepResearchAgent",
definition=PromptAgentDefinition(
model="o3-deep-research",
instructions="You are a helpful assistant that can search the web",
tools=[WebSearchPreviewTool()],
),
description="Agent for deep research with web search.",
)
print(f"Agent created (id: {agent.id}, name: {agent.name}, version: {agent.version})")
# Create a conversation for the agent interaction
conversation = openai.conversations.create()
print(f"Created conversation (id: {conversation.id})")
# Send a query to search the web
stream_response = openai.responses.create(
stream=True,
conversation=conversation.id,
input="What are the latest advancements in quantum computing?",
extra_body={"agent_reference": {"name": agent.name, "type": "agent_reference"}},
)
# Process streaming events as they arrive
for event in stream_response:
if event.type == "response.created":
print(f"Response created with ID: {event.response.id}")
elif event.type == "response.output_text.delta":
print(f"Delta: {event.delta}")
elif event.type == "response.output_text.done":
print(f"\nResponse done!")
elif event.type == "response.completed":
print(f"\nResponse completed!")
print(f"Full response: {event.response.output_text}")
# Clean up resources
project.agents.delete_version(agent_name=agent.name, agent_version=agent.version)
print("Agent deleted")
Ricerca Web generale
Nell'esempio seguente viene illustrato come concedere a un agente l'accesso alla ricerca Web. Selezionare Prompt Agents per usare Azure AI Projects SDK per creare un agente prompt sul lato server o Hosted Agents per usare Microsoft Agent Framework per creare un agente temporaneo e in-process.
Agenti rapidi
In questo esempio si usa l'agente per eseguire la ricerca Web nel percorso specificato. L'esempio in questa sezione usa chiamate sincrone. Per un esempio asincrono, vedere il codice sample nel Azure SDK per .NET repository in GitHub.
Creare l'agente ed eseguire una ricerca
using System;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
// Create project client to call Foundry API
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: new DefaultAzureCredential());
// Create an agent with the web search tool
DeclarativeAgentDefinition agentDefinition = new(model: "gpt-5-mini")
{
Instructions = "You are a helpful assistant that can search the web",
Tools = {
ResponseTool.CreateWebSearchTool(userLocation: WebSearchToolLocation.CreateApproximateLocation(
country: "GB",
city: "London",
region: "London"
)
),
}
};
AgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myAgent",
options: new(agentDefinition));
// Ask a question related to London.
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
ResponseResult response = responseClient.CreateResponse("Show me the latest London Underground service updates");
// Create the response and verify it completed.
Console.WriteLine($"Response status: {response.Status}");
Console.WriteLine(response.GetOutputText());
// Delete the created agent version.
projectClient.AgentAdministrationClient.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
Output previsto
Di seguito è riportato un esempio dell'output previsto durante l'esecuzione del codice C#:
Response status: Completed
The London Underground currently has service disruptions on ...
Agent deleted
Agenti ospitati
Questo esempio crea la casella degli strumenti di ricerca Web con Azure AI Projects SDK, quindi usa l'integrazione di Microsoft Agent Framework AddFoundryToolboxes per rendere disponibile la ricerca Web all'agente ospitato. Impostare le AZURE_AI_PROJECT_ENDPOINTvariabili di ambiente , AZURE_OPENAI_ENDPOINTe AZURE_AI_MODEL_DEPLOYMENT_NAME e accedere con az login.
Creare una casella degli strumenti ed eseguire un agente ospitato
using Azure.AI.AgentServer.Responses;
using Azure.AI.AgentServer.Responses.Models;
using Azure.AI.OpenAI;
using Azure.AI.Projects;
using Azure.AI.Extensions.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Agents.AI.Foundry.Hosting;
using Microsoft.Extensions.DependencyInjection;
using OpenAI.Chat;
const string AgentInstructions = "You are a helpful assistant that can search the web to find current information and answer questions accurately.";
const string AgentName = "WebSearchAgent";
string projectEndpoint = Environment.GetEnvironmentVariable("AZURE_AI_PROJECT_ENDPOINT")
?? "https://<account>.services.ai.azure.com/api/projects/<project>";
string openAiEndpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
string deploymentName = Environment.GetEnvironmentVariable("AZURE_AI_MODEL_DEPLOYMENT_NAME") ?? "gpt-5-mini";
DefaultAzureCredential credential = new();
// 1. Create the web search tool and add it to a toolbox. Using a toolbox is the
// recommended way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
AIProjectClient projectClient = new(
endpoint: new Uri(projectEndpoint),
tokenProvider: credential);
ProjectsAgentTool webTool = ProjectsAgentTool.AsProjectTool(
ResponseTool.CreateWebSearchTool(userLocation: WebSearchToolLocation.CreateApproximateLocation(
"GB", "London", "London")));
ToolboxVersion toolboxVersion = projectClient.AgentAdministrationClient
.GetAgentToolboxes().CreateToolboxVersion(
toolboxName: "web-search-toolbox",
tools: [webTool],
description: "Toolbox with the web search tool");
// Create the hosted agent and register the toolbox integration.
AIAgent agent = projectClient.AsAIAgent(
model: deploymentName,
instructions: "You are a helpful assistant with access to the toolbox tools.",
name: "hosted-toolbox-agent");
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddFoundryResponses(agent);
builder.Services.AddFoundryToolboxes(credential, toolboxVersion.Name);
var app = builder.Build();
app.MapFoundryResponses();
app.Run();
Output previsto
L'agente risponde usando informazioni aggiornate dal Web e stampa tutte le citazioni URL restituite dallo strumento. L'output varia in base alle modifiche apportate al contenuto sul Web:
Response: Today in Seattle it is mostly cloudy with a high near 55°F ...
Title: National Weather Service – Seattle
URL: https://www.weather.gov/sew/
L'agente ospitato si connette a un endpoint della casella degli strumenti e individua lo strumento di ricerca Web in fase di esecuzione. È possibile aggiungere altri strumenti alla casella degli strumenti senza modificare il codice dell'agente ospitato.
Ricerca Web con restrizioni di dominio
Per abilitare l'agente all'uso di Ricerca Web con Grounding con l'istanza di Ricerca personalizzata Bing.
- Creare prima di tutto il client del progetto e definire i valori usati nei passaggi successivi.
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
var projectEndpoint = "your_project_endpoint";
var modelDeploymentName = "gpt-4.1-mini";
var connectionName = "your_custom_bing_connection_name";
var customInstanceName = "your_bing_custom_search_instance_name";
AIProjectClient projectClient = new(endpoint: new Uri(projectEndpoint), tokenProvider: new DefaultAzureCredential());
- Crea un agente in grado di usare la ricerca Web su Grounding con l'istanza di Ricerca personalizzata Bing.
Esempio sincrono:
AIProjectConnection bingConnection = projectClient.Connections.GetConnection(connectionName: connectionName);
WebSearchTool webSearchTool = ResponseTool.CreateWebSearchTool();
webSearchTool.CustomSearchConfiguration = new(bingConnection.Id, customInstanceName);
DeclarativeAgentDefinition agentDefinition = new(model: modelDeploymentName)
{
Instructions = "You are a helpful agent.",
Tools = { webSearchTool }
};
AgentVersion agentVersion = projectClient.AgentAdministrationClient.CreateAgentVersion(
agentName: "myAgent",
options: new(agentDefinition));
Esempio asincrono:
AIProjectConnection bingConnection = projectClient.Connections.GetConnection(connectionName: connectionName);
WebSearchTool webSearchTool = ResponseTool.CreateWebSearchTool();
webSearchTool.CustomSearchConfiguration = new(bingConnection.Id, customInstanceName);
DeclarativeAgentDefinition agentDefinition = new(model: modelDeploymentName)
{
Instructions = "You are a helpful agent.",
Tools = { webSearchTool }
};
AgentVersion agentVersion = await projectClient.AgentAdministrationClient.CreateAgentVersionAsync(
agentName: "myAgent",
options: new(agentDefinition));
- Chiamare il
GetFormattedAnnotationmetodo per formattare l'annotazione.
private static string GetFormattedAnnotation(ResponseItem item)
{
if (item is MessageResponseItem messageItem)
{
foreach (ResponseContentPart content in messageItem.Content)
{
foreach (ResponseMessageAnnotation annotation in content.OutputTextAnnotations)
{
if (annotation is UriCitationMessageAnnotation uriAnnotation)
{
return $" [{uriAnnotation.Title}]({uriAnnotation.Uri})";
}
}
}
}
return "";
}
- Porre la domanda e trasmettere la risposta.
Esempio sincrono:
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
string annotation = "";
string text = "";
CreateResponseOptions options = new()
{
ToolChoice = ResponseToolChoice.CreateRequiredChoice(),
InputItems = { ResponseItem.CreateUserMessageItem("How many medals did the USA win in the 2024 summer olympics?") },
};
foreach (StreamingResponseUpdate streamResponse in responseClient.CreateResponseStreaming(options))
{
if (streamResponse is StreamingResponseCreatedUpdate createUpdate)
{
Console.WriteLine($"Stream response created with ID: {createUpdate.Response.Id}");
}
else if (streamResponse is StreamingResponseOutputTextDeltaUpdate textDelta)
{
Console.WriteLine($"Delta: {textDelta.Delta}");
}
else if (streamResponse is StreamingResponseOutputTextDoneUpdate textDoneUpdate)
{
text = textDoneUpdate.Text;
}
else if (streamResponse is StreamingResponseOutputItemDoneUpdate itemDoneUpdate)
{
if (annotation.Length == 0)
{
annotation = GetFormattedAnnotation(itemDoneUpdate.Item);
}
}
else if (streamResponse is StreamingResponseErrorUpdate errorUpdate)
{
throw new InvalidOperationException($"The stream has failed: {errorUpdate.Message}");
}
}
Console.WriteLine($"{text}{annotation}");
Esempio asincrono:
ProjectResponsesClient responseClient = projectClient.ProjectOpenAIClient.GetProjectResponsesClientForAgent(agentVersion.Name);
string annotation = "";
string text = "";
CreateResponseOptions options = new()
{
ToolChoice = ResponseToolChoice.CreateRequiredChoice(),
InputItems = { ResponseItem.CreateUserMessageItem("How many medals did the USA win in the 2024 summer olympics?") },
};
await foreach (StreamingResponseUpdate streamResponse in responseClient.CreateResponseStreamingAsync(options))
{
if (streamResponse is StreamingResponseCreatedUpdate createUpdate)
{
Console.WriteLine($"Stream response created with ID: {createUpdate.Response.Id}");
}
else if (streamResponse is StreamingResponseOutputTextDeltaUpdate textDelta)
{
Console.WriteLine($"Delta: {textDelta.Delta}");
}
else if (streamResponse is StreamingResponseOutputTextDoneUpdate textDoneUpdate)
{
text = textDoneUpdate.Text;
}
else if (streamResponse is StreamingResponseOutputItemDoneUpdate itemDoneUpdate)
{
if (annotation.Length == 0)
{
annotation = GetFormattedAnnotation(itemDoneUpdate.Item);
}
}
else if (streamResponse is StreamingResponseErrorUpdate errorUpdate)
{
throw new InvalidOperationException($"The stream has failed: {errorUpdate.Message}");
}
}
Console.WriteLine($"{text}{annotation}");
- Eliminare tutte le risorse create dall'esempio.
Esempio sincrono:
projectClient.AgentAdministrationClient.DeleteAgentVersionAsync(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
Esempio asincrono:
await projectClient.AgentAdministrationClient.DeleteAgentVersionAsync(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
Output previsto
Di seguito è riportato un esempio dell'output previsto durante l'esecuzione del codice C#:
Response status: Completed
The London Underground currently has service disruptions on ...
Agent deleted
Ricerca Web generale
Ottenere un token di accesso:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
Il modo consigliato per aggiungere la ricerca Web è tramite una casella degli strumenti, quindi allegare la casella degli strumenti all'agente come strumento MCP. Vedi Che cos'è una toolbox?
Creare una casella degli strumenti contenente lo strumento di ricerca Web:
curl --request POST \ --url "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/web-search-toolbox/versions?api-version=v1" \ -H "Authorization: Bearer $AGENT_TOKEN" \ -H "Content-Type: application/json" \ --data '{ "description": "Toolbox with the web search tool", "tools": [ { "type": "web_search" } ] }'La casella degli strumenti espone un endpoint compatibile con MCP in
$FOUNDRY_PROJECT_ENDPOINT/toolboxes/web-search-toolbox/versions/<version>/mcp?api-version=v1, dove<version>è la versione restituita dalla chiamata precedente.Creare una connessione al progetto strumento remoto che punti all'endpoint della casella degli strumenti, usando un token Entra dell'utente in modo che l'identità del chiamante venga trasmessa (audience
https://ai.azure.com).azd ai connection create web-search-toolbox-conn \ --kind remote-tool \ --target "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/web-search-toolbox/versions/<version>/mcp?api-version=v1" \ --auth-type user-entra-token \ --audience https://ai.azure.comCreare una risposta che usa la casella degli strumenti collegandola come strumento MCP.
curl --request POST \ --url "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \ -H "Authorization: Bearer $AGENT_TOKEN" \ -H "Content-Type: application/json" \ --data '{ "model": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'", "input": "Tell me about the latest news about AI", "tool_choice": "required", "tools": [ { "type": "mcp", "server_label": "toolbox", "server_url": "'$FOUNDRY_PROJECT_ENDPOINT'/toolboxes/web-search-toolbox/versions/<version>/mcp?api-version=v1", "require_approval": "never", "project_connection_id": "web-search-toolbox-conn" } ] }'
Output previsto
L'esempio seguente mostra l'output previsto quando si usa lo strumento di ricerca Web tramite l'API REST:
{
"id": "resp_abc123xyz",
"object": "response",
"created_at": 1702345678,
"status": "completed",
"output": [
{
"id": "msg_abc123xyz",
"type": "message",
"role": "assistant",
"status": "completed",
"content": [
{
"type": "output_text",
"text": "Here is a grounded response with citations.",
"annotations": [
{
"type": "url_citation",
"url": "https://contoso.com/example-source",
"start_index": 0,
"end_index": 43
}
]
}
]
}
]
}
Ricerca Web con restrizioni di dominio
Ottenere un token di accesso:
export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)
Il modo consigliato per aggiungere la ricerca Web con restrizioni di dominio è tramite una casella degli strumenti, quindi collegare la casella degli strumenti all'agente come strumento MCP.
Creare una casella degli strumenti contenente lo strumento di ricerca Web con restrizioni di dominio:
curl --request POST \ --url "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/web-search-toolbox/versions?api-version=v1" \ -H "Authorization: Bearer $AGENT_TOKEN" \ -H "Content-Type: application/json" \ --data '{ "description": "Toolbox with the domain-restricted web search tool", "tools": [ { "type": "web_search", "custom_search_configuration": { "project_connection_id": "'$BING_CUSTOM_SEARCH_PROJECT_CONNECTION_ID'", "instance_name": "'$BING_CUSTOM_SEARCH_INSTANCE_NAME'" } } ] }'Creare una connessione al progetto strumento remoto che punti all'endpoint della casella degli strumenti, usando un token Entra dell'utente in modo che l'identità del chiamante venga trasmessa (audience
https://ai.azure.com).azd ai connection create web-search-toolbox-conn \ --kind remote-tool \ --target "$FOUNDRY_PROJECT_ENDPOINT/toolboxes/web-search-toolbox/versions/<version>/mcp?api-version=v1" \ --auth-type user-entra-token \ --audience https://ai.azure.comCreare una risposta che usa la casella degli strumenti collegandola come strumento MCP.
curl --request POST \ --url "$FOUNDRY_PROJECT_ENDPOINT/openai/v1/responses" \ -H "Authorization: Bearer $AGENT_TOKEN" \ -H "Content-Type: application/json" \ --data '{ "model": "'$FOUNDRY_MODEL_DEPLOYMENT_NAME'", "input": "Tell me about the latest news about AI", "tool_choice": "required", "tools": [ { "type": "mcp", "server_label": "toolbox", "server_url": "'$FOUNDRY_PROJECT_ENDPOINT'/toolboxes/web-search-toolbox/versions/<version>/mcp?api-version=v1", "require_approval": "never", "project_connection_id": "web-search-toolbox-conn" } ] }'
Usare lo strumento di ricerca Web con TypeScript
Nell'esempio TypeScript seguente viene illustrato come creare un agente con lo strumento di ricerca Web. Per un esempio che usa JavaScript, vedere il codice di esempio nel repository Azure SDK per JavaScript in GitHub.
Creare un agente supportato dalla casella degli strumenti
In questo esempio viene illustrato come eseguire operazioni dell'agente di richiesta usando lo strumento di ricerca Web. Illustra come creare un agente con funzionalità di ricerca Web, inviare una query per eseguire ricerche nel Web e quindi pulire le risorse.
Lo strumento Ricerca Web usa Grounding con Bing, con costi e condizioni aggiuntivi: condizioni per l'utilizzo e l'informativa sulla privacy. I dati dei clienti passano all'esterno del limite di conformità Azure.
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
export async function main(): Promise<void> {
// Create AI Project client
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
console.log("Creating a toolbox with the web search tool...");
// 1. Add the web search tool to a toolbox. Using a toolbox is the recommended
// way to give agents tools. See /azure/foundry/agents/concepts/toolbox-overview
const toolbox = await project.toolboxes.createVersion(
"web-search-toolbox",
[
{
type: "web_search",
user_location: {
type: "approximate",
country: "GB",
city: "London",
region: "London",
},
},
],
{ description: "Toolbox with the web search tool" },
);
// 2. The toolbox exposes an MCP-compatible endpoint.
const toolboxMcpUrl =
`${PROJECT_ENDPOINT}/toolboxes/${toolbox.name}` +
`/versions/${toolbox.version}/mcp?api-version=v1`;
// 3. Create a remote-tool project connection that points at the toolbox endpoint.
// Use a user Entra token so the caller's identity is passed through
// (audience https://ai.azure.com). Create the connection once, for example
// with the Azure Developer CLI:
//
// azd ai connection create web-search-toolbox-conn \
// --kind remote-tool \
// --target "<toolboxMcpUrl>" \
// --auth-type user-entra-token \
// --audience https://ai.azure.com
const toolboxConnectionName = "web-search-toolbox-conn";
// 4. Attach the toolbox to a prompt agent as an MCP tool.
const agent = await project.agents.createVersion("agent-web-search", {
kind: "prompt",
model: "gpt-5-mini",
instructions: "You are a helpful assistant that can search the web",
tools: [
{
type: "mcp",
server_label: "toolbox",
server_url: toolboxMcpUrl,
require_approval: "never",
project_connection_id: toolboxConnectionName,
},
],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Create a conversation for the agent interaction
const conversation = await openai.conversations.create();
console.log(`Created conversation (id: ${conversation.id})`);
// Send a query to search the web
console.log("\nSending web search query...");
const response = await openai.responses.create(
{
conversation: conversation.id,
input: "Show me the latest London Underground service updates",
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
},
);
console.log(`Response: ${response.output_text}`);
// Clean up resources
console.log("\nCleaning up resources...");
await openai.conversations.delete(conversation.id);
console.log("Conversation deleted");
await project.agents.deleteVersion(agent.name, agent.version);
console.log("Agent deleted");
console.log("\nWeb search sample completed!");
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Output previsto
L'esempio seguente mostra l'output previsto durante l'esecuzione del codice TypeScript:
Agent created (id: 12345, name: agent-web-search, version: 1)
Response: The agent returns a grounded response that includes citations.
Agent deleted
Ricerca con restrizioni di dominio con Ricerca personalizzata Bing
L'esempio seguente illustra come limitare la ricerca Web a domini specifici collegando lo strumento di ricerca Web direttamente all'agente con una configurazione di Ricerca personalizzata Bing.
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
const BING_CUSTOM_SEARCH_CONNECTION_ID = "your_bing_custom_search_connection_id";
const BING_CUSTOM_SEARCH_INSTANCE_NAME = "your_bing_custom_search_instance_name";
export async function main(): Promise<void> {
// Create AI Project client
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
// Create an agent with the web search tool configured for Bing Custom Search
const agent = await project.agents.createVersion("agent-web-search-custom", {
kind: "prompt",
model: "gpt-5-mini",
instructions: "You are a helpful assistant that can search the web and bing",
tools: [
{
type: "web_search",
custom_search_configuration: {
project_connection_id: BING_CUSTOM_SEARCH_CONNECTION_ID,
instance_name: BING_CUSTOM_SEARCH_INSTANCE_NAME,
},
},
],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Send a query and stream the response
const stream = openai.responses.stream(
{
input: "What are the latest updates from Microsoft Learn?",
tool_choice: "required",
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
},
);
// Process streaming events as they arrive
for await (const event of stream) {
if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
} else if (event.type === "response.output_item.done") {
if (event.item.type === "message" && event.item.content) {
const lastContent = event.item.content[event.item.content.length - 1];
if (lastContent.type === "output_text" && lastContent.annotations) {
for (const annotation of lastContent.annotations) {
if (annotation.type === "url_citation") {
console.log(`\nURL Citation: ${annotation.url}`);
}
}
}
}
} else if (event.type === "response.completed") {
console.log("\n\nResponse completed!");
}
}
// Clean up resources
await project.agents.deleteVersion(agent.name, agent.version);
console.log("Agent deleted");
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Output previsto
Agent created (id: abc123, name: agent-web-search-custom, version: 1)
URL Citation: https://your-allowed-domain.com/article
Response completed!
Agent deleted
Ricerca approfondita con la ricerca Web
Nell'esempio seguente viene illustrato come usare il o3-deep-research modello con lo strumento di anteprima della ricerca Web diretta. Non indirizzare la ricerca Web tramite una casella degli strumenti di ricerca approfondita perché il modello richiede lo strumento di ricerca Web di risposte dirette.
import { DefaultAzureCredential } from "@azure/identity";
import { AIProjectClient } from "@azure/ai-projects";
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
const PROJECT_ENDPOINT = "your_project_endpoint";
export async function main(): Promise<void> {
// Create AI Project client
const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential());
const openai = project.getOpenAIClient();
// Create a prompt agent with the direct web search preview tool
const agent = await project.agents.createVersion("agent-deep-research", {
kind: "prompt",
model: "o3-deep-research",
instructions: "You are a helpful assistant that can search the web",
tools: [{ type: "web_search_preview" }],
});
console.log(`Agent created (id: ${agent.id}, name: ${agent.name}, version: ${agent.version})`);
// Create a conversation for the agent interaction
const conversation = await openai.conversations.create();
console.log(`Created conversation (id: ${conversation.id})`);
// Send a query to search the web
const stream = openai.responses.stream(
{
conversation: conversation.id,
input: "What are the latest advancements in quantum computing?",
},
{
body: { agent_reference: { name: agent.name, type: "agent_reference" } },
},
);
// Process streaming events as they arrive
for await (const event of stream) {
if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
} else if (event.type === "response.completed") {
console.log("\n\nResponse completed!");
console.log(`Full response: ${event.response.output_text}`);
}
}
// Clean up resources
await project.agents.deleteVersion(agent.name, agent.version);
console.log("Agent deleted");
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
Output previsto
Agent created (id: abc123, name: agent-deep-research, version: 1)
Created conversation (id: conv_456)
Response completed!
Full response: Recent advancements in quantum computing include ...
Agent deleted
Usare la ricerca Web in un agente Java
Tip
Consigliato: Per la maggior parte degli agenti, aggiungere lo strumento di ricerca Web tramite una casella degli strumenti e allegare la casella degli strumenti all'agente come strumento MCP. L'SDK di Java non espone ancora un'API di creazione della casella degli strumenti, quindi creare la casella degli strumenti usando l'esempio Python, l'API REST, C# o TypeScript o il portale Foundry. Quindi, fare riferimento al relativo endpoint MCP dall'agente Java come McpTool. L'esempio seguente collega lo strumento di ricerca Web direttamente all'agente.
Aggiungi la dipendenza a pom.xml:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-agents</artifactId>
<version>2.2.0</version>
</dependency>
Creare un agente con ricerca Web
import com.azure.ai.agents.AgentsClient;
import com.azure.ai.agents.AgentsClientBuilder;
import com.azure.ai.agents.ResponsesClient;
import com.azure.ai.agents.models.AgentReference;
import com.azure.ai.agents.models.AgentVersionDetails;
import com.azure.ai.agents.models.AzureCreateResponseOptions;
import com.azure.ai.agents.models.PromptAgentDefinition;
import com.azure.ai.agents.models.WebSearchTool;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import java.util.Collections;
public class WebSearchExample {
public static void main(String[] args) {
// Format: "https://resource_name.ai.azure.com/api/projects/project_name"
String projectEndpoint = "your_project_endpoint";
AgentsClientBuilder builder = new AgentsClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint(projectEndpoint);
AgentsClient agentsClient = builder.buildAgentsClient();
ResponsesClient responsesClient = builder.buildResponsesClient();
// Create web search tool with user location
WebSearchTool webSearchTool = new WebSearchTool();
// Create agent with web search tool
PromptAgentDefinition agentDefinition = new PromptAgentDefinition("gpt-5-mini")
.setInstructions("You are a helpful assistant that can search the web for current information.")
.setTools(Collections.singletonList(webSearchTool));
AgentVersionDetails agent = agentsClient.createAgentVersion("web-search-agent", agentDefinition);
System.out.printf("Agent created: %s (version %s)%n", agent.getName(), agent.getVersion());
// Create a response
AgentReference agentReference = new AgentReference(agent.getName())
.setVersion(agent.getVersion());
Response response = responsesClient.createAzureResponse(
new AzureCreateResponseOptions().setAgentReference(agentReference),
ResponseCreateParams.builder()
.input("What are the latest trends in renewable energy?"));
System.out.println("Response: " + response.output());
// Clean up
agentsClient.deleteAgentVersion(agent.getName(), agent.getVersion());
}
}
Output previsto
Agent created: web-search-agent (version 1)
Response: [ResponseOutputItem with web search results about renewable energy trends ...]
Configurare lo strumento di ricerca Web
È possibile configurare il comportamento di ricerca Web quando si crea l'agente.
Formato della risposta di ricerca Web su MCP
Nota
Quando Ricerca Web restituisce risultati su MCP, la risposta è un resource elemento di contenuto contenente la risposta sintetizzata con collegamenti di origine Markdown inline. Le citazioni URL sono in content[].resource._meta.annotations[]. Per esempio:
{
"jsonrpc": "2.0",
"id": "ws-call-1",
"result": {
"_meta": {
"tool_configuration": {
"type": "web_search",
"name": "web-search-default"
}
},
"content": [
{
"type": "resource",
"resource": {
"uri": "about:web-search-answer",
"mimeType": "text/plain",
"text": "Here are the latest updates on Azure OpenAI Service...\n\n- **GPT-image-1 Release (January 7, 2026)** Microsoft introduced GPT-image-1 ([serverless-solutions.com](https://...)).\n\n..."
},
"annotations": {
"audience": ["assistant"]
},
"_meta": {
"annotations": [
{
"type": "url_citation",
"url": "https://www.serverless-solutions.com/blog/...",
"title": "Microsoft expands Foundry with powerful new OpenAI models",
"start_index": 741,
"end_index": 879
}
],
"action": {
"type": "search",
"query": "Azure OpenAI service updates 2026",
"queries": ["Azure OpenAI service updates 2026"]
},
"response_id": "resp_001fcebcc300..."
}
}
],
"isError": false
}
}
Parametri facoltativi per la ricerca Web generale
-
user_location: consente alla ricerca Web di restituire risultati rilevanti per l'area geografica di un utente. Usa una posizione approssimativa quando vuoi che i risultati si localizzati in un paese/area geografica/città. -
search_context_size: controlla la quantità di spazio della finestra di contesto da usare per la ricerca. I valori supportati sonolow,mediumehigh. Il valore predefinito èmedium.
Considerazioni sulla sicurezza e sulla privacy
- Considerare i risultati della ricerca Web come input non attendibile. Convalidare e purificare i dati prima di usarli nei sistemi downstream.
- Evitare di inviare segreti o dati personali sensibili in richieste che potrebbero essere inoltrate a servizi esterni.
- Esaminare le note sui termini, la privacy e i limiti dei dati nella sezione di anteprima di questo articolo prima di abilitare la ricerca Web nell'ambiente di produzione.
Limitazioni note
Per informazioni sul comportamento e sulle limitazioni della ricerca Web nell'API Risposte, vedere Ricerca Web con l'API Risposte.
Risoluzione dei problemi
| Problema | Causa | Risoluzione |
|---|---|---|
| La ricerca Web non viene usata e non vengono visualizzate citazioni | Il modello non ha determinato che era necessaria la ricerca Web | Aggiorna le istruzioni per consentire in modo esplicito la ricerca web per domande aggiornate e porre una query che richiedono informazioni correnti. |
| Le richieste hanno esito negativo dopo l'abilitazione della ricerca Web | La ricerca Web è disabilitata a livello di sottoscrizione | Chiedere a un amministratore di abilitare la ricerca Web. Vedere Controllo amministratore per lo strumento di ricerca Web. |
| Le richieste REST restituiscono errori di autenticazione | Token di connessione mancante, scaduto o con autorizzazioni insufficienti | Aggiornare il token e confermare l'accesso al progetto e all'agente. |
| La ricerca restituisce informazioni obsolete | Contenuto Web non indicizzato di recente | Perfezionare la query per richiedere in modo esplicito le informazioni più recenti. I risultati dipendono dalla pianificazione dell'indicizzazione di Bing. |
| Nessun risultato per argomenti specifici | Query troppo stretta o contenuto non indicizzato | Ampliare i criteri di ricerca. Alcuni argomenti di nicchia potrebbero avere una copertura Web limitata. |
| Errori di limitazione della frequenza (429) | Troppe richieste in un breve periodo di tempo | Implementare il backoff esponenziale e la logica di ripetizione dei tentativi. Prendere in considerazione il distanziamento delle richieste. |
| Formattazione di citazione incoerente | Il formato della risposta varia in base al tipo di query | Standardizzare la gestione delle citazioni nel codice dell'applicazione. Analizzare sia le citazioni inline che le citazioni di tipo riferimento. |
| Strumento non disponibile per la distribuzione | Limitazioni a livello di area o di modello | Verifica che la ricerca Web sia disponibile nella tua regione e con l'implementazione del modello. Controllare le procedure consigliate dello strumento. |
Controllo amministratore per lo strumento di ricerca Web
È possibile abilitare o disabilitare lo strumento di ricerca Web nel servizio Foundry Agent a livello di sottoscrizione usando interfaccia della riga di comando di Azure. Questa impostazione si applica a tutti gli account all'interno della sottoscrizione specificata.
Prerequisiti
Prima di eseguire i comandi seguenti, assicurarsi di:
- Aver installato interfaccia della riga di comando di Azure.
- Sei connesso a Azure utilizzando
az login. - Attivare Collaboratore a livello di sottoscrizione just-in-time tramite Microsoft Entra PIM. L'ambito della sottoscrizione è obbligatorio perché questa impostazione si applica a tutte le risorse Foundry nella sottoscrizione. Disattivare il ruolo dopo la modifica dell'impostazione. Gli sviluppatori dell'agente quotidiano e gli utenti di runtime non hanno bisogno di questo ruolo.
Disabilitare la ricerca Web
Per disabilitare lo strumento di ricerca Web per tutti gli account in una sottoscrizione, eseguire il comando seguente:
az feature register \
--name OpenAI.BlockedTools.web_search \
--namespace Microsoft.CognitiveServices \
--subscription "<subscription-id>"
Questo comando disabilita la ricerca Web in tutti gli account nella sottoscrizione specificata.
Abilitare la ricerca Web
Per abilitare lo strumento di ricerca Web, eseguire il comando seguente:
az feature unregister \
--name OpenAI.BlockedTools.web_search \
--namespace Microsoft.CognitiveServices \
--subscription "<subscription-id>"
Questo comando abilita la funzionalità di ricerca Web per tutti gli account nella sottoscrizione.