feat: implement chat history and retrieval settings

- Added new API endpoints for managing chat history configuration and retrieval settings, allowing tenants to enable message indexing and configure search parameters.
- Introduced new Vue components for ChatHistorySettings and RetrievalSettings, providing a user-friendly interface for managing these configurations.
- Updated localization files to include new settings descriptions and labels in multiple languages.
- Enhanced the KnowledgeSearch view to support searching across both knowledge bases and chat history, improving the overall search functionality.

These changes significantly enhance the application's capabilities in managing and retrieving chat history, contributing to a more robust user experience.
This commit is contained in:
wizardchen
2026-03-06 21:06:10 +08:00
committed by lyingbug
parent c516d1f9bd
commit 1fb2bedd2b
27 changed files with 2755 additions and 199 deletions
+47
View File
@@ -0,0 +1,47 @@
package types
import (
"database/sql/driver"
"encoding/json"
)
// ChatHistoryConfig represents the chat history knowledge base configuration for a tenant.
// This config is managed via the settings UI and controls how chat messages are indexed
// and searched using a knowledge base for vector search.
//
// The KnowledgeBaseID is auto-managed: when the user enables the feature and picks an
// embedding model, the backend automatically creates (or reuses) a hidden KB.
// Users do NOT pick a KB themselves.
type ChatHistoryConfig struct {
// Enabled controls whether chat history indexing is active
Enabled bool `json:"enabled"`
// EmbeddingModelID is the ID of the embedding model used for vectorizing chat messages.
// Once messages have been indexed, the model cannot be changed (requires re-indexing).
EmbeddingModelID string `json:"embedding_model_id"`
// KnowledgeBaseID is the auto-managed hidden knowledge base for chat history.
// This is set internally when the feature is first enabled; users should not set this directly.
KnowledgeBaseID string `json:"knowledge_base_id"`
}
// Value implements the driver.Valuer interface for database serialization
func (c ChatHistoryConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface for database deserialization
func (c *ChatHistoryConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
// IsConfigured returns true if the chat history KB is properly configured and ready to use.
// Requires: enabled + embedding model selected + KB auto-created.
func (c *ChatHistoryConfig) IsConfigured() bool {
return c != nil && c.Enabled && c.EmbeddingModelID != "" && c.KnowledgeBaseID != ""
}
+43 -1
View File
@@ -31,11 +31,53 @@ type MessageService interface {
// DeleteMessage deletes a message
DeleteMessage(ctx context.Context, sessionID string, id string) error
// SearchMessages searches messages by keyword and/or vector similarity across all sessions of the current tenant.
// Uses the chat history knowledge base for vector search instead of in-memory computation.
SearchMessages(ctx context.Context, params *types.MessageSearchParams) (*types.MessageSearchResult, error)
// IndexMessageToKB indexes a message (Q&A pair) into the chat history knowledge base asynchronously.
// Called after assistant message is created to enable future vector search.
IndexMessageToKB(ctx context.Context, userQuery string, assistantAnswer string, messageID string, sessionID string)
// DeleteMessageKnowledge deletes the Knowledge entry associated with a message from the chat history KB.
DeleteMessageKnowledge(ctx context.Context, knowledgeID string)
// DeleteSessionKnowledge deletes all Knowledge entries for messages in a session from the chat history KB.
DeleteSessionKnowledge(ctx context.Context, sessionID string)
// GetChatHistoryKBStats returns statistics about the chat history knowledge base (indexed message count, etc.)
GetChatHistoryKBStats(ctx context.Context) (*types.ChatHistoryKBStats, error)
}
// MessageRepository defines the message repository interface
type MessageRepository interface {
MessageService
// CreateMessage creates a message
CreateMessage(ctx context.Context, message *types.Message) (*types.Message, error)
// GetMessage gets a message
GetMessage(ctx context.Context, sessionID string, id string) (*types.Message, error)
// GetMessagesBySession gets all messages of a session
GetMessagesBySession(ctx context.Context, sessionID string, page int, pageSize int) ([]*types.Message, error)
// GetRecentMessagesBySession gets recent messages of a session
GetRecentMessagesBySession(ctx context.Context, sessionID string, limit int) ([]*types.Message, error)
// GetMessagesBySessionBeforeTime gets messages before a specific time of a session
GetMessagesBySessionBeforeTime(
ctx context.Context, sessionID string, beforeTime time.Time, limit int,
) ([]*types.Message, error)
// UpdateMessage updates a message
UpdateMessage(ctx context.Context, message *types.Message) error
// DeleteMessage deletes a message
DeleteMessage(ctx context.Context, sessionID string, id string) error
// GetFirstMessageOfUser gets the first message of a user
GetFirstMessageOfUser(ctx context.Context, sessionID string) (*types.Message, error)
// SearchMessagesByKeyword searches messages by keyword (ILIKE) across sessions for a tenant
SearchMessagesByKeyword(ctx context.Context, tenantID uint64, keyword string, sessionIDs []string, limit int) ([]*types.MessageWithSession, error)
// GetMessagesByKnowledgeIDs retrieves messages by their associated Knowledge IDs
GetMessagesByKnowledgeIDs(ctx context.Context, knowledgeIDs []string) ([]*types.MessageWithSession, error)
// GetMessagesByRequestIDs retrieves messages by their request IDs (used to fetch Q&A pair partners)
GetMessagesByRequestIDs(ctx context.Context, requestIDs []string) ([]*types.MessageWithSession, error)
// GetKnowledgeIDsBySessionID retrieves all knowledge IDs for messages in a session
GetKnowledgeIDsBySessionID(ctx context.Context, sessionID string) ([]string, error)
// UpdateMessageKnowledgeID updates the knowledge_id field for a message
UpdateMessageKnowledgeID(ctx context.Context, messageID string, knowledgeID string) error
}
+89
View File
@@ -82,6 +82,9 @@ type Message struct {
IsFallback bool `json:"is_fallback,omitempty"`
// Agent total execution duration in milliseconds (from query start to answer start)
AgentDurationMs int64 `json:"agent_duration_ms,omitempty" gorm:"column:agent_duration_ms;default:0"`
// KnowledgeID links this message to a Knowledge entry in the chat history knowledge base
// Used for vector search indexing: when set, the message content has been indexed as a Knowledge passage
KnowledgeID string `json:"knowledge_id,omitempty" gorm:"type:varchar(36);index"`
// Message creation timestamp
CreatedAt time.Time `json:"created_at"`
// Last update timestamp
@@ -136,3 +139,89 @@ func (m *Message) BeforeCreate(tx *gorm.DB) (err error) {
}
return nil
}
// MessageSearchMode represents the search mode for message search
type MessageSearchMode string
const (
// MessageSearchModeKeyword searches by keyword only
MessageSearchModeKeyword MessageSearchMode = "keyword"
// MessageSearchModeVector searches by vector similarity only
MessageSearchModeVector MessageSearchMode = "vector"
// MessageSearchModeHybrid combines keyword and vector search with RRF fusion
MessageSearchModeHybrid MessageSearchMode = "hybrid"
)
// MessageSearchParams defines the parameters for searching chat history messages
type MessageSearchParams struct {
// Query text for search
Query string `json:"query" binding:"required"`
// Search mode: "keyword", "vector", "hybrid" (default: "hybrid")
Mode MessageSearchMode `json:"mode"`
// Maximum number of results to return (default: 20)
Limit int `json:"limit"`
// Filter by specific session IDs (optional, empty means all sessions)
SessionIDs []string `json:"session_ids"`
}
// MessageWithSession extends Message with session title for search results
type MessageWithSession struct {
Message
// Title of the session this message belongs to
SessionTitle string `json:"session_title"`
}
// MessageSearchResultItem represents a single search result item (internal, pre-merge)
type MessageSearchResultItem struct {
// The matched message with session info
MessageWithSession
// Search relevance score (higher is better)
Score float64 `json:"score"`
// How this result was matched: "keyword", "vector", or "hybrid"
MatchType string `json:"match_type"`
}
// MessageSearchGroupItem represents a merged Q&A pair in search results.
// Messages sharing the same request_id are grouped together so that the user query
// and assistant answer are displayed side by side.
type MessageSearchGroupItem struct {
// The request_id that groups Q&A together
RequestID string `json:"request_id"`
// Session info
SessionID string `json:"session_id"`
SessionTitle string `json:"session_title"`
// User query content (role=user)
QueryContent string `json:"query_content"`
// Assistant answer content (role=assistant), may be empty if only Q matched
AnswerContent string `json:"answer_content"`
// Best score among the matched messages in this group
Score float64 `json:"score"`
// How this result was matched: "keyword", "vector", or "hybrid"
MatchType string `json:"match_type"`
// Timestamp of the earliest message in the group
CreatedAt time.Time `json:"created_at"`
}
// MessageSearchResult represents the search result for message search
type MessageSearchResult struct {
// List of merged Q&A pairs
Items []*MessageSearchGroupItem `json:"items"`
// Total number of results
Total int `json:"total"`
}
// ChatHistoryKBStats represents statistics about the chat history knowledge base
type ChatHistoryKBStats struct {
// Whether the chat history KB is configured and enabled
Enabled bool `json:"enabled"`
// ID of the embedding model used
EmbeddingModelID string `json:"embedding_model_id,omitempty"`
// ID of the knowledge base used for chat history
KnowledgeBaseID string `json:"knowledge_base_id,omitempty"`
// Name of the knowledge base
KnowledgeBaseName string `json:"knowledge_base_name,omitempty"`
// Number of indexed message entries (Knowledge count)
IndexedMessageCount int64 `json:"indexed_message_count"`
// Whether there are any indexed messages (used by frontend to lock embedding model)
HasIndexedMessages bool `json:"has_indexed_messages"`
}
+84
View File
@@ -0,0 +1,84 @@
package types
import (
"database/sql/driver"
"encoding/json"
)
// RetrievalConfig holds the global retrieval/search configuration for a tenant.
// This replaces the retrieval-related fields previously scattered in ConversationConfig
// and ChatHistoryConfig. Both knowledge search and message search share these parameters.
//
// Stored as a JSONB column on the tenants table, managed via the settings UI
// at /tenants/kv/retrieval-config.
type RetrievalConfig struct {
// EmbeddingTopK is the maximum number of chunks returned by vector search (default: 50)
EmbeddingTopK int `json:"embedding_top_k"`
// VectorThreshold is the minimum vector similarity score (0-1, default: 0.15)
VectorThreshold float64 `json:"vector_threshold"`
// KeywordThreshold is the minimum keyword match score (0-1, default: 0.3)
KeywordThreshold float64 `json:"keyword_threshold"`
// RerankTopK is the maximum number of results after reranking (default: 10)
RerankTopK int `json:"rerank_top_k"`
// RerankThreshold is the minimum rerank score (0-1, default: 0.2)
RerankThreshold float64 `json:"rerank_threshold"`
// RerankModelID is the ID of the rerank model to use (required for search)
RerankModelID string `json:"rerank_model_id"`
}
// GetEffectiveEmbeddingTopK returns EmbeddingTopK with a fallback default.
func (c *RetrievalConfig) GetEffectiveEmbeddingTopK() int {
if c == nil || c.EmbeddingTopK <= 0 {
return 50
}
return c.EmbeddingTopK
}
// GetEffectiveVectorThreshold returns VectorThreshold with a fallback default.
func (c *RetrievalConfig) GetEffectiveVectorThreshold() float64 {
if c == nil || c.VectorThreshold <= 0 {
return 0.15
}
return c.VectorThreshold
}
// GetEffectiveKeywordThreshold returns KeywordThreshold with a fallback default.
func (c *RetrievalConfig) GetEffectiveKeywordThreshold() float64 {
if c == nil || c.KeywordThreshold <= 0 {
return 0.3
}
return c.KeywordThreshold
}
// GetEffectiveRerankTopK returns RerankTopK with a fallback default.
func (c *RetrievalConfig) GetEffectiveRerankTopK() int {
if c == nil || c.RerankTopK <= 0 {
return 10
}
return c.RerankTopK
}
// GetEffectiveRerankThreshold returns RerankThreshold with a fallback default.
func (c *RetrievalConfig) GetEffectiveRerankThreshold() float64 {
if c == nil || c.RerankThreshold <= 0 {
return 0.2
}
return c.RerankThreshold
}
// Value implements the driver.Valuer interface for database serialization
func (c RetrievalConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface for database deserialization
func (c *RetrievalConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
+4
View File
@@ -103,6 +103,10 @@ type Tenant struct {
ParserEngineConfig *ParserEngineConfig `yaml:"parser_engine_config" json:"parser_engine_config" gorm:"type:jsonb"`
// Storage engine config: parameters for Local, MinIO, COS. Used for document/file storage and docreader.
StorageEngineConfig *StorageEngineConfig `yaml:"storage_engine_config" json:"storage_engine_config" gorm:"type:jsonb"`
// Chat history config: knowledge base configuration for indexing and searching chat messages via vector search
ChatHistoryConfig *ChatHistoryConfig `yaml:"chat_history_config" json:"chat_history_config" gorm:"type:jsonb"`
// Retrieval config: global search/retrieval parameters shared by knowledge search and message search
RetrievalConfig *RetrievalConfig `yaml:"retrieval_config" json:"retrieval_config" gorm:"type:jsonb"`
// Creation time
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time