Feature: Chat & Conversation
Relevant source files
The following files were used as context for generating this wiki page:
- src/store/chat/slices/message/action.ts
- src/store/chat/slices/topic/action.ts
- packages/database/src/repositories/dataImporter/deprecated/tests/index.test.ts
- src/tools/artifacts/systemRole.ts
- src/services/chat/index.ts
- packages/const/src/guide.ts
- src/features/ShareModal/ShareText/template.test.ts
- AGENTS.md
- src/locales/default/discover.ts
The Chat & Conversation feature is the core interactive component of LobeChat. It facilitates communication between the user and various AI models, managing the entire lifecycle of a conversation from message creation to storage and display. This system is built upon a structured data model of sessions, topics, and messages, managed by a sophisticated state management layer using Zustand.
The architecture is designed to be robust and extensible, supporting features like automatic topic generation, message regeneration, tool calls (plugins), and the creation of content artifacts. Data flows from the UI, through a series of state management actions, to backend services for processing by AI models, and back to the UI for rendering. This documentation provides a deep dive into the data model, state management, key workflows, and advanced features of the conversation system.
Core Data Model
The conversation data is organized hierarchically into Sessions, Topics, and Messages. This structure allows for organized and context-aware conversations.
This ER diagram illustrates the relationships between Sessions, Topics, and Messages. A Session can contain multiple Topics, and each Topic can contain multiple Messages. Messages can also be directly associated with a Session (e.g., in the "inbox"). Messages can be linked to a parent message, forming a threaded conversation.
- Sessions: Represent a single chat context, typically associated with a specific AI Agent. It holds the configuration (
config) and metadata (meta) for the agent. - Topics: Act as sub-conversations within a session. This allows for organizing different threads of discussion. Topics can be favorited and are automatically or manually titled.
- Messages: The individual units of a conversation, which can be from a
user,assistant,tool, orsystem. They are linked to both a session and an optional topic.
Sources: packages/database/src/repositories/dataImporter/deprecated/tests/index.test.ts
State Management with Zustand
The chat state is managed using Zustand, with actions and state slices for messages and topics.
Message Actions (ChatMessageAction)
The ChatMessageAction interface defines all operations related to messages within a conversation. These actions handle everything from sending a message to deleting and regenerating it.
| Action | Description |
|---|---|
sendMessage | Sends a new message from the user and triggers the AI response flow. |
regenerateMessage | Resends a previous message context to get a new AI response. |
deleteMessage | Deletes a message and any associated tool call messages. |
delAndRegenerateMessage | Deletes a message and immediately triggers a regeneration. |
clearMessage | Clears all messages and topics from the active session. |
modifyMessageContent | Updates the content of an existing message. |
stopGenerateMessage | Aborts an in-progress AI message generation. |
copyMessage | Copies a message's content to the clipboard. |
Sources: src/store/chat/slices/message/action.ts:64-92
Topic Actions (ChatTopicAction)
The ChatTopicAction interface manages conversation topics, including their creation, deletion, and modification.
| Action | Description |
|---|---|
createTopic | Creates a new topic with the current active messages. |
saveToTopic | Saves the current set of messages into a new topic. |
duplicateTopic | Creates a copy of an existing topic with its messages. |
summaryTopicTitle | Automatically generates a title for a topic based on its messages. |
updateTopicTitle | Manually updates the title of a topic. |
removeTopic | Deletes a specific topic and its associated messages. |
switchTopic | Switches the active conversation to a different topic within the same session. |
favoriteTopic | Marks or unmarks a topic as a favorite. |
Sources: src/store/chat/slices/topic/action.ts:31-50
Key Workflows
Sending a Message
The sendMessage action orchestrates the entire process of sending a user message and receiving an AI response. This is a central workflow in the application.
The following sequence diagram shows the detailed flow of sending a message.
Automatic Topic Creation and Naming
LobeChat can automatically organize conversations by creating and naming topics.
This flowchart illustrates the logic for automatic topic management when a new message is sent.
- When
sendMessageis called, it checks ifenableAutoCreateTopicis active in the agent's configuration. - If there's no active topic and the number of messages in the current session exceeds
autoCreateTopicThreshold, a new topic is created. - The
summaryTopicTitleaction is then triggered. It useschatService.fetchPresetTaskResultwith a prompt generated bychainSummaryTitleto ask an AI model to generate a concise title for the new topic. - The topic's title is updated in the state and persisted to the database.
Sources: src/store/chat/slices/message/action.ts:300-320, src/store/chat/slices/topic/action.ts:133-162
Advanced Features
Artifacts in Conversation
The assistant can generate self-contained content blocks called "artifacts" during a conversation. These are used for substantial content like code, documents, or diagrams that a user might want to modify or reuse.
The generation is guided by a system prompt that defines when and how to create artifacts using a special <lobeArtifact> XML tag.
// Example from system prompt
<lobeArtifact identifier="factorial-script" type="application/lobe.artifacts.code" language="python" title="Simple Python factorial script">
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
</lobeArtifact>
Sources: src/tools/artifacts/systemRole.ts:100-107
The system prompt specifies several artifact types:
| Type | MIME Type | Description |
|---|---|---|
| Code | application/lobe.artifacts.code | For code snippets in any language. |
| Documents | text/markdown | For plain text or Markdown documents. |
| HTML | text/html | For single-file HTML pages that can be rendered in the UI. |
| SVG | image/svg+xml | For Scalable Vector Graphics images. |
| Mermaid Diagrams | application/lobe.artifacts.mermaid | For Mermaid syntax diagrams that will be rendered. |
| React Components | application/lobe.artifacts.react | For renderable React components, with access to libraries like recharts and lucide-react. |
Sources: src/tools/artifacts/systemRole.ts:37-90
Data Import
LobeChat supports importing chat data from a JSON file. The DataImporter repository handles the logic of parsing the file and inserting the data into the database while maintaining relationships.
The importer can process the following entities:
sessionGroupssessionsagents(created from session configs)topicsmessages
During import, it correctly maps relationships, such as associating messages with their respective sessions and topics, and linking sessions to agents. It also handles skipping existing entries to prevent duplicates.
Share as Markdown
Users can share conversations as formatted Markdown text. The generateMarkdown function is responsible for this.
It filters out loading messages and can optionally include:
- A system role definition.
- Role labels (
User:,Assistant:). - Tool call results.
This provides a flexible way to export and share conversations for documentation or collaboration.
Sources: src/features/ShareModal/ShareText/template.test.ts:18-31