跳转到内容

使用模式

从索引构建聊天引擎:

chat_engine = index.as_chat_engine()

与您的数据进行对话:

response = chat_engine.chat("Tell me a joke.")

重置聊天记录以开始新的对话:

chat_engine.reset()

进入交互式聊天 REPL:

chat_engine.chat_repl()

配置聊天引擎与配置查询引擎非常相似。

你可以用一行代码直接从索引中构建并配置聊天引擎:

chat_engine = index.as_chat_engine(chat_mode="condense_question", verbose=True)

注意:您可以通过将 chat_mode 指定为关键字参数来访问不同的聊天引擎。condense_question 对应 CondenseQuestionChatEnginereact 对应 ReActChatEnginecontext 对应 ContextChatEngine

注意:虽然高级API优化了易用性,但它并未暴露完整的可配置范围。

  • best - 将查询引擎转换为工具,供 ReAct 数据智能体或 OpenAI 数据智能体使用,具体取决于您的LLM支持哪种类型。OpenAI 数据智能体需要 gpt-3.5-turbogpt-4,因为它们使用OpenAI的函数调用API。
  • condense_question - 查看聊天历史记录并重写用户消息,使其成为索引查询。在读取查询引擎的响应后返回响应。
  • context - 使用每条用户消息从索引中检索节点。检索到的文本会被插入到系统提示中,这样聊天引擎既可以自然回复,也可以利用来自查询引擎的上下文信息。
  • condense_plus_context - condense_questioncontext 的组合。查看聊天历史记录并将用户消息重写为索引的检索查询。检索到的文本被插入到系统提示中,以便聊天引擎可以自然地响应或使用来自查询引擎的上下文。
  • simple - 与LLM直接进行的简单对话,不涉及查询引擎。
  • react - 与 best 相同,但强制使用 ReAct 数据智能体。
  • openai - 与 best 相同,但强制使用 OpenAI 数据智能体。

如果您需要更细粒度的控制,可以使用底层组合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="")

查看端到端教程