主题
LlamaIndex 支持在回答生成的同时进行流式输出。这样你可以在完整回答结束之前就开始打印或处理回答的开头部分,从而显著降低查询的感知延迟。
准备
要启用流式,你需要使用支持流式的 LLM。目前 OpenAI、HuggingFaceLLM 以及大多数 LangChain LLM(经由 LangChainLLM)都支持流式。
注:如果你选的 LLM 不支持流式,会抛出
NotImplementedError。
要用高层 API 让查询引擎启用流式,只需在构建查询引擎时设置 streaming=True。
query_engine = index.as_query_engine(streaming=True, similarity_top_k=1)1
如果你用低层 API 组装查询引擎,则在构造 Response Synthesizer 时传入 streaming=True:
from llama_index.core import get_response_synthesizer
synth = get_response_synthesizer(streaming=True, ...)
query_engine = RetrieverQueryEngine(response_synthesizer=synth, ...)1
2
3
4
2
3
4
流式响应
把 LLM 和查询引擎都正确配置好之后,调用 query 就会返回一个 StreamingResponse 对象。
streaming_response = query_engine.query(
"What did the author do growing up?",
)1
2
3
2
3
在 LLM 调用开始时响应就会立即返回,而不必等待完整生成结束。
注:如果查询引擎会发起多次 LLM 调用,那么只有最后一次 LLM 调用会被流式返回,且响应是在最后一次调用开始时返回的。
你可以从流式响应里拿到一个 Generator,并随着 token 到达逐个遍历:
for text in streaming_response.response_gen:
# do something with text as they arrive.
pass1
2
3
2
3
或者,如果你只想边到达边打印文本:
streaming_response.print_response_stream()1
可参见一个端到端示例