本地部署 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 应用程序接入该模型进行代码生成等操作。