C#测试基于OllamaSharp调用本地DeepSeek模型
基于Ollama在本地部署DeepSeek模型后,使用Ater.DeepSeek.Core包没法调用本地服务接口,而是需要使用OllamaSharp包。
OllamaSharp包中最重要的类为OllamaApiClient,该类的构造函数中传入本地Ollama服务地址(一般为http://127.0.0.1:11434),常用的两个函数如下(其它函数及说用说明详见参考文献3):
1)ListLocalModelsAsync函数获取本地部署的模型列表;
2)GenerateAsync函数根据输入的对话内容返回对话结果。
主要代码如下:
private OllamaApiClient m_client = null;
private List<OllamaSharp.Models.Model> m_models;
//Winform构造函数中初始化上述两个属性
m_client = new OllamaApiClient(new Uri("http://127.0.0.1:11434"));
m_models = new List<OllamaSharp.Models.Model>();
//Winform的load时间中加载本地模型
var modelResponse = await m_client.ListLocalModelsAsync();
if (modelResponse is null)
{
MessageBox.Show("获取本地模型失败");
return;
}
foreach (var model in modelResponse)
{
m_models.Add(model);
comboBox1.Items.Add(model.Name);
}
//点击对话按钮调用本地模型对话
m_client.SelectedModel = m_models[comboBox1.SelectedIndex].Name;
txtResult.Text = string.Empty;
await foreach (var stream in m_client.GenerateAsync(txtChat.Text))
{
txtResult.Text += stream.Response;
}
程序运行效果如下:
参考文献:
[1]https://blog.csdn.net/weixin_72139050/article/details/145861436
[2]https://blog.csdn.net/daremeself/article/details/145769387
[3]https://github.com/awaescher/OllamaSharp
[4]https://blog.csdn.net/zlbcdn/article/details/145954736