SpringBoot调用deepseek

1、效果截图:

2、代码部分:

application.properties

java 复制代码
server.port=8080

deepseek.api.token=sk-d34e929e887b4881813395241df2f745
deepseek.api.url=https://api.deepseek.com/chat/completions

controller部分 请求参数可以缩短,写成实体类形式

java 复制代码
package com.example.springbootai.demos.web;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author caojun
 */
@RestController
public class TestController {

    public static final RestTemplate restTemplate = new RestTemplate();

    @Value("${deepseek.api.token}")
    private String apiToken;

    @Value("${deepseek.api.url}")
    private String apiUrl;


    @PostMapping("/deepSeek")
    public String callDeepSeek(@RequestBody String question) {

        // 创建消息列表
        List<Map<String, Object>> messages = new ArrayList<>();

        // 添加系统消息
        Map<String, Object> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "You are a helpful assistant");
        messages.add(systemMessage);

        // 添加用户消息
        Map<String, Object> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", question);
        messages.add(userMessage);

        // 创建请求 Map
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("model", "deepseek-chat");
        requestMap.put("messages", messages);
        requestMap.put("frequency_penalty", 0);
        requestMap.put("max_tokens", 2048);
        requestMap.put("presence_penalty", 0);
        requestMap.put("response_format", Collections.singletonMap("type", "text"));
        requestMap.put("stop", null);
        requestMap.put("stream", false);
        requestMap.put("stream_options", null);
        requestMap.put("temperature", 1);
        requestMap.put("top_p", 1);
        requestMap.put("tools", null);
        requestMap.put("tool_choice", "none");
        requestMap.put("logprobs", false);
        requestMap.put("top_logprobs", null);

        // 将 requestMap 转换为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String requestBody = null;
        try {
            requestBody = objectMapper.writeValueAsString(requestMap);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiToken);
        headers.set("Content-Type", "application/json");

        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, String.class);
        // 解析响应 JSON
        JSONObject jsonResponse = JSONObject.parseObject(response.getBody());
        String generatedText = jsonResponse.getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("message")
                .getString("content");
        return generatedText;
    }

    @GetMapping("/getBalance")
    public String getBalance() {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiToken);
        headers.set("Content-Type", "application/json");

        HttpEntity<String> entity = new HttpEntity<>(headers);


        // 发送 GET 请求
        ResponseEntity<String> response = restTemplate.exchange(
                "https://api.deepseek.com/user/balance",
                HttpMethod.GET,
                entity,
                String.class
        );
        System.out.println(response.getBody());
        return response.getBody();
    }


}

3、依赖

java 复制代码
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>

controller可以简化这样的

java 复制代码
@PostMapping("/deepSeek")
    public String callDeepSeek(@RequestBody String question) {

        // 创建消息列表
        List<Map<String, Object>> messages = new ArrayList<>();

        // 添加系统消息
        Map<String, Object> systemMessage = new HashMap<>();
        systemMessage.put("role", "system");
        systemMessage.put("content", "You are a helpful assistant");
        messages.add(systemMessage);

        // 添加用户消息
        Map<String, Object> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", question);
        messages.add(userMessage);

        // 创建请求 Map
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("model", "deepseek-chat");
        requestMap.put("messages", messages);
        requestMap.put("stream", false);

        // 将 requestMap 转换为 JSON 字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String requestBody = null;
        try {
            requestBody = objectMapper.writeValueAsString(requestMap);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Bearer " + apiToken);
        headers.set("Content-Type", "application/json");

        HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.exchange(apiUrl, HttpMethod.POST, entity, String.class);
        // 解析响应 JSON
        JSONObject jsonResponse = JSONObject.parseObject(response.getBody());
        String generatedText = jsonResponse.getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("message")
                .getString("content");
        return generatedText;
    }
相关推荐
谷哥的小弟1 分钟前
Spring Framework源码解析——ApplicationContextInitializer
java·spring·源码
布谷歌4 分钟前
在java中实现c#的int.TryParse方法
java·开发语言·python·c#
+VX:Fegn08957 分钟前
计算机毕业设计|基于springboot + vue图书管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
AntBlack8 分钟前
忍不住推荐 : AI 时代 ,桌面端真的可以考虑一下Go+Wails 的组合
后端·go·ai编程
码事漫谈13 分钟前
C++20协程如何撕开异步编程的牢笼
后端
while(1){yan}15 分钟前
网络基础知识
java·网络·青少年编程·面试·电脑常识
Ulana19 分钟前
计算机基础10大高频考题解析
java·人工智能·算法
黄俊懿26 分钟前
【深入理解SpringCloud微服务】Seata(AT模式)源码解析——@GlobalTransactional注解与@globalLock生效的原理
java·spring cloud·微服务·云原生·架构·系统架构·架构师
wheelmouse778830 分钟前
一个优雅、通用、零侵入的 CSV 导出工具类(Java 实战)
java·开发语言
DevYK1 小时前
Coze Studio 二次开发(二)支持 MCP Server 动态配置
后端·agent·coze