Skip to content

使用模式#

快速开始#

从索引构建聊天引擎:

chat_engine = index.as_chat_engine()

Tip

要了解如何构建索引,请参阅索引指南

与您的数据进行对话:

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对应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#

如果需要更细粒度的控制,可以使用低级组合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端点。

Warning

这与查询引擎有些不一致(在查询引擎中您传入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="")

查看端到端教程