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问答,仅供参考,具体以实际为准。

相关推荐
隐退山林2 分钟前
JavaEE:多线程初阶(一)
java·开发语言·jvm
C_心欲无痕5 分钟前
ts - 模板字面量类型与 `keyof` 的魔法组合:`keyof T & `on${string}`使用
linux·运维·开发语言·前端·ubuntu·typescript
最贪吃的虎8 分钟前
Redis其实并不是线程安全的
java·开发语言·数据库·redis·后端·缓存·lua
一勺菠萝丶10 分钟前
Java 后端想学 Vue,又想写浏览器插件?
java·前端·vue.js
乾元11 分钟前
无线定位与链路质量预测——从“知道你在哪”,到“提前知道你会不会掉线”的网络服务化实践
运维·开发语言·人工智能·网络协议·重构·信息与通信
xie_pin_an11 分钟前
C++ 类和对象全解析:从基础语法到高级特性
java·jvm·c++
AC赳赳老秦11 分钟前
Unity游戏开发实战指南:核心逻辑与场景构建详解
开发语言·spring boot·爬虫·搜索引擎·全文检索·lucene·deepseek
Tao____13 分钟前
企业级物联网平台
java·网络·物联网·mqtt·网络协议
山峰哥15 分钟前
数据库工程与SQL调优实战:从原理到案例的深度解析
java·数据库·sql·oracle·性能优化·编辑器
kaico201815 分钟前
远程调用组件openfeign
java·spring cloud