Skip to content

Commit dabd3ae

Browse files
committed
consolidating code
1 parent 03ad44f commit dabd3ae

File tree

1 file changed

+59
-71
lines changed

1 file changed

+59
-71
lines changed

articles/ai-foundry/agents/how-to/tools/function-calling.md

Lines changed: 59 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -54,17 +54,12 @@ def fetch_weather(location: str) -> str:
5454
user_functions = {fetch_weather}
5555
```
5656

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
6458

6559
> [!NOTE]
6660
> 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).
6761
62+
Use the following code sample to create an agent and call the function.
6863

6964
```python
7065
import os, time
@@ -74,7 +69,7 @@ from azure.ai.agents.models import FunctionTool
7469

7570
# Retrieve the project endpoint from environment variables
7671
project_endpoint = os.environ["PROJECT_ENDPOINT"]
77-
72+
model_name = os.environ["MODEL_DEPLOYMENT_NAME"]
7873
# Initialize the AIProjectClient
7974
project_client = AIProjectClient(
8075
endpoint=project_endpoint,
@@ -87,15 +82,13 @@ functions = FunctionTool(functions=user_functions)
8782
with project_client:
8883
# Create an agent with custom functions
8984
agent = project_client.agents.create_agent(
90-
model=os.environ["MODEL_DEPLOYMENT_NAME"],
85+
model=model_name,
9186
name="my-agent",
9287
instructions="You are a helpful agent",
9388
tools=functions.definitions,
9489
)
9590
print(f"Created agent, ID: {agent.id}")
96-
```
97-
## Create a thread
98-
```python
91+
9992
# Create a thread for communication
10093
thread = project_client.agents.threads.create()
10194
print(f"Created thread, ID: {thread.id}")
@@ -107,9 +100,7 @@ message = project_client.agents.messages.create(
107100
content="Hello, send an email with the datetime and weather information in New York?",
108101
)
109102
print(f"Created message, ID: {message['id']}")
110-
```
111-
## Create a run and check the output
112-
```python
103+
113104
# Create and process a run for the agent to handle the message
114105
run = project_client.agents.runs.create(thread_id=thread.id, agent_id=agent.id)
115106
print(f"Created run, ID: {run.id}")
@@ -123,7 +114,7 @@ while run.status in ["queued", "in_progress", "requires_action"]:
123114
tool_calls = run.required_action.submit_tool_outputs.tool_calls
124115
tool_outputs = []
125116
for tool_call in tool_calls:
126-
if tool_call.name == "fetch_weather":
117+
if tool_call.function.name == "fetch_weather":
127118
output = fetch_weather("New York")
128119
tool_outputs.append({"tool_call_id": tool_call.id, "output": output})
129120
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")
147138
> [!NOTE]
148139
> 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).
149140
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
153142

154143
```csharp
155144
using Azure;
@@ -158,7 +147,8 @@ using Azure.Identity;
158147
using Microsoft.Extensions.Configuration;
159148
using System.Text.Json;
160149

161-
// Load configuration from appsettings.json file
150+
//First, set up the configuration using `appsettings.json`, load it, and create a `PersistentAgentsClient`.
151+
162152
IConfigurationRoot configuration = new ConfigurationBuilder()
163153
.SetBasePath(AppContext.BaseDirectory)
164154
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
@@ -169,13 +159,10 @@ var projectEndpoint = configuration["ProjectEndpoint"];
169159
var modelDeploymentName = configuration["ModelDeploymentName"];
170160
// Initialize the client to interact with the Azure AI Agents Persistent Client using default credentials
171161
PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());
172-
```
173162

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.
176165
177-
```csharp
178-
// Function to get the user's favorite city (hardcoded for example)
179166
string GetUserFavoriteCity() => "Seattle, WA";
180167
// Definition for the GetUserFavoriteCity function, describing its purpose to the agent
181168
FunctionToolDefinition getUserFavoriteCityTool = new("getUserFavoriteCity", "Gets the user's favorite city.");
@@ -240,14 +227,14 @@ FunctionToolDefinition getCurrentWeatherAtLocationTool = new(
240227
Required = new[] { "location" },
241228
},
242229
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }));
243-
```
244230

245-
## Implement function execution logic
231+
//Implement function execution logic
246232
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+
*/
248237

249-
```csharp
250-
// Helper function to execute the correct local C# function based on the tool call request from the agent
251238
ToolOutput GetResolvedToolOutput(RequiredToolCall toolCall)
252239
{
253240
// Check if the required call is a function call
@@ -285,13 +272,15 @@ ToolOutput GetResolvedToolOutput(RequiredToolCall toolCall)
285272
// Return null if the tool call type isn't handled
286273
return null;
287274
}
288-
```
289275

290-
## Create agent and conversation thread
276+
//Create agent and conversation thread
291277
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+
*/
293283

294-
```csharp
295284
// Create the agent instance
296285
PersistentAgent agent = client.Administration.CreateAgent(
297286
model: modelDeploymentName,
@@ -309,14 +298,17 @@ client.Messages.CreateMessage(
309298
thread.Id,
310299
MessageRole.User,
311300
"What's the weather like in my favorite city?");
312-
```
313301

314-
## Process run and handle function calls
302+
//Process run and handle function calls
315303
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+
*/
317311

318-
```csharp
319-
// Start a run for the agent to process the messages in the thread
320312
ThreadRun run = client.Runs.CreateRun(thread.Id, agent.Id);
321313

322314
// Loop to check the run status and handle required actions
@@ -340,20 +332,21 @@ do
340332
toolOutputs.Add(GetResolvedToolOutput(toolCall));
341333
}
342334
// Submit the collected tool outputs back to the run
343-
run = client.Runs.SubmitToolOutputsToRun(run, toolOutputs);
335+
run = client.Runs.SubmitToolOutputsToRun(run, toolOutputs, null);
344336
}
345337
}
346338
// Continue looping while the run is in progress or requires action
347339
while (run.Status == RunStatus.Queued
348340
|| run.Status == RunStatus.InProgress
349341
|| run.Status == RunStatus.RequiresAction);
350-
```
351342

352-
## Retrieve and display results
343+
// Retrieve and display results
353344
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+
*/
355349

356-
```csharp
357350
// Retrieve all messages from the completed thread, oldest first
358351
Pageable<PersistentThreadMessage> messages = client.Messages.GetMessages(
359352
threadId: thread.Id,
@@ -378,28 +371,39 @@ foreach (PersistentThreadMessage threadMessage in messages)
378371
}
379372
}
380373
}
381-
```
382374

383-
## Clean up resources
375+
// Clean up resources
384376
377+
/*
385378
Finally, clean up the created resources by deleting the thread and the agent.
379+
*/
386380

387-
```csharp
388381
// Delete the conversation thread
389382
client.Threads.DeleteThread(threadId: thread.Id);
390383
// Delete the agent definition
391384
client.Administration.DeleteAgent(agentId: agent.Id);
392-
```
393385

394386
::: zone-end
395387

396388
::: zone pivot="javascript"
397389

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
401391

402392
```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+
403407
class FunctionToolExecutor {
404408
functionTools;
405409

@@ -488,17 +492,8 @@ class FunctionToolExecutor {
488492
});
489493
}
490494
}
491-
```
492-
493-
## Create a client and agent
494495

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
502497
503498
const projectEndpoint = process.env["PROJECT_ENDPOINT"];
504499

@@ -512,12 +507,8 @@ const functionToolExecutor = new FunctionToolExecutor();
512507
tools: functionTools,
513508
});
514509
console.log(`Created agent, agent ID: ${agent.id}`);
515-
```
516-
517-
## Create a thread
518510

519-
```javascript
520-
// Create thread
511+
// Create a thread
521512
const thread = await client.threads.create();
522513
console.log(`Created Thread, thread ID: ${thread.id}`);
523514

@@ -528,12 +519,9 @@ const message = await client.messages.create(
528519
"What's the weather like in my favorite city?",
529520
);
530521
console.log(`Created message, message ID ${message.id}`);
531-
```
532522

533-
## Create a run and check the output
523+
// Create a run and check the output
534524
535-
```javascript
536-
// Create run
537525
let run = await client.runs.create(thread.id, agent.id);
538526
console.log(`Created Run, Run ID: ${run.id}`);
539527

@@ -579,7 +567,7 @@ for await (const threadMessage of messages) {
579567
}
580568
});
581569
}
582-
// Delete agent
570+
// Delete agent - comment this out if you want to keep your agent
583571
await client.deleteAgent(agent.id);
584572
console.log(`Deleted agent, agent ID: ${agent.id}`);
585573

0 commit comments

Comments
 (0)