Skip to content

Commit 5d6be33

Browse files
committed
Add code snippet
1 parent 341979f commit 5d6be33

File tree

1 file changed

+126
-1
lines changed

1 file changed

+126
-1
lines changed

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

Lines changed: 126 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,5 +117,130 @@ dotnet run ./04-dotnet-agent-framework.cs
117117
See [`04-dotnet-agent-framework.cs`](./04-dotnet-agent-framework.cs) for the complete code.
118118

119119
```csharp
120-
120+
#!/usr/bin/dotnet run
121+
122+
#:package Microsoft.Extensions.AI@10.*
123+
#:package Microsoft.Agents.AI.OpenAI@1.*-*
124+
125+
using System.ClientModel;
126+
using System.ComponentModel;
127+
128+
using Microsoft.Agents.AI;
129+
using Microsoft.Extensions.AI;
130+
131+
using OpenAI;
132+
133+
// Tool Function: Random Destination Generator
134+
// This static method will be available to the agent as a callable tool
135+
// The [Description] attribute helps the AI understand when to use this function
136+
// This demonstrates how to create custom tools for AI agents
137+
[Description("Provides a random vacation destination.")]
138+
static string GetRandomDestination()
139+
{
140+
// List of popular vacation destinations around the world
141+
// The agent will randomly select from these options
142+
var destinations = new List<string>
143+
{
144+
"Paris, France",
145+
"Tokyo, Japan",
146+
"New York City, USA",
147+
"Sydney, Australia",
148+
"Rome, Italy",
149+
"Barcelona, Spain",
150+
"Cape Town, South Africa",
151+
"Rio de Janeiro, Brazil",
152+
"Bangkok, Thailand",
153+
"Vancouver, Canada"
154+
};
155+
156+
// Generate random index and return selected destination
157+
// Uses System.Random for simple random selection
158+
var random = new Random();
159+
int index = random.Next(destinations.Count);
160+
return destinations[index];
161+
}
162+
163+
// Extract configuration from environment variables
164+
// Retrieve the GitHub Models API endpoint, defaults to https://models.github.ai/inference if not specified
165+
// Retrieve the model ID, defaults to openai/gpt-5-mini if not specified
166+
// Retrieve the GitHub token for authentication, throws exception if not specified
167+
var github_endpoint = Environment.GetEnvironmentVariable("GH_ENDPOINT") ?? "https://models.github.ai/inference";
168+
var github_model_id = Environment.GetEnvironmentVariable("GH_MODEL_ID") ?? "openai/gpt-5-mini";
169+
var github_token = Environment.GetEnvironmentVariable("GH_TOKEN") ?? throw new InvalidOperationException("GH_TOKEN is not set.");
170+
171+
// Configure OpenAI Client Options
172+
// Create configuration options to point to GitHub Models endpoint
173+
// This redirects OpenAI client calls to GitHub's model inference service
174+
var openAIOptions = new OpenAIClientOptions()
175+
{
176+
Endpoint = new Uri(github_endpoint)
177+
};
178+
179+
// Initialize OpenAI Client with GitHub Models Configuration
180+
// Create OpenAI client using GitHub token for authentication
181+
// Configure it to use GitHub Models endpoint instead of OpenAI directly
182+
var openAIClient = new OpenAIClient(new ApiKeyCredential(github_token), openAIOptions);
183+
184+
// Define Agent Identity and Comprehensive Instructions
185+
// Agent name for identification and logging purposes
186+
var AGENT_NAME = "TravelAgent";
187+
188+
// Detailed instructions that define the agent's personality, capabilities, and behavior
189+
// This system prompt shapes how the agent responds and interacts with users
190+
var AGENT_INSTRUCTIONS = """
191+
You are a helpful AI Agent that can help plan vacations for customers.
192+
193+
Important: When users specify a destination, always plan for that location. Only suggest random destinations when the user hasn't specified a preference.
194+
195+
When the conversation begins, introduce yourself with this message:
196+
"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:
197+
1. Plan a day trip to a specific location
198+
2. Suggest a random vacation destination
199+
3. Find destinations with specific features (beaches, mountains, historical sites, etc.)
200+
4. Plan an alternative trip if you don't like my first suggestion
201+
202+
What kind of trip would you like me to help you plan today?"
203+
204+
Always prioritize user preferences. If they mention a specific destination like "Bali" or "Paris," focus your planning on that location rather than suggesting alternatives.
205+
""";
206+
207+
// Create AI Agent with Advanced Travel Planning Capabilities
208+
// Initialize complete agent pipeline: OpenAI client → Chat client → AI agent
209+
// Configure agent with name, detailed instructions, and available tools
210+
// This demonstrates the .NET agent creation pattern with full configuration
211+
AIAgent agent = openAIClient
212+
.GetChatClient(github_model_id)
213+
.CreateAIAgent(
214+
name: AGENT_NAME,
215+
instructions: AGENT_INSTRUCTIONS,
216+
tools: [AIFunctionFactory.Create(GetRandomDestination)]
217+
);
218+
219+
// Create New Conversation Thread for Context Management
220+
// Initialize a new conversation thread to maintain context across multiple interactions
221+
// Threads enable the agent to remember previous exchanges and maintain conversational state
222+
// This is essential for multi-turn conversations and contextual understanding
223+
AgentThread thread = agent.GetNewThread();
224+
225+
// Execute Agent: First Travel Planning Request
226+
// Run the agent with an initial request that will likely trigger the random destination tool
227+
// The agent will analyze the request, use the GetRandomDestination tool, and create an itinerary
228+
// Using the thread parameter maintains conversation context for subsequent interactions
229+
await foreach (var update in agent.RunStreamingAsync("Plan me a day trip", thread))
230+
{
231+
await Task.Delay(10);
232+
Console.Write(update);
233+
}
234+
235+
Console.WriteLine();
236+
237+
// Execute Agent: Follow-up Request with Context Awareness
238+
// Demonstrate contextual conversation by referencing the previous response
239+
// The agent remembers the previous destination suggestion and will provide an alternative
240+
// This showcases the power of conversation threads and contextual understanding in .NET agents
241+
await foreach (var update in agent.RunStreamingAsync("I don't like that destination. Plan me another vacation.", thread))
242+
{
243+
await Task.Delay(10);
244+
Console.Write(update);
245+
}
121246
```

0 commit comments

Comments
 (0)