使用JavaScript中的LangChain流式传输响应

我正在使用LangChain库编写一个小型JavaScript应用程序。我有以下代码片段:

/* LangChain Imports */import { OpenAI } from "langchain/llms/openai";import { BufferMemory } from "langchain/memory";import { ConversationChain } from "langchain/chains";// ========================================================================================= //  // ============= Use LangChain to send request to OpenAi API =============================== //  // ========================================================================================= //  const openAILLMOptions = {    modelName: chatModel.value,    openAIApiKey: decryptedString,    temperature: parseFloat(temperatureValue.value),    topP: parseFloat(topP.value),    maxTokens: parseInt(maxTokens.value),    stop: stopSequences.value.length > 0 ? stopSequences.value : null,    streaming: true,};  const model = new OpenAI(openAILLMOptions);  const memory = new BufferMemory();  const chain = new ConversationChain({ llm: model, memory: memory });  try {    const response = await chain.call({ input: content.value, signal: signal }, undefined,      [        {          handleLLMNewToken(token) {            process.stdout.write(token);          },        },      ]    );// handle the response}

这不起作用(我尝试过使用TypeScript和不使用类型来处理token)。我查阅了各种论坛,它们要么是用Python实现流式传输,要么它们的解决方案与这个问题无关。总之,我可以通过LangChain的ConversationChain() API调用成功获取OpenAI的响应,但无法流式传输响应。有解决方案吗?


回答:

供参考,以下是我如何实现流式传输的:

const openAILLMOptions = {    modelName: chatModel.value,    cache: true,    openAIApiKey: openAIDecryptedString,    temperature: parseFloat(temperatureValue.value),    topP: parseFloat(topP.value),    maxTokens: parseInt(maxTokens.value),    stop: stopSequences.value.length > 0 ? stopSequences.value : null,    streaming: true,    verbose: true,  };const chat = new ChatOpenAI(openAILLMOptions);      const chatPrompt = ChatPromptTemplate.fromMessages([        [          "system",          systemPrompt.value,        ],        new MessagesPlaceholder("history"),        ["human", content.value],      ]);      const chain = new ConversationChain({        memory: new BufferMemory({ returnMessages: true, memoryKey: "history" }),        prompt: chatPrompt,        llm: chat,      });      await chain.call({        input: content.value,        signal: signal,        callbacks: [          {            handleLLMNewToken(token) {              aiResponse.value += token;            }          }        ]      });

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注