Skip to content

Commit 9a7d939

Browse files
.NET: Add Foundry Agents Tool Sample - Bing Custom Search (#3701)
* .NET: Add Bing Custom Search sample #3674 * Apply format fixes * .NET: Improve Bing Custom Search sample with dual MEAI/Native SDK options - Add MEAI (Option 1) and Native SDK (Option 2) agent creation patterns - Add DefaultAzureCredential with standard WARNING comment - Add sample to solution file and FoundryAgents README index - Improve README with connection ID/instance name guidance - Fix missing newline at EOF in .csproj - Suppress CS8321 for unused local function pattern Co-authored-by: Copilot <[email protected]> * Address PR review comments for Bing Custom Search sample - Add Async suffix to CreateAgentWithMEAI and CreateAgentWithNativeSDK methods - Clarify comment to reference ResponseTool instead of BingCustomSearchTool - Update README Option 1 description to accurately reflect SDK usage Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]>
1 parent 1086d1d commit 9a7d939

5 files changed

Lines changed: 163 additions & 0 deletions

File tree

‎dotnet/agent-framework-dotnet.slnx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@
183183
<Project Path="samples/GettingStarted/FoundryAgents/FoundryAgents_Step15_ComputerUse/FoundryAgents_Step15_ComputerUse.csproj" />
184184
<Project Path="samples/GettingStarted/FoundryAgents/FoundryAgents_Step18_FileSearch/FoundryAgents_Step18_FileSearch.csproj" />
185185
<Project Path="samples/GettingStarted/FoundryAgents/FoundryAgents_Step19_OpenAPITools/FoundryAgents_Step19_OpenAPITools.csproj" />
186+
<Project Path="samples/GettingStarted/FoundryAgents/FoundryAgents_Step21_BingCustomSearch/FoundryAgents_Step21_BingCustomSearch.csproj" />
186187
<Project Path="samples/GettingStarted/FoundryAgents/FoundryAgents_Step25_WebSearch/FoundryAgents_Step25_WebSearch.csproj" />
187188
<Project Path="samples/GettingStarted/FoundryAgents/FoundryAgents_Step26_MemorySearch/FoundryAgents_Step26_MemorySearch.csproj" />
188189
<Project Path="samples/GettingStarted/FoundryAgents/FoundryAgents_Evaluations_Step01_RedTeaming/FoundryAgents_Evaluations_Step01_RedTeaming.csproj" />
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<Project Sdk="Microsoft.NET.Sdk">
2+
3+
<PropertyGroup>
4+
<OutputType>Exe</OutputType>
5+
<TargetFrameworks>net10.0</TargetFrameworks>
6+
7+
<Nullable>enable</Nullable>
8+
<ImplicitUsings>enable</ImplicitUsings>
9+
<NoWarn>$(NoWarn);CA1812;CS8321</NoWarn>
10+
</PropertyGroup>
11+
12+
<ItemGroup>
13+
<PackageReference Include="Microsoft.Extensions.Logging.Console" />
14+
<PackageReference Include="Azure.Identity" />
15+
<PackageReference Include="Azure.AI.Projects" />
16+
</ItemGroup>
17+
18+
<ItemGroup>
19+
<ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.AzureAI\Microsoft.Agents.AI.AzureAI.csproj" />
20+
</ItemGroup>
21+
22+
</Project>
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
3+
// This sample shows how to use Bing Custom Search Tool with AI Agents.
4+
5+
using Azure.AI.Projects;
6+
using Azure.AI.Projects.OpenAI;
7+
using Azure.Identity;
8+
using Microsoft.Agents.AI;
9+
using OpenAI.Responses;
10+
11+
string endpoint = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_ENDPOINT") ?? throw new InvalidOperationException("AZURE_FOUNDRY_PROJECT_ENDPOINT is not set.");
12+
string deploymentName = Environment.GetEnvironmentVariable("AZURE_FOUNDRY_PROJECT_DEPLOYMENT_NAME") ?? "gpt-4o-mini";
13+
string connectionId = Environment.GetEnvironmentVariable("BING_CUSTOM_SEARCH_PROJECT_CONNECTION_ID") ?? throw new InvalidOperationException("BING_CUSTOM_SEARCH_PROJECT_CONNECTION_ID is not set.");
14+
string instanceName = Environment.GetEnvironmentVariable("BING_CUSTOM_SEARCH_INSTANCE_NAME") ?? throw new InvalidOperationException("BING_CUSTOM_SEARCH_INSTANCE_NAME is not set.");
15+
16+
const string AgentInstructions = """
17+
You are a helpful agent that can use Bing Custom Search tools to assist users.
18+
Use the available Bing Custom Search tools to answer questions and perform tasks.
19+
""";
20+
21+
// Get a client to create/retrieve/delete server side agents with Azure Foundry Agents.
22+
// WARNING: DefaultAzureCredential is convenient for development but requires careful consideration in production.
23+
// In production, consider using a specific credential (e.g., ManagedIdentityCredential) to avoid
24+
// latency issues, unintended credential probing, and potential security risks from fallback mechanisms.
25+
AIProjectClient aiProjectClient = new(new Uri(endpoint), new DefaultAzureCredential());
26+
27+
// Bing Custom Search tool parameters shared by both options
28+
BingCustomSearchToolParameters bingCustomSearchToolParameters = new([
29+
new BingCustomSearchConfiguration(connectionId, instanceName)
30+
]);
31+
32+
AIAgent agent = await CreateAgentWithMEAIAsync();
33+
// AIAgent agent = await CreateAgentWithNativeSDKAsync();
34+
35+
Console.WriteLine($"Created agent: {agent.Name}");
36+
37+
// Run the agent with a search query
38+
AgentResponse response = await agent.RunAsync("Search for the latest news about Microsoft AI");
39+
40+
Console.WriteLine("\n=== Agent Response ===");
41+
foreach (var message in response.Messages)
42+
{
43+
Console.WriteLine(message.Text);
44+
}
45+
46+
// Cleanup by deleting the agent
47+
await aiProjectClient.Agents.DeleteAgentAsync(agent.Name);
48+
Console.WriteLine($"\nDeleted agent: {agent.Name}");
49+
50+
// --- Agent Creation Options ---
51+
52+
// Option 1 - Using AsAITool wrapping for the ResponseTool returned by AgentTool.CreateBingCustomSearchTool (MEAI + AgentFramework)
53+
async Task<AIAgent> CreateAgentWithMEAIAsync()
54+
{
55+
return await aiProjectClient.CreateAIAgentAsync(
56+
model: deploymentName,
57+
name: "BingCustomSearchAgent-MEAI",
58+
instructions: AgentInstructions,
59+
tools: [((ResponseTool)AgentTool.CreateBingCustomSearchTool(bingCustomSearchToolParameters)).AsAITool()]);
60+
}
61+
62+
// Option 2 - Using PromptAgentDefinition with AgentTool.CreateBingCustomSearchTool (Native SDK)
63+
async Task<AIAgent> CreateAgentWithNativeSDKAsync()
64+
{
65+
return await aiProjectClient.CreateAIAgentAsync(
66+
name: "BingCustomSearchAgent-NATIVE",
67+
creationOptions: new AgentVersionCreationOptions(
68+
new PromptAgentDefinition(model: deploymentName)
69+
{
70+
Instructions = AgentInstructions,
71+
Tools = {
72+
(ResponseTool)AgentTool.CreateBingCustomSearchTool(bingCustomSearchToolParameters),
73+
}
74+
})
75+
);
76+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Using Bing Custom Search with AI Agents
2+
3+
This sample demonstrates how to use the Bing Custom Search tool with AI agents to perform customized web searches.
4+
5+
## What this sample demonstrates
6+
7+
- Creating agents with Bing Custom Search capabilities
8+
- Configuring custom search instances via connection ID and instance name
9+
- Two agent creation approaches: MEAI abstraction (Option 1) and Native SDK (Option 2)
10+
- Running search queries through the agent
11+
- Managing agent lifecycle (creation and deletion)
12+
13+
## Agent creation options
14+
15+
This sample provides two approaches for creating agents with Bing Custom Search:
16+
17+
- **Option 1 - MEAI + AgentFramework**: Uses the Agent Framework `ResponseTool` wrapped with `AsAITool()` to call the `CreateAIAgentAsync` overload that accepts `tools:[]`, while still relying on the same underlying Azure AI Projects SDK types as Option 2.
18+
- **Option 2 - Native SDK**: Uses `PromptAgentDefinition` with `AgentVersionCreationOptions` to create the agent directly with the Azure AI Projects SDK types.
19+
20+
Both options produce the same result. Toggle between them by commenting/uncommenting the corresponding `CreateAgentWith*Async` call in `Program.cs`.
21+
22+
## Prerequisites
23+
24+
Before you begin, ensure you have the following prerequisites:
25+
26+
- .NET 10 SDK or later
27+
- Azure Foundry service endpoint and deployment configured
28+
- Azure CLI installed and authenticated (for Azure credential authentication)
29+
- A Bing Custom Search resource configured in Azure and connected to your Foundry project
30+
31+
**Note**: This demo uses Azure Default credentials for authentication. Make sure you're logged in with `az login` and have access to the Azure Foundry resource.
32+
33+
Set the following environment variables:
34+
35+
```powershell
36+
$env:AZURE_FOUNDRY_PROJECT_ENDPOINT="https://your-foundry-service.services.ai.azure.com/api/projects/your-foundry-project"
37+
$env:AZURE_FOUNDRY_PROJECT_DEPLOYMENT_NAME="gpt-4o-mini" # Optional, defaults to gpt-4o-mini
38+
$env:BING_CUSTOM_SEARCH_PROJECT_CONNECTION_ID="/subscriptions/<sub-id>/resourceGroups/<rg>/providers/Microsoft.CognitiveServices/accounts/<account>/projects/<project>/connections/<connection-name>"
39+
$env:BING_CUSTOM_SEARCH_INSTANCE_NAME="your-configuration-name"
40+
```
41+
42+
### Finding the connection ID and instance name
43+
44+
- **Connection ID**: The full ARM resource path including the `/projects/<name>/connections/<connection-name>` segment. Find the connection name in your Foundry project under **Management center** → **Connected resources**.
45+
- **Instance Name**: The **configuration name** from the Bing Custom Search resource (Azure portal → your Bing Custom Search resource → **Configurations**). This is _not_ the Azure resource name.
46+
47+
## Run the sample
48+
49+
Navigate to the FoundryAgents sample directory and run:
50+
51+
```powershell
52+
cd dotnet/samples/GettingStarted/FoundryAgents
53+
dotnet run --project .\FoundryAgents_Step21_BingCustomSearch
54+
```
55+
56+
## Expected behavior
57+
58+
The sample will:
59+
60+
1. Create an agent with Bing Custom Search tool capabilities
61+
2. Run the agent with a search query about Microsoft AI
62+
3. Display the search results returned by the agent
63+
4. Clean up resources by deleting the agent

‎dotnet/samples/GettingStarted/FoundryAgents/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ Before you begin, ensure you have the following prerequisites:
5858
|[Using plugins](./FoundryAgents_Step13_Plugins/)|This sample demonstrates how to use plugins with a Foundry agent|
5959
|[Code interpreter](./FoundryAgents_Step14_CodeInterpreter/)|This sample demonstrates how to use the code interpreter tool with a Foundry agent|
6060
|[Computer use](./FoundryAgents_Step15_ComputerUse/)|This sample demonstrates how to use computer use capabilities with a Foundry agent|
61+
|[Bing Custom Search](./FoundryAgents_Step21_BingCustomSearch/)|This sample demonstrates how to use Bing Custom Search tool with a Foundry agent|
6162
|[Web search](./FoundryAgents_Step25_WebSearch/)|This sample demonstrates how to use the Responses API web search tool with a Foundry agent|
6263
|[Memory search](./FoundryAgents_Step26_MemorySearch/)|This sample demonstrates how to use memory search tool with a Foundry agent|
6364
|[File search](./FoundryAgents_Step18_FileSearch/)|This sample demonstrates how to use the file search tool with a Foundry agent|

0 commit comments

Comments
 (0)