.Net9中通过HttpClient简单调用Ollama中的DeepSeek R1模型

本文主要使用.Net9中的HttpClient组件,调用本地部署的Ollama提供的API接口,获取对应的问答信息。

1、🥇测试环境

  • VS2022;

  • .Net9控制台程序;

  • HttpClient组件;

  • 本地部署的Ollama环境

  • DeepSeek R1模型(deepseek-r1:1.5b)

关于本地部署的Ollama环境,可参见文章【通过Ollama本地部署DeepSeek R1以及简单使用的教程(超详细)】。


2、🥈创建控制台程序

我们使用VS2022创建一个基于.Net9的控制台程序,具体如下所示:

控制台程序

控制台程序

控制台程序

上述我们就创建好了一个控制台程序。


3、🥉Ollama接口

Ollama为我们提供了多种接口,最常用的接口为:

  • POST /api/generate

  • POST /api/chat

上述两个接口为最常用的,具体说明可参见【https://github.com/ollama/ollama/blob/main/docs/api.md】说明,如下所示为部分使用说明的截图:

Ollama接口

Ollama接口


4、🏅调用实现

4.1、🎀generate接口

我们在Program.cs文件中编写具体的代码。

具体代码实现如下所示(复制粘贴即可运行),都有对应的说明:

using System.Data;
using System.Text;
using System.Text.Json;

// HttpClient实例
var httpClient = new HttpClient();

// Ollama API请求地址
var requestUrl = "http://localhost:11434/api/generate";

Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("请输入对话内容(输入exit退出):");

while (true)
{
    // 读取输入的内容
    var input = Console.ReadLine();

    if (input != null && input.ToLower() == "exit")
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("程序即将退出...");

        // 退出循环,程序结束
        break;
    }

    // 请求参数
    var requestData = new
    {
        // 指定模型标识符
        model = "deepseek-r1:1.5b",
        // 输入的提示文本
        prompt = input,
        // 是否启用流式响应
        stream = true,
        // 其他选项
        options = new
        {
            // 控制生成随机性(0-1)
            temperature = 0.7,
            // 最大生成 token 数
            max_tokens = 500
        }
    };

    // 创建HttpRequestMessage实例以及设置请求内容
    using var request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
    request.Content = new StringContent(JsonSerializer.Serialize(requestData), Encoding.UTF8, "application/json");

    // 发送请求并获取响应
    using var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
    await using var stream = await response.Content.ReadAsStreamAsync();
    using var reader = new StreamReader(stream);

    // 循环读取响应流
    while (!reader.EndOfStream)
    {
        var content = await reader.ReadLineAsync();
        if (!string.IsNullOrEmpty(content))
        {
            var partialResponse = JsonSerializer.Deserialize<OllamaResponse>(content);

            // 输出响应内容
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(partialResponse?.response);
        }
    }

    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine("\r\n\r\n请输入对话内容(输入exit退出):");
}

/// <summary>
/// Ollama API响应实体类
/// </summary>
public class OllamaResponse
{
    /// <summary>
    /// 模型标识符
    /// </summary>
    public string model { get; set; }

    /// <summary>
    /// 创建时间戳
    /// </summary>
    public string created_at { get; set; }

    /// <summary>
    /// 响应内容
    /// </summary>
    public string response { get; set; }

    /// <summary>
    /// 是否完成
    /// </summary>
    public bool done { get; set; }

    /// <summary>
    /// 完成原因
    /// </summary>
    public string done_reason { get; set; }

    public int[] context { get; set; }
    public long total_duration { get; set; }
    public long load_duration { get; set; }
    public int prompt_eval_count { get; set; }
    public long prompt_eval_duration { get; set; }
    public int eval_count { get; set; }
    public long eval_duration { get; set; }
}

运行效果:

运行效果

4.2、🎁chat接口

我们在Program.cs文件中编写具体的代码。

具体代码实现如下所示(复制粘贴即可运行),都有对应的说明:

using System.Data;
using System.Text;
using System.Text.Json;

// HttpClient实例
var httpClient = new HttpClient();

// Ollama API请求地址
var requestUrl = "http://localhost:11434/api/chat";

Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("请输入对话内容(输入exit退出):");

while (true)
{
    // 读取输入的内容
    var input = Console.ReadLine();

    if (input != null && input.ToLower() == "exit")
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine("程序即将退出...");

        // 退出循环,程序结束
        break;
    }

    // 请求参数
    var requestData = new
    {
        // 指定模型标识符
        model = "deepseek-r1:1.5b",
        // 输入的提示文本
        messages = new[]
        {
            new { role = "user", content = input }
        },
        // 是否启用流式响应
        stream = true,
        // 其他选项
        options = new
        {
            // 控制生成随机性(0-1)
            temperature = 0.7,
            // 最大生成 token 数
            max_tokens = 500
        }
    };

    // 创建HttpRequestMessage实例以及设置请求内容
    using var request = new HttpRequestMessage(HttpMethod.Post, requestUrl);
    request.Content = new StringContent(JsonSerializer.Serialize(requestData), Encoding.UTF8, "application/json");

    // 发送请求并获取响应
    using var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
    await using var stream = await response.Content.ReadAsStreamAsync();
    using var reader = new StreamReader(stream);

    // 循环读取响应流
    while (!reader.EndOfStream)
    {
        var content = await reader.ReadLineAsync();
        if (!string.IsNullOrEmpty(content))
        {
            var partialResponse = JsonSerializer.Deserialize<OllamaResponse>(content);

            // 输出响应内容
            Console.ForegroundColor = ConsoleColor.White;
            Console.Write(partialResponse?.message.content);
        }
    }

    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine("\r\n\r\n请输入对话内容(输入exit退出):");
}

/// <summary>
/// Ollama API响应实体类
/// </summary>
public class OllamaResponse
{
    /// <summary>
    /// 模型标识符
    /// </summary>
    public string model { get; set; }

    /// <summary>
    /// 创建时间戳
    /// </summary>
    public string created_at { get; set; }

    /// <summary>
    /// 响应内容
    /// </summary>
    public OllamaResponseMessage message { get; set; }

    /// <summary>
    /// 是否完成
    /// </summary>
    public bool done { get; set; }

    /// <summary>
    /// 完成原因
    /// </summary>
    public string done_reason { get; set; }

    public long total_duration { get; set; }
    public long load_duration { get; set; }
    public int prompt_eval_count { get; set; }
    public long prompt_eval_duration { get; set; }
    public int eval_count { get; set; }
    public long eval_duration { get; set; }
}

/// <summary>
/// Ollama API响应实体类的message子类
/// </summary>
public class OllamaResponseMessage
{
    /// <summary>
    /// 角色
    /// </summary>
    public string role { get; set; }

    /// <summary>
    /// 内容
    /// </summary>
    public string content { get; set; }
}

运行效果:

运行效果


到此,通过.Net9的HttpClient简单调用Ollama的API就完成了。


5、🔖其他文章:

posted @ 2025-02-08 15:28  Qubernet  阅读(312)  评论(0编辑  收藏  举报
🛧