Java调用DeepSeek API实现对话问答

Java调用DeepSeek接口实现对话功能

下文将简要介绍java如何调deepseek接口实现对话问答,前提条件需要安装jdk运行环境。

注册账号及申请api key

1.访问deepseek 官网:https://www.deepseek.com

2.注册登录后,点击进入API开放平台:

需要注册后实名认证,api计费使用,需要充值,收费标准参考官网说明

3.创建api key,点击API keys.再点击创建API key

api key 创建完成需要保存起来,只有创建时能看完整的key

查看官方文档

1.点击接口文档

2.找到API 文档->对话补全,选择JAVA

这里还可以选择其他语言

3.查看调用的地址和请求方式

请求方式:post

url: https://api.deepseek.com/chat/completions

4.查看请求和返回格式

请求格式:

是一个json类型的参数,包含一个message数组,message包含role和content,role表示角色类型,左侧有对应角色的含义,content是需要询问的问题

返回格式:

choices是返回给我们的结果,通过展开发现下面是个messge,返回信息同样封装再content中。

代码实现

1.pom.xml,只提供了核心依赖,按需引入,使用其他工具调用也可如okclient、apache client、hutool工具,此处使用springboot 的restTemplate

复制代码
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>    
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
          <dependency>
            <groupId>org.springdoc</groupId>
            <artifactId>springdoc-openapi-ui</artifactId>
            <version>1.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>2.2.19</version>
        </dependency>
        <dependency>
            <groupId>io.swagger.core.v3</groupId>
            <artifactId>swagger-models</artifactId>
            <version>2.2.19</version>
        </dependency>

2.配置文件 yml中增加deepseek配置

复制代码
deepseek:
  api:
    key: sk-c3784d7******4b68ce79dfc888a0a #你申请的api key
    url: https://api.deepseek.com/chat/completions #文档提供的地址

3.封装message对象、请求对象和返回对象

message:

复制代码
import lombok.Data;

@Data
public class Message {
    String role;
    String content;
}

请求对象:

复制代码
@Data
public class DeepseekRequest {
    private String model;
    private List<Message> messages;
    private double temperature;
    private int max_tokens;
}

返回对象:在这里插入代码片

复制代码
@Data
public class Choice {
   private  Message message;
}
@Data
public class DeepSeekResponse {
    private List<Choice> choices;
}

4.定义业务类,用于发送和接收信息

复制代码
@Service
public class DeepSeekService {
    @Value("${deepseek.api.key}")
    private String apiKey;
    @Value("${deepseek.api.url}")
    private String apiUrl;
    public final RestTemplate restTemplate;
    DeepSeekService(RestTemplate restTemplate){
        this.restTemplate=restTemplate;
    }
    public DeepSeekResponse callChatApi(String message) {
        // 构造请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);
        // 构造HTTP请求
        DeepseekRequest requestBody = new DeepseekRequest();
        requestBody.setTemperature(1);
        requestBody.setMax_tokens(100);
        requestBody.setModel("deepseek-chat");
        Message message1 = new Message();
        message1.setRole("user");
        message1.setContent(message);
        List<Message> messages = new ArrayList<>();
        messages.add(message1);
        requestBody.setMessages(messages);
        HttpEntity<DeepseekRequest> requestEntity = new HttpEntity<>(requestBody, headers);
        // 发送请求并获取响应
        ResponseEntity<DeepSeekResponse> responseEntity = restTemplate.exchange(
                apiUrl,
                HttpMethod.POST,
                requestEntity,
                DeepSeekResponse.class
        );

        // 返回响应内容
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        } else {
            throw new RuntimeException("Failed to call DeepSeek API: " + responseEntity.getStatusCode());
        }
    }

5.定义controller

复制代码
@RestController
@RequestMapping("/deepseek")
@Tag(name = "deepSeek测试")
public class DeepSeekTestController {
    @Resource
    private DeepSeekService deepSeekService;
    @PostMapping("/chat")
    @Operation(summary = "deekseek接口")
    public String getResponse(@RequestBody String prompt) {
        String content = deepSeekService.callChatApi(prompt).getChoices().get(0).getMessage().getContent();
        return content;
    }

}

测试

1.输入你好

2.输入请介绍自己

以上简单实现deepseek问答,仅供参考,具体以实际为准。

相关推荐
Eloudy3 分钟前
业界宽松内存模型的不统一而导致的软件问题, gcc, linux kernel, JVM
java·linux·jvm·arch·gem5
不学无术の码农21 分钟前
《Effective Python》第六章 推导式和生成器——避免在推导式中使用超过两个控制子表达式
开发语言·python
Musennn29 分钟前
leetcode17.电话号码的字母组合:字符串映射与回溯的巧妙联动
java·数据结构·算法·leetcode
cxh_陈33 分钟前
org.junit.runners.model.InvalidTestClassError:此类问题的解决
java·开发语言·junit
猿六凯37 分钟前
历年厦门大学计算机保研上机真题
java·考研
钮钴禄·爱因斯晨39 分钟前
赛博算命之“帝王之术”——奇门遁甲的JAVA实现
java·开发语言·python
虾球xz39 分钟前
CppCon 2014 学习:Pragmatic Type Erasure
开发语言·c++·学习
dudly39 分钟前
Python字符串格式化(三): t-string前瞻(Python 3.14 新特性)
开发语言·python
向哆哆1 小时前
Java代码重构:如何提升项目的可维护性和扩展性?
java·python·重构
怡人蝶梦1 小时前
Spring Boot启动慢?Redis缓存击穿?Kafka消费堆积?——Java后端常见问题排查实战
java·jvm·redis·kafka·springboot·prometheus·microservices