Skip to content

Commit ebcaa85

Browse files
authored
Merge pull request #4 from petehauge/initial-sample-changes
Update Bing Grounding Sample
2 parents 35fa1be + 44f4be2 commit ebcaa85

File tree

1 file changed

+199
-0
lines changed

1 file changed

+199
-0
lines changed
Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
# Sample for use of an agent with Bing grounding in Azure.AI.Agents.
2+
3+
To enable your Agent to perform search through Bing search API, you use `BingGroundingToolDefinition` along with a connection.
4+
1. First we need to create an agent and read the environment variables, which will be used in the next steps.
5+
6+
```C# Snippet:AgentsBingGrounding_CreateProject
7+
8+
// Get Connection information from Environment Variables
9+
// To use App Config instead: https://learn.microsoft.com/en-us/visualstudio/ide/managing-application-settings-dotnet
10+
var projectEndpoint = System.Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
11+
var modelDeploymentName = System.Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME");
12+
var connectionId = System.Environment.GetEnvironmentVariable("AZURE_BING_CONECTION_ID");
13+
14+
// Create the Agent Client
15+
PersistentAgentsClient agentClient = new(projectEndpoint, new DefaultAzureCredential());
16+
```
17+
18+
2. We will use the Bing connection ID to initialize the `BingGroundingToolDefinition`.
19+
20+
```C# Snippet:AgentsBingGrounding_GetConnection
21+
ToolConnectionList connectionList = new()
22+
{
23+
ConnectionList = { new ToolConnection(bingConnectionId) }
24+
};
25+
BingGroundingToolDefinition bingGroundingTool = new(connectionList);
26+
```
27+
28+
3. We will use the `BingGroundingToolDefinition` during the agent initialization.
29+
30+
Synchronous sample:
31+
```C# Snippet:AgentsBingGrounding_CreateAgent
32+
// Create the Agent
33+
PersistentAgent agent = agentClient.CreateAgent(
34+
model: modelDeploymentName,
35+
name: "my-agent",
36+
instructions: "You are a helpful agent.",
37+
tools: [bingGroundingTool]);
38+
```
39+
40+
Asynchronous sample:
41+
```C# Snippet:AgentsBingGroundingAsync_CreateAgent
42+
// Create the Agent
43+
PersistentAgent agent = await agentClient.CreateAgentAsync(
44+
model: modelDeploymentName,
45+
name: "my-agent",
46+
instructions: "You are a helpful agent.",
47+
tools: [ bingGroundingTool ]);
48+
```
49+
50+
4. Now we will create the thread, add the message , containing a question for agent and start the run.
51+
52+
Synchronous sample:
53+
```C# Snippet:AgentsBingGrounding_CreateThreadMessage
54+
PersistentAgentThread thread = agentClient.CreateThread();
55+
56+
// Create message and run the agent
57+
ThreadMessage message = agentClient.CreateMessage(
58+
thread.Id,
59+
MessageRole.User,
60+
"How does wikipedia explain Euler's Identity?");
61+
ThreadRun run = agentClient.CreateRun(thread, agent);
62+
63+
// Wait for the agent to finish running
64+
do
65+
{
66+
Thread.Sleep(TimeSpan.FromMilliseconds(500));
67+
run = agentClient.GetRun(thread.Id, run.Id);
68+
}
69+
while (run.Status == RunStatus.Queued
70+
|| run.Status == RunStatus.InProgress);
71+
72+
// Confirm that the run completed successfully
73+
if (run.Status != RunStatus.Completed)
74+
{
75+
throw new Exception("Run did not complete successfully, error: " + run.LastError?.Message);
76+
}
77+
78+
```
79+
80+
Asynchronous sample:
81+
```C# Snippet:AgentsBingGroundingAsync_CreateThreadMessage
82+
PersistentAgentThread thread = await agentClient.CreateThreadAsync();
83+
84+
// Create message and run the agent
85+
ThreadMessage message = await agentClient.CreateMessageAsync(
86+
thread.Id,
87+
MessageRole.User,
88+
"How does wikipedia explain Euler's Identity?");
89+
ThreadRun run = await agentClient.CreateRunAsync(thread, agent);
90+
91+
// Wait for the agent to finish running
92+
do
93+
{
94+
await Task.Delay(TimeSpan.FromMilliseconds(500));
95+
run = await agentClient.GetRunAsync(thread.Id, run.Id);
96+
}
97+
while (run.Status == RunStatus.Queued
98+
|| run.Status == RunStatus.InProgress);
99+
100+
// Confirm that the run completed successfully
101+
if (run.Status != RunStatus.Completed)
102+
{
103+
throw new Exception("Run did not complete successfully, error: " + run.LastError?.Message);
104+
}
105+
106+
```
107+
108+
5. Print the agent messages to console in chronological order.
109+
110+
Synchronous sample:
111+
```C# Snippet:AgentsBingGrounding_Print
112+
PageableList<ThreadMessage> messages = agentClient.GetMessages(
113+
threadId: thread.Id,
114+
order: ListSortOrder.Ascending
115+
);
116+
117+
foreach (ThreadMessage threadMessage in messages)
118+
{
119+
Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
120+
foreach (MessageContent contentItem in threadMessage.ContentItems)
121+
{
122+
if (contentItem is MessageTextContent textItem)
123+
{
124+
string response = textItem.Text;
125+
if (textItem.Annotations != null)
126+
{
127+
foreach (MessageTextAnnotation annotation in textItem.Annotations)
128+
{
129+
if (annotation is MessageTextUrlCitationAnnotation urlAnnotation)
130+
{
131+
response = response.Replace(urlAnnotation.Text, $" [{urlAnnotation.UrlCitation.Title}]({urlAnnotation.UrlCitation.Url})");
132+
}
133+
}
134+
}
135+
Console.Write($"Agent response: {response}");
136+
}
137+
else if (contentItem is MessageImageFileContent imageFileItem)
138+
{
139+
Console.Write($"<image from ID: {imageFileItem.FileId}");
140+
}
141+
Console.WriteLine();
142+
}
143+
}
144+
```
145+
146+
Asynchronous sample:
147+
```C# Snippet:AgentsBingGroundingAsync_Print
148+
PageableList<ThreadMessage> messages = await agentClient.GetMessagesAsync(
149+
threadId: thread.Id,
150+
order: ListSortOrder.Ascending
151+
);
152+
153+
foreach (ThreadMessage threadMessage in messages)
154+
{
155+
Console.Write($"{threadMessage.CreatedAt:yyyy-MM-dd HH:mm:ss} - {threadMessage.Role,10}: ");
156+
157+
foreach (MessageContent contentItem in threadMessage.ContentItems)
158+
{
159+
if (contentItem is MessageTextContent textItem)
160+
{
161+
string response = textItem.Text;
162+
163+
// If we have Text URL citation annotations, reformat the response to show title & URL for citations
164+
if (textItem.Annotations != null)
165+
{
166+
foreach (MessageTextAnnotation annotation in textItem.Annotations)
167+
{
168+
if (annotation is MessageTextUrlCitationAnnotation urlAnnotation)
169+
{
170+
response = response.Replace(urlAnnotation.Text, $" [{urlAnnotation.UrlCitation.Title}]({urlAnnotation.UrlCitation.Url})");
171+
}
172+
}
173+
}
174+
Console.Write($"Agent response: {response}");
175+
}
176+
else if (contentItem is MessageImageFileContent imageFileItem)
177+
{
178+
Console.Write($"<image from ID: {imageFileItem.FileId}");
179+
}
180+
Console.WriteLine();
181+
}
182+
}
183+
```
184+
185+
6. Clean up resources by deleting thread and agent.
186+
187+
Synchronous sample:
188+
```C# Snippet:AgentsBingGroundingCleanup
189+
// Delete thread and agent
190+
agentClient.DeleteThread(threadId: thread.Id);
191+
agentClient.DeleteAgent(agentId: agent.Id);
192+
```
193+
194+
Asynchronous sample:
195+
```C# Snippet:AgentsBingGroundingCleanupAsync
196+
// Delete thread and agent
197+
await agentClient.DeleteThreadAsync(threadId: thread.Id);
198+
await agentClient.DeleteAgentAsync(agentId: agent.Id);
199+
```

0 commit comments

Comments
 (0)