Skip to content

Commit d8717a3

Browse files
committed
Update 03-dotnet-agent-framework
1 parent 7107e07 commit d8717a3

File tree

3 files changed

+155
-55
lines changed

3 files changed

+155
-55
lines changed

03-agentic-design-patterns/README.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,13 @@ Imagine you are designing a Travel Agent, here is how you could think about usin
8686
2. **Control** – Make sure it’s clear how the user can modify the Agent after it’s been created with things like the System Prompt. Enable the user to choose how verbose the Agent is, its writing style, and any caveats on what the Agent should not talk about. Allow the user to view and delete any associated files or data, prompts, and past conversations.
8787
3. **Consistency** – Make sure the icons for Share Prompt, add a file or photo and tag someone or something are standard and recognizable. Use the paperclip icon to indicate file upload/sharing with the Agent, and an image icon to indicate graphics upload.
8888

89-
### Got More Questions about AI Agentic Design Patterns?
89+
## Sample Codes
90+
91+
- Python: [Agent Framework](./code_samples/03-python-agent-framework.ipynb)
92+
- .NET: [Agent Framework](./code_samples/03-dotnet-agent-framework.md)
93+
94+
95+
## Got More Questions about AI Agentic Design Patterns?
9096

9197
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.
9298

Lines changed: 84 additions & 27 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;
10-
using Microsoft.Extensions.AI;
7+
using System.ComponentModel;
8+
119
using Microsoft.Agents.AI;
12-
using OpenAI;
13-
using DotNetEnv;
10+
using Microsoft.Extensions.AI;
1411

15-
// Load environment variables
16-
Env.Load("../../../.env");
12+
using OpenAI;
1713

18-
// Define the GetRandomDestination tool
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,37 +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-
// Get configuration from environment variables
42-
var github_endpoint = Environment.GetEnvironmentVariable("GITHUB_ENDPOINT") ?? throw new InvalidOperationException("GITHUB_ENDPOINT is not set.");
43-
var github_model_id = Environment.GetEnvironmentVariable("GITHUB_MODEL_ID") ?? "gpt-4o-mini";
44-
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.");
4551

46-
// Configure OpenAI client options
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
4755
var openAIOptions = new OpenAIClientOptions()
4856
{
4957
Endpoint = new Uri(github_endpoint)
5058
};
5159

52-
// Create OpenAI client
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
5363
var openAIClient = new OpenAIClient(new ApiKeyCredential(github_token), openAIOptions);
5464

55-
// Create AI Agent with vacation planning capabilities
56-
AIAgent agent = new OpenAIClient(new ApiKeyCredential(github_token), openAIOptions)
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.
75+
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
5793
.GetChatClient(github_model_id)
5894
.CreateAIAgent(
59-
instructions: "You are a helpful AI Agent that can help plan vacations for customers at random destinations",
60-
tools: [AIFunctionFactory.Create((Func<string>)GetRandomDestination)]);
95+
name: AGENT_NAME,
96+
instructions: AGENT_INSTRUCTIONS,
97+
tools: [AIFunctionFactory.Create(GetRandomDestination)]
98+
);
6199

62-
// Create a new conversation thread
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
63104
AgentThread thread = agent.GetNewThread();
64105

65-
// First vacation planning request
66-
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();
67117

68-
// Second vacation planning request (with context from first)
69-
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+
}

03-agentic-design-patterns/code_samples/03-dotnet-agent-framework.md

Lines changed: 64 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22

33
## 📋 Learning Objectives
44

5-
This notebook demonstrates enterprise-grade design patterns for building intelligent agents using the Microsoft Agent Framework in .NET with GitHub Models integration. You'll learn professional patterns and architectural approaches that make agents production-ready, maintainable, and scalable.
5+
This example demonstrates enterprise-grade design patterns for building intelligent agents using the Microsoft Agent Framework in .NET with GitHub Models integration. You'll learn professional patterns and architectural approaches that make agents production-ready, maintainable, and scalable.
6+
7+
### Enterprise Design Patterns
68

7-
**Enterprise Design Patterns:**
89
- 🏭 **Factory Pattern**: Standardized agent creation with dependency injection
910
- 🔧 **Builder Pattern**: Fluent agent configuration and setup
1011
- 🧵 **Thread-Safe Patterns**: Concurrent conversation management
@@ -13,12 +14,14 @@ This notebook demonstrates enterprise-grade design patterns for building intelli
1314
## 🎯 .NET-Specific Architectural Benefits
1415

1516
### Enterprise Features
17+
1618
- **Strong Typing**: Compile-time validation and IntelliSense support
1719
- **Dependency Injection**: Built-in DI container integration
1820
- **Configuration Management**: IConfiguration and Options patterns
1921
- **Async/Await**: First-class asynchronous programming support
2022

2123
### Production-Ready Patterns
24+
2225
- **Logging Integration**: ILogger and structured logging support
2326
- **Health Checks**: Built-in monitoring and diagnostics
2427
- **Configuration Validation**: Strong typing with data annotations
@@ -27,67 +30,57 @@ This notebook demonstrates enterprise-grade design patterns for building intelli
2730
## 🔧 Technical Architecture
2831

2932
### Core .NET Components
33+
3034
- **Microsoft.Extensions.AI**: Unified AI service abstractions
3135
- **Microsoft.Agents.AI**: Enterprise agent orchestration framework
3236
- **GitHub Models Integration**: High-performance API client patterns
3337
- **Configuration System**: appsettings.json and environment integration
3438

3539
### Design Pattern Implementation
36-
```csharp
37-
IServiceCollectionAgent BuilderConfigurationTool RegistryAI Agent
40+
41+
```mermaid
42+
graph LR
43+
A[IServiceCollection] --> B[Agent Builder]
44+
B --> C[Configuration]
45+
C --> D[Tool Registry]
46+
D --> E[AI Agent]
3847
```
3948

4049
## 🏗️ Enterprise Patterns Demonstrated
4150

4251
### 1. **Creational Patterns**
52+
4353
- **Agent Factory**: Centralized agent creation with consistent configuration
4454
- **Builder Pattern**: Fluent API for complex agent configuration
4555
- **Singleton Pattern**: Shared resources and configuration management
4656
- **Dependency Injection**: Loose coupling and testability
4757

4858
### 2. **Behavioral Patterns**
59+
4960
- **Strategy Pattern**: Interchangeable tool execution strategies
5061
- **Command Pattern**: Encapsulated agent operations with undo/redo
5162
- **Observer Pattern**: Event-driven agent lifecycle management
5263
- **Template Method**: Standardized agent execution workflows
5364

5465
### 3. **Structural Patterns**
66+
5567
- **Adapter Pattern**: GitHub Models API integration layer
5668
- **Decorator Pattern**: Agent capability enhancement
5769
- **Facade Pattern**: Simplified agent interaction interfaces
5870
- **Proxy Pattern**: Lazy loading and caching for performance
5971

60-
## ⚙️ Prerequisites & Setup
61-
62-
**Development Environment:**
63-
- .NET 9.0 SDK or higher
64-
- Visual Studio 2022 or VS Code with C# extension
65-
- GitHub Models API access
66-
67-
**NuGet Dependencies:**
68-
```xml
69-
<PackageReference Include="Microsoft.Extensions.AI" Version="9.9.0" />
70-
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" Version="9.9.0-preview.1.25458.4" />
71-
<PackageReference Include="DotNetEnv" Version="3.1.1" />
72-
```
73-
74-
**Configuration (.env file):**
75-
```env
76-
GITHUB_TOKEN=your_github_personal_access_token
77-
GITHUB_ENDPOINT=https://models.inference.ai.azure.com
78-
GITHUB_MODEL_ID=gpt-4o-mini
79-
```
80-
8172
## 📚 .NET Design Principles
8273

8374
### SOLID Principles
75+
8476
- **Single Responsibility**: Each component has one clear purpose
8577
- **Open/Closed**: Extensible without modification
8678
- **Liskov Substitution**: Interface-based tool implementations
8779
- **Interface Segregation**: Focused, cohesive interfaces
8880
- **Dependency Inversion**: Depend on abstractions, not concretions
8981

9082
### Clean Architecture
83+
9184
- **Domain Layer**: Core agent and tool abstractions
9285
- **Application Layer**: Agent orchestration and workflows
9386
- **Infrastructure Layer**: GitHub Models integration and external services
@@ -96,18 +89,21 @@ GITHUB_MODEL_ID=gpt-4o-mini
9689
## 🔒 Enterprise Considerations
9790

9891
### Security
92+
9993
- **Credential Management**: Secure API key handling with IConfiguration
10094
- **Input Validation**: Strong typing and data annotation validation
10195
- **Output Sanitization**: Secure response processing and filtering
10296
- **Audit Logging**: Comprehensive operation tracking
10397

10498
### Performance
99+
105100
- **Async Patterns**: Non-blocking I/O operations
106101
- **Connection Pooling**: Efficient HTTP client management
107102
- **Caching**: Response caching for improved performance
108103
- **Resource Management**: Proper disposal and cleanup patterns
109104

110105
### Scalability
106+
111107
- **Thread Safety**: Concurrent agent execution support
112108
- **Resource Pooling**: Efficient resource utilization
113109
- **Load Management**: Rate limiting and backpressure handling
@@ -123,6 +119,47 @@ GITHUB_MODEL_ID=gpt-4o-mini
123119

124120
Ready to build enterprise-grade intelligent agents with .NET? Let's architect something robust! 🏢✨
125121

126-
## Code Sample
122+
## 🚀 Getting Started
123+
124+
### Prerequisites
125+
126+
- [.NET 10 SDK](https://dotnet.microsoft.com/download/dotnet/10.0) or higher
127+
- [GitHub Models API access token](https://docs.github.com/github-models/github-models-at-scale/using-your-own-api-keys-in-github-models)
128+
129+
### Required Environment Variables
130+
131+
```bash
132+
# zsh/bash
133+
export GH_TOKEN=<your_github_token>
134+
export GH_ENDPOINT=https://models.github.ai/inference
135+
export GH_MODEL_ID=openai/gpt-5-mini
136+
```
137+
138+
```powershell
139+
# PowerShell
140+
$env:GH_TOKEN = "<your_github_token>"
141+
$env:GH_ENDPOINT = "https://models.github.ai/inference"
142+
$env:GH_MODEL_ID = "openai/gpt-5-mini"
143+
```
144+
145+
### Sample Code
146+
147+
To run the code example,
148+
149+
```bash
150+
# zsh/bash
151+
chmod +x ./03-dotnet-agent-framework.cs
152+
./03-dotnet-agent-framework.cs
153+
```
154+
155+
Or using the dotnet CLI:
156+
157+
```bash
158+
dotnet run ./03-dotnet-agent-framework.cs
159+
```
160+
161+
See [`03-dotnet-agent-framework.cs`](./03-dotnet-agent-framework.cs) for the complete code.
162+
163+
```csharp
127164

128-
For a complete working example, see [03-dotnet-agent-framework.cs](./03-dotnet-agent-framework.cs).
165+
```

0 commit comments

Comments
 (0)