Skip to content

对话补全

官方api

定义apikey

shell
vim ~/.zshrc

export DEEP_SEED_API_KEY=sk-xxxxx

引入

yaml
spring:
  ai:
    deepseek:
      api-key: ${DEEP_SEED_API_KEY}

定义Controller

java
@Slf4j
@RestController
public class ChatController {

    @Autowired
    DeepSeekService deepSeekService;

    @RequestMapping("/chat")
    public String chat(@RequestParam(value = "message",
                                     required = true,
                                     defaultValue = "你是谁,你是如何训练出来的?") String msg){
        return deepSeekService.chat(msg);
    }
}

接口调用

java
@Value("${spring.ai.deepseek.api-key}")
String deepSeekApiKey;

public String chat(String msg) {
  try {
      OkHttpClient client = new OkHttpClient().newBuilder()
              .build();
      MediaType mediaType = MediaType.parse("application/json");
      JSONObject body = new JSONObject();
      List<DeepSeekMessage> messages = new ArrayList<>();
      messages.add(new DeepSeekMessage().setContent("You are a helpful assistant").setRole("system"));
      messages.add(new DeepSeekMessage().setContent(msg).setRole("user"));
      body.put("messages", messages);
      body.put("model", "deepseek-chat");
      System.out.println(body.toJSONString());
      RequestBody requestBody = RequestBody.create(mediaType, body.toJSONString());
      Request request = new Request.Builder()
              .url("https://api.deepseek.com/chat/completions")
              .method("POST", requestBody)
              .addHeader("Content-Type", "application/json")
              .addHeader("Accept", "application/json")
              .addHeader("Authorization", "Bearer " + deepSeekApiKey)
              .build();
      response = client.newCall(request).execute();
      log.info("状态码: {}" ,response.code());

      // 获取响应体的字符串内容
      String responseBody = response.body().string();
      log.info("响应 Body: {}",responseBody);

      DeepSeekResponse deepSeekResponse = JSONObject.parseObject(responseBody, DeepSeekResponse.class);

      // 获取具体的响应字段
      if (response.isSuccessful()) {
          String content = deepSeekResponse.getChoices()[0].getMessage().getContent();
          log.info("响应: {}",content);
          return content;
      }
      log.error("出错了 {}", deepSeekResponse.getError());
      return deepSeekResponse.getError();
  } catch (Exception ex) {
      ex.printStackTrace();
  } finally {
      if (response != null) {
          response.close();
      }

  }
  return "出错了";
}

演示结果

FlbiZhYNLZc-8I5lu4e1zI2pBakcFi9rNXiwe7E16CauEKc6jbg5n82xFsP0Lg6--AJYs9Wg32W8AEoFsGSx