我应该如何将langchain回调传递给nestjs的sse返回?

问题描述 投票:0回答:1
type Typescript
@Post()
  @Sse('sse')
  async createChat(
    @Res() res,
    @Body() createChatRequestDto: CreateChatRequestDto,
  ) {
    const { chain, sanitizedQuestion, histories } =
      await this.chatService.createChat(createChatRequestDto);

    await chain.call(
      {
        question: sanitizedQuestion,
        chat_history: histories || [],
      },
      [
        {
          handleLLMNewToken(token: string) {
            res.write(token);
          },
        },
      ],
    );
  }

我找到了一种通过langchain中的流式传输得到答案的方法。我不知道如何使用nestjs的服务器端事件将其转发到前端。你能帮忙吗?

nestjs server-sent-events openai-api langchain
1个回答
0
投票

该问题可能与您将数据写入响应的方式有关。在SSE中,数据应该以特定的格式发送。以下是如何修改 createChat 方法以正确使用 SSE 和 LangChain:

@Post()
@Sse('sse')
async createChat(
  @Res() res: Response,
  @Body() createChatRequestDto: CreateChatRequestDto,
) {
  const { chain, sanitizedQuestion, histories } =
    await this.chatService.createChat(createChatRequestDto);

  res.setHeader('Content-Type', 'text/event-stream');
  res.setHeader('Cache-Control', 'no-cache');
  res.setHeader('Connection', 'keep-alive');
  res.flushHeaders();

  await chain.call(
    {
      question: sanitizedQuestion,
      chat_history: histories || [],
    },
    [
      {
        handleLLMNewToken(token: string) {
          res.write(`data: ${token}\n\n`); // write the token as an SSE event
        },
      },
    ],
  );

  res.end();
}

在此代码中,您将为 SSE 设置必要的标头,然后使用 res.write 将数据发送到客户端。每条消息都以 data: 为前缀,并以两个换行符 ( )这是SSE所需的格式

© www.soinside.com 2019 - 2024. All rights reserved.