1、安装NuGet包
dotnet add package Microsoft.Extensions.AI
dotnet add package Microsoft.Extensions.AI.OpenAI
2、使用Microsoft.Extensions.AI调用大模型
(1)非流式输出
using Microsoft.Extensions.AI;
using OpenAI;
var chatclient=new OpenAIClient(
new System.ClientModel.ApiKeyCredential("ms-ee0ab5e3-d373-498b-923e-c727be632d50"),
new OpenAIClientOptions{
Endpoint = new Uri("https://api-inference.modelscope.cn/v1")
}).GetChatClient("deepseek-ai/DeepSeek-V3.2").AsIChatClient();
/*调用本地大模型
using OllamaSharp; //dotnet add package OllamaSharp
IChatClient chatclient=OllamaApiClient(new Uri("http://localhost:11434/"), "phi3:mini");*/
while(true){
Console.Write("Q:")
string msg=Console.ReadLine("")??"exit";
if(msg=="exit") break;
Console.Write("AI:");
Console.WriteLine(await chatclient.GetResponseAsync(msg)); //一次性输出大模型的回答
}
(2)带对话历史(上下文,短期记忆)的非流式输出
using Microsoft.Extensions.AI;
using OpenAI;
var chatclient=new OpenAIClient(
new System.ClientModel.ApiKeyCredential("ms-ee0ab5e3-d373-498b-923e-c727be632d50"),
new OpenAIClientOptions{
Endpoint = new Uri("https://api-inference.modelscope.cn/v1")
}).GetChatClient("deepseek-ai/DeepSeek-V3.2").AsIChatClient();
List<ChatMessage> history=[];
history.Add(new ChatMessage(ChatRole.System,"你是一名python专家,回答python专业问题"));
while(true){
Console.Write("Q:")
string msg=Console.ReadLine("")??"exit";
if(msg=="exit") break;
history.Add(new(ChatRole.User,msg));
Console.Write("AI:");
ChatResponse response=await chatclient.GetResponseAsync(history)
Console.WriteLine(response);
history.AddMessages(response);
}
(3)流式输出
using Microsoft.Extensions.AI;
using OpenAI;
var chatclient=new OpenAIClient(
new System.ClientModel.ApiKeyCredential("ms-ee0ab5e3-d373-498b-923e-c727be632d50"),
new OpenAIClientOptions{
Endpoint = new Uri("https://api-inference.modelscope.cn/v1")
}).GetChatClient("deepseek-ai/DeepSeek-V3.2").AsIChatClient();
while(true){
Console.Write("Q:")
string msg=Console.ReadLine("")??"exit";
if(msg=="exit") break;
Console.Write("AI:");
await foreach(ChatResponseUpdate update in chatclient.GetStreamingResponseAsync(msg)){
Console.Write(update);
}
Console.WriteLine();
}
(4)带对话历史(上下文,短期记忆)的流式输出
using Microsoft.Extensions.AI;
using OpenAI;
var chatclient=new OpenAIClient(
new System.ClientModel.ApiKeyCredential("ms-ee0ab5e3-d373-498b-923e-c727be632d50"),
new OpenAIClientOptions{
Endpoint = new Uri("https://api-inference.modelscope.cn/v1")
}).GetChatClient("deepseek-ai/DeepSeek-V3.2").AsIChatClient();
List<ChatMessage> history=[];
history.Add(new(ChatRole.System,"你是一名python专家,回答python专业问题"));
while(true){
Console.Write("Q:")
string msg=Console.ReadLine("")??"exit";
if(msg=="exit") break;
history.Add(new(ChatRole.User,msg));
List<ChatResponseUpdate> updates=[];
Console.Write("AI:");
await foreach(ChatResponseUpdate update in GetStreamingResponseAsync(history){
Console.Write(update);
updates.Add(update);
}
Console.WriteLine();
history.AddMessages(updates);
}
3、在asp.net core中使用
下一篇:没有了