Ollama系列教程(六):C#使用OllamaSharp集成Ollama服务

372 阅读1分钟

本文是Ollama系列教程的第6篇,主要介绍如何通过SDK将ollama集成到c#程序中。

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)

原文地址:https://www.cnblogs.com/youring2/p/18792401