Microsoft.Extensions.AI介绍

Microsoft.Extensions.AI介绍

Microsoft.Extensions.AI介绍

Microsoft.Extensions.AI定位于.NET系统AI框架的底层,提供常用的核心接口,比如IChatClient,它目的是抽象出一系列的方法,无论日后用什么AI框架,都可以无缝衔接。接口也比较简单,主要围绕2个接口:

  1. IChatClient:和AI聊天有关,可以是文本,图片,音频等
  2. IEmbeddingGenerator<TInput, TEmbedding>:和向量有关,毕竟大模型底层玩的是向量,作为开发者,你肯定离不开向量的

meai-architecture-diagram

简单使用

  1. OpenAI API都快作为行业标准了,很多大模型都是支持这个的,所以对于兼容OpenAI API的服务,Microsoft.Extensions.AI.OpenAI中有OpenAIClient
1
2
3
OpenAIClientOptions clientOptions = new OpenAIClientOptions();
clientOptions.Endpoint = new Uri("https://....");
OpenAIClient aiClient = new OpenAIClient(new System.ClientModel.ApiKeyCredential("....."),clientOptions);
  1. 有很多本地部署的可以用OllamaSharpvar aiClient = new OllamaApiClient(arguments.Uri, arguments.Model);

IChatClient

  1. 简单聊天使用
1
2
3
4
5
6
7
8
OpenAIClientOptions clientOptions = new OpenAIClientOptions();
clientOptions.Endpoint = new Uri("https:....");

OpenAIClient aiClient = new OpenAIClient(new System.ClientModel.ApiKeyCredential("...."),clientOptions);
ChatClient chatClient = aiClient.GetChatClient("qwen3");
//其实chatClient已经可以聊天了,但是为了接口统一,可以转成IChatClient
IChatClient chatService = chatClient.AsIChatClient();
ChatResponse response = await chatService.GetResponseAsync("你好");
  1. 用流式响应的方式
1
2
3
4
5
6
7
8
ChatResponse response = await chatService.GetResponseAsync("你好");
IAsyncEnumerable<ChatResponseUpdate> responseAsync = chatService.GetStreamingResponseAsync("写一篇100字的文章");

await foreach(var chunk in responseAsync)
{
chunk.Text.Dump();
await Task.Delay(100);
}
  1. 获得服务的元数据,如大模型

var meta = chatService.GetRequiredService<ChatClientMetadata>();

image-20251113180106148

总结

IChatClient的三大方法:

方法返回值
GetResponseAsync普通聊天,返回ChatResponse,一组消息和元信息
GetStreamingResponseAsync响应式聊天,返回IAsyncEnumerable<ChatResponseUpdate>
GetRequiredService获得服务的元数据

IEmbeddingGenerator

  1. 简单使用,本处使用Azure OpenAI
1
2
3
4
5
6
7
8
9
10
11
12
13
var azureEndpoint = new Uri("https:....");
var azureCredential = new ApiKeyCredential("xxxx");
AzureOpenAIClient azureClient = new AzureOpenAIClient(azureEndpoint, azureCredential);

//获取向量模型
EmbeddingClient embeddingClient = azureClient.GetEmbeddingClient("text-embedding-3-small");
//获取向量生成器,IEmbeddingGenerator<string,Embedding<float>>表示输入字符串,输出float类型的嵌入
IEmbeddingGenerator<string,Embedding<float>> embeddingGenerator = embeddingClient.AsIEmbeddingGenerator();

var document = new[]{
"测试向量1","测试向量2"
};
GeneratedEmbeddings<Embedding<float>> generatedEmbeddings = await embeddingGenerator.GenerateAsync(document);

image-20251113181750848

  1. 上面的案例会返回包括向量的完整信息,如果只想获得向量,可以这样,只获得Vector向量
1
ReadOnlyMemory<float> singleVector = await embeddingGenerator.GenerateVectorAsync("测试向量1");

image-20251113182240016

  1. 也可以获得向量生成器的一些元信息
1
var embeddingMeata = embeddingGenerator.GetRequiredService<EmbeddingGeneratorMetadata>();

image-20251113182404625

作者

步步为营

发布于

2025-11-13

更新于

2025-11-13

许可协议