如何从LLM流式传输响应
所有 LLM 都实现了 Runnable接口,它提供了标准Runnable方法的默认实现(例如 ainvoke、batch、abatch、stream、astream、astream_events)。
这些默认流式传输实现提供了一个 AsyncGenerator,它只产生一个值:来自底层聊天模型提供者的最终输出。
逐token流式传输的能力取决于提供者是否实现了正确的流式传输支持。
查看哪些集成支持逐token流式传输。
:::{.callout-note}
默认实现不提供逐token流式传输支持,但它确保了模型可以替换为任何其他模型,因为它支持相同的标准化接口。
:::
使用 .stream()
流式传输的最简单方法是使用 .stream() 方法。这将返回一个可读取的流,你可以对其进行迭代:
:::提示 请参阅安装集成包的一般说明部分。 :::
- npm
- Yarn
- pnpm
npm install @langchain/openai @langchain/core
yarn add @langchain/openai @langchain/core
pnpm add @langchain/openai @langchain/core
import { OpenAI } from "@langchain/openai";
const model = new OpenAI({
maxTokens: 25,
});
const stream = await model.stream("Tell me a joke.");
for await (const chunk of stream) {
console.log(chunk);
}
/*
Q
:
What
did
the
fish
say
when
it
hit
the
wall
?
A
:
Dam
!
*/
API Reference:
- OpenAI from
@langchain/openai
对于不支持流式传输的模型,整个响应将作为单个数据块返回。
使用回调处理器
你还可以像这样使用 CallbackHandler:
import { OpenAI } from "@langchain/openai";
// To enable streaming, we pass in `streaming: true` to the LLM constructor.
// Additionally, we pass in a handler for the `handleLLMNewToken` event.
const model = new OpenAI({
maxTokens: 25,
streaming: true,
});
const response = await model.invoke("Tell me a joke.", {
callbacks: [
{
handleLLMNewToken(token: string) {
console.log({ token });
},
},
],
});
console.log(response);
/*
{ token: '\n' }
{ token: '\n' }
{ token: 'Q' }
{ token: ':' }
{ token: ' Why' }
{ token: ' did' }
{ token: ' the' }
{ token: ' chicken' }
{ token: ' cross' }
{ token: ' the' }
{ token: ' playground' }
{ token: '?' }
{ token: '\n' }
{ token: 'A' }
{ token: ':' }
{ token: ' To' }
{ token: ' get' }
{ token: ' to' }
{ token: ' the' }
{ token: ' other' }
{ token: ' slide' }
{ token: '.' }
Q: Why did the chicken cross the playground?
A: To get to the other slide.
*/
API Reference:
- OpenAI from
@langchain/openai
即使使用 generate,我们仍然可以访问最终的 LLMResult。然而,在流式传输时,可能并非所有模型提供者都支持 tokenUsage。