Partager via


Web Search

La recherche web permet aux agents de rechercher sur le web des informations de up-to-date. Cet outil permet aux agents de répondre à des questions sur les événements actuels, de trouver de la documentation et d’accéder aux informations au-delà de leurs données d’entraînement.

Note

La disponibilité de la recherche web dépend du fournisseur d’agent sous-jacent. Consultez La vue d’ensemble des fournisseurs pour obtenir une prise en charge spécifique au fournisseur.

L’exemple suivant montre comment créer un agent avec l’outil Recherche web :

using System;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

// Requires: dotnet add package Microsoft.Agents.AI.Foundry --prerelease
var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT is not set.");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";

// Create an agent with the web search (Bing grounding) tool
AIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
    .AsAIAgent(
        model: deploymentName,
        instructions: "You are a helpful assistant that can search the web for current information.",
        tools: [new WebSearchToolDefinition()]);

Console.WriteLine(await agent.RunAsync("What is the current weather in Seattle?"));

Avertissement

DefaultAzureCredential est pratique pour le développement, mais nécessite une considération minutieuse en production. En production, envisagez d’utiliser des informations d’identification spécifiques (par exemple ManagedIdentityCredential) pour éviter les problèmes de latence, la détection involontaire des informations d’identification et les risques de sécurité potentiels liés aux mécanismes de secours.

L’exemple suivant montre comment créer un agent avec l’outil Recherche web :

# Copyright (c) Microsoft. All rights reserved.

import asyncio

from agent_framework import Agent
from agent_framework.openai import OpenAIChatClient

"""
OpenAI Responses Client with Web Search Example

This sample demonstrates using get_web_search_tool() with OpenAI Responses Client
for direct real-time information retrieval and current data access.
"""


async def main() -> None:
    client = OpenAIChatClient()

    # Create web search tool with location context
    web_search_tool = client.get_web_search_tool(
        user_location={"city": "Seattle", "region": "US"},
    )

    agent = Agent(
        client=client,
        instructions="You are a helpful assistant that can search the web for current information.",
        tools=[web_search_tool],
    )

    message = "What is the current weather? Do not ask for my current location."
    stream = False
    print(f"User: {message}")

    if stream:
        print("Assistant: ", end="")
        async for chunk in agent.run(message, stream=True):
            if chunk.text:
                print(chunk.text, end="")
        print("")
    else:
        response = await agent.run(message)
        print(f"Assistant: {response}")


if __name__ == "__main__":
    asyncio.run(main())

Prochaines étapes