DeepSeek本地部署 + Unity(C#)中调用

LiFasT
LiFasT
Published on 2025-02-01 / 35 Visits
0
0

前言

最近DeepSeek非常火,不过我对本地部署更敢兴趣。本地部署意味着个人开发者也可以在游戏内放置一个语言大模型,甚至于用本地模型控制游戏内容,这是很颠覆性的概念,不过现在还处于模糊期。

本篇文章简单说说DeepSeekR1模型的本地部署和在Unity(C#)中进行调用,顺便再讲一讲关于RESTfulAPI的知识。

RESTful API

这是一个前置条件,但是不是今天的重点,所以就简单讲讲概念和使用方法吧。

RESTful API是什么?

RESTfulAPI本质上是一种API,其遵循REST架构风格设计,用户可以通过标准的HTTP方法与其(服务器)进行交互。

为啥要讲这玩意?

本文的本地部署方式是通过ollama,ollama本身是一个模型语言运行平台,但其提供了一套RESTful API,用户可以通过这套API来与不同模型进行交互,因此了解这玩意是了解这玩意是前置条件。

Ollama的API文档(GitHub)

点击这里

DeepSeek

视频操作可以参考

部署步骤

  1. 进入Ollama官网(这蓝字是超链接)下载并安装

  2. 打开CMD输入ollama查看是否安装成功

  3. 安装DeepSeek模型,选择适合的版本安装

常见问题

  • 如何运行ollama

可以通过点击Ollama应用或者CMD中输入ollama serve运行

  • 如何关闭ollama

任务管理器搜ollama直接关掉

  • 如何选择版本

推荐7b及以上,1.5b基本是不可用状态,把b改为g就是显存要求

Csharp中使用

在Unity中使用其实就是在Cs中使用,所以这里就重点说说在Cs中使用。

原理

上文说到,ollama本身提供了一套API用于交互,于是我们可以通过HTTP协议与ollama通信,从而调用模型。因此在Cs中,我们只需要通过POST请求就可以通信了,具体API文档请参考

非流式传输

以下是一个Cs控制台示例:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

class Program
{
    private static readonly HttpClient httpClient = new HttpClient();
    private static readonly string ollamaApiUrl = "http://localhost:11434/api/chat"; // Ollama 默认地址
    private static List<object> chatHistory = new List<object>(); // 用于存储上下文

    static async Task Main()
    {
        Console.WriteLine("Chat with Cat7B. Type 'exit' to quit.");

        while (true)
        {
            Console.Write("You: ");
            string userInput = Console.ReadLine();
            if (userInput?.ToLower() == "exit")
                break;

            string response = await SendMessageToOllama(userInput);
            Console.WriteLine($"Ollama: {response}");
        }
    }

    private static async Task<string> SendMessageToOllama(string message)
    {
        // 记录对话上下文
        chatHistory.Add(new { role = "user", content = message });

        var requestBody = new
        {
            model = "Cat", // 你的模型名称
            messages = chatHistory,
            stream = false // 关闭流式返回,直接获取完整响应
        };

        string jsonContent = JsonSerializer.Serialize(requestBody);
        var response = await httpClient.PostAsync(ollamaApiUrl, new StringContent(jsonContent, Encoding.UTF8, "application/json"));

        if (!response.IsSuccessStatusCode)
        {
            return $"Error: {response.StatusCode}";
        }
        var responseString = await response.Content.ReadAsStringAsync();
        using var doc = JsonDocument.Parse(responseString);
        string reply = doc.RootElement.GetProperty("message").GetProperty("content").GetString();
        // 记录模型的回复
        chatHistory.Add(new { role = "assistant", content = reply });
        return reply;
    }
}


Comment