使用java-openai调用deepsek-api

1.申请apikey

登录 硅基流动 https://siliconflow.cn/  注册账号 申请apikey

2.添加依赖

  <dependency>
    <groupId>com.litongjava</groupId>
    <artifactId>java-openai</artifactId>
    <version>1.1.4</version>
  </dependency>

  <dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.52</version>
  </dependency></dependencies>

3.将apikey添加到配置文件

src/main/java/app.properties

SILICONFLOW_API_KEY=

3.编写代码

http请求

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.litongjava.openai.chat.OpenAiChatMessage;
import com.litongjava.openai.chat.OpenAiChatRequestVo;
import com.litongjava.openai.chat.OpenAiChatResponseVo;
import com.litongjava.openai.client.OpenAiClient;
import com.litongjava.siliconflow.SiliconFlowConsts;
import com.litongjava.siliconflow.SiliconFlowModels;
import com.litongjava.tio.utils.environment.EnvUtils;
import com.litongjava.tio.utils.json.JsonUtils;

import okhttp3.Response;

public class SiliconFlowDeepSeekTest {
  public static void main(String[] args) {
    // 从配置中加载 SILICONFLOW_API_KEY
    EnvUtils.load();
    String apiKey = EnvUtils.getStr("SILICONFLOW_API_KEY");

    // 创建消息列表
    List<OpenAiChatMessage> messages = new ArrayList<>();
    messages.add(new OpenAiChatMessage("user", "How are you?"));

    // 创建聊天请求
    OpenAiChatRequestVo chatRequestVo = new OpenAiChatRequestVo();
    chatRequestVo.setStream(false);
    chatRequestVo.setModel(SiliconFlowModels.DEEPSEEK_R1);
    chatRequestVo.setMessages(messages);

    String json = JsonUtils.toSkipNullJson(chatRequestVo);
    System.out.println("请求 JSON:\n" + json);

    // 发送 HTTP 请求
    try (Response response = OpenAiClient.chatCompletions(SiliconFlowConsts.SELICONFLOW_API_BASE, apiKey, json)) {
      if (response.isSuccessful()) {
        String responseBody = response.body().string();
        OpenAiChatResponseVo chatCompletions = JsonUtils.parse(responseBody, OpenAiChatResponseVo.class);
        System.out.println("响应:\n" + JsonUtils.toSkipNullJson(chatCompletions));
      } else {
        System.err.println("请求失败: " + response);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}


sse请求

package com.litongjava.perplexica.services;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.litongjava.openai.chat.ChatResponseDelta;
import com.litongjava.openai.chat.Choice;
import com.litongjava.openai.chat.OpenAiChatMessage;
import com.litongjava.openai.chat.OpenAiChatRequestVo;
import com.litongjava.openai.chat.OpenAiChatResponseVo;
import com.litongjava.openai.client.OpenAiClient;
import com.litongjava.siliconflow.SiliconFlowConsts;
import com.litongjava.siliconflow.SiliconFlowModels;
import com.litongjava.tio.utils.environment.EnvUtils;
import com.litongjava.tio.utils.json.FastJson2Utils;
import com.litongjava.tio.utils.json.JsonUtils;

import lombok.extern.slf4j.Slf4j;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.BufferedSource;

@Slf4j
public class SiliconFlowDeepSeekStreamTest {
  public static void main(String[] args) {
    // 从配置中加载 OPENAI_API_KEY
    EnvUtils.load();
    String apiKey = EnvUtils.getStr("SILICONFLOW_API_KEY");

    // 创建消息列表
    List<OpenAiChatMessage> messages = new ArrayList<>();
    messages.add(new OpenAiChatMessage("user", "How are you?"));

    // 创建聊天请求
    OpenAiChatRequestVo chatRequestVo = new OpenAiChatRequestVo();
    chatRequestVo.setStream(true);
    chatRequestVo.setModel(SiliconFlowModels.DEEPSEEK_R1);
    chatRequestVo.setMessages(messages);

    String json = JsonUtils.toSkipNullJson(chatRequestVo);
    System.out.println("请求 JSON:\n" + json);

    Call call = OpenAiClient.chatCompletions(SiliconFlowConsts.SELICONFLOW_API_BASE, apiKey, json, new Callback() {

      @Override
      public void onResponse(Call arg0, Response response) throws IOException {
        if (!response.isSuccessful()) {
          String string = response.body().string();
          String message = "Chat model response an unsuccessful message:" + string;
          log.error("message:{}", message);
          return;
        }

        onResponseSuccess(response);

      }

      @Override
      public void onFailure(Call arg0, IOException arg1) {
      }
    });
    log.info("call:{}", call);
  }
  
  private static void onResponseSuccess(Response response) throws IOException {
    try (ResponseBody responseBody = response.body()) {
      StringBuffer completionContent = new StringBuffer();
      BufferedSource source = responseBody.source();
      String line;

      while ((line = source.readUtf8Line()) != null) {
        if (line.length() < 1) {
          continue;
        }
        // 处理数据行
        if (line.length() > 6) {
          String data = line.substring(6);
          if (data.endsWith("}")) {
            OpenAiChatResponseVo chatResponse = FastJson2Utils.parse(data, OpenAiChatResponseVo.class);
            List<Choice> choices = chatResponse.getChoices();
            if (!choices.isEmpty()) {
              ChatResponseDelta delta = choices.get(0).getDelta();
              String part = delta.getContent();
              if (part != null && !part.isEmpty()) {
                completionContent.append(part);
              }
              String reasoning_content = delta.getReasoning_content();
              if (reasoning_content != null && !reasoning_content.isEmpty()) {
                log.info("reasoning_content:{}",reasoning_content);
              }
            }
          } else if (": keep-alive".equals(line)) {
            log.info("keep-alive");
          } else {
            log.info("Data does not end with }:{}", line);

          }
        }
      }
      log.info("completionContent:{}",completionContent);
    }
  }
}

输出示例

请求 JSON:
{"stream":true,"model":"deepseek-ai/DeepSeek-R1","messages":[{"role":"user","content":[{"type":"text","text":"How are you?"}]}]}
2025-02-09 16:07:23.344 [main] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.main:65 - call:okhttp3.internal.connection.RealCall@3f57bcad
2025-02-09 16:08:04.394 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:Alright
2025-02-09 16:08:04.396 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:, someone
2025-02-09 16:08:04.398 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: asked
2025-02-09 16:08:04.400 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:,
2025-02-09 16:08:04.401 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: "How
2025-02-09 16:08:04.403 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: are you
2025-02-09 16:08:04.405 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:?" H
2025-02-09 16:08:04.406 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:mm,
2025-02-09 16:08:04.408 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: I need
2025-02-09 16:08:04.410 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: to consider
2025-02-09 16:08:04.412 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: how
2025-02-09 16:08:04.414 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: to respond
2025-02-09 16:08:04.415 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: appropriately
2025-02-09 16:08:04.417 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:. Since
2025-02-09 16:08:04.419 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: I'm
2025-02-09 16:08:04.420 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: an AI
2025-02-09 16:08:04.422 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:, I
2025-02-09 16:08:04.424 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: don't
2025-02-09 16:08:04.426 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: have feelings
2025-02-09 16:08:04.428 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:,
2025-02-09 16:08:04.430 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: so
2025-02-09 16:08:04.431 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: I should
2025-02-09 16:08:04.433 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: clarify
2025-02-09 16:08:04.434 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: that.
2025-02-09 16:08:04.436 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: But I
2025-02-09 16:08:04.439 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: also want
2025-02-09 16:08:04.440 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: to be
2025-02-09 16:08:04.442 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: helpful and
2025-02-09 16:08:04.444 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: friendly.
2025-02-09 16:08:04.446 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: Maybe start
2025-02-09 16:08:04.447 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: by thanking
2025-02-09 16:08:04.448 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: them for
2025-02-09 16:08:04.450 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: asking,
2025-02-09 16:08:04.452 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: then explain
2025-02-09 16:08:04.453 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: my status
2025-02-09 16:08:04.455 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: as an
2025-02-09 16:08:04.457 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: AI,
2025-02-09 16:08:04.460 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: and offer
2025-02-09 16:08:04.462 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: assistance.
2025-02-09 16:08:04.464 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: Let
2025-02-09 16:08:04.465 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: me check
2025-02-09 16:08:04.467 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: if that
2025-02-09 16:08:04.468 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: makes
2025-02-09 16:08:04.470 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: sense.
2025-02-09 16:08:04.472 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: Also
2025-02-09 16:08:04.473 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:, make
2025-02-09 16:08:04.475 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: sure the
2025-02-09 16:08:04.477 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: tone is
2025-02-09 16:08:04.479 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: positive and
2025-02-09 16:08:04.480 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: not
2025-02-09 16:08:04.482 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: too robotic
2025-02-09 16:08:04.483 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:. Y
2025-02-09 16:08:04.485 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:ep,
2025-02-09 16:08:04.487 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: that should
2025-02-09 16:08:04.488 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: work.
2025-02-09 16:08:04.521 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: Let me
2025-02-09 16:08:04.755 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: put that
2025-02-09 16:08:05.006 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content: together smoothly
2025-02-09 16:08:05.240 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:92 - reasoning_content:.

2025-02-09 16:08:11.186 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:98 - Data does not end with }:data: [DONE]
2025-02-09 16:08:11.188 [OkHttp https://api.siliconflow.cn/...] INFO   c.l.p.s.SiliconFlowDeepSeekStreamTest.onResponseSuccess:103 - completionContent:

Thanks for asking! I'm just a computer program, so I don't have feelings, but I'm here and ready to help with any questions or tasks you have. What can I assist you with today? 😊


完毕

评论区

热门分享

扫码入社