当API像SSE(服务器发送事件)一样流时,如何在Axios中获得响应

2skhul33  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(393)

工作环境:网络浏览器,JavaScript。
我想使用post方法调用sse API(服务器发送事件),如
https://platform.openai.com/docs/api-reference/completions/create

curl https://api.openai.com/v1/completions \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $OPENAI_API_KEY" \
      -d '{
        "model": "gpt-3.5-turbo",
        "prompt": "Say this is a test",
        "max_tokens": 7,
        "steam": true,
        "temperature": 0
      }'

我在网上做了一些研究,发现我不能使用EventSource,因为它不支持发送帖子数据。
所以我写了这样的代码在浏览器中尝试阅读蒸汽中的文本。
我不知道这样好不好

const response = await axios({
                    method: 'post',
                    url: '/my-service/chat',
                    data: data,
                    headers: {
                        'SESSION_ID': 'Header-Value',
                        "Content-Type": "application/json",
                        "Accept": "text/event-stream",
                    }
                    , responseType: 'steam',
                });
//TODO: read steam and convert to text

我很感激你能提供的任何帮助。在此先谢谢您!

k5ifujac

k5ifujac1#

我的解决方案选择了fetch-event-source框架。
https://github.com/Azure/fetch-event-source
以下是一些其他的选择:
JavaScript+axios:

axios({
  url: 'https://api',
  data: {
    prompt: 'json data'
  },
  headers: {
    'accept': '*',
    'content-type': 'application/json'
  },
  method: 'POST',
  onDownloadProgress: progressEvent => {
     const xhr = progressEvent.event.target
     const { responseText } = xhr
     console.log("=====responseText======")
     console.log(responseText)
  }
}).then(({ data }) => Promise.resolve(data));

服务器+Java代码:
spring-server-sent-events:https://www.baeldung.com/spring-server-sent-events

public void consumeServerSentEvent() {
        WebClient client = WebClient.create("http://localhost:8080/sse-server");
        ParameterizedTypeReference<ServerSentEvent<String>> type
         = new ParameterizedTypeReference<ServerSentEvent<String>>() {};
    
        Flux<ServerSentEvent<String>> eventStream = client.get()
          .uri("/stream-sse")
          .retrieve()
          .bodyToFlux(type);
    
        eventStream.subscribe(
          content -> logger.info("Time: {} - event: name[{}], id [{}], content[{}] ",
            LocalTime.now(), content.event(), content.id(), content.data()),
          error -> logger.error("Error receiving SSE: {}", error),
          () -> logger.info("Completed!!!"));
    }

相关问题