OllamaSharp

awaescherMIT活跃维护

在 .NET 里调用 Ollama 本地大模型最省事的 C# 客户端库,封装了 API 和流式输出,让 C# 项目快速接入 Llama 等模型。

The easiest way to use Ollama in .NET

5.5.2发布于 2026-11-05 06:27 UTC1,414star +1 / 7 天188fork同步于 2026-11-10 17:50 UTC

怎么上手

由 README 提炼,执行前请确认
dotnet add package OllamaSharp
var ollama = new OllamaApiClient(new Uri("http://localhost:11434"));
硬件要求按 README 说明

README 未说明;模型实际运行在 Ollama 服务端,显存与 GPU 要求取决于所选的 Ollama 模型

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

Ollama 的 .NET 绑定库,让 C# 项目几行代码就能调用本地或远程 Ollama 模型

在 .NET 里调用 Ollama 本地大模型最省事的 C# 客户端库,封装了 API 和流式输出,让 C# 项目快速接入 Llama 等模型。

核心能力

  • 封装 Ollama 全部 API 端点,含聊天、嵌入、模型拉取与创建
  • 支持响应流式输出,逐 token 推送到应用
  • 内置 Chat 类自动维护多轮消息与工具调用历史
  • 用源生成器实现函数调用工具引擎
  • 支持视觉模型、结构化 JSON 输出与 Native AOT

容易踩的坑

需先自行安装并启动 Ollama 服务,默认地址为 http://localhost:11434;使用前需先拉取模型并设置 SelectedModel;SystemOneAsync 需要 Ollama v0.35.0 或更高版本

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本5.5.2
  1. 5.5.2Release 5.5.2最新正式版2026-11-05 · 2026-11-05 06:27 UTC

    What's Changed

    What's Changed

    New Contributors

    Full Changelog: https://github.com/awaescher/OllamaSharp/compare/5.5.1...5.5.2

  2. 5.5.1Release 5.5.12026-11-05 · 2026-11-05 06:23 UTC
    查看更新说明

    What's Changed

    What's Changed

    New Contributors

    Full Changelog: https://github.com/awaescher/OllamaSharp/compare/5.5.0...5.5.1

  3. 5.5.0Release 5.5.02026-09-30 · 2026-09-30 06:47 UTC
    查看更新说明

    What's Changed

    What's Changed

    Full Changelog: https://github.com/awaescher/OllamaSharp/compare/5.4.30...5.5.0

  4. 5.4.30Release 5.4.302026-07-24 · 2026-07-24 10:06 UTC
    查看更新说明

    What's Changed

    What's Changed

    Full Changelog: https://github.com/awaescher/OllamaSharp/compare/5.4.29...5.4.30

  5. 5.4.29Release 5.4.292026-07-24 · 2026-07-24 10:05 UTC
    查看更新说明

    What's Changed

    What's Changed

    Full Changelog: https://github.com/awaescher/OllamaSharp/compare/5.4.28...5.4.29

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    nuget version nuget downloads Api docs

    OllamaSharp 🦙

    OllamaSharp provides .NET bindings for the Ollama API, simplifying interactions with Ollama both locally and remotely.

    🏆 Recommended by Microsoft

    Features

    📖 Documentation

    TopicDescription
    Getting startedInstallation, client setup and first steps
    Chat and GenerateChat class, GenerateAsync, streaming, images, structured output, thinking models
    Model ManagementList, pull, push, copy, delete, show, embed
    Tool supportFunction calling with source generators
    Advanced ConfigurationConfiguration options that go beyond the basics
    Native AOT supportAhead-of-Time compilation guidance
    API referenceFull auto-generated API docs

    Usage

    OllamaSharp wraps each Ollama API endpoint in awaitable methods that fully support response streaming.

    The following list shows a few simple code examples.

    ℹ Try our full featured demo application that's included in this repository

    Initializing

    // set up the client
    var uri = new Uri("http://localhost:11434");
    var ollama = new OllamaApiClient(uri);
    
    // select a model which should be used for further operations
    ollama.SelectedModel = "qwen3.5:35b-a3b";
    

    Native AOT Support

    For .NET Native AOT scenarios, create a custom JsonSerializerContext with your types and pass it into the constructor.

    [JsonSerializable(typeof(MyCustomType))]
    public partial class MyJsonContext : JsonSerializerContext { }
    
    // Use the static factory method for NativeAOT
    var ollama = new OllamaApiClient(uri, "qwen3.5:35b-a3b", MyJsonContext.Default);
    

    See the Native AOT documentation for detailed guidance.

    Listing all models that are available locally

    var models = await ollama.ListLocalModelsAsync();
    

    Pulling a model and reporting progress

    await foreach (var status in ollama.PullModelAsync("qwen3.5:35b-a3b"))
        Console.WriteLine($"{status.Percent}% {status.Status}");
    

    Generating a completion directly into the console

    GenerateAsync maps to the /api/generate endpoint and is ideal for single-turn, context-free completions.

    await foreach (var stream in ollama.GenerateAsync("How are you today?"))
        Console.Write(stream.Response);
    

    Building interactive chats

    The Chat class is the recommended way to build conversational applications. It automatically tracks the full message history (including tool calls and their results) across turns so the model always has full context.

    // messages including their roles and tool calls will automatically be tracked within the chat object
    // and are accessible via the Messages property
    
    var chat = new Chat(ollama);
    
    while (true)
    {
        var message = Console.ReadLine();
        await foreach (var answerToken in chat.SendAsync(message))
            Console.Write(answerToken);
    }
    

    You can also set a system prompt, send images for vision models, request structured JSON output, and enable thinking mode for reasoning models. See the Chat and Generate documentation for the full guide.

    Answering typed questions with System One

    SystemOneAsync maps to the /v1/systemone endpoint (Ollama v0.35.0 or later). Instead of generating text, a System One model like nimble answers choice, yes/no and score questions about a given state and returns probabilities.

    var response = await ollama.SystemOneAsync(new SystemOneRequest
    {
        Model = "nimble",
        State = "Our checkout has returned 500 errors since 9am.",
        Questions = new()
        {
            ["label"] = new SystemOneChoiceQuestion
            {
                Instructions = "Which label fits this ticket?",
                Criteria = new() { ["billing"] = "Payments and refunds", ["bug"] = "Software errors", ["account"] = "Login and account access" }
            },
            ["refund"] = new SystemOneNoulQuestion { Instructions = "Is the customer requesting a refund?" },
            ["urgency"] = new SystemOneScoreQuestion
            {
                Instructions = "How urgently does this ticket need a response?",
                Criteria = ["Routine", "Soon", "Immediate"]
            }
        }
    });
    
    var label = (SystemOneChoiceAnswer)response.Answers["label"];     // label.Choice == "bug"
    var refund = (SystemOneNoulAnswer)response.Answers["refund"];     // refund.Noul == probability of "yes"
    var urgency = (SystemOneScoreAnswer)response.Answers["urgency"];  // urgency.Score from 0 to 2
    

    See the Ollama decision guide for more details.

    Usage with Microsoft.Extensions.AI

    Microsoft built an abstraction library to streamline the usage of different AI providers. This is a really interesting concept if you plan to build apps that might use different providers, like ChatGPT, Claude and local models with Ollama.

    I encourage you to read their accouncement Introducing Microsoft.Extensions.AI Preview – Unified AI Building Blocks for .NET.

    OllamaSharp is the first full implementation of their IChatClient and IEmbeddingGenerator that makes it possible to use Ollama just like every other chat provider.

    To do this, simply use the OllamaApiClient as IChatClient instead of IOllamaApiClient.

    // install package Microsoft.Extensions.AI.Abstractions
    
    private static IChatClient CreateChatClient(Arguments arguments)
    {
      if (arguments.Provider.Equals("ollama", StringComparison.OrdinalIgnoreCase))
        return new OllamaApiClient(arguments.Uri, arguments.Model);
      else
        return new OpenAIChatClient(new OpenAI.OpenAIClient(arguments.ApiKey), arguments.Model); // ChatGPT or compatible
    }
    

    The OllamaApiClient implements both interfaces from Microsoft.Extensions.AI, you just need to cast it accordingly:

    • IChatClient for model inference
    • IEmbeddingGenerator<string, Embedding<float>> for embedding generation

    Cloud models aka Ollama Turbo

    OllamaSharp can be used with Ollama cloud models as well. Use the constructor that takes an HttpClient and set it up to send the api key as default request header.

    var client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:11434");
    client.DefaultRequestHeaders.Add(/* your api key here */);
    var ollama = new OllamaApiClient(client);
    

    OllamaSharp vs. Microsoft.Extensions.AI vs. Semantic Kernel

    It can be confusing which library to use with AI in C#. The following paragraph should help you decide which library to start with.

    Prefer OllamaSharp if ...

    • you plan to use Ollama models only
    • you want to use the native Ollama API, not only chats and embeddings but model management, usage information and more

    Prefer Microsoft.Extensions.AI if ...

    • you only need chat and embedding functionality
    • you want to be able to use different providers like Ollama, OpenAI, Hugging Face, etc.

    Prefer Semantic Kernel if ...

    • you need the highest flexibility with different providers, plugins, middlewares, caching, memory and more
    • you need advanced prompt techniques like variable substitution and templating
    • you want to build agentic systems

    No matter which one you choose, OllamaSharp should always be the bridge to Ollama behind the scenes as recommended by Microsoft (1) (2) (3).

    Thanks

    I would like to thank all the contributors who take the time to improve OllamaSharp. First and foremost mili-tan, who always keeps OllamaSharp in sync with the Ollama API.

    The icon and name were reused from the amazing Ollama project.