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;
    }
相关推荐
SimonKing15 分钟前
Archery:开源、一站式的数据库 SQL 审核与运维平台
java·后端·程序员
AI小智29 分钟前
为了帮我搞定旅行清单:我的小白老婆报名了30万奖金的黑客松!
后端
双向3339 分钟前
RTX 4090助力深度学习:从PyTorch到生产环境的完整实践指南
后端
shengjk141 分钟前
Java vs Python Web 服务器深度对比:从传统到现代的演进之路
后端
绝无仅有42 分钟前
某辅导教育大厂真实面试过程与经验总结
后端·面试·架构
绝无仅有44 分钟前
Java后端技术面试:银行业技术架构相关问题解答
后端·面试·github
这里有鱼汤1 小时前
【花姐小课堂】新手也能秒懂!用「风险平价」打造扛造的投资组合
后端·python
CodeSheep1 小时前
当了leader才发现,大厂最想裁掉的,不是上班总迟到的,也不是下班搞失联的,而是经常把这3句话挂在嘴边的
前端·后端·程序员
shark_chili1 小时前
Git Worktree:优雅解决多分支开发痛点的终极利器
后端
程序员爱钓鱼2 小时前
Go语言实战案例-项目实战篇:新闻聚合工具
后端·google·go