(1)进入api接口文档
(2)充值并创建APIkey
<!--糊涂工具包-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>${hutool.version}</version>
</dependency>
package com.bwie.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
@Data
@AllArgsConstructor
public class ReqMessage implements Serializable {
String role;
String content;
}
package com.bwie.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class RequestData implements Serializable {
String model;
ReqMessage[] messages;
boolean stream;
}
package com.bwie.entity;
import lombok.Data;
@Data
public class ApiResponse {
private String id;
private String object;
private Long created;
private String model;
private Choice[] choices;
private Usage usage;
}
@Data
class Choice {
private Integer index;
private ReqMessage message;
private String finish_reason;
}
@Data
class Usage {
private Integer prompt_tokens;
private Integer completion_tokens;
private Integer total_tokens;
}
package com.bwie.controller;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.bwie.entity.ReqMessage;
import com.bwie.entity.RequestData;
import com.bwie.utils.R;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bwie.entity.*;
@RestController
@RequestMapping("/deepSeek")
public class DeepSeekController {
private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
private static final String API_KEY = "sk-1257c8adsfageaasw531bc4c4b3630f3837d";
@PostMapping("/ask/{question}")
public R ask(@PathVariable("question") String question) {
// 构建请求的 JSON 数据
RequestData requestData = new RequestData();
requestData.setModel("deepseek-chat");
requestData.setMessages( new ReqMessage[]{
new ReqMessage("user", question)
});
requestData.setStream( false);
String postResult = HttpUtil.createPost(API_URL)
//这个请求头.header是自己项目需要加的,可以省略
.header("Content-Type", "application/json")
//这两个请求头是项目需要加的,可以省略
.header("Authorization", "Bearer " + API_KEY)
//传输参数
.body(JSON.toJSONString(requestData))
.execute()
.body();
System.out.println("查询结果:"+postResult);
ApiResponse apiResponse = JSON.parseObject(postResult, ApiResponse.class);
return R.OK(apiResponse);
}
}