Langchain 流式传输无法与 Next.JS 13+(Next.JS App Router)一起使用

问题描述 投票:0回答:1

我正在尝试在我的 NextJS 13(应用程序路由器)应用程序中实现 Langchain(会话检索 QA 流),但无法将数据流式传输到 FE,我正在尝试使用这个

NextResponse(stream);
我想做这样的事情

    res.writeHead(200, {
      'Content-Type': 'text/event-stream',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Transfer-Encoding': 'chunked',
    });
    completion.data.on('data', (data) => {
      res.write('event: message\n');
      res.write('data: ' + JSON.stringify(contentValue) + '\n\n');
    });
    completion.data.on('end', () => {
      res.write('event: close\n');
      res.write('data: close\n\n');
      res.end(); // End the response stream
    });

这是我的另一个 open.ai 项目中的 NodeJS 示例。

next.js streaming langchain
1个回答
2
投票

试试这个:

api/example/route.ts

const stream = await chain.stream({
  chatHistory: userChatHistory,
  question: userQuestion,
});

return new NextResponse(stream, {
  headers: {
    'Content-Type': 'text/event-stream',
    'Connection': 'keep-alive',
    'Cache-Control': 'no-cache, no-transform',
  },
});

客户

const res = await fetch('/api/example', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: yourPayload,
});


if (!res.ok) throw new Error(res.statusText);
    const data = res.body;
    if (!data) return;

    const reader = data.getReader();
    const decoder = new TextDecoder();
    let done = false;
    let accumulatedContent = '';
    while (!done) {
      
      const { value, done: doneReading } = await reader.read();
      done = doneReading;
      const chunkValue = decoder.decode(value);
      accumulatedContent += chunkValue;
      console.log(accumulatedContent);
    }

    if (done) {
      console.log(accumulatedContent);
    }
© www.soinside.com 2019 - 2024. All rights reserved.