Skip to content

ChatGPT流式输出如何终止 #296

Description

@q2316367743

在使用ChatGPT流式输出时:

openAiClient.streamChatCompletion(chatCompletion, new EventSourceListener() {});

此处没有返回值,该如何终止这个流式输出

看了下源码:

public <T extends BaseChatCompletion> void streamChatCompletion(T chatCompletion, EventSourceListener eventSourceListener) {
      if (Objects.isNull(eventSourceListener)) {
          log.error("参数异常:EventSourceListener不能为空,可以参考:com.unfbx.chatgpt.sse.ConsoleEventSourceListener");
          throw new BaseException(CommonError.PARAM_ERROR);
      }
      if (!chatCompletion.isStream()) {
          chatCompletion.setStream(true);
      }
      try {
          EventSource.Factory factory = EventSources.createFactory(this.okHttpClient);
          ObjectMapper mapper = new ObjectMapper();
          String requestBody = mapper.writeValueAsString(chatCompletion);
          Request request = new Request.Builder()
                  .url(this.apiHost + "v1/chat/completions")
                  .post(RequestBody.create(MediaType.parse(ContentType.JSON.getValue()), requestBody))
                  .build();
          //创建事件
          EventSource eventSource = factory.newEventSource(request, eventSourceListener);
      } catch (JsonProcessingException e) {
          log.error("请求参数解析异常:{}", e);
          e.printStackTrace();
      } catch (Exception e) {
          log.error("请求参数解析异常:{}", e);
          e.printStackTrace();
      }
  }

最后的EventSource是存在cancel()方法的,但是没返回

public interface EventSource {
    Request request();

    void cancel();

    public interface Factory {
        EventSource newEventSource(Request var1, EventSourceListener var2);
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions