Skip to content

Commit 3f52a24

Browse files
authored
Merge pull request #408 from microsoft/docs/04-tool-use
Review Microsoft Agent Framework in .NET for chapter 04
2 parents 71cb52c + 5d6be33 commit 3f52a24

File tree

3 files changed

+266
-53
lines changed

3 files changed

+266
-53
lines changed

04-tool-use/README.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,12 @@ A common concern with SQL dynamically generated by LLMs is security, particularl
309309

310310
Running the app in a secure environment further enhances protection. In enterprise scenarios, data is typically extracted and transformed from operational systems into a read-only database or data warehouse with a user-friendly schema. This approach ensures that the data is secure, optimized for performance and accessibility, and that the app has restricted, read-only access.
311311

312-
### Got More Questions about the Tool Use Design Patterns?
312+
## Sample Codes
313+
314+
- Python: [Agent Framework](./code_samples/04-python-agent-framework.ipynb)
315+
- .NET: [Agent Framework](./code_samples/04-dotnet-agent-framework.md)
316+
317+
## Got More Questions about the Tool Use Design Patterns?
313318

314319
Join the [Azure AI Foundry Discord](https://aka.ms/ai-agents/discord) to meet with other learners, attend office hours and get your AI Agents questions answered.
315320

Lines changed: 85 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,25 @@
11
#!/usr/bin/dotnet run
2-
#:package Microsoft.Extensions.AI@9.9.1
3-
#:package Microsoft.Agents.AI.OpenAI@1.0.0-preview.251001.3
4-
#:package Microsoft.Agents.AI@1.0.0-preview.251001.3
5-
#:package DotNetEnv@3.1.1
62

7-
using System;
8-
using System.ComponentModel;
3+
#:package Microsoft.Extensions.AI@10.*
4+
#:package Microsoft.Agents.AI.OpenAI@1.*-*
5+
96
using System.ClientModel;
7+
using System.ComponentModel;
108

11-
using Microsoft.Extensions.AI;
129
using Microsoft.Agents.AI;
13-
using OpenAI;
14-
15-
using DotNetEnv;
10+
using Microsoft.Extensions.AI;
1611

17-
Env.Load("../../../.env");
12+
using OpenAI;
1813

14+
// Tool Function: Random Destination Generator
15+
// This static method will be available to the agent as a callable tool
16+
// The [Description] attribute helps the AI understand when to use this function
17+
// This demonstrates how to create custom tools for AI agents
1918
[Description("Provides a random vacation destination.")]
2019
static string GetRandomDestination()
2120
{
21+
// List of popular vacation destinations around the world
22+
// The agent will randomly select from these options
2223
var destinations = new List<string>
2324
{
2425
"Paris, France",
@@ -33,27 +34,93 @@ static string GetRandomDestination()
3334
"Vancouver, Canada"
3435
};
3536

37+
// Generate random index and return selected destination
38+
// Uses System.Random for simple random selection
3639
var random = new Random();
3740
int index = random.Next(destinations.Count);
3841
return destinations[index];
3942
}
4043

41-
var github_endpoint = Environment.GetEnvironmentVariable("GITHUB_ENDPOINT") ?? throw new InvalidOperationException("GITHUB_ENDPOINT is not set.");
42-
var github_model_id = Environment.GetEnvironmentVariable("GITHUB_MODEL_ID") ?? "gpt-4o-mini";
43-
var github_token = Environment.GetEnvironmentVariable("GITHUB_TOKEN") ?? throw new InvalidOperationException("GITHUB_TOKEN is not set.");
44+
// Extract configuration from environment variables
45+
// Retrieve the GitHub Models API endpoint, defaults to https://models.github.ai/inference if not specified
46+
// Retrieve the model ID, defaults to openai/gpt-5-mini if not specified
47+
// Retrieve the GitHub token for authentication, throws exception if not specified
48+
var github_endpoint = Environment.GetEnvironmentVariable("GH_ENDPOINT") ?? "https://models.github.ai/inference";
49+
var github_model_id = Environment.GetEnvironmentVariable("GH_MODEL_ID") ?? "openai/gpt-5-mini";
50+
var github_token = Environment.GetEnvironmentVariable("GH_TOKEN") ?? throw new InvalidOperationException("GH_TOKEN is not set.");
4451

52+
// Configure OpenAI Client Options
53+
// Create configuration options to point to GitHub Models endpoint
54+
// This redirects OpenAI client calls to GitHub's model inference service
4555
var openAIOptions = new OpenAIClientOptions()
4656
{
4757
Endpoint = new Uri(github_endpoint)
4858
};
4959

60+
// Initialize OpenAI Client with GitHub Models Configuration
61+
// Create OpenAI client using GitHub token for authentication
62+
// Configure it to use GitHub Models endpoint instead of OpenAI directly
5063
var openAIClient = new OpenAIClient(new ApiKeyCredential(github_token), openAIOptions);
5164

52-
AIAgent agent = new OpenAIClient(new ApiKeyCredential(github_token), openAIOptions).GetChatClient(github_model_id).CreateAIAgent(
53-
instructions: "You are a helpful AI Agent that can help plan vacations for customers at random destinations", tools: [AIFunctionFactory.Create(GetRandomDestination)]);
65+
// Define Agent Identity and Comprehensive Instructions
66+
// Agent name for identification and logging purposes
67+
var AGENT_NAME = "TravelAgent";
68+
69+
// Detailed instructions that define the agent's personality, capabilities, and behavior
70+
// This system prompt shapes how the agent responds and interacts with users
71+
var AGENT_INSTRUCTIONS = """
72+
You are a helpful AI Agent that can help plan vacations for customers.
73+
74+
Important: When users specify a destination, always plan for that location. Only suggest random destinations when the user hasn't specified a preference.
5475
76+
When the conversation begins, introduce yourself with this message:
77+
"Hello! I'm your TravelAgent assistant. I can help plan vacations and suggest interesting destinations for you. Here are some things you can ask me:
78+
1. Plan a day trip to a specific location
79+
2. Suggest a random vacation destination
80+
3. Find destinations with specific features (beaches, mountains, historical sites, etc.)
81+
4. Plan an alternative trip if you don't like my first suggestion
82+
83+
What kind of trip would you like me to help you plan today?"
84+
85+
Always prioritize user preferences. If they mention a specific destination like "Bali" or "Paris," focus your planning on that location rather than suggesting alternatives.
86+
""";
87+
88+
// Create AI Agent with Advanced Travel Planning Capabilities
89+
// Initialize complete agent pipeline: OpenAI client → Chat client → AI agent
90+
// Configure agent with name, detailed instructions, and available tools
91+
// This demonstrates the .NET agent creation pattern with full configuration
92+
AIAgent agent = openAIClient
93+
.GetChatClient(github_model_id)
94+
.CreateAIAgent(
95+
name: AGENT_NAME,
96+
instructions: AGENT_INSTRUCTIONS,
97+
tools: [AIFunctionFactory.Create(GetRandomDestination)]
98+
);
99+
100+
// Create New Conversation Thread for Context Management
101+
// Initialize a new conversation thread to maintain context across multiple interactions
102+
// Threads enable the agent to remember previous exchanges and maintain conversational state
103+
// This is essential for multi-turn conversations and contextual understanding
55104
AgentThread thread = agent.GetNewThread();
56105

57-
Console.WriteLine(await agent.RunAsync("Plan me a day trip", thread));
106+
// Execute Agent: First Travel Planning Request
107+
// Run the agent with an initial request that will likely trigger the random destination tool
108+
// The agent will analyze the request, use the GetRandomDestination tool, and create an itinerary
109+
// Using the thread parameter maintains conversation context for subsequent interactions
110+
await foreach (var update in agent.RunStreamingAsync("Plan me a day trip", thread))
111+
{
112+
await Task.Delay(10);
113+
Console.Write(update);
114+
}
115+
116+
Console.WriteLine();
58117

59-
Console.WriteLine(await agent.RunAsync("I don't like that destination. Plan me another vacation.", thread));
118+
// Execute Agent: Follow-up Request with Context Awareness
119+
// Demonstrate contextual conversation by referencing the previous response
120+
// The agent remembers the previous destination suggestion and will provide an alternative
121+
// This showcases the power of conversation threads and contextual understanding in .NET agents
122+
await foreach (var update in agent.RunStreamingAsync("I don't like that destination. Plan me another vacation.", thread))
123+
{
124+
await Task.Delay(10);
125+
Console.Write(update);
126+
}

0 commit comments

Comments
 (0)