Use the web search tool in Foundry Agent Service to retrieve real-time information and ground AI responses. Includes code examples.
Items marked (preview) in this article are currently in public preview. This preview is provided without a service-level agreement, and we don’t recommend it for production workloads. Certain features might not be supported or might have constrained capabilities. For more information, see Supplemental Terms of Use for Microsoft Azure Previews.
The web search tool in Foundry Agent Service enables models to retrieve and ground responses with real-time information from the public web before generating output. When enabled, the model can return up-to-date answers with inline citations, helping you build agents that provide current, factual information to users.
The Microsoft Data Protection Addendum doesn’t apply to data sent to Grounding with Bing Search and Grounding with Bing Custom Search. When you use Grounding with Bing Search and Grounding with Bing Custom Search, data transfers occur outside compliance and geographic boundaries.
Use of Grounding with Bing Search and Grounding with Bing Custom Search incurs costs. See pricing for details.
See the management section for information about how Azure admins can manage access to use of web search.
Agent created: <agent-name> (version 1)Response: The latest trends in renewable energy include ...URL Citation: https://example.com/sourceFollow-up completed!Full response: Based on current data ...Agent deleted
The following example shows how to use the o3-deep-research model with the web search tool. This approach replaces the deprecated Deep Research tool, enabling multi-step research using public web data directly through the web search tool.
Set the AZURE_AI_MODEL_DEPLOYMENT_NAME environment variable to your o3-deep-research deployment name.
import osimport sysfrom dotenv import load_dotenvfrom azure.identity import DefaultAzureCredentialfrom azure.ai.projects import AIProjectClientfrom azure.ai.projects.models import PromptAgentDefinition, WebSearchPreviewToolload_dotenv()project_client = AIProjectClient( endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"], credential=DefaultAzureCredential(),)openai_client = project_client.get_openai_client()with project_client: # Create Agent with web search tool using o3-deep-research model agent = project_client.agents.create_version( agent_name="MyDeepResearchAgent", definition=PromptAgentDefinition( model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"], 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_client.conversations.create() print(f"Created conversation (id: {conversation.id})") # Send a query to search the web response = openai_client.responses.create( stream=True, conversation=conversation.id, input="What are the latest advancements in quantum computing?", extra_body={"agent": {"name": agent.name, "type": "agent_reference"}}, ) # Process streaming events as they arrive for event in response: if event.type == "response.created": print(f"Stream response created with ID: {event.response.id}") elif event.type == "response.output_text.delta": print(f"Delta: {event.delta}") elif event.type == "response.text.done": print(f"\nResponse done with full message: {event.text}") elif event.type == "response.completed": print(f"\nResponse completed!") print(f"Full response: {event.response.output_text}") print("\nCleaning up...") project_client.agents.delete_version(agent_name=agent.name, agent_version=agent.version) print("Agent deleted")
In this example, you use the agent to perform the web search in the given location. The example in this section uses synchronous calls. For an asynchronous example, see the sample code in the Azure SDK for .NET repository on GitHub.
using System;using Azure.AI.Projects;using Azure.AI.Projects.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 APIAIProjectClient projectClient = new( endpoint: new Uri(projectEndpoint), tokenProvider: new DefaultAzureCredential());// Create an agent with the web search toolPromptAgentDefinition 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.Agents.CreateAgentVersion( agentName: "myAgent", options: new(agentDefinition));// Ask a question related to London.ProjectResponsesClient responseClient = projectClient.OpenAI.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.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
Expected outputThe following is an example of the expected output when running the C# code:
Response status: CompletedThe London Underground currently has service disruptions on ...Agent deleted
The following TypeScript example demonstrates how to create an agent with the web search tool. For an example that uses JavaScript, see the sample code example in the Azure SDK for JavaScript repository on GitHub.
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 clients to call Foundry API const project = new AIProjectClient(PROJECT_ENDPOINT, new DefaultAzureCredential()); const openai = project.getOpenAIClient(); // Create agent with web search 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: "web_search_preview", user_location: { type: "approximate", country: "GB", city: "London", region: "London", }, }, ], }); 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(); // Send a query to search the web const response = await openai.responses.create( { conversation: conversation.id, input: "Show me the latest London Underground service updates", }, { body: { agent: { name: agent.name, type: "agent_reference" } }, }, ); console.log(`Response: ${response.output_text}`); // Clean up resources await openai.conversations.delete(conversation.id); await project.agents.deleteVersion(agent.name, agent.version); console.log("Agent deleted");}main().catch((err) => { console.error("The sample encountered an error:", err);});
user_location: Helps web search return results relevant to a user’s geography. Use an approximate location when you want results localized to a country/region/city.
search_context_size: Controls how much context window space to use for the search. Supported values are low, medium, and high. The default is medium.
You can enable or disable the web search tool in Foundry Agent Service at the subscription level by using Azure CLI. This setting applies to all accounts within the specified subscription.