李锋镝的博客

  • 首页
  • 时间轴
  • 留言
  • 插件
  • 左邻右舍
  • 关于我
    • 关于我
    • 另一个网站
  • 知识库
  • 赞助
Destiny
自是人生长恨水长东
  1. 首页
  2. 原创
  3. 正文

本地部署 DeepSeek 模型并进行 Spring Boot 整合

2025年2月16日 325点热度 1人点赞 0条评论

本地部署 DeepSeek 模型

1. 环境准备

硬件:确保你的机器有足够的内存和计算资源,因为模型运行需要一定的硬件支持。
软件:安装 Python 3.7 及以上版本,以及相关依赖库,如 PyTorch 等。

2. 下载和部署模型

你可以从官方渠道下载 DeepSeek Coder 模型的权重文件,然后使用开源的推理框架(如 Hugging Face 的 Transformers 库)来加载和运行模型。以下是一个简单的 Python 脚本示例:

from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

# 加载分词器和模型
tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-1.3b", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-1.3b", trust_remote_code=True).cuda()

# 定义推理函数
def generate_code(prompt):
    inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
    outputs = model.generate(**inputs, max_new_tokens=512, do_sample=True, top_p=0.95, temperature=0.35)
    generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return generated_text

3. 搭建 API 服务

为了让 Spring Boot 能够调用本地的 DeepSeek 模型,你需要将上述推理函数封装成一个 API 服务。可以使用 Flask 或 FastAPI 来实现,以下是一个使用 Flask 的示例:

from flask import Flask, request, jsonify
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

app = Flask(__name__)

# 加载分词器和模型
tokenizer = AutoTokenizer.from_pretrained("deepseek-ai/deepseek-coder-1.3b", trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained("deepseek-ai/deepseek-coder-1.3b", trust_remote_code=True).cuda()

# 定义推理函数
def generate_code(prompt):
    inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
    outputs = model.generate(**inputs, max_new_tokens=512, do_sample=True, top_p=0.95, temperature=0.35)
    generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return generated_text

@app.route('/generate', methods=['POST'])
def generate():
    data = request.get_json()
    prompt = data.get('prompt')
    if prompt:
        result = generate_code(prompt)
        return jsonify({'result': result})
    else:
        return jsonify({'error': 'Missing prompt'}), 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Spring Boot 接入本地部署的 DeepSeek 服务

1. 创建 Spring Boot 项目

使用 Spring Initializr 创建一个新的 Spring Boot 项目,添加 Spring Web 依赖。

2. 添加依赖

在 pom.xml 中添加 OkHttp 依赖,用于发送 HTTP 请求:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.9.3</version>
    </dependency>
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.8</version>
    </dependency>
</dependencies>

3. 编写服务类

创建一个服务类来调用本地部署的 DeepSeek API:

import com.google.gson.Gson;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class DeepSeekService {
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private final OkHttpClient client = new OkHttpClient();
    private final Gson gson = new Gson();
    private static final String API_URL = "http://localhost:5000/generate";

    public String callDeepSeekApi(String prompt) throws IOException {
        // 构建请求体
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("prompt", prompt);
        String json = gson.toJson(requestBody);
        RequestBody body = RequestBody.create(json, JSON);

        // 构建请求
        Request request = new Request.Builder()
               .url(API_URL)
               .post(body)
               .build();

        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            return response.body().string();
        }
    }
}

4. 编写控制器类

创建一个控制器类来处理客户端的请求,并调用 DeepSeek 服务:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
public class DeepSeekController {
    @Autowired
    private DeepSeekService deepSeekService;

    @GetMapping("/deepseek")
    public String callDeepSeek(@RequestParam String prompt) {
        try {
            return deepSeekService.callDeepSeekApi(prompt);
        } catch (IOException e) {
            e.printStackTrace();
            return "Error calling DeepSeek API: " + e.getMessage();
        }
    }
}

5. 测试

启动本地的 Python API 服务和 Spring Boot 应用程序,访问 http://localhost:8080/deepseek?prompt=生成一个 Java 方法,用于计算两个整数的和,你将得到 DeepSeek 模型生成的代码结果。
通过以上步骤,你可以在本地部署 DeepSeek 模型,并让 Spring Boot 应用程序接入该模型进行代码生成等操作。

除非注明,否则均为李锋镝的博客原创文章,转载必须以链接形式标明本文链接

本文链接:https://www.lifengdi.com/archives/article/4196

相关文章

  • Springboot接入DeepSeek API
  • SpringBoot常用注解
  • CompletableFuture使用详解
  • SpringBoot 中内置的 49 个常用工具类
  • SpringBoot 实现接口防刷的 5 种实现方案
本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: AI DeepSeek SpringBoot
最后更新:2025年2月16日

李锋镝

既然选择了远方,便只顾风雨兼程。

打赏 点赞
< 上一篇
下一篇 >

文章评论

1 2 3 4 5 6 7 8 9 11 12 13 14 15 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 46 47 48 49 50 51 52 53 54 55 57 58 60 61 62 63 64 65 66 67 69 72 74 76 77 78 79 80 81 82 85 86 87 90 92 93 94 95 96 97 98 99
取消回复

曾虑多情损梵行,入山又恐别倾城。世间安得双全法,不负如来不负卿。

最新 热点 随机
最新 热点 随机
SpringBoot框架自动配置之spring.factories和AutoConfiguration.imports 应用型负载均衡(ALB)和网络型负载均衡(NLB)区别 什么是Helm? TransmittableThreadLocal介绍与使用 ReentrantLock深度解析 RedisTemplate和Redisson的区别
玩博客的人是不是越来越少了?准备入手个亚太的ECS,友友们有什么建议吗?什么是Helm?2024年11月1号 农历十月初一别再背线程池的七大参数了,现在面试官都这么问URL地址末尾加不加“/”有什么区别
【漫画】戏说外行对程序员的误会有多深 彻底搞懂mysql日志系统binlog,redolog,undolog Spring中@Autowired和@Resource的区别详解 TestNG基本注解 吐槽下Google浏览器~ Java设计模式:模板方法模式
标签聚合
文学 ElasticSearch JAVA K8s 教程 IDEA 分布式 MySQL 数据库 SQL 架构 面试 docker 设计模式 JVM 日常 多线程 Spring SpringBoot Redis
友情链接
  • i架构
  • 临窗旋墨
  • 博友圈
  • 博客录
  • 博客星球
  • 哥斯拉
  • 志文工作室
  • 搬砖日记
  • 旋律的博客
  • 旧时繁华
  • 林羽凡
  • 知向前端
  • 蜗牛工作室
  • 集博栈
  • 韩小韩博客
  • 風の声音

COPYRIGHT © 2025 lifengdi.com. ALL RIGHTS RESERVED.

Theme Kratos Made By Dylan

津ICP备2024022503号-3