@@ -136,112 +136,132 @@ print("Deleted agent")
136
136
137
137
:::zone pivot="csharp"
138
138
139
- ## Step 1: Create an Azure AI Client
140
- First, create an Azure AI Client using the connection string of your project.
139
+ ## Step 1: Create a project client
140
+ Create a client object, which will contain the project endpoint for connecting to your AI project and other resources .
141
141
142
142
``` csharp
143
+ using Azure ;
144
+ using Azure .AI .Agents .Persistent ;
145
+ using Azure .Identity ;
146
+ using Microsoft .Extensions .Configuration ;
143
147
using System ;
144
- using System .Threading .Tasks ;
145
- using Azure .Core ;
146
- using Azure .Core .TestFramework ;
147
- using NUnit .Framework ;
148
- using System .Collections .Generic ;
149
-
150
- // Create an Azure AI Client from a connection string, copied from your Azure AI Foundry project.
151
- // At the moment, it should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<ProjectName>"
152
- // Customer needs to login to Azure subscription via Azure CLI and set the environment variables
153
- var connectionString = TestEnvironment .AzureAICONNECTIONSTRING ;
154
- var clientOptions = new AIProjectClientOptions ();
155
-
156
- // Adding the custom headers policy
157
- clientOptions .AddPolicy (new CustomHeadersPolicy (), HttpPipelinePosition .PerCall );
158
- var projectClient = new AIProjectClient (connectionString , new DefaultAzureCredential (), clientOptions );
159
- ```
148
+ using System .Threading ;
160
149
161
- ## Step 2: Get the connection ID for the Azure AI Search resource
162
- Get the connection ID of the Azure AI Search connection in the project.
150
+ // Get Connection information from app configuration
151
+ IConfigurationRoot configuration = new ConfigurationBuilder ()
152
+ .SetBasePath (AppContext .BaseDirectory )
153
+ .AddJsonFile (" appsettings.json" , optional : false , reloadOnChange : true )
154
+ .Build ();
163
155
164
- ``` csharp
165
- ListConnectionsResponse connections = await projectClient .GetConnectionsClient ().GetConnectionsAsync (ConnectionType .AzureAISearch ).ConfigureAwait (false );
156
+ var projectEndpoint = configuration [" ProjectEndpoint" ];
157
+ var modelDeploymentName = configuration [" ModelDeploymentName" ];
158
+ var azureAiSearchConnectionId = configuration [" AzureAiSearchConnectionId" ];
166
159
167
- if (connections ? .Value == null || connections .Value .Count == 0 )
168
- {
169
- throw new InvalidOperationException (" No connections found for the Azure AI Search." );
170
- }
160
+ // Create the Agent Client
161
+ PersistentAgentsClient agentClient = new (projectEndpoint , new DefaultAzureCredential ());
171
162
```
172
163
173
- ## Step 3 : Configure the Azure AI Search tool
174
- Using the connection ID you got in the previous step, you can now configure the Azure AI Search tool to use your Azure AI Search index.
164
+ ## Step 2 : Configure the Azure AI Search tool
165
+ Using the AI Search Connection ID, configure the Azure AI Search tool to use your Azure AI Search index.
175
166
176
167
``` csharp
177
- // TO DO: replace this value with the connection ID of the search index
178
- ConnectionResponse connection = connections .Value [0 ];
168
+ AzureAISearchResource searchResource = new (
169
+ indexConnectionId : azureAiSearchConnectionId ,
170
+ indexName : " sample_index" ,
171
+ topK : 5 ,
172
+ filter : " category eq 'sleeping bag'" ,
173
+ queryType : AzureAISearchQueryType .Simple
174
+ );
175
+
176
+ ToolResources toolResource = new () { AzureAISearch = searchResource };
179
177
180
- // Initialize agent Azure AI search tool and add the search index connection ID and index name
181
- // TO DO: replace <your-index-name> with the name of the index you want to use
182
- ToolResources searchResource = new ToolResources
183
- {
184
- AzureAISearch = new AzureAISearchResource
185
- {
186
- IndexList = { new IndexResource (connection .Id , " <your-index-name>" , " <select-search-type>" ) }
187
- }
188
- };
189
178
```
190
179
191
- ## Step 4 : Create an agent with the Azure AI Search tool enabled
180
+ ## Step 3 : Create an agent with the Azure AI Search tool enabled
192
181
Change the model to the one deployed in your project. You can find the model name in the Azure AI Foundry under the ** Models** tab. You can also change the name and instructions of the agent to suit your needs.
193
182
194
183
``` csharp
195
- AgentsClient agentClient = projectClient .GetAgentsClient ();
196
-
197
- Response < Agent > agentResponse = await agentClient .CreateAgentAsync (
198
- model : " gpt-4o-mini" ,
199
- name : " my-assistant" ,
200
- instructions : " You are a helpful assistant." ,
201
- tools : new List <ToolDefinition > { new AzureAISearchToolDefinition () },
202
- toolResources : searchResource );
203
- Agent agent = agentResponse .Value ;
184
+ // Create an agent with Tools and Tool Resources
185
+ PersistentAgent agent = agentClient .Administration .CreateAgent (
186
+ model : modelDeploymentName ,
187
+ name : " my-agent" ,
188
+ instructions : " You are a helpful agent." ,
189
+ tools : [new AzureAISearchToolDefinition ()],
190
+ toolResources : toolResource );
191
+
204
192
```
205
193
206
- ## Step 5 : Ask the agent questions about data in the index
194
+ ## Step 4 : Ask the agent questions about data in the index
207
195
Now that the agent is created, ask it questions about the data in your Azure AI Search index.
208
196
209
197
``` csharp
210
198
// Create thread for communication
211
- Response < AgentThread > threadResponse = await agentClient .CreateThreadAsync ();
212
- AgentThread thread = threadResponse .Value ;
199
+ PersistentAgentThread thread = agentClient .Threads .CreateThread ();
213
200
214
- // Create message to thread
215
- Response < ThreadMessage > messageResponse = await agentClient .CreateMessageAsync (
201
+ // Create message and run the agent
202
+ ThreadMessage message = agentClient .Messages . CreateMessage (
216
203
thread .Id ,
217
204
MessageRole .User ,
218
- " what are my health insurance plan coverage types?" );
219
- ThreadMessage message = messageResponse .Value ;
205
+ " What is the temperature rating of the cozynights sleeping bag?" );
206
+ ThreadRun run = agentClient .Runs .CreateRun (thread , agent );
207
+
208
+ ```
209
+
210
+ ## Step 4: Wait for the agent to complete and print the output
220
211
221
- // Run the agent
222
- Response < ThreadRun > runResponse = await agentClient .CreateRunAsync (thread , agent );
212
+ Wait for the agent to complete the run and print output to console.
223
213
214
+ ``` csharp
215
+ // Wait for the agent to finish running
224
216
do
225
217
{
226
- await Task . Delay (TimeSpan .FromMilliseconds (500 ));
227
- runResponse = await agentClient .GetRunAsync (thread .Id , runResponse . Value .Id );
218
+ Thread . Sleep (TimeSpan .FromMilliseconds (500 ));
219
+ run = agentClient .Runs . GetRun (thread .Id , run .Id );
228
220
}
229
- while (runResponse . Value .Status == RunStatus .Queued
230
- || runResponse . Value .Status == RunStatus .InProgress );
221
+ while (run .Status == RunStatus .Queued
222
+ || run .Status == RunStatus .InProgress );
231
223
232
- Response < PageableList < ThreadMessage >> afterRunMessagesResponse
233
- = await agentClient .GetMessagesAsync (thread .Id );
234
- IReadOnlyList < ThreadMessage > messages = afterRunMessagesResponse .Value .Data ;
224
+ // Confirm that the run completed successfully
225
+ if (run .Status != RunStatus .Completed )
226
+ {
227
+ throw new Exception (" Run did not complete successfully, error: " + run .LastError ? .Message );
228
+ }
229
+
230
+ // Retrieve the messages from the agent client
231
+ Pageable < ThreadMessage > messages = agentClient .Messages .GetMessages (
232
+ threadId : thread .Id ,
233
+ order : ListSortOrder .Ascending
234
+ );
235
235
236
- // Note: messages iterate from newest to oldest, with the messages[0] being the most recent
236
+ // Process messages in order
237
237
foreach (ThreadMessage threadMessage in messages )
238
238
{
239
239
Console .Write ($" {threadMessage .CreatedAt : yyyy - MM - dd HH : mm : ss } - {threadMessage .Role ,10 }: " );
240
240
foreach (MessageContent contentItem in threadMessage .ContentItems )
241
241
{
242
242
if (contentItem is MessageTextContent textItem )
243
243
{
244
- Console .Write (textItem .Text );
244
+ // We need to annotate only Agent messages.
245
+ if (threadMessage .Role == MessageRole .Agent && textItem .Annotations .Count > 0 )
246
+ {
247
+ string annotatedText = textItem .Text ;
248
+
249
+ // If we have Text URL citation annotations, reformat the response to show title & URL for citations
250
+ foreach (MessageTextAnnotation annotation in textItem .Annotations )
251
+ {
252
+ if (annotation is MessageTextUrlCitationAnnotation urlAnnotation )
253
+ {
254
+ annotatedText = annotatedText .Replace (
255
+ urlAnnotation .Text ,
256
+ $" [see {urlAnnotation .UrlCitation .Title }] ({urlAnnotation .UrlCitation .Url })" );
257
+ }
258
+ }
259
+ Console .Write (annotatedText );
260
+ }
261
+ else
262
+ {
263
+ Console .Write (textItem .Text );
264
+ }
245
265
}
246
266
else if (contentItem is MessageImageFileContent imageFileItem )
247
267
{
@@ -250,6 +270,17 @@ foreach (ThreadMessage threadMessage in messages)
250
270
Console .WriteLine ();
251
271
}
252
272
}
273
+ ```
274
+ ## Step 5: Clean up resources
275
+
276
+ Clean up the resources from this sample.
277
+
278
+ ``` csharp
279
+
280
+ // Delete thread and agent
281
+ agentClient .Threads .DeleteThread (thread .Id );
282
+ agentClient .Administration .DeleteAgent (agent .Id );
283
+
253
284
```
254
285
255
286
::: zone-end
0 commit comments