🔍 探索 Microsoft Agent 框架 - 基本 Agent (.NET)

📋 学习目标

此示例通过 .NET 中的基本代理实现探索 Microsoft 代理框架的基本概念。您将学习核心代理模式,并了解智能代理如何使用 C# 和 .NET 生态系统在幕后工作。

你会发现什么

  • 🏗️ 代理架构:了解 .NET 中 AI 代理的基本结构
  • 🛠️ 工具集成:代理如何使用外部函数来扩展功能
  • 💬 对话流:通过线程管理管理多轮对话和上下文
  • 🔧 配置模式:.NET 中代理设置和管理的最佳实践

🎯 涵盖的关键概念

代理框架原则

  • 自治:代理如何使用 .NET AI 抽象做出独立决策
  • 反应性:响应环境变化和用户输入
  • 主动性:根据目标和背景采取主动
  • 社交能力:通过自然语言与对话线程进行交互

技术组件

  • AIAgent:核心代理编排和对话管理 (.NET)
  • 工具功能:使用 C# 方法和属性扩展代理功能
  • OpenAI 集成:通过标准化 .NET API 利用语言模型
  • 安全配置:基于环境的API密钥管理

🔧 技术堆栈

核心技术

  • 微软代理框架(.NET)
  • GitHub 模型 API 集成
  • OpenAI 兼容的客户端模式
  • 使用 DotNetEnv 基于环境的配置

代理能力

  • 自然语言理解和生成
  • 具有C#属性的函数调用和工具使用
  • 对话线程的上下文感知响应
  • 具有依赖注入模式的可扩展架构

📚 框架比较

此示例演示了 Microsoft 代理框架方法与其他代理框架的比较:

特色 微软代理框架 其他框架
整合 原生微软生态系统 多种兼容性
简单 干净、直观的 API 通常很复杂的设置
可扩展性 轻松的工具集成 依赖框架
企业就绪 专为生产而打造 因框架而异

🚀 开始使用

先决条件

所需的环境变量

1
2
3
4
# zsh/bash
export GH_TOKEN=<your_github_token>
export GH_ENDPOINT=https://models.github.ai/inference
export GH_MODEL_ID=openai/gpt-5-mini
1
2
3
4
# PowerShell
$env:GH_TOKEN = "<your_github_token>"
$env:GH_ENDPOINT = "https://models.github.ai/inference"
$env:GH_MODEL_ID = "openai/gpt-5-mini"

示例代码

要运行代码示例,

1
2
3
# zsh/bash
chmod +x ./02-dotnet-agent-framework.cs
./02-dotnet-agent-framework.cs

或者使用 dotnet CLI:

1
dotnet run ./02-dotnet-agent-framework.cs

有关完整代码,请参阅 02-dotnet-agent-framework.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/dotnet run

#:package Microsoft.Extensions.AI@10.*
#:package Microsoft.Agents.AI.OpenAI@1.*-*

using System.ClientModel;
using System.ComponentModel;

using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

using OpenAI;

// Tool Function: Random Destination Generator
// This static method will be available to the agent as a callable tool
// The [Description] attribute helps the AI understand when to use this function
// This demonstrates how to create custom tools for AI agents
[Description("Provides a random vacation destination.")]
static string GetRandomDestination()
{
// List of popular vacation destinations around the world
// The agent will randomly select from these options
var destinations = new List<string>
{
"Paris, France",
"Tokyo, Japan",
"New York City, USA",
"Sydney, Australia",
"Rome, Italy",
"Barcelona, Spain",
"Cape Town, South Africa",
"Rio de Janeiro, Brazil",
"Bangkok, Thailand",
"Vancouver, Canada"
};

// Generate random index and return selected destination
// Uses System.Random for simple random selection
var random = new Random();
int index = random.Next(destinations.Count);
return destinations[index];
}

// Extract configuration from environment variables
// Retrieve the GitHub Models API endpoint, defaults to https://models.github.ai/inference if not specified
// Retrieve the model ID, defaults to openai/gpt-5-mini if not specified
// Retrieve the GitHub token for authentication, throws exception if not specified
var github_endpoint = Environment.GetEnvironmentVariable("GH_ENDPOINT") ?? "https://models.github.ai/inference";
var github_model_id = Environment.GetEnvironmentVariable("GH_MODEL_ID") ?? "openai/gpt-5-mini";
var github_token = Environment.GetEnvironmentVariable("GH_TOKEN") ?? throw new InvalidOperationException("GH_TOKEN is not set.");

// Configure OpenAI Client Options
// Create configuration options to point to GitHub Models endpoint
// This redirects OpenAI client calls to GitHub's model inference service
var openAIOptions = new OpenAIClientOptions()
{
Endpoint = new Uri(github_endpoint)
};

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

// Define Agent Identity and Comprehensive Instructions
// Agent name for identification and logging purposes
var AGENT_NAME = "TravelAgent";

// Detailed instructions that define the agent's personality, capabilities, and behavior
// This system prompt shapes how the agent responds and interacts with users
var AGENT_INSTRUCTIONS = """
You are a helpful AI Agent that can help plan vacations for customers.

Important: When users specify a destination, always plan for that location. Only suggest random destinations when the user hasn't specified a preference.

When the conversation begins, introduce yourself with this message:
"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:
1. Plan a day trip to a specific location
2. Suggest a random vacation destination
3. Find destinations with specific features (beaches, mountains, historical sites, etc.)
4. Plan an alternative trip if you don't like my first suggestion

What kind of trip would you like me to help you plan today?"

Always prioritize user preferences. If they mention a specific destination like "Bali" or "Paris," focus your planning on that location rather than suggesting alternatives.
""";

// Create AI Agent with Advanced Travel Planning Capabilities
// Initialize complete agent pipeline: OpenAI client → Chat client → AI agent
// Configure agent with name, detailed instructions, and available tools
// This demonstrates the .NET agent creation pattern with full configuration
AIAgent agent = openAIClient
.GetChatClient(github_model_id)
.CreateAIAgent(
name: AGENT_NAME,
instructions: AGENT_INSTRUCTIONS,
tools: [AIFunctionFactory.Create(GetRandomDestination)]
);

// Create New Conversation Thread for Context Management
// Initialize a new conversation thread to maintain context across multiple interactions
// Threads enable the agent to remember previous exchanges and maintain conversational state
// This is essential for multi-turn conversations and contextual understanding
AgentThread thread = agent.GetNewThread();

// Execute Agent: First Travel Planning Request
// Run the agent with an initial request that will likely trigger the random destination tool
// The agent will analyze the request, use the GetRandomDestination tool, and create an itinerary
// Using the thread parameter maintains conversation context for subsequent interactions
await foreach (var update in agent.RunStreamingAsync("Plan me a day trip", thread))
{
await Task.Delay(10);
Console.Write(update);
}

Console.WriteLine();

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

🎓 要点

  1. 代理架构:Microsoft Agent Framework 提供了一种干净、类型安全的方法来在 .NET 中构建 AI 代理
  2. 工具集成:用[Description]属性修饰的函数成为代理可用的工具
  3. 对话上下文:线程管理可实现具有完整上下文感知的多轮对话
  4. 配置管理:环境变量和安全凭证处理遵循 .NET 最佳实践
  5. OpenAI 兼容性:GitHub 模型集成通过 OpenAI 兼容的 API 无缝运行

🔗 其他资源