java(webflux)流式接入deepseek推理大模型

  • deepseek请求体
@Data
public class DeepSeekRequestBody {

    private String model;

    private List<DeepSeekMessage> messages;

    private Boolean stream;


}


@Data
@NoArgsConstructor
@AllArgsConstructor
public class DeepSeekMessage {

    private String role;

    private String content;

}
  • deepseek返回结果对象
@Data
public class DeepSeekResult {

    private Integer index;

    private JSONObject delta;

}
  • main方法
public static void main(String[] args) throws InterruptedException {
        //创建webclient客户端
        WebClient webClient = WebClient.create("https://api.deepseek.com");
        //构建deepseek请求体
        DeepSeekRequestBody deepSeekRequestBody = new DeepSeekRequestBody();
        deepSeekRequestBody.setStream(true);
        deepSeekRequestBody.setModel("deepseek-reasoner");
        deepSeekRequestBody.setMessages(List.of(new DeepSeekMessage("user", "你想要问的问题")));
        Semaphore semaphore = new Semaphore(0);
        List<String> resultList = new ArrayList<>();
        webClient.post()
                .uri("/chat/completions")
                .contentType(MediaType.APPLICATION_JSON)
                .header("Authorization", "Bearer API-keys")
                .bodyValue(JSON.toJSON(deepSeekRequestBody))
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(String.class)
                .subscribeOn(Schedulers.boundedElastic())
                .doOnError(e-> log.error("异常:",e))
                .subscribe(re->{
                    if("[DONE]".equals(re)){
                        semaphore.release();
                        return;
                    }
                    JSONObject jsonObject = JSON.parseObject(re,JSONObject.class);
                    List<DeepSeekResult> deepSeekResultList = JSON.parseArray(jsonObject.getString("choices"),DeepSeekResult.class);
                    String content = deepSeekResultList.stream().map(deepSeekResult -> {
                        JSONObject delta = deepSeekResult.getDelta();
                        return delta.getString("content");
                    }).filter(StringUtils::isNotBlank).collect(Collectors.joining());
                    resultList.add(content);
                });
        semaphore.acquire();
        //最终结果
        String finalResult = String.join("", resultList);
        log.info("结果:{}",finalResult);
        semaphore.release();
    }

### Java 实现 DeepSeek 流式问答调用并返回前端 为了使用 Java 调用 DeepSeek 进行流式问答并将结果返回给前端,需要完成几个主要部分的工作: #### 1. 添加依赖项 首先,在项目的 `pom.xml` 文件中添加必要的 Maven 依赖来处理 HTTP 请求和 JSON 数据解析。 ```xml <dependencies> <!-- Apache HttpClient --> <dependency> <groupId>org.apache.httpcomponents.client5</groupId> <artifactId>httpclient5</artifactId> <version>5.2</version> </dependency> <!-- Gson for JSON parsing --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.9.0</version> </dependency> </dependencies> ``` #### 2. 构建请求体 创建一个类用于构建发送至 DeepSeek API 的消息对象。这通常包括对话历史记录以及当前用户的输入。 ```java public class Message { private String role; private String content; public Message(String role, String content) { this.role = role; this.content = content; } // Getters and Setters... } ``` #### 3. 发起 POST 请求 编写函数发起带有适当参数的 POST 请求到指定 URL 地址,并设置好认证信息(如 API 密钥)。这里采用异步方式读取服务器响应数据以便支持流式传输[^1]。 ```java import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.nio.AsyncEntityConsumer; import org.apache.hc.core5.http.nio.support.BasicAsyncRequestProducer; import org.apache.hc.core5.reactor.IOReactorConfig; import org.apache.hc.core5.reactor.ListenerEndpoint; import org.apache.hc.core5.util.Timeout; import java.net.URI; import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; // ... private static void sendStreamedChatCompletion(List<Message> messages, String apiKey) throws Exception { final CountDownLatch latch = new CountDownLatch(1); try (final CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom() .setDefaultIOReactorConfig(IOReactorConfig.custom().setSoTimeout(Duration.ofSeconds(10)).build()) .build()) { httpclient.start(); final URI uri = new URI("https://api.deepseek.com/v1/chat/completions"); final BasicAsyncRequestProducer requestProducer = BasicAsyncRequestProducer.create( RequestBuilder.post(uri) .addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()) .addHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey), EntityEnclosingRequestCallback.INSTANCE, Json.encode(new ChatRequest(messages)) ); AsyncEntityConsumer<String> consumer = new SimpleResponseConsumer<>(new StringBuilder(), StandardCharsets.UTF_8); Future<Boolean> future = httpclient.execute(requestProducer, consumer, null, Timeout.ofMilliseconds(5000)); while (!future.isDone() && !Thread.currentThread().isInterrupted()) { Thread.sleep(10); // Polling interval can be adjusted as needed. if(consumer.getResult()!=null){ System.out.println(consumer.getResult()); // Process the chunk of data here before it's fully received // For example, you could push each part directly to your frontend via WebSocket or Server-Sent Events (SSE). } } latch.await(); } catch (Exception e) { throw new RuntimeException(e); } } ``` 请注意上述代码片段中的 `consumer.getResult()` 方法会获取每次接收到的数据块,可以根据实际情况调整轮询间隔时间以优化性能表现。对于实时性要求较高的应用场景建议考虑使用 Websocket 或者 SSE 技术向客户端推送更新内容而不是简单地打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值