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;
    }
相关推荐
驰羽8 分钟前
[GO]GORM 常用 Tag 速查手册
开发语言·后端·golang
楚韵天工17 分钟前
宠物服务平台(程序+文档)
java·网络·数据库·spring cloud·编辑器·intellij-idea·宠物
helloworddm19 分钟前
Orleans Stream SubscriptionId 生成机制详解
java·系统架构·c#
失散1322 分钟前
分布式专题——43 ElasticSearch概述
java·分布式·elasticsearch·架构
ajsbxi23 分钟前
【Java 基础】核心知识点梳理
java·开发语言·笔记
Q_Q51100828542 分钟前
python基于web的汽车班车车票管理系统/火车票预订系统/高铁预定系统 可在线选座
spring boot·python·django·flask·node.js·汽车·php
AntBlack1 小时前
虽迟但到 :盘一盘 SpringAI 现在发展得怎么样了?
后端·spring·openai
聪明的笨猪猪1 小时前
Java JVM “调优” 面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
重整旗鼓~1 小时前
28.redisson源码分析分布式锁
java·开发语言
Query*1 小时前
Java 设计模式——工厂模式:从原理到实战的系统指南
java·python·设计模式