如何流式传输聊天模型响应
所有 聊天模型 都实现了 Runnable 接口,该接口带有标准 runnable 方法的默认实现(即 ainvoke
、batch
、abatch
、stream
、astream
、astream_events
)。
默认的流式实现提供一个 Iterator
(对于异步流式处理,则为 AsyncIterator
),它产生单个值:来自底层聊天模型提供程序的最终输出。
提示
默认实现不提供逐个 token 流式传输的支持,但它确保模型可以替换为任何其他模型,因为它支持相同的标准接口。
逐个 token 流式传输输出的能力取决于提供程序是否已实现适当的流式传输支持。
在此处查看哪些 集成支持逐个 token 流式传输。
同步流式传输
下面我们使用 |
来帮助可视化 token 之间的分隔符。
from langchain_anthropic.chat_models import ChatAnthropic
chat = ChatAnthropic(model="claude-3-haiku-20240307")
for chunk in chat.stream("Write me a 1 verse song about goldfish on the moon"):
print(chunk.content, end="|", flush=True)
API 参考:ChatAnthropic
Here| is| a| |1| |verse| song| about| gol|dfish| on| the| moon|:|
Floating| up| in| the| star|ry| night|,|
Fins| a|-|gl|im|mer| in| the| pale| moon|light|.|
Gol|dfish| swimming|,| peaceful| an|d free|,|
Se|ren|ely| |drif|ting| across| the| lunar| sea|.|
异步流式传输
from langchain_anthropic.chat_models import ChatAnthropic
chat = ChatAnthropic(model="claude-3-haiku-20240307")
async for chunk in chat.astream("Write me a 1 verse song about goldfish on the moon"):
print(chunk.content, end="|", flush=True)
API 参考:ChatAnthropic
Here| is| a| |1| |verse| song| about| gol|dfish| on| the| moon|:|
Floating| up| above| the| Earth|,|
Gol|dfish| swim| in| alien| m|irth|.|
In| their| bowl| of| lunar| dust|,|
Gl|it|tering| scales| reflect| the| trust|
Of| swimming| free| in| this| new| worl|d,|
Where| their| aqu|atic| dream|'s| unf|ur|le|d.|
Astream 事件
聊天模型还支持标准的 astream events 方法。
如果您正在从包含多个步骤(例如,由提示、llm 和解析器组成的 LLM 链)的较大的 LLM 应用程序流式传输输出,则此方法非常有用。
from langchain_anthropic.chat_models import ChatAnthropic
chat = ChatAnthropic(model="claude-3-haiku-20240307")
idx = 0
async for event in chat.astream_events(
"Write me a 1 verse song about goldfish on the moon", version="v1"
):
idx += 1
if idx >= 5: # Truncate the output
print("...Truncated")
break
print(event)
API 参考:ChatAnthropic
{'event': 'on_chat_model_start', 'run_id': '08da631a-12a0-4f07-baee-fc9a175ad4ba', 'name': 'ChatAnthropic', 'tags': [], 'metadata': {}, 'data': {'input': 'Write me a 1 verse song about goldfish on the moon'}}
{'event': 'on_chat_model_stream', 'run_id': '08da631a-12a0-4f07-baee-fc9a175ad4ba', 'tags': [], 'metadata': {}, 'name': 'ChatAnthropic', 'data': {'chunk': AIMessageChunk(content='Here', id='run-08da631a-12a0-4f07-baee-fc9a175ad4ba')}}
{'event': 'on_chat_model_stream', 'run_id': '08da631a-12a0-4f07-baee-fc9a175ad4ba', 'tags': [], 'metadata': {}, 'name': 'ChatAnthropic', 'data': {'chunk': AIMessageChunk(content="'s", id='run-08da631a-12a0-4f07-baee-fc9a175ad4ba')}}
{'event': 'on_chat_model_stream', 'run_id': '08da631a-12a0-4f07-baee-fc9a175ad4ba', 'tags': [], 'metadata': {}, 'name': 'ChatAnthropic', 'data': {'chunk': AIMessageChunk(content=' a', id='run-08da631a-12a0-4f07-baee-fc9a175ad4ba')}}
...Truncated