Ollama系列06:C#使用OllamaSharp集成Ollama服務
本文是Ollama系列教程的第6篇,主要介紹如何通過SDK將ollama集成到c#程序中。
Ollama系列教程目錄(持續更新中):
Ollama 提供了HTTP API的訪問,如果需要使用SDK集成到項目中,需要引用第三方庫OllamaSharp,直接使用nuget進行安裝即可。

功能亮點
- 簡單易用:幾行代碼就能玩轉Ollama
- 值得信賴:已為Semantic Kernal、.NET Aspire和Microsoft.Extensions.AI提供支持
- 全接口覆蓋:支持所有Ollama API接口,包括聊天對話、嵌入生成、模型列表查看、模型下載與創建等
- 實時流傳輸:直接將響應流推送到您的應用
- 進度可視化:實時反饋模型下載等任務的進度狀態
- 工具引擎:通過源碼生成器提供強大的工具支持
- 多模態能力:支持視覺模型處理
調用示例
初始化client
// set up the client
var uri = new Uri("http://localhost:11434");
var ollama = new OllamaApiClient(uri);
獲取模型列表
// list models
var models = await ollama.ListLocalModelsAsync();
if (models != null && models.Any())
{
Console.WriteLine("Models: ");
foreach (var model in models)
{
Console.WriteLine(" " + model.Name);
}
}
創建對話
// chat with ollama
var chat = new Chat(ollama);
Console.WriteLine();
Console.WriteLine($"Chat with {ollama.SelectedModel}");
while (true)
{
var currentMessageCount = chat.Messages.Count;
Console.Write(">>");
var message = Console.ReadLine();
await foreach (var answerToken in chat.SendAsync(message, Tools))
Console.Write(answerToken);
Console.WriteLine();
// find the latest message from the assistant and possible tools
var newMessages = chat.Messages.Skip(currentMessageCount - 1);
foreach (var newMessage in newMessages)
{
if (newMessage.ToolCalls?.Any() ?? false)
{
Console.WriteLine("\nTools used:");
foreach (var function in newMessage.ToolCalls.Where(t => t.Function != null).Select(t => t.Function))
{
Console.WriteLine($" - {function!.Name}");
Console.WriteLine($" - parameters");
if (function?.Arguments is not null)
{
foreach (var argument in function.Arguments)
Console.WriteLine($" - {argument.Key}: {argument.Value}");
}
}
}
if (newMessage.Role.GetValueOrDefault() == OllamaSharp.Models.Chat.ChatRole.Tool)
Console.WriteLine($" - results: \"{newMessage.Content}\"");
}
}
Tools
如果是LLM是大腦,那么工具就是四肢,通過工具我們能具備LLM與外界交互的能力。
定義工具:
/// <summary>
/// Gets the current datetime
/// </summary>
/// <returns>The current datetime</returns>
[OllamaTool]
public static string GetDateTime() => $"{DateTime.Now: yyyy-MM-dd HH:mm:ss ddd}";
使用工具:
public static List<object> Tools { get; } = [
new GetDateTimeTool(),
];
await chat.SendAsync(message, Tools)
?? 持續分享AI工具,AI應用場景,AI學習資源 ??

推薦閱讀
資源分享

浙公網安備 33010602011771號