上次笔记记录了CSharp调用OpenAI接口的方法。链接如下:
如果要使用免费的本地部署的Ollama模型代码,只需修改简单几个参数就好。
这里使用Windows11系统,已经通过Ollama下载好了glm4模型,那么调用代码如下:
using Microsoft.SemanticKernel;
using OpenAI;
using System.ClientModel;
namespace CSharpAI
{
internal class s05_chat_prompt
{
public async Task RunAsync()
{
OpenAIClientOptions options = new OpenAIClientOptions();
options.Endpoint = new Uri("http://localhost:11434/v1");
OpenAIClient client = new OpenAIClient(new ApiKeyCredential("ollama"), options);
Kernel kernel = Kernel.CreateBuilder()
.AddOpenAIChatCompletion(modelId: "glm4", client)
.Build();
string chatPrompt = """
<message role="user">What is Seattle?</message>
<message role="system">Respond with JSON.</message>
""";
Console.WriteLine(await kernel.InvokePromptAsync(chatPrompt));
}
public static async Task Main()
{
await new s05_chat_prompt().RunAsync();
}
}
}
如果要使用其他模型,只需将代码中的modelId的值修改为对应模型名即可。