🛠️ GitHub 模型 (.NET) 的高级工具使用

📋 学习目标

本笔记本演示了使用 .NET 中的 Microsoft Agent Framework 与 GitHub 模型的企业级工具集成模式。您将学习利用 C# 的强类型和 .NET 的企业功能,使用多种专用工具构建复杂的代理。

您将掌握的高级工具功能

  • 🔧 多工具架构:构建具有多种专业功能的代理
  • 🎯 类型安全工具执行:利用 C# 的编译时验证
  • 📊 企业工具模式:生产就绪的工具设计和错误处理
  • 🔗 工具组合:组合复杂业务工作流程的工具

🎯 .NET 工具架构的优点

企业工具功能

  • 编译时验证:强类型确保工具参数的正确性
  • 依赖注入:用于工具管理的 IoC 容器集成
  • 异步/等待模式:通过适当的资源管理实现非阻塞工具执行
  • 结构化日志记录:用于工具执行监控的内置日志记录集成

生产就绪模式

  • 异常处理:使用类型化异常进行全面的错误管理
  • 资源管理:正确的处置模式和内存管理
  • 性能监控:内置指标和性能计数器
  • 配置管理:带有验证的类型安全配置

🔧 技术架构

核心 .NET 工具组件

  • Microsoft.Extensions.AI:统一工具抽象层
  • Microsoft.Agents.AI:企业级工具编排
  • GitHub 模型集成:具有连接池的高性能 API 客户端

工具执行管道

1
2
3
4
5
6
7
8
9
10
graph LR
A[User Request] --> B[Agent Analysis]
B --> C[Tool Selection]
C --> D[Type Validation]
B --> E[Parameter Binding]
E --> F[Tool Execution]
C --> F
F --> G[Result Processing]
D --> G
G --> H[Response]

🛠️ 工具类别和模式

1. 数据处理工具

  • 输入验证:带有数据注释的强类型
  • 转换操作:类型安全的数据转换和格式化
  • 业务逻辑:特定领域的计算和分析工具
  • 输出格式:结构化响应生成

2. 集成工具

  • API 连接器:与 HttpClient 的 RESTful 服务集成
  • 数据库工具:用于数据访问的实体框架集成
  • 文件操作:通过验证保护文件系统操作
  • 外部服务:第三方服务集成模式

3. 实用工具

  • 文本处理:字符串操作和格式化实用程序
  • 日期/时间操作:文化感知的日期/时间计算
  • 数学工具:精确计算和统计运算
  • 验证工具:业务规则验证和数据验证

准备好在 .NET 中构建具有强大、类型安全工具功能的企业级代理了吗?让我们构建一些专业级的解决方案! 🏢⚡

🚀 开始使用

先决条件

所需的环境变量

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 ./04-dotnet-agent-framework.cs
./04-dotnet-agent-framework.cs

或者使用 dotnet CLI:

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

有关完整代码,请参阅 04-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);
}