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

相关推荐
脉动数据行情4 分钟前
Python 实现融通金行情数据对接(实时推送 + K 线 + 产品列表)
开发语言·python
DavidSoCool27 分钟前
Spring AI Alibaba ReactAgent 调用Tool 实现多轮对话
java·人工智能·spring·多轮对话·reactagent
skywalk816341 分钟前
Trae生成的中文编程语言关键字(如“定“、“函“、“印“等)需要和标识符之间用 空格 隔开,以确保正确识别
服务器·开发语言·编程
神所夸赞的夏天1 小时前
如何获取多层json数据,存成dictionary,并取最大最小值
java·前端·json
红色的小鳄鱼1 小时前
前端面试js手写
开发语言·前端·javascript
9号达人1 小时前
为什么你应该在 MQ 里用多个消费者,而不是一个
java·后端·架构
焦糖玛奇朵婷1 小时前
健身房预约小程序开发、设计
java·大数据·服务器·前端·小程序
海盗12341 小时前
C#中的IEqualityComparer<T>使用
开发语言·c#
小新同学^O^1 小时前
简单学习 --> TCP协议
java·网络·tcp
江公望1 小时前
Qt QSharedPointer用法,10分钟讲清楚
开发语言·qt