使用模式#
快速开始#
从索引构建聊天引擎:
chat_engine = index.as_chat_engine()
提示
要了解如何构建索引,请参阅索引
与您的数据进行对话:
response = chat_engine.chat("Tell me a joke.")
重置聊天记录以开始新的对话:
chat_engine.reset()
进入交互式聊天REPL环境:
chat_engine.chat_repl()
配置聊天引擎#
配置聊天引擎与配置查询引擎非常相似。
高级API#
你可以直接用一行代码从索引中构建并配置一个聊天引擎:
chat_engine = index.as_chat_engine(chat_mode="condense_question", verbose=True)
注意:您可以通过将
chat_mode
指定为关键字参数来访问不同的聊天引擎。condense_question
对应CondenseQuestionChatEngine
,react
对应ReActChatEngine
,context
对应ContextChatEngine
。注意:虽然高级API优化了易用性,但它并未暴露全部的可配置选项。
可用的聊天模式#
best
- 将查询引擎转换为一个工具,用于与ReAct
数据智能体或OpenAI
数据智能体配合使用,具体取决于您的LLM支持哪种方式。OpenAI
数据智能体需要gpt-3.5-turbo
或gpt-4
,因为它们使用了OpenAI的函数调用API。condense_question
- 查看聊天历史记录并重写用户消息,使其成为索引的查询。在读取查询引擎的响应后返回响应。context
- 通过每条用户消息从索引中检索节点。检索到的文本会被插入到系统提示中,这样聊天引擎既可以自然响应,也可以利用来自查询引擎的上下文信息。condense_plus_context
- 结合了condense_question
和context
的功能。查看聊天历史记录并重写用户消息,使其成为索引的检索查询。检索到的文本会被插入到系统提示中,这样聊天引擎既可以自然响应,也可以使用来自查询引擎的上下文信息。simple
- 直接与LLM进行简单聊天,不涉及查询引擎。react
- 与best
相同,但强制使用ReAct
数据智能体。openai
- 与best
相同,但强制使用OpenAI
数据智能体。
底层组合API#
如果需要更细粒度的控制,可以使用底层组合API。
具体来说,您需要显式构造ChatEngine
对象,而不是调用index.as_chat_engine(...)
。
注意:您可能需要查阅API参考或示例笔记本。
以下是一个配置示例:
- 配置问题浓缩提示,
- 使用一些现有的历史记录初始化对话,
- 打印详细的调试信息。
from llama_index.core import PromptTemplate
from llama_index.core.llms import ChatMessage, MessageRole
from llama_index.core.chat_engine import CondenseQuestionChatEngine
custom_prompt = PromptTemplate(
"""\
Given a conversation (between Human and Assistant) and a follow up message from Human, \
rewrite the message to be a standalone question that captures all relevant context \
from the conversation.
<Chat History>
{chat_history}
<Follow Up Message>
{question}
<Standalone question>
"""
)
# list of `ChatMessage` objects
custom_chat_history = [
ChatMessage(
role=MessageRole.USER,
content="Hello assistant, we are having a insightful discussion about Paul Graham today.",
),
ChatMessage(role=MessageRole.ASSISTANT, content="Okay, sounds good."),
]
query_engine = index.as_query_engine()
chat_engine = CondenseQuestionChatEngine.from_defaults(
query_engine=query_engine,
condense_question_prompt=custom_prompt,
chat_history=custom_chat_history,
verbose=True,
)
流式处理#
要启用流式传输,您只需调用stream_chat
端点而非chat
端点。
警告
这与查询引擎有些不一致(在查询引擎中您需要传入streaming=True
标志)。我们正在努力使行为更加一致!
chat_engine = index.as_chat_engine()
streaming_response = chat_engine.stream_chat("Tell me a joke.")
for token in streaming_response.response_gen:
print(token, end="")
查看一个端到端教程