DeepSeek-V3 + Spring Boot实战:10分钟接入国产大模型API
一、DeepSeek-V3 简介DeepSeek-V3是深度求索推出的最新大语言模型在代码生成和中文理解上表现优异。其API兼容OpenAI格式开发者可零成本迁移。本文将手把手演示Spring Boot接入DeepSeek-V3 API。回到顶部二、获取API Key1. 访问 platform.deepseek.com 注册账号2. 进入API Keys页面点击创建API Key3. 复制Key格式sk-xxxxxxxx4. 新用户赠送500万Tokens额度回到顶部三、Spring Boot项目搭建3.1 添加依赖dependencies dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-web/artifactId /dependency dependency groupIdcom.squareup.okhttp3/groupId artifactIdokhttp/artifactId version4.12.0/version /dependency dependency groupIdcom.alibaba.fastjson2/groupId artifactIdfastjson2/artifactId version2.0.47/version /dependency /dependencies3.2 配置文件deepseek: api-key: sk-your-api-key-here base-url: https://api.deepseek.com model: deepseek-chat max-tokens: 2048 temperature: 0.73.3 配置类Configuration ConfigurationProperties(prefix deepseek) Data public class DeepSeekConfig { private String apiKey; private String baseUrl https://api.deepseek.com; private String model deepseek-chat; private int maxTokens 2048; private double temperature 0.7; Bean public OkHttpClient okHttpClient() { return new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .build(); } }回到顶部四、核心服务实现4.1 请求DTOData public class ChatRequest { private String model; private ListMessage messages; private int max_tokens; private double temperature; Data AllArgsConstructor NoArgsConstructor public static class Message { private String role; private String content; } public static ChatRequest create(String systemPrompt, String userMsg, DeepSeekConfig config) { ChatRequest req new ChatRequest(); req.setModel(config.getModel()); req.setMax_tokens(config.getMaxTokens()); req.setTemperature(config.getTemperature()); req.setMessages(List.of( new Message(system, systemPrompt), new Message(user, userMsg) )); return req; } }4.2 DeepSeek服务Service Slf4j public class DeepSeekService { Autowired private DeepSeekConfig config; Autowired private OkHttpClient httpClient; public String chat(String systemPrompt, String userMsg) { ChatRequest request ChatRequest.create(systemPrompt, userMsg, config); String jsonBody JSON.toJSONString(request); RequestBody body RequestBody.create(jsonBody, MediaType.parse(application/json; charsetutf-8)); Request httpRequest new Request.Builder() .url(config.getBaseUrl() /v1/chat/completions) .addHeader(Authorization, Bearer config.getApiKey()) .post(body).build(); try (Response response httpClient.newCall(httpRequest).execute()) { if (!response.isSuccessful()) { throw new RuntimeException(API error: response.code()); } String respJson response.body().string(); JSONObject resp JSON.parseObject(respJson); return resp.getJSONArray(choices) .getJSONObject(0).getJSONObject(message).getString(content); } catch (IOException e) { throw new RuntimeException(API exception, e); } } }回到顶部五、流式响应SSEGetMapping(value /chat/stream, produces MediaType.TEXT_EVENT_STREAM_VALUE) public SseEmitter streamChat(RequestParam String message) { SseEmitter emitter new SseEmitter(120000L); ChatRequest request ChatRequest.create(AI助手, message, config); request.setStream(true); String jsonBody JSON.toJSONString(request); RequestBody body RequestBody.create(jsonBody, MediaType.parse(application/json; charsetutf-8)); Request httpRequest new Request.Builder() .url(config.getBaseUrl() /v1/chat/completions) .addHeader(Authorization, Bearer config.getApiKey()) .post(body).build(); httpClient.newCall(httpRequest).enqueue(new Callback() { public void onFailure(Call call, IOException e) { emitter.completeWithError(e); } public void onResponse(Call call, Response response) { try (ResponseBody rb response.body()) { BufferedReader reader new BufferedReader( new InputStreamReader(rb.byteStream(), StandardCharsets.UTF_8)); String line; while ((line reader.readLine()) ! null) { if (line.startsWith(data: ) !line.contains([DONE])) { JSONObject json JSON.parseObject(line.substring(6)); String content json.getJSONArray(choices) .getJSONObject(0).getJSONObject(delta).getString(content); if (content ! null) emitter.send(SseEmitter.event().data(content)); } } emitter.complete(); } catch (Exception e) { emitter.completeWithError(e); } } }); return emitter; }回到顶部六、ControllerRestController RequestMapping(/api/deepseek) public class DeepSeekController { Autowired private DeepSeekService deepSeekService; PostMapping(/chat) public MapString, String chat(RequestBody MapString, String params) { String msg params.get(message); String sys params.getOrDefault(systemPrompt, 你是AI助手); String reply deepSeekService.chat(sys, msg); return Map.of(reply, reply, model, deepseek-chat); } GetMapping(/chat/stream) public SseEmitter streamChat(RequestParam String message) { return deepSeekService.streamChat(message); } }回到顶部七、测试curl -X POST http://localhost:8080/api/deepseek/chat -H Content-Type: application/json -d {message:用Java写单例,systemPrompt:Java专家} # 返回: {reply:以下是线程安全单例...,model:deepseek-chat} # 流式 curl -N http://localhost:8080/api/deepseek/chat/stream?messageSpring%20Boot回到顶部八、最佳实践