Skip to content

Commit aa31878

Browse files
committed
Update 04-dotnet-agent-framework
1 parent d8717a3 commit aa31878

File tree

3 files changed

+141
-53
lines changed

3 files changed

+141
-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+
}

04-tool-use/code_samples/04-dotnet-agent-framework.md

Lines changed: 50 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44

55
This notebook demonstrates enterprise-grade tool integration patterns using the Microsoft Agent Framework in .NET with GitHub Models. You'll learn to build sophisticated agents with multiple specialized tools, leveraging C#'s strong typing and .NET's enterprise features.
66

7-
**Advanced Tool Capabilities You'll Master:**
7+
### Advanced Tool Capabilities You'll Master
8+
89
- 🔧 **Multi-Tool Architecture**: Building agents with multiple specialized capabilities
910
- 🎯 **Type-Safe Tool Execution**: Leveraging C#'s compile-time validation
1011
- 📊 **Enterprise Tool Patterns**: Production-ready tool design and error handling
@@ -13,12 +14,14 @@ This notebook demonstrates enterprise-grade tool integration patterns using the
1314
## 🎯 .NET Tool Architecture Benefits
1415

1516
### Enterprise Tool Features
17+
1618
- **Compile-Time Validation**: Strong typing ensures tool parameter correctness
1719
- **Dependency Injection**: IoC container integration for tool management
1820
- **Async/Await Patterns**: Non-blocking tool execution with proper resource management
1921
- **Structured Logging**: Built-in logging integration for tool execution monitoring
2022

2123
### Production-Ready Patterns
24+
2225
- **Exception Handling**: Comprehensive error management with typed exceptions
2326
- **Resource Management**: Proper disposal patterns and memory management
2427
- **Performance Monitoring**: Built-in metrics and performance counters
@@ -27,79 +30,92 @@ This notebook demonstrates enterprise-grade tool integration patterns using the
2730
## 🔧 Technical Architecture
2831

2932
### Core .NET Tool Components
33+
3034
- **Microsoft.Extensions.AI**: Unified tool abstraction layer
3135
- **Microsoft.Agents.AI**: Enterprise-grade tool orchestration
3236
- **GitHub Models Integration**: High-performance API client with connection pooling
3337

3438
### Tool Execution Pipeline
35-
```
36-
User Request → Agent Analysis → Tool Selection → Type Validation
37-
↓ ↓ ↓
38-
Parameter Binding → Tool Execution → Result Processing → Response
39+
40+
```mermaid
41+
graph LR
42+
A[User Request] --> B[Agent Analysis]
43+
B --> C[Tool Selection]
44+
C --> D[Type Validation]
45+
B --> E[Parameter Binding]
46+
E --> F[Tool Execution]
47+
C --> F
48+
F --> G[Result Processing]
49+
D --> G
50+
G --> H[Response]
3951
```
4052

4153
## 🛠️ Tool Categories & Patterns
4254

4355
### 1. **Data Processing Tools**
56+
4457
- **Input Validation**: Strong typing with data annotations
4558
- **Transform Operations**: Type-safe data conversion and formatting
4659
- **Business Logic**: Domain-specific calculation and analysis tools
4760
- **Output Formatting**: Structured response generation
4861

4962
### 2. **Integration Tools**
63+
5064
- **API Connectors**: RESTful service integration with HttpClient
5165
- **Database Tools**: Entity Framework integration for data access
5266
- **File Operations**: Secure file system operations with validation
5367
- **External Services**: Third-party service integration patterns
5468

5569
### 3. **Utility Tools**
70+
5671
- **Text Processing**: String manipulation and formatting utilities
5772
- **Date/Time Operations**: Culture-aware date/time calculations
5873
- **Mathematical Tools**: Precision calculations and statistical operations
5974
- **Validation Tools**: Business rule validation and data verification
6075

61-
## ⚙️ Prerequisites & Setup
76+
Ready to build enterprise-grade agents with powerful, type-safe tool capabilities in .NET? Let's architect some professional-grade solutions! 🏢⚡
6277

63-
**Development Environment:**
64-
- .NET 9.0 SDK or higher
65-
- Visual Studio 2022 or VS Code with C# extension
66-
- GitHub Models API access
78+
## 🚀 Getting Started
6779

68-
**Required NuGet Packages:**
69-
```xml
70-
<PackageReference Include="Microsoft.Extensions.AI" Version="9.9.0" />
71-
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="9.9.0-preview.1.25458.4" />
72-
<PackageReference Include="DotNetEnv" Version="3.1.1" />
73-
```
80+
### Prerequisites
7481

75-
**Environment Configuration (.env file):**
76-
```env
77-
GITHUB_TOKEN=your_github_personal_access_token
78-
GITHUB_ENDPOINT=https://models.inference.ai.azure.com
79-
GITHUB_MODEL_ID=gpt-4o-mini
80-
```
82+
- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) or higher
83+
- [GitHub Models API access token](https://docs.github.com/github-models/github-models-at-scale/using-your-own-api-keys-in-github-models)
8184

82-
Ready to build enterprise-grade agents with powerful, type-safe tool capabilities in .NET? Let's architect some professional-grade solutions! 🏢⚡
85+
### Required Environment Variables
8386

84-
## 💻 Code Implementation
87+
```bash
88+
# zsh/bash
89+
export GH_TOKEN=<your_github_token>
90+
export GH_ENDPOINT=https://models.github.ai/inference
91+
export GH_MODEL_ID=openai/gpt-5-mini
92+
```
8593

86-
The complete C# implementation is available in the companion file `04-dotnet-agent-framework.cs`. This .NET Single File App demonstrates:
94+
```powershell
95+
# PowerShell
96+
$env:GH_TOKEN = "<your_github_token>"
97+
$env:GH_ENDPOINT = "https://models.github.ai/inference"
98+
$env:GH_MODEL_ID = "openai/gpt-5-mini"
99+
```
87100

88-
- Loading environment variables for GitHub Models configuration
89-
- Defining custom tools using C# methods with attributes
90-
- Creating an AI agent with tool integration
91-
- Managing conversation threads
92-
- Executing agent requests with tool invocation
101+
### Sample Code
93102

94-
To run the example:
103+
To run the code example,
95104

96105
```bash
97-
chmod +x 04-dotnet-agent-framework.cs
106+
# zsh/bash
107+
chmod +x ./04-dotnet-agent-framework.cs
98108
./04-dotnet-agent-framework.cs
99109
```
100110

101-
Or using the .NET CLI:
111+
Or using the dotnet CLI:
102112

103113
```bash
104-
dotnet run 04-dotnet-agent-framework.cs
114+
dotnet run ./04-dotnet-agent-framework.cs
105115
```
116+
117+
See [`04-dotnet-agent-framework.cs`](./04-dotnet-agent-framework.cs) for the complete code.
118+
119+
```csharp
120+
121+
```

0 commit comments

Comments
 (0)