聊天与会话系统
聊天与对话系统
相关源文件
本章引用的主要源码文件:
backend/onyx/chat/chat_state.pybackend/onyx/chat/chat_utils.pybackend/onyx/chat/llm_loop.pybackend/onyx/chat/llm_step.pybackend/onyx/chat/models.pybackend/onyx/chat/process_message.pybackend/onyx/chat/prompt_utils.pybackend/onyx/context/search/models.pybackend/onyx/context/search/pipeline.pybackend/onyx/db/chat.pybackend/onyx/deep_research/dr_loop.pybackend/onyx/prompts/chat_prompts.pybackend/onyx/prompts/deep_research/__init__.pybackend/onyx/prompts/deep_research/dr_tool_prompts.pybackend/onyx/prompts/deep_research/orchestration_layer.pybackend/onyx/prompts/deep_research/research_agent.pybackend/onyx/prompts/prompt_utils.pybackend/onyx/prompts/tool_prompts.pybackend/onyx/server/query_and_chat/chat_backend.pybackend/onyx/server/query_and_chat/models.pybackend/onyx/tools/fake_tools/research_agent.pybackend/onyx/tools/models.pybackend/onyx/tools/tool_implementations/search/search_tool.pybackend/onyx/tools/tool_runner.pybackend/tests/unit/onyx/chat/test_llm_loop.pybackend/tests/unit/onyx/chat/test_llm_step.pyweb/src/app/app/interfaces.tsweb/src/app/app/message/HumanMessage.tsxweb/src/app/app/message/MultiModelPanel.tsxweb/src/app/app/message/MultiModelResponseView.tsxweb/src/app/app/message/codeUtils.test.tsweb/src/app/app/message/codeUtils.tsweb/src/app/app/message/custom-code-styles.cssweb/src/app/app/message/interfaces.tsweb/src/app/app/message/messageComponents/AgentMessage.tsxweb/src/app/app/message/messageComponents/markdownUtils.tsxweb/src/app/app/message/messageComponents/renderers/MessageTextRenderer.tsxweb/src/app/app/services/lib.tsxweb/src/app/app/stores/useChatSessionStore.tsweb/src/app/css/colors.cssweb/src/components/chat/DynamicBottomSpacer.tsxweb/src/components/chat/ScrollContainerContext.tsxweb/src/hooks/useChatController.tsweb/src/hooks/useSmoothStreaming.tsweb/src/hooks/useTypewriter.tsweb/src/sections/chat/ChatScrollContainer.tsxweb/src/sections/chat/ChatUI.tsxweb/src/sections/input/QueuedMessageBar.tsx
目的与范围
本文档描述了 Onyx 中的聊天与对话系统,该系统负责处理用户与助手交互的完整生命周期。内容涵盖消息处理、大语言模型(LLM)编排、工具执行、流式响应以及持久化存储。系统支持标准聊天、深度研究模式以及多轮工具调用工作流。
有关具体组件的详细信息,请参阅以下子页面:
- 聊天架构与数据模型 — 数据库模型、消息分支与树结构。
- 消息处理流程 —
handle_stream_message_objects管线与大语言模型(LLM)循环编排。 - 聊天前端界面 — Next.js UI 组件与流式数据包处理。
- 检索与引用 — 搜索工具集成与引用追踪。
- 深度研究模式 — 多智能体研究循环与自动化报告合成。
核心数据模型
ChatSession 与 ChatMessage
聊天系统使用两个主要数据库模型来表示对话:
| 模型 | 用途 | 关键字段 |
|---|---|---|
ChatSession | 对话线程的容器 | id、user_id、persona_id、description、project_id、current_alternate_model |
ChatMessage | 会话中的单条消息 | id、chat_session_id、parent_message_id、latest_child_id、message、message_type、token_count、files |
ToolCall | 消息中的工具调用 | id、chat_message_id、tool_name、tool_arguments、tool_result |
ChatMessage 模型使用树结构,每条消息都有 parent_message_id 和 latest_child_id,支持消息重新生成和分支。根消息(parent_message_id = None)作为锚点。
消息类型(来自 MessageType 枚举):
USER— 用户输入消息ASSISTANT— AI 生成的响应SYSTEM— 系统提示(在 UI 中不可见)USER_REMINDER— 注入的提醒(例如引用说明)TOOL_CALL_RESPONSE— 工具执行结果
来源:backend/onyx/db/models.py、backend/onyx/configs/constants.py:61-63、backend/onyx/db/chat.py:50-91
流式数据模型
为在消息生成期间实现实时通信,系统使用标准的 Packet 包装器:
# backend/onyx/server/query_and_chat/streaming_models.py 中的核心流式类型
Packet # 包含 placement 和 payload 对象的容器
AgentResponseStart # 表示答案流式传输开始
AgentResponseDelta # 单个 Token 片段
ReasoningStart/Delta # 推理 Token(用于 o1/R1 风格模型)
ToolCallKickoff # 工具调用元数据
CitationInfo # 引用元数据(编号、文档 ID、链接)
OverallStop # 生成结束信号
Packet 模型使用 Placement 元数据(turn_index、tab_index、sub_turn_index)包装所有流式对象,以跟踪在多轮工具调用流程或并行模型比较中的位置。
来源:backend/onyx/server/query_and_chat/streaming_models.py:39-125、backend/onyx/chat/models.py:40-52、backend/onyx/server/query_and_chat/placement.py:7-22
消息处理架构
高层流程
下图将用户请求的"自然语言空间"桥接到后端处理的"代码实体空间"。
聊天编排图
来源:backend/onyx/server/query_and_chat/chat_backend.py:110-150、backend/onyx/chat/process_message.py:426-920、backend/onyx/chat/llm_loop.py:564-900
请求入口点:handle_send_chat_message()
FastAPI 端点 POST /chat/send-chat-message 接收 SendMessageRequest。该模型是 Onyx 应用的核心契约。
# 定义在 backend/onyx/server/query_and_chat/models.py:115-150
class SendMessageRequest(BaseModel):
message: str # 用户消息文本
chat_session_id: UUID | None # 现有会话或 None
parent_message_id: int | None # 用于分支/重新生成
llm_override: LLMOverride | None # 单个模型覆盖
llm_overrides: list[LLMOverride] # 多模型并行模式
file_descriptors: list[FileDescriptor] # 附加文件
deep_research: bool # 启用深度研究模式
stream: bool = True # SSE 流式传输 vs 完整响应
端点验证请求,通过 check_token_rate_limits 检查速率限制,并在调用流式管线之前验证大语言模型(LLM)成本限制。
来源:backend/onyx/server/query_and_chat/chat_backend.py:538-650、backend/onyx/server/query_and_chat/models.py:115-150
大语言模型(LLM)循环与多轮执行
标准聊天循环:run_llm_loop()
run_llm_loop 函数管理调用大语言模型(LLM)、执行工具以及将结果反馈回上下文的迭代过程。
多轮执行图
关键编排细节:
- 历史截断:
construct_message_history计算可用 Token 并使用compress_chat_history截断对话,确保保留system_prompt和最近的消息。backend/onyx/chat/llm_loop.py:250-498、backend/onyx/chat/compression.py:33-40 - 工具选择:循环根据当前周期和用户设置确定
tool_choice(AUTO、REQUIRED 或 NONE)。backend/onyx/chat/llm_loop.py:564-900 - 回退提取:如果大语言模型(LLM)未能使用原生工具调用 API,但在文本中输出了 XML/JSON 工具调用,
_try_fallback_tool_extraction会使用extract_tool_calls_from_response_text解析它们以维持功能。backend/onyx/chat/llm_loop.py:149-171、backend/onyx/chat/llm_step.py:66-75
来源:backend/onyx/chat/llm_loop.py:564-900、backend/onyx/chat/llm_step.py:153-180
深度研究模式
深度研究模式(run_deep_research_llm_loop)实现了一个高层编排器,将复杂查询分解为研究计划。
深度研究编排
- 澄清阶段:大语言模型(LLM)可以使用
clarification_tool在开始前向用户询问缺失的细节。backend/onyx/deep_research/dr_loop.py:238-299 - 编排器智能体:使用
ORCHESTRATOR_PROMPT管理多个并行的research_agent调用。backend/onyx/deep_research/dr_loop.py:389-600 - 研究智能体:一个专门的子智能体,使用
SearchTool、WebSearchTool和OpenURLTool执行自己的多轮循环,通过generate_intermediate_report合成中间报告。backend/onyx/tools/fake_tools/research_agent.py:87-143、backend/onyx/tools/fake_tools/research_agent.py:205-500 - 最终合成:
generate_final_report将所有中间发现合并为一份带有引用的长文文档。backend/onyx/deep_research/dr_loop.py:100-184
有关详细信息,请参阅深度研究模式。
检索与上下文管理
聊天系统通过两条路径将检索直接集成到大语言模型(LLM)上下文中:
- 上下文内加载:如果附加文件适合大语言模型(LLM)的上下文窗口,它们会通过
build_file_context直接注入到提示中。backend/onyx/chat/chat_utils.py:67-111 - 工具中介检索:对于较大的文件或一般查询,使用
SearchTool。它执行语义搜索,合并相邻片段,并向大语言模型(LLM)提供相关摘要。backend/onyx/tools/tool_implementations/search/search_tool.py:37-57
引用追踪:在大语言模型(LLM)生成文本时,DynamicCitationProcessor 监控引用标记并将其与工具检索到的 SearchDoc 实体关联,向前端发送 CitationInfo 数据包。backend/onyx/chat/citation_processor.py
有关详细信息,请参阅检索与引用。
聊天会话管理
聊天会话持久化在 PostgreSQL 中,支持以下功能:
- 消息分支:用户可以编辑旧消息,通过
create_chat_history_chain在对话树中创建新分支。backend/onyx/chat/chat_utils.py:162-211 - 重新生成:从历史记录中的任意点重新运行助手响应。
- 自动命名:
generate_chat_session_name工具使用一个小型大语言模型(LLM)调用,根据前几条消息创建简洁的标题。backend/onyx/secondary_llm_flows/chat_session_naming.py:74 - 共享:会话可以通过
ChatSessionSharedStatus设置为PUBLIC或PRIVATE。backend/onyx/db/models.py:30
来源:backend/onyx/server/query_and_chat/chat_backend.py:152-510、backend/onyx/db/chat.py:50-91