Skip to content

Commit 7b6c73c

Browse files
committed
new article
1 parent faa88f2 commit 7b6c73c

File tree

3 files changed

+263
-243
lines changed

3 files changed

+263
-243
lines changed
Lines changed: 255 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,255 @@
1+
---
2+
title: 'How to use the Custom Bing Search with Azure AI Agent Service tool'
3+
titleSuffix: Azure OpenAI
4+
description: Find samples to ground Azure AI Agents using Custom Bing Search results.
5+
services: cognitive-services
6+
manager: nitinme
7+
ms.service: azure-ai-agent-service
8+
ms.topic: how-to
9+
ms.date: 04/15/2025
10+
author: aahill
11+
ms.author: aahi
12+
ms.custom: azure-ai-agents
13+
zone_pivot_groups: selection-bing-custom-grounding
14+
---
15+
16+
# How to use Grounding with Bing Custom Search
17+
18+
19+
::: zone pivot="portal"
20+
21+
22+
1. Go to the [Azure AI Foundry portal](https://ai.azure.com/) and use the Grounding with Bing Custom Search tool in your agent.
23+
24+
1. Select the agent you created.
25+
26+
1. Select to add a knowledge tool.
27+
28+
1. Select the **Grounding with Bing Custom Search** tool
29+
30+
1. Select to create a new connection or use an existing connection
31+
32+
1. For new connection, select your Grounding with Bing Custom Search resource.
33+
34+
1. Once you have connected to a resource, select the configuration name.
35+
36+
1. Save the tool and start chatting with your agent.
37+
:::zone-end
38+
39+
::: zone pivot="javascript"
40+
41+
## Step 1: Create a project client
42+
43+
Create a client object, which will contain the connection string for connecting to your AI project and other resources.
44+
45+
```javascript
46+
const { AIProjectsClient, ToolUtility, isOutputOfType } = require("@azure/ai-projects");
47+
const { delay } = require("@azure/core-util");
48+
const { DefaultAzureCredential } = require("@azure/identity");
49+
50+
require("dotenv/config");
51+
52+
const connectionString =
53+
process.env["AZURE_AI_PROJECTS_CONNECTION_STRING"] || "<project connection string>";
54+
55+
// Create an Azure AI Client from a connection string, copied from your AI Foundry project.
56+
// At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<HubName>"
57+
// Customer needs to login to Azure subscription via Azure CLI and set the environment variables
58+
const client = AIProjectsClient.fromConnectionString(
59+
connectionString || "",
60+
new DefaultAzureCredential(),
61+
);
62+
```
63+
64+
65+
## Step 2: Create an Agent with the Grounding with Bing search tool enabled
66+
67+
To make the Grounding with Bing search tool available to your agent, use a connection to initialize the tool and attach it to the agent. You can find your connection in the **connected resources** section of your project in the [Azure AI Foundry portal](https://ai.azure.com/).
68+
69+
```javascript
70+
const bingCustomSearchConnection = await client.connections.getConnection(
71+
process.env["BING_CUSTOM_SEARCH"] || "<connection-name>",
72+
);
73+
console.log(`Bing custom search connection ID:`, bingCustomSearchConnection.id);
74+
75+
// Initialize agent bing custom search tool with the connection id
76+
const bingCustomSearchTool = ToolUtility.createBingCustomSearchTool([
77+
{
78+
connectionId: bingCustomSearchConnection.id,
79+
instanceName: bingCustomSearchConnection.name,
80+
},
81+
]);
82+
83+
// Create agent with the bing tool and process assistant run
84+
const agent = await client.agents.createAgent("gpt-4o", {
85+
name: "my-agent",
86+
instructions:
87+
"You are a customer support chatbot. Use the tools provided and your knowledge base to best respond to customer queries",
88+
tools: [bingCustomSearchTool.definition]
89+
});
90+
console.log(`Created agent, agent ID : ${agent.id}`);
91+
```
92+
93+
## Step 3: Create a thread
94+
95+
```javascript
96+
// create a thread
97+
const thread = await client.agents.createThread();
98+
99+
// add a message to thread
100+
await client.agents.createMessage(
101+
thread.id, {
102+
role: "user",
103+
content: "What is the weather in Seattle?",
104+
});
105+
```
106+
107+
## Step 4: Create a run and check the output
108+
109+
Create a run and observe that the model uses the Grounding with Bing Search tool to provide a response to the user's question.
110+
111+
112+
```javascript
113+
114+
// create a run
115+
const streamEventMessages = await client.agents.createRun(thread.id, agent.id).stream();
116+
117+
for await (const eventMessage of streamEventMessages) {
118+
switch (eventMessage.event) {
119+
case RunStreamEvent.ThreadRunCreated:
120+
break;
121+
case MessageStreamEvent.ThreadMessageDelta:
122+
{
123+
const messageDelta = eventMessage.data;
124+
messageDelta.delta.content.forEach((contentPart) => {
125+
if (contentPart.type === "text") {
126+
const textContent = contentPart;
127+
const textValue = textContent.text?.value || "No text";
128+
}
129+
});
130+
}
131+
break;
132+
133+
case RunStreamEvent.ThreadRunCompleted:
134+
break;
135+
case ErrorEvent.Error:
136+
console.log(`An error occurred. Data ${eventMessage.data}`);
137+
break;
138+
case DoneEvent.Done:
139+
break;
140+
}
141+
}
142+
143+
// Print the messages from the agent
144+
const messages = await client.agents.listMessages(thread.id);
145+
146+
// Messages iterate from oldest to newest
147+
// messages[0] is the most recent
148+
for (let i = messages.data.length - 1; i >= 0; i--) {
149+
const m = messages.data[i];
150+
if (isOutputOfType<MessageTextContentOutput>(m.content[0], "text")) {
151+
const textContent = m.content[0];
152+
console.log(`${textContent.text.value}`);
153+
console.log(`---------------------------------`);
154+
}
155+
}
156+
```
157+
158+
:::zone-end
159+
160+
::: zone pivot="python"
161+
162+
## Step 1: Create a project client
163+
164+
Create a client object, which will contain the connection string for connecting to your AI project and other resources.
165+
166+
```python
167+
168+
import os
169+
from azure.ai.projects import AIProjectClient
170+
from azure.ai.projects.models import MessageRole, BingCustomSearchTool
171+
from azure.identity import DefaultAzureCredential
172+
173+
174+
# Create an Azure AI Client from a connection string, copied from your Azure AI Foundry project.
175+
# At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<HubName>"
176+
# Customer needs to login to Azure subscription via Azure CLI and set the environment variables
177+
178+
project_client = AIProjectClient.from_connection_string(
179+
credential=DefaultAzureCredential(),
180+
conn_str=os.environ["PROJECT_CONNECTION_STRING"],
181+
)
182+
183+
```
184+
185+
186+
## Step 2: Create an Agent with the Grounding with Bing search tool enabled
187+
188+
To make the Grounding with Bing search tool available to your agent, use a connection to initialize the tool and attach it to the agent. You can find your connection in the **connected resources** section of your project in the [Azure AI Foundry portal](https://ai.azure.com/).
189+
190+
```python
191+
bing_custom_connection = project_client.connections.get(connection_name=os.environ["BING_CUSTOM_CONNECTION_NAME"])
192+
conn_id = bing_custom_connection.id
193+
194+
print(conn_id)
195+
196+
# Initialize agent bing custom search tool and add the connection id
197+
bing_custom_tool = BingCustomSearchTool(connection_id=conn_id, instance_name="<config_instance_name>")
198+
199+
# Create agent with the bing custom search tool and process assistant run
200+
with project_client:
201+
agent = project_client.agents.create_agent(
202+
model=os.environ["MODEL_DEPLOYMENT_NAME"],
203+
name="my-agent",
204+
instructions="You are a helpful agent",
205+
tools=bing_custom_tool.definitions
206+
)
207+
print(f"Created agent, ID: {agent.id}")
208+
```
209+
210+
## Step 3: Create a thread
211+
212+
```python
213+
# Create thread for communication
214+
thread = project_client.agents.create_thread()
215+
print(f"Created thread, ID: {thread.id}")
216+
217+
# Create message to thread
218+
message = project_client.agents.create_message(
219+
thread_id=thread.id,
220+
role="user",
221+
content="What is the top news today",
222+
)
223+
print(f"Created message, ID: {message.id}")
224+
```
225+
226+
## Step 4: Create a run and check the output
227+
228+
Create a run and observe that the model uses the Grounding with Bing Search tool to provide a response to the user's question.
229+
230+
231+
```python
232+
# Create and process agent run in thread with tools
233+
run = project_client.agents.create_and_process_run(thread_id=thread.id, agent_id=agent.id)
234+
print(f"Run finished with status: {run.status}")
235+
236+
if run.status == "failed":
237+
print(f"Run failed: {run.last_error}")
238+
239+
# Delete the assistant when done
240+
project_client.agents.delete_agent(agent.id)
241+
print("Deleted agent")
242+
243+
# Print the Agent's response message with optional citation
244+
response_message = project_client.agents.list_messages(thread_id=thread.id).get_last_message_by_role(
245+
MessageRole.AGENT
246+
)
247+
if response_message:
248+
for text_message in response_message.text_messages:
249+
print(f"Agent response: {text_message.text.value}")
250+
for annotation in response_message.url_citation_annotations:
251+
print(f"URL Citation: [{annotation.url_citation.title}]({annotation.url_citation.url})")
252+
```
253+
254+
255+
:::zone-end

0 commit comments

Comments
 (0)