Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Bug Report — workers cannot streamed response to web client #2032

Closed
Whyjsee opened this issue Apr 17, 2024 · 0 comments
Closed

🐛 Bug Report — workers cannot streamed response to web client #2032

Whyjsee opened this issue Apr 17, 2024 · 0 comments

Comments

@Whyjsee
Copy link

Whyjsee commented Apr 17, 2024

i make a openai streaming service in fetch in workers, but the response in web client will always be not-streaming response , it will always return response after openai’s request totally finished. how can i make it return in stream ?

here’s my test code in workers:

export default {
  async fetch(request: Request, env: any, ctx: ExecutionContext) {
    const openai = new OpenAI({
      apiKey: env.OPENAI_API_KEY,
      baseURL: env.OPENAI_API,
    });

    const stream = await openai.chat.completions.create({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: (await request.json()) || '' }],
      stream: true,
    });

    return new Response(stream.toReadableStream());
  },
};

and here’s my web client code:

export const fetchTest = async () => {
  const streamApiUrl = '/xxx/query'
  const response = await fetch(streamApiUrl, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      content: 'who are you'
    })
  })

  const bodyReader = response.body.getReader()
  while (true) {
    const { value, done } = await bodyReader.read()    // it won't return like stream , it will return all data once and for all after request finished
    if (done) break
    console.log(value)
  }
}

fetchTest()

here's my chrome devtools screenshot:
WeChatWorkScreenshot_7c85cbc7-ec2a-4d5c-aea8-a9a0bd4f1b22

WeChatWorkScreenshot_35b3ea21-6941-4774-8aa6-c34b19bf91bd
@Whyjsee Whyjsee closed this as completed Apr 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant