目前的LLM中,Ollama跟Azure上的API使用算是佔大多數,當然也有其它的AI可選擇,但整合這些API時,如果都要各別包裝就太麻煩了,幸好微軟有推出Microsoft.Extensions.AI套件,方便程式人員做整合。

這次的主題,會需要下列套件:

  • Microsoft.Extensions.AI
  • Microsoft.Extensions.AI.Ollama
  • Microsoft.Extensions.Hosting
  • Microsoft.Extensions.AI.AzureAIInferenc

接下來示範ollama的整合,中間還有DI的使用方式,可以用在ASP.NET中:

var builder = Host.CreateApplicationBuilder();
string model = "gemma";
builder.Services.AddChatClient(new OllamaChatClient(new Uri("http://localhost:11434"), model));
var app = builder.Build();
var chatClient = app.Services.GetRequiredService<IChatClient>();
var chatCompletion = await chatClient.GetResponseAsync("什麼是女僕咖啡店");
foreach (var message in chatCompletion.Messages)
{
    Console.Write(message.Text);
}
Console.WriteLine();

而如果是使用Azure API,也只需多設定必要的API key及端點:

string key = "your key";
string deploymentName = "gpt-4o-mini";
var endpoint = new Uri("https://example.openai.azure.com/openai/deployments/gpt-4o-mini");
var credential = new AzureKeyCredential(key);
var client = new ChatCompletionsClient(
    endpoint,
    credential,
    new AzureAIInferenceClientOptions()
).AsIChatClient(deploymentName);
Console.WriteLine(await client.GetResponseAsync("什麼是女僕咖啡店"));

當然OpenAI也是可以整合進去的,但筆者個人沒有申請帳號。

參考資料