RAG 检索增强生成
MAF 支持通过将 AI 上下文提供程序添加到 Agent,轻松地向 Agent 添加检索增强生成(RAG)功能。
TextSearchProvider
TextSearchProvider 类是 RAG 上下文提供程序的现成实现。它支持不同的操作模式,例如使用聊天历史记录对每个代理执行搜索,或播发用于执行搜索的工具。
附加到 ChatClientAgent
csharp
TextSearchProviderOptions textSearchOptions = new()
{
SearchTime = TextSearchProviderOptions
.TextSearchBehavior.BeforeAIInvoke,
};
AIAgent agent = azureOpenAIClient
.GetChatClient(deploymentName)
.AsAIAgent(new ChatClientAgentOptions
{
ChatOptions = new()
{
Instructions = "You are a helpful support specialist. " +
"Answer questions using the provided context and " +
"cite the source document when available."
},
AIContextProviders = [
new TextSearchProvider(SearchAdapter, textSearchOptions)
]
});实现搜索适配器
TextSearchProvider 需要一个提供给定查询的搜索结果的函数。可以使用任何搜索技术实现——Azure AI Search、Web 搜索引擎、或自定义实现。
csharp
static Task<IEnumerable<TextSearchProvider.TextSearchResult>>
SearchAdapter(string query, CancellationToken cancellationToken)
{
var results = new List<TextSearchProvider.TextSearchResult>();
if (query.Contains("return", StringComparison.OrdinalIgnoreCase)
|| query.Contains("refund", StringComparison.OrdinalIgnoreCase))
{
results.Add(new()
{
SourceName = "Contoso Outdoors Return Policy",
SourceLink = "https://contoso.com/policies/returns",
Text = "Customers may return any item within 30 days " +
"of delivery. Refunds are issued within 5 " +
"business days of inspection."
});
}
return Task.FromResult<
IEnumerable<TextSearchProvider.TextSearchResult>>(results);
}SourceName 和 SourceLink 是可选的,但如果 Agent 将在回答时引用信息来源,建议提供。
TextSearchProvider 选项
csharp
TextSearchProviderOptions textSearchOptions = new()
{
// 每次模型调用前运行搜索
SearchTime = TextSearchProviderOptions
.TextSearchBehavior.BeforeAIInvoke,
// 简短聊天历史滚动窗口
MaxHistoryMessages = 10,
};搜索时机选项
| SearchTime | 说明 |
|---|---|
BeforeAIInvoke | 每次 LLM 调用前都执行搜索 |
AsFunctionTool | 以函数工具的形式暴露搜索,Agent 自主决定何时搜索 |
下一步:声明性代理 — 用 YAML/JSON 定义 Agent。