Ferramenta de pesquisa web

A ferramenta de pesquisa na web do Foundry Agent Service permite que o modelo Foundry do agente busque e fundamente respostas com informação em tempo real da web pública antes de gerar a saída. Quando disponibilizado, o modelo pode devolver respostas atualizadas com citações incorporadas, ajudando-o a construir agentes que fornecem informação atual e factual aos utilizadores finais.

Importante

  • A Pesquisa Web utiliza o Grounding com Bing Search e o Grounding com Bing Custom Search, que são Serviços de Consumo de Primeira Parte regidos por estes termos de uso do Grounding com Bing e pela Declaração de Privacidade da Microsoft.
  • O Adendo Microsoft Proteção de Dados não se aplica a dados enviados para Grounding com Bing Search e Grounding com Bing Custom Search. Quando utiliza Grounding com Bing Search e Grounding com Bing Custom Search, as transferências de dados ocorrem fora dos limites de conformidade e geográficos.
  • A utilização de Grounding com Bing Search e Grounding com Bing Custom Search implica custos. Consulte os preços para mais detalhes.
  • Consulte a secção management para informações sobre como os administradores Azure podem gerir o acesso à pesquisa web.

Tip

Considera adicionar esta ferramenta usando uma caixa de ferramentas. Ao utilizar uma caixa de ferramentas, pode reutilizar a ferramenta entre agentes e runtimes, bem como centralizar a gestão de credenciais, versionamento e aplicação de políticas através de um endpoint MCP gerido. Veja o guia de início rápido da caixa de ferramentas.

Suporte de utilização

A tabela seguinte mostra o suporte para SDK e configuração.

Suporte ao Microsoft Foundry Python SDK C# SDK SDK de JavaScript SDK de Java API REST Configuração básica do agente Configuração padrão do agente
✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️

Pré-requisitos

  • Um ambiente de agente básico ou padrão

  • O pacote SDK mais recente. O SDK .NET está atualmente em fase de pré-visualização. Consulte o quickstart para mais detalhes.

  • Papel de utilizador do Foundry no projeto Foundry para criar e gerir agentes.

    Importante

    As funções RBAC do Foundry foram recentemente renomeadas. Foundry User, Foundry Owner, Foundry Account Owner e Foundry Project Manager foram anteriormente nomeados Azure AI User, Azure AI Owner, Azure AI Account Owner e Azure AI Project Manager. Poderá ainda ver os nomes anteriores em alguns locais enquanto esta alteração de nome está a ser implementada. Os IDs das funções e as permissões principais não são alterados por esta mudança de nome.

  • Função de Gestor de Projeto do Foundry no projeto Foundry se criar a ligação do projeto remote-tool para pesquisa com restrição de domínio.

  • Azure credenciais configuradas para autenticação (como DefaultAzureCredential).

  • O URL do endpoint do seu projeto Foundry e o nome de implementação do modelo.

Escolha um cenário de fundamentação na Web

Scenario Escolhe-o quando Comece aqui
Pesquisa Geral na Web O seu agente precisa de informação atual da web pública, sem um recurso Bing separado ou ligação ao projeto. Adicione a pesquisa na web diretamente a um agente de prompts.
Pesquisa Personalizada Bing com restrição de domínio Os resultados de pesquisa devem vir de domínios públicos configurados na sua instância de Pesquisa Personalizada do Bing. Configurar pesquisa com restrição de domínio.
Investigação aprofundada O seu o3-deep-research agente precisa de pesquisa e síntese em várias etapas. Utilize a pesquisa direta na web para uma pesquisa aprofundada.
Ferramentas de fundamentação do Bing Precisa do tipo de ferramenta explícito bing_grounding ou bing_custom_search_preview com uma ligação a um projeto do Bing. Use o Grounding com as ferramentas de pesquisa do Bing.

Adicionar pesquisa web diretamente a um agente

Comece pelo separador Prompt Agents. Adiciona WebSearchTool diretamente a um agente no lado do servidor e não requer uma caixa de ferramentas nem uma ligação separada ao projeto Bing. Este caminho oferece o caminho mais curto para uma resposta fundamentada com citações.

O separador Agentes Alojados utiliza WebSearchToolboxTool para adicionar pesquisa na Web a uma caixa de ferramentas e depois liga-se ao endpoint MCP da caixa de ferramentas. Mantenha separados os tipos de ferramentas de agente direto e toolbox, porque se aplicam a diferentes superfícies da API.

Nota

Para informações sobre como otimizar o uso de ferramentas, consulte as melhores práticas.

O exemplo seguinte mostra como dar a um agente acesso à pesquisa web. Selecione Prompt Agents para usar o SDK Azure AI Projects para criar um agente de prompt do lado do servidor, ou Hosted Agents para usar o Agent Framework FoundryChatClient para construir um agente efémero em processo.

Agentes de comando

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")

Produção esperada

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

Agentes alojados

Este exemplo utiliza FoundryChatClient do Microsoft Agent Framework e liga-se ao endpoint MCP da toolbox usando FoundryToolbox. Instale o pacote com pip install agent-framework-foundry, defina as variáveis de ambiente FOUNDRY_PROJECT_ENDPOINT e FOUNDRY_MODEL e inicie sessão com az login. Para o padrão completo da caixa de ferramentas do agente hospedado, consulte a amostra completa.

Crie uma caixa de ferramentas e execute um agente alojado

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())

Produção esperada

O agente responde usando informações frescas da web e imprime quaisquer citações URL que a ferramenta tenha devolvedo. A produção varia conforme o conteúdo na web muda:

Agent: The latest updates to Microsoft Foundry include ...
URL Citation: [Microsoft Foundry documentation](https://learn.microsoft.com/azure/ai-foundry/)

A ferramenta de pesquisa web executa-se do lado do servidor na API Foundry Responses. Pode combiná-lo com ferramentas de funções locais, adicionando entradas adicionais (por exemplo, uma função com o decorador @tool) à lista tools. Para saber mais, consulte Início Rápido: Utilizar a API Foundry Responses.


O exemplo seguinte mostra como restringir a pesquisa web a domínios específicos usando uma instância de Pesquisa Personalizada do Bing. Esta abordagem dá-lhe controlo sobre que sites o seu agente pode pesquisar.

Crie a ligação Bing Custom Search com a CLI do Azure Developer

O azd ai connection create comando não suporta atualmente a GroundingWithBingCustomSearch categoria de ligação. Defina a ligação em azure.yaml em vez disso, e execute azd provision:

resources:
  - kind: connection
    name: bing-custom-search
    category: GroundingWithBingCustomSearch
    target: https://api.bing.microsoft.com/
    credentials:
      type: ApiKey
      key: <bing-custom-search-key>

Não comprometas a chave com controlo de versão. Insira-o a partir de um repositório seguro antes de o executar:

azd provision

Crie a caixa de ferramentas e o agente restrito ao domínio

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")

Produção esperada

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

Grounding com o Bing Custom Search é uma ferramenta poderosa que pode usar para selecionar um subespaço da web e limitar o conhecimento de grounding do seu agente. Aqui ficam algumas dicas para o ajudar a tirar pleno partido desta capacidade:

  • Se possui um site público que pretende incluir na pesquisa mas o Bing ainda não indexou, consulte as Diretrizes para Webmasters do Bing para detalhes sobre como indexar o seu site. A documentação do webmaster também fornece detalhes sobre como fazer o Bing rastrear o seu site se o índice estiver desatualizado.
  • Para criar uma configuração, ative a função Contribuidor no recurso Bing Custom Search just-in-time através do Microsoft Entra PIM. Desative a função após a configuração. Desenvolvedores de agentes do dia a dia e utilizadores de runtime não precisam deste papel.
  • Pode bloquear certos domínios e fazer uma pesquisa no resto da web (por exemplo, no site de um concorrente).
  • A pesquisa com o Bing Custom Search só retorna resultados para domínios e páginas web que são públicos e indexados pelo Bing.
  • Pode especificar diferentes níveis de granularidade:
    • Domínio (por exemplo, https://www.microsoft.com)
    • Domínio e caminho (por exemplo, https://www.microsoft.com/surface)
    • Página web (por exemplo, https://www.microsoft.com/en-us/p/surface-earbuds/8r9cpq146064)

O exemplo seguinte mostra como usar o o3-deep-research modelo com a ferramenta de pré-visualização direta da pesquisa web. Esta abordagem substitui a ferramenta obsoleta Deep Research. Não encaminhe a pesquisa na web por uma caixa de ferramentas para pesquisa aprofundada porque o modelo requer a ferramenta de pesquisa web Direct Responses.

Crie o agente de investigação profunda

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")

Pesquisa geral na web

O exemplo seguinte mostra como dar a um agente acesso à pesquisa web. Selecione Prompt Agents para usar o SDK Azure AI Projects para criar um agente de prompt do lado do servidor, ou Hosted Agents para usar o Microsoft Agent Framework para construir um agente efémero em processo.

Agentes de comando

Neste exemplo, usa o agente para realizar a pesquisa na web na localização indicada. O exemplo nesta secção utiliza chamadas síncronas. Para um exemplo assíncrono, veja o código exemplo no SDK do Azure para .NET repositório no GitHub.

Crie o agente e faça uma pesquisa

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

Produção esperada

Segue-se um exemplo da saída esperada ao executar o código C#:

Response status: Completed
The London Underground currently has service disruptions on ...
Agent deleted

Agentes alojados

Este exemplo cria a caixa de ferramentas de pesquisa web com o Azure AI Projects SDK, e depois utiliza a integração com o Microsoft Agent Framework AddFoundryToolboxes para disponibilizar a pesquisa web ao agente alojado. Defina as AZURE_AI_PROJECT_ENDPOINTvariáveis , AZURE_OPENAI_ENDPOINT, e AZURE_AI_MODEL_DEPLOYMENT_NAME de ambiente, e faça login com az login.

Crie uma caixa de ferramentas e execute um agente alojado

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();

Produção esperada

O agente responde usando informações frescas da web e imprime quaisquer citações URL que a ferramenta tenha devolvedo. A produção varia conforme o conteúdo na web muda:

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/

O agente alojado liga-se a um endpoint da caixa de ferramentas e descobre a ferramenta de pesquisa web em tempo de execução. Pode adicionar outras ferramentas à caixa de ferramentas sem alterar o código do agente hospedado.


Para permitir que o seu Agente utilize a Pesquisa Web com contexto usando a instância personalizada de Pesquisa Bing.

  1. Primeiro, crie o cliente do projeto e defina os valores usados nos próximos passos.
// 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());
  1. Crie um Agente capaz de usar a pesquisa web no Grounding com a instância de Pesquisa Personalizada do Bing.

Exemplo síncrono:

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

Amostra assíncrona:

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));
  1. Chama o GetFormattedAnnotation método para formatar a anotação.
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 "";
}
  1. Faz a pergunta e transmite a resposta em streaming.

Exemplo síncrono:

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

Amostra assíncrona:

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}");
  1. Apague todos os recursos que a amostra criou.

Exemplo síncrono:

projectClient.AgentAdministrationClient.DeleteAgentVersionAsync(agentName: agentVersion.Name, agentVersion: agentVersion.Version);

Amostra assíncrona:

await projectClient.AgentAdministrationClient.DeleteAgentVersionAsync(agentName: agentVersion.Name, agentVersion: agentVersion.Version);

Produção esperada

Segue-se um exemplo da saída esperada ao executar o código C#:

Response status: Completed
The London Underground currently has service disruptions on ...
Agent deleted

Pesquisa geral na web

Obtenha um token de acesso:

export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)

A forma recomendada de adicionar pesquisa na web é através de uma caixa de ferramentas e depois anexar a caixa de ferramentas ao seu agente como uma ferramenta MCP. Veja O que é uma caixa de ferramentas?

  1. Crie uma caixa de ferramentas que contenha a ferramenta de pesquisa 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" }
        ]
      }'
    

    A caixa de ferramentas expõe um endpoint compatível com MCP em $FOUNDRY_PROJECT_ENDPOINT/toolboxes/web-search-toolbox/versions/<version>/mcp?api-version=v1, onde <version> é a versão devolvida pela chamada anterior.

  2. Crie uma ligação de projeto da ferramenta remota que aponte para o ponto final da caixa de ferramentas, utilizando um token Entra de utilizador para que a identidade do autor da chamada seja transmitida (destinatário 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.com
    
  3. Cria uma resposta que use a caixa de ferramentas anexando-a como uma ferramenta 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"
          }
        ]
      }'
    

Produção esperada

O exemplo seguinte mostra a saída esperada ao utilizar a ferramenta de pesquisa web através da 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
            }
          ]
        }
      ]
    }
  ]
}

Pesquisa web restrita a domínio

Obtenha um token de acesso:

export AGENT_TOKEN=$(az account get-access-token --scope "https://ai.azure.com/.default" --query accessToken -o tsv)

A forma recomendada de adicionar pesquisa web com domínio restrito é através de uma caixa de ferramentas e depois anexar a caixa de ferramentas ao seu agente como uma ferramenta MCP.

  1. Crie uma caixa de ferramentas que contenha a ferramenta de pesquisa web restrita ao domínio:

    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'"
            }
          }
        ]
      }'
    
  2. Crie uma ligação de projeto da ferramenta remota que aponte para o ponto final da caixa de ferramentas, utilizando um token Entra de utilizador para que a identidade do autor da chamada seja transmitida (destinatário 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.com
    
  3. Cria uma resposta que use a caixa de ferramentas anexando-a como uma ferramenta 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"
          }
        ]
      }'
    

Use a ferramenta de pesquisa web com o TypeScript

O exemplo seguinte de TypeScript demonstra como criar um agente com a ferramenta de pesquisa web. Para um exemplo que utiliza JavaScript, veja o código de exemplo no repositório SDK do Azure for JavaScript no GitHub.

Crie um agente apoiado por uma caixa de ferramentas

Este exemplo demonstra como executar operações com o Prompt Agent utilizando a Ferramenta de Pesquisa Web. Mostra como criar um agente com capacidades de pesquisa na web, enviar uma consulta para pesquisar na web e depois limpar recursos.

A ferramenta de Pesquisa Web utiliza o Grounding with Bing, que tem custos e termos adicionais: termos de utilização e declaração de privacidade. Os dados dos clientes fluem fora dos limites de conformidade do 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);
});

Produção esperada

O exemplo seguinte mostra a saída esperada ao executar o código TypeScript:

Agent created (id: 12345, name: agent-web-search, version: 1)
Response: The agent returns a grounded response that includes citations.
Agent deleted

Pesquisa restrita ao domínio com Bing Custom Search

O exemplo seguinte mostra como restringir a pesquisa web a domínios específicos, anexando a ferramenta de pesquisa web diretamente ao agente com uma configuração Bing Custom Search.

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

Produção esperada

Agent created (id: abc123, name: agent-web-search-custom, version: 1)

URL Citation: https://your-allowed-domain.com/article

Response completed!
Agent deleted

Investigação aprofundada com pesquisa na web

O exemplo seguinte mostra como usar o o3-deep-research modelo com a ferramenta de pré-visualização direta da pesquisa web. Não encaminhe a pesquisa na web por uma caixa de ferramentas para pesquisa aprofundada porque o modelo requer a ferramenta de pesquisa web Direct Responses.

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

Produção esperada

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

Usar pesquisa web num agente Java

Tip

Recomendado: Para a maioria dos agentes, adicione a ferramenta de pesquisa web através de uma caixa de ferramentas e anexe a caixa de ferramentas ao seu agente como uma ferramenta MCP. O SDK Java ainda não expõe uma API de criação de toolbox, por isso cria a toolbox usando o exemplo de Python, API REST, C# ou TypeScript, ou o portal Foundry. Depois, refira o respetivo endpoint MCP no seu agente Java como um McpTool. O exemplo seguinte associa a ferramenta de pesquisa web diretamente ao agente.

Adicione a dependência ao seu pom.xml:

<dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-ai-agents</artifactId>
    <version>2.2.0</version>
</dependency>
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());
    }
}

Produção esperada

Agent created: web-search-agent (version 1)
Response: [ResponseOutputItem with web search results about renewable energy trends ...]

Configurar a ferramenta de pesquisa web

Pode configurar o comportamento de pesquisa na web ao criar o seu agente.

Formato da resposta da pesquisa na Web através de MCP

Nota

Quando o Web Search retorna resultados através do MCP, a resposta é um resource item de conteúdo que contém a resposta sintetizada com links de origem Markdown incorporados. As citações de URL encontram-se em content[].resource._meta.annotations[]. Por exemplo:

{
  "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
  }
}
  • user_location: Ajuda a pesquisa web a devolver resultados relevantes para a geografia do utilizador. Use uma localização aproximada quando quiser que os resultados sejam localizados para um país/região/cidade.
  • search_context_size: Controla quanto espaço de janela de contexto usar para a pesquisa. Os valores suportados são low, medium, e high. O padrão é medium.

Considerações de segurança e privacidade

  • Trate os resultados da pesquisa web como entrada não confiável. Valide e higienize os dados antes de os usar em sistemas a jusante.
  • Evite enviar segredos ou dados pessoais sensíveis em prompts que possam ser encaminhados para serviços externos.
  • Consulte os termos, as notas de privacidade e limites de dados na secção de pré-visualização deste artigo antes de ativar a pesquisa web em produção.

Limitações conhecidas

Para informações sobre o comportamento da pesquisa na web e as limitações na API de Respostas, consulte a pesquisa na Web com a API de Respostas.

Resolução de problemas

Problema Causa Resolução
A pesquisa na web não é usada e não aparecem citações O modelo não considerou necessária uma pesquisa na web Atualize as suas instruções para permitir explicitamente a pesquisa na web por perguntas atualizadas e formule uma consulta que exija informações atuais.
Os pedidos falham após ativar a pesquisa web A pesquisa na web está desativada ao nível de subscrição Pede a um administrador para ativar a pesquisa na web. Consulte Controlo de administrador para a ferramenta de pesquisa web.
Os pedidos REST retornam erros de autenticação O token portador está em falta, expirou ou tem permissões insuficientes Atualize o seu token e confirme o seu acesso ao projeto e ao agente.
A pesquisa devolve informações desatualizadas Conteúdo web não indexado recentemente Refina a tua consulta para pedir explicitamente a informação mais recente. Os resultados dependem do calendário de indexação do Bing.
Sem resultados para tópicos específicos Consulta demasiado restrita ou conteúdo não indexado Amplia a tua pesquisa. Alguns temas de nicho podem ter uma cobertura limitada na web.
Erros de limitação de taxa (429) Demasiados pedidos num curto espaço de tempo Implementar a lógica de backoff exponencial e de repetição. Considere espaçar os pedidos.
Formatação inconsistente das citações O formato da resposta varia consoante o tipo de consulta Padronize o tratamento de citações no seu código de aplicação. Analise tanto as citações em linha como as de referência.
Ferramenta não disponível para implementação Limitações regionais ou de modelos Confirme que a pesquisa na web está disponível na sua região e com a implementação do modelo. Verifique as melhores práticas das ferramentas.

Controlo de administrador para a ferramenta de pesquisa web

Pode ativar ou desativar a ferramenta de pesquisa web no Foundry Agent Service ao nível da subscrição usando o CLI do Azure. Esta definição aplica-se a todas as contas dentro da subscrição especificada.

Pré-requisitos

Antes de executar os seguintes comandos, certifique-se de:

  1. Tenha CLI do Azure instalado.
  2. Estão com sessão iniciada no Azure usando az login.
  3. Ative Colaborador ao nível da subscrição em regime just-in-time através do Microsoft Entra PIM. O âmbito da subscrição é necessário porque esta definição aplica-se a todos os recursos do Foundry na subscrição. Desative a função depois de alterar a definição. Desenvolvedores de agentes do dia a dia e utilizadores de runtime não precisam deste papel.

Para desativar a ferramenta de pesquisa web para todas as contas numa subscrição, execute o seguinte comando:

az feature register \
  --name OpenAI.BlockedTools.web_search \
  --namespace Microsoft.CognitiveServices \
  --subscription "<subscription-id>"

Este comando desativa a pesquisa web em todas as contas da subscrição especificada.

Para ativar a ferramenta de pesquisa web, execute o seguinte comando:

az feature unregister \
  --name OpenAI.BlockedTools.web_search \
  --namespace Microsoft.CognitiveServices \
  --subscription "<subscription-id>"

Este comando permite a funcionalidade de pesquisa web para todas as contas da subscrição.

Próximos passos