Ollama系列06:C#使用OllamaSharp集成Ollama服务

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

Ollama系列教程目录(持续更新中):

  1. 轻松3步本地部署deepseek

  2. 快速上手搭建私有的AI对话框和智能体—chatbox版

  3. 快速上手搭建私有的AI对话框和智能体—cherryStudio版

  4. 进阶篇-搭建专属的知识库和问答系统—cherryStudio版

  5. 进阶篇-Ollama API 使用指南

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学习资源 ❤️

推荐阅读

资源分享

  1. 资源分享:清华出品 DeepSeek 从入门到精通 PPT 分享

  2. 资源分享:清华大学DeepSeek 全家桶PPT下载

  3. 北大内部培训资料:DeepSeek与AIGC应用,PPT分享

  4. 北大内部培训资料:DeepSeek提示词工程和落地场景PPT分享

  5. 干货分享!厦大140页PPT读懂大模型,从概念到实践

posted @ 2025-03-25 21:47  拓荒者IT  阅读(192)  评论(0)    收藏  举报
皮肤配置 参考地址:https://www.yuque.com/awescnb/user