@@ -54,17 +54,12 @@ def fetch_weather(location: str) -> str:
54
54
user_functions = {fetch_weather}
55
55
```
56
56
57
- ## Create a client and agent
58
-
59
- <!--
60
- In the sample below we create a client and define a `toolset` which will be used to process the functions defined in `user_functions`.
61
-
62
- `toolset`: When using the toolset parameter, you provide not only the function definitions and descriptions but also their implementations. The SDK will execute these functions within `create_and_run_process` or streaming. These functions will be invoked based on their definitions.
63
- -->
57
+ ## Example agent code
64
58
65
59
> [ !NOTE]
66
60
> You can find a streaming example on [ GitHub] ( https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/ai/azure-ai-agents/samples/agents_streaming/sample_agents_stream_eventhandler_with_functions.py ) .
67
61
62
+ Use the following code sample to create an agent and call the function.
68
63
69
64
``` python
70
65
import os, time
@@ -74,7 +69,7 @@ from azure.ai.agents.models import FunctionTool
74
69
75
70
# Retrieve the project endpoint from environment variables
76
71
project_endpoint = os.environ[" PROJECT_ENDPOINT" ]
77
-
72
+ model_name = os.environ[ " MODEL_DEPLOYMENT_NAME " ]
78
73
# Initialize the AIProjectClient
79
74
project_client = AIProjectClient(
80
75
endpoint = project_endpoint,
@@ -87,15 +82,13 @@ functions = FunctionTool(functions=user_functions)
87
82
with project_client:
88
83
# Create an agent with custom functions
89
84
agent = project_client.agents.create_agent(
90
- model = os.environ[ " MODEL_DEPLOYMENT_NAME " ] ,
85
+ model = model_name ,
91
86
name = " my-agent" ,
92
87
instructions = " You are a helpful agent" ,
93
88
tools = functions.definitions,
94
89
)
95
90
print (f " Created agent, ID: { agent.id} " )
96
- ```
97
- ## Create a thread
98
- ``` python
91
+
99
92
# Create a thread for communication
100
93
thread = project_client.agents.threads.create()
101
94
print (f " Created thread, ID: { thread.id} " )
@@ -107,9 +100,7 @@ message = project_client.agents.messages.create(
107
100
content = " Hello, send an email with the datetime and weather information in New York?" ,
108
101
)
109
102
print (f " Created message, ID: { message[' id' ]} " )
110
- ```
111
- ## Create a run and check the output
112
- ``` python
103
+
113
104
# Create and process a run for the agent to handle the message
114
105
run = project_client.agents.runs.create(thread_id = thread.id, agent_id = agent.id)
115
106
print (f " Created run, ID: { run.id} " )
@@ -123,7 +114,7 @@ while run.status in ["queued", "in_progress", "requires_action"]:
123
114
tool_calls = run.required_action.submit_tool_outputs.tool_calls
124
115
tool_outputs = []
125
116
for tool_call in tool_calls:
126
- if tool_call.name == " fetch_weather" :
117
+ if tool_call.function. name == " fetch_weather" :
127
118
output = fetch_weather(" New York" )
128
119
tool_outputs.append({" tool_call_id" : tool_call.id, " output" : output})
129
120
project_client.agents.runs.submit_tool_outputs(thread_id = thread.id, run_id = run.id, tool_outputs = tool_outputs)
@@ -147,9 +138,7 @@ print("Deleted agent")
147
138
> [ !NOTE]
148
139
> You can find a streaming example on [ GitHub] ( https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/ai/Azure.AI.Agents.Persistent/samples/Sample8_PersistentAgents_FunctionsWithStreaming.md ) .
149
140
150
- ## Configure client and define functions
151
-
152
- First, set up the configuration using ` appsettings.json ` and create a ` PersistentAgentsClient ` .
141
+ ## Configure the client and define functions
153
142
154
143
``` csharp
155
144
using Azure ;
@@ -158,7 +147,8 @@ using Azure.Identity;
158
147
using Microsoft .Extensions .Configuration ;
159
148
using System .Text .Json ;
160
149
161
- // Load configuration from appsettings.json file
150
+ // First, set up the configuration using `appsettings.json`, load it, and create a `PersistentAgentsClient`.
151
+
162
152
IConfigurationRoot configuration = new ConfigurationBuilder ()
163
153
.SetBasePath (AppContext .BaseDirectory )
164
154
.AddJsonFile (" appsettings.json" , optional : false , reloadOnChange : true )
@@ -169,13 +159,10 @@ var projectEndpoint = configuration["ProjectEndpoint"];
169
159
var modelDeploymentName = configuration [" ModelDeploymentName" ];
170
160
// Initialize the client to interact with the Azure AI Agents Persistent Client using default credentials
171
161
PersistentAgentsClient client = new (projectEndpoint , new DefaultAzureCredential ());
172
- ```
173
162
174
- ## Define functions
175
- Define the local C# functions that your agent can call, along with their ` FunctionToolDefinition ` to describe their purpose and parameters to the agent.
163
+ // Define the local C# functions that your agent can call,
164
+ // along with their `FunctionToolDefinition` to describe their purpose and parameters to the agent.
176
165
177
- ``` csharp
178
- // Function to get the user's favorite city (hardcoded for example)
179
166
string GetUserFavoriteCity () => " Seattle, WA" ;
180
167
// Definition for the GetUserFavoriteCity function, describing its purpose to the agent
181
168
FunctionToolDefinition getUserFavoriteCityTool = new (" getUserFavoriteCity" , " Gets the user's favorite city." );
@@ -240,14 +227,14 @@ FunctionToolDefinition getCurrentWeatherAtLocationTool = new(
240
227
Required = new [] { " location" },
241
228
},
242
229
new JsonSerializerOptions () { PropertyNamingPolicy = JsonNamingPolicy .CamelCase }));
243
- ```
244
230
245
- ## Implement function execution logic
231
+ // Implement function execution logic
246
232
247
- Create a helper function , `GetResolvedToolOutput `, to process `RequiredToolCall ` objects from the agent . This function will invoke the appropriate C # local function and return its output to the agent .
233
+ /*
234
+ Create a helper function, `GetResolvedToolOutput`, to process `RequiredToolCall` objects from the agent.
235
+ This function will invoke the appropriate C# local function and return its output to the agent.
236
+ */
248
237
249
- ```csharp
250
- // Helper function to execute the correct local C# function based on the tool call request from the agent
251
238
ToolOutput GetResolvedToolOutput (RequiredToolCall toolCall )
252
239
{
253
240
// Check if the required call is a function call
@@ -285,13 +272,15 @@ ToolOutput GetResolvedToolOutput(RequiredToolCall toolCall)
285
272
// Return null if the tool call type isn't handled
286
273
return null ;
287
274
}
288
- ```
289
275
290
- ## Create agent and conversation thread
276
+ // Create agent and conversation thread
291
277
292
- Now , create the `PersistentAgent `, providing the model deployment name , a descriptive name , instructions for its behavior , and the list of `FunctionToolDefinitions ` it can use . Then , create a `PersistentAgentThread ` and add an initial user message to start the conversation .
278
+ /*
279
+ Create the `PersistentAgent`, providing the model deployment name, a descriptive name,
280
+ instructions for its behavior, and the list of `FunctionToolDefinitions` it can use.
281
+ Then, create a `PersistentAgentThread` and add an initial user message to start the conversation.
282
+ */
293
283
294
- ```csharp
295
284
// Create the agent instance
296
285
PersistentAgent agent = client .Administration .CreateAgent (
297
286
model : modelDeploymentName ,
@@ -309,14 +298,17 @@ client.Messages.CreateMessage(
309
298
thread .Id ,
310
299
MessageRole .User ,
311
300
" What's the weather like in my favorite city?" );
312
- ```
313
301
314
- ## Process run and handle function calls
302
+ // Process run and handle function calls
315
303
316
- Create a `ThreadRun ` for the agent on the thread . Poll for the run 's completion status . If the run status is `RequiresAction `, it means the agent needs to call one of your local functions . Use the `GetResolvedToolOutput ` helper to get the function 's result and submit it back to the run .
304
+ /*
305
+ Create a `ThreadRun` for the agent on the thread. Poll for the run's completion status.
306
+ If the run status is `RequiresAction`, it means the agent needs to call one of your local functions.
307
+ Use the `GetResolvedToolOutput` helper to get the function's result and submit it back to the run.
308
+
309
+ Start a run for the agent to process the messages in the thread
310
+ */
317
311
318
- ```csharp
319
- // Start a run for the agent to process the messages in the thread
320
312
ThreadRun run = client .Runs .CreateRun (thread .Id , agent .Id );
321
313
322
314
// Loop to check the run status and handle required actions
340
332
toolOutputs .Add (GetResolvedToolOutput (toolCall ));
341
333
}
342
334
// Submit the collected tool outputs back to the run
343
- run = client .Runs .SubmitToolOutputsToRun (run , toolOutputs );
335
+ run = client .Runs .SubmitToolOutputsToRun (run , toolOutputs , null );
344
336
}
345
337
}
346
338
// Continue looping while the run is in progress or requires action
347
339
while (run .Status == RunStatus .Queued
348
340
|| run .Status == RunStatus .InProgress
349
341
|| run .Status == RunStatus .RequiresAction );
350
- ```
351
342
352
- ## Retrieve and display results
343
+ // Retrieve and display results
353
344
354
- After the run completes , retrieve all messages from the thread to see the full conversation , including the agent 's final response .
345
+ /*
346
+ After the run completes, retrieve all messages from the thread to see the full conversation,
347
+ including the agent's final response.
348
+ */
355
349
356
- ```csharp
357
350
// Retrieve all messages from the completed thread, oldest first
358
351
Pageable < PersistentThreadMessage > messages = client .Messages .GetMessages (
359
352
threadId : thread .Id ,
@@ -378,28 +371,39 @@ foreach (PersistentThreadMessage threadMessage in messages)
378
371
}
379
372
}
380
373
}
381
- ```
382
374
383
- ## Clean up resources
375
+ // Clean up resources
384
376
377
+ /*
385
378
Finally, clean up the created resources by deleting the thread and the agent.
379
+ */
386
380
387
- ```csharp
388
381
// Delete the conversation thread
389
382
client .Threads .DeleteThread (threadId : thread .Id );
390
383
// Delete the agent definition
391
384
client .Administration .DeleteAgent (agentId : agent .Id );
392
- ```
393
385
394
386
::: zone - end
395
387
396
388
::: zone pivot = " javascript"
397
389
398
- ## Define a function for your agent to call
399
-
400
- Start by defining a function for your agent to call . When you create a function for an agent to call , you describe its structure of it with any required parameters in a docstring .
390
+ ## Example code
401
391
402
392
```javascript
393
+
394
+ // Define a function for your agent to call
395
+
396
+ /*
397
+ Start by defining a function for your agent to call. When you create a function for an agent to call,
398
+ you describe its structure of it with any required parameters in a docstring.
399
+ */
400
+
401
+ const { AgentsClient , ToolUtility , isOutputOfType } = require (" @azure/ai-agents" );
402
+ const { delay } = require (" @azure/core-util" );
403
+ const { DefaultAzureCredential } = require (" @azure/identity" );
404
+
405
+ require (" dotenv/config" );
406
+
403
407
class FunctionToolExecutor {
404
408
functionTools ;
405
409
@@ -488,17 +492,8 @@ class FunctionToolExecutor {
488
492
});
489
493
}
490
494
}
491
- ```
492
-
493
- ## Create a client and agent
494
495
495
-
496
- ```javascript
497
- const { AgentsClient , ToolUtility , isOutputOfType } = require (" @azure/ai-agents" );
498
- const { delay } = require (" @azure/core-util" );
499
- const { DefaultAzureCredential } = require (" @azure/identity" );
500
-
501
- require (" dotenv/config" );
496
+ // Create a client and agent
502
497
503
498
const projectEndpoint = process .env [" PROJECT_ENDPOINT" ];
504
499
@@ -512,12 +507,8 @@ const functionToolExecutor = new FunctionToolExecutor();
512
507
tools : functionTools ,
513
508
});
514
509
console .log (`Created agent , agent ID : ${agent .id }`);
515
- ```
516
-
517
- ## Create a thread
518
510
519
- ``` javascript
520
- // Create thread
511
+ // Create a thread
521
512
const thread = await client .threads .create ();
522
513
console .log (`Created Thread , thread ID : ${thread .id }`);
523
514
@@ -528,12 +519,9 @@ const message = await client.messages.create(
528
519
" What's the weather like in my favorite city?" ,
529
520
);
530
521
console .log (`Created message , message ID ${message .id }`);
531
- ```
532
522
533
- ## Create a run and check the output
523
+ // Create a run and check the output
534
524
535
- ``` javascript
536
- // Create run
537
525
let run = await client .runs .create (thread .id , agent .id );
538
526
console .log (`Created Run , Run ID : ${run .id }`);
539
527
@@ -579,7 +567,7 @@ for await (const threadMessage of messages) {
579
567
}
580
568
});
581
569
}
582
- // Delete agent
570
+ // Delete agent - comment this out if you want to keep your agent
583
571
await client .deleteAgent (agent .id );
584
572
console .log (`Deleted agent , agent ID : ${agent .id }`);
585
573
0 commit comments