ChatClientAgentOptions 完全解析
一句话简介
ChatClientAgentOptions 是创建 AI Agent 的核心配置类,包含 8 大配置项,支持运行时通过 ChatClientAgentRunOptions 扩展。
🎯 八大配置项
|
|
|
|
|---|---|---|
| Id | string? |
|
| Name | string? |
|
| Instructions | string? |
|
| Description | string? |
|
| ChatOptions | ChatOptions? |
|
| ChatMessageStoreFactory | Func<...>? |
|
| AIContextProviderFactory | Func<...>? |
|
| UseProvidedChatClientAsIs | bool |
|
💻 基础配置
Name 和 Instructions
var agent = chatClient.CreateAIAgent(
options: new ChatClientAgentOptions
{
Name = "EnglishCoach",
Instructions = @"
你是一名专业的英语口语教练,名字叫 Alex。
你的职责:帮助用户提升英语口语能力
你的风格:友好、鼓励、耐心
回复格式:先肯定 → 指出改进点 → 给出正确表达"
});
Instructions 最佳实践:
-
🎯 角色定位:你是谁?专业背景? -
🎯 职责范围:能做什么?不能做什么? -
🎯 回复风格:语气、长度、格式
💻 ChatOptions 配置
配置工具和参数
var chatOptions = new ChatOptions
{
Temperature = 0.3f, // 输出稳定性
MaxOutputTokens = 500, // 限制输出长度
Tools = [
AIFunctionFactory.Create(GetWeather),
AIFunctionFactory.Create(GetStockPrice)
],
ToolMode = ChatToolMode.Auto
};
var agent = chatClient.CreateAIAgent(
options: new ChatClientAgentOptions
{
Name = "InfoAssistant",
ChatOptions = chatOptions
});
💻 运行时扩展
使用 ChatClientAgentRunOptions
// 运行时扩展配置(临时生效,不影响默认配置)
var response = await agent.RunAsync(
"用户消息",
thread,
options: new ChatClientAgentRunOptions
{
ChatOptions = new ChatOptions
{
Temperature = 0.1f, // 覆盖默认值
Tools = [AdditionalTool] // ✅ 与默认工具合并
}
});
合并机制:
-
集合类型(如 Tools):会合并(union),不是替换 -
标量值(如 Temperature):运行时值会覆盖默认值
💻 高级配置
工厂函数配置
var options = new ChatClientAgentOptions
{
// 消息存储工厂(持久化)
ChatMessageStoreFactory = ctx => new DatabaseChatMessageStore(connectionString),
// 上下文提供者工厂(动态注入)
AIContextProviderFactory = ctx => new UserContextProvider(currentUserId)
};
UseProvidedChatClientAsIs
// 自定义中间件管道
var customClient = baseChatClient
.AsBuilder()
.Use(new CustomLoggingMiddleware())
.UseFunctionInvocation() // ⚠️ 必须手动添加
.Build();
var agent = customClient.CreateAIAgent(
options: new ChatClientAgentOptions
{
UseProvidedChatClientAsIs = true // 禁用默认装饰器
});
⚠️ 注意:使用 true 时必须手动添加 .UseFunctionInvocation()
🏢 配置策略
|
|
|
|---|---|
| 简单对话 |
|
| 带工具 |
|
| 持久化 |
|
| 个性化 |
|
| 自定义管道 |
|
🎯 总结
-
✅ 8 大配置项:Id、Name、Instructions、Description、ChatOptions、两个 Factory、UseProvidedChatClientAsIs -
✅ 运行时扩展:通过 ChatClientAgentRunOptions 临时扩展配置 -
✅ 合并机制:Tools 合并、Temperature 覆盖 -
✅ 工厂模式:支持自定义消息存储和上下文注入

