init commit

This commit is contained in:
wizardchen
2025-08-05 15:08:07 +08:00
commit 56eb2bce33
282 changed files with 49077 additions and 0 deletions
+64
View File
@@ -0,0 +1,64 @@
package types
import (
"database/sql/driver"
"encoding/json"
)
// ChatResponse chat response
type ChatResponse struct {
Content string `json:"content"`
// Usage information
Usage struct {
// Prompt tokens
PromptTokens int `json:"prompt_tokens"`
// Completion tokens
CompletionTokens int `json:"completion_tokens"`
// Total tokens
TotalTokens int `json:"total_tokens"`
} `json:"usage"`
}
// Response type
type ResponseType string
const (
// Answer response type
ResponseTypeAnswer ResponseType = "answer"
// References response type
ResponseTypeReferences ResponseType = "references"
)
// StreamResponse stream response
type StreamResponse struct {
// Unique identifier
ID string `json:"id"`
// Response type
ResponseType ResponseType `json:"response_type"`
// Current fragment content
Content string `json:"content"`
// Whether the response is complete
Done bool `json:"done"`
// Knowledge references
KnowledgeReferences References `json:"knowledge_references"`
}
// References references
type References []*SearchResult
// Value implements the driver.Valuer interface, used to convert References to database values
func (c References) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database values to References
func (c *References) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
+114
View File
@@ -0,0 +1,114 @@
package types
// ChatManage represents the configuration and state for a chat session
// including query processing, search parameters, and model configurations
type ChatManage struct {
SessionID string `json:"session_id"` // Unique identifier for the chat session
Query string `json:"query,omitempty"` // Original user query
ProcessedQuery string `json:"processed_query,omitempty"` // Query after preprocessing
RewriteQuery string `json:"rewrite_query,omitempty"` // Query after rewriting for better retrieval
History []*History `json:"history,omitempty"` // Chat history for context
KnowledgeBaseID string `json:"knowledge_base_id"` // ID of the knowledge base to search against
VectorThreshold float64 `json:"vector_threshold"` // Minimum score threshold for vector search results
KeywordThreshold float64 `json:"keyword_threshold"` // Minimum score threshold for keyword search results
EmbeddingTopK int `json:"embedding_top_k"` // Number of top results to retrieve from embedding search
VectorDatabase string `json:"vector_database"` // Vector database type/name to use
RerankModelID string `json:"rerank_model_id"` // Model ID for reranking search results
RerankTopK int `json:"rerank_top_k"` // Number of top results after reranking
RerankThreshold float64 `json:"rerank_threshold"` // Minimum score threshold for reranked results
ChatModelID string `json:"chat_model_id"` // Model ID for chat completion
SummaryConfig SummaryConfig `json:"summary_config"` // Configuration for summary generation
FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // Strategy when no relevant results are found
FallbackResponse string `json:"fallback_response"` // Default response when fallback occurs
// Internal fields for pipeline data processing
SearchResult []*SearchResult `json:"-"` // Results from search phase
RerankResult []*SearchResult `json:"-"` // Results after reranking
MergeResult []*SearchResult `json:"-"` // Final merged results after all processing
UserContent string `json:"-"` // Processed user content
ChatResponse *ChatResponse `json:"-"` // Final response from chat model
ResponseChan <-chan StreamResponse `json:"-"` // Channel for streaming responses
}
// Clone creates a deep copy of the ChatManage object
func (c *ChatManage) Clone() *ChatManage {
return &ChatManage{
Query: c.Query,
ProcessedQuery: c.ProcessedQuery,
RewriteQuery: c.RewriteQuery,
SessionID: c.SessionID,
KnowledgeBaseID: c.KnowledgeBaseID,
VectorThreshold: c.VectorThreshold,
KeywordThreshold: c.KeywordThreshold,
EmbeddingTopK: c.EmbeddingTopK,
VectorDatabase: c.VectorDatabase,
RerankModelID: c.RerankModelID,
RerankTopK: c.RerankTopK,
RerankThreshold: c.RerankThreshold,
ChatModelID: c.ChatModelID,
SummaryConfig: SummaryConfig{
MaxTokens: c.SummaryConfig.MaxTokens,
RepeatPenalty: c.SummaryConfig.RepeatPenalty,
TopK: c.SummaryConfig.TopK,
TopP: c.SummaryConfig.TopP,
FrequencyPenalty: c.SummaryConfig.FrequencyPenalty,
PresencePenalty: c.SummaryConfig.PresencePenalty,
Prompt: c.SummaryConfig.Prompt,
ContextTemplate: c.SummaryConfig.ContextTemplate,
NoMatchPrefix: c.SummaryConfig.NoMatchPrefix,
Temperature: c.SummaryConfig.Temperature,
Seed: c.SummaryConfig.Seed,
MaxCompletionTokens: c.SummaryConfig.MaxCompletionTokens,
},
FallbackStrategy: c.FallbackStrategy,
FallbackResponse: c.FallbackResponse,
}
}
// EventType represents different stages in the RAG (Retrieval Augmented Generation) pipeline
type EventType string
const (
PREPROCESS_QUERY EventType = "preprocess_query" // Query preprocessing stage
REWRITE_QUERY EventType = "rewrite_query" // Query rewriting for better retrieval
CHUNK_SEARCH EventType = "chunk_search" // Search for relevant chunks
CHUNK_RERANK EventType = "chunk_rerank" // Rerank search results
CHUNK_MERGE EventType = "chunk_merge" // Merge similar chunks
INTO_CHAT_MESSAGE EventType = "into_chat_message" // Convert chunks into chat messages
CHAT_COMPLETION EventType = "chat_completion" // Generate chat completion
CHAT_COMPLETION_STREAM EventType = "chat_completion_stream" // Stream chat completion
STREAM_FILTER EventType = "stream_filter" // Filter streaming output
FILTER_TOP_K EventType = "filter_top_k" // Keep only top K results
)
// Pipline defines the sequence of events for different chat modes
var Pipline = map[string][]EventType{
"chat": { // Simple chat without retrieval
CHAT_COMPLETION,
},
"chat_stream": { // Streaming chat without retrieval
CHAT_COMPLETION_STREAM,
STREAM_FILTER,
},
"rag": { // Retrieval Augmented Generation
CHUNK_SEARCH,
CHUNK_RERANK,
CHUNK_MERGE,
INTO_CHAT_MESSAGE,
CHAT_COMPLETION,
},
"rag_stream": { // Streaming Retrieval Augmented Generation
REWRITE_QUERY,
PREPROCESS_QUERY,
CHUNK_SEARCH,
CHUNK_RERANK,
CHUNK_MERGE,
FILTER_TOP_K,
INTO_CHAT_MESSAGE,
CHAT_COMPLETION_STREAM,
STREAM_FILTER,
},
}
+90
View File
@@ -0,0 +1,90 @@
// Package types defines data structures and types used throughout the system
// These types are shared across different service modules to ensure data consistency
package types
import (
"time"
"gorm.io/gorm"
)
// ChunkType 定义了不同类型的 Chunk
type ChunkType string
const (
// ChunkTypeText 表示普通的文本 Chunk
ChunkTypeText ChunkType = "text"
// ChunkTypeImageOCR 表示图片 OCR 文本的 Chunk
ChunkTypeImageOCR ChunkType = "image_ocr"
// ChunkTypeImageCaption 表示图片描述的 Chunk
ChunkTypeImageCaption ChunkType = "image_caption"
// ChunkTypeSummary 表示摘要类型的 Chunk
ChunkTypeSummary = "summary"
// ChunkTypeEntity 表示实体类型的 Chunk
ChunkTypeEntity ChunkType = "entity"
// ChunkTypeRelationship 表示关系类型的 Chunk
ChunkTypeRelationship ChunkType = "relationship"
)
// ImageInfo 表示与 Chunk 关联的图片信息
type ImageInfo struct {
// 图片URL(COS)
URL string `json:"url" gorm:"type:text"`
// 原始图片URL
OriginalURL string `json:"original_url" gorm:"type:text"`
// 图片在文本中的开始位置
StartPos int `json:"start_pos"`
// 图片在文本中的结束位置
EndPos int `json:"end_pos"`
// 图片描述
Caption string `json:"caption"`
// 图片OCR文本
OCRText string `json:"ocr_text"`
}
// Chunk represents a document chunk
// Chunks are meaningful text segments extracted from original documents
// and are the basic units of knowledge base retrieval
// Each chunk contains a portion of the original content
// and maintains its positional relationship with the original text
// Chunks can be independently embedded as vectors and retrieved, supporting precise content localization
type Chunk struct {
// Unique identifier of the chunk, using UUID format
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
// Tenant ID, used for multi-tenant isolation
TenantID uint `json:"tenant_id"`
// ID of the parent knowledge, associated with the Knowledge model
KnowledgeID string `json:"knowledge_id"`
// ID of the knowledge base, for quick location
KnowledgeBaseID string `json:"knowledge_base_id"`
// Actual text content of the chunk
Content string `json:"content"`
// Index position of the chunk in the original document
ChunkIndex int `json:"chunk_index"`
// Whether the chunk is enabled, can be used to temporarily disable certain chunks
IsEnabled bool `json:"is_enabled" gorm:"default:true"`
// Starting character position in the original text
StartAt int `json:"start_at" `
// Ending character position in the original text
EndAt int `json:"end_at"`
// Previous chunk ID
PreChunkID string `json:"pre_chunk_id"`
// Next chunk ID
NextChunkID string `json:"next_chunk_id"`
// Chunk 类型,用于区分不同类型的 Chunk
ChunkType ChunkType `json:"chunk_type" gorm:"type:varchar(20);default:'text'"`
// 父 Chunk ID,用于关联图片 Chunk 和原始文本 Chunk
ParentChunkID string `json:"parent_chunk_id" gorm:"type:varchar(36);index"`
// 关系 Chunk ID,用于关联关系 Chunk 和原始文本 Chunk
RelationChunks JSON `json:"relation_chunks" gorm:"type:json"`
// 间接关系 Chunk ID,用于关联间接关系 Chunk 和原始文本 Chunk
IndirectRelationChunks JSON `json:"indirect_relation_chunks" gorm:"type:json"`
// 图片信息,存储为 JSON
ImageInfo string `json:"image_info" gorm:"type:text"`
// Chunk creation time
CreatedAt time.Time `json:"created_at"`
// Chunk last update time
UpdatedAt time.Time `json:"updated_at"`
// Soft delete marker, supports data recovery
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
}
+4
View File
@@ -0,0 +1,4 @@
package types
// CleanupFunc represents the resource cleanup function
type CleanupFunc func() error
+20
View File
@@ -0,0 +1,20 @@
package types
// ContextKey defines a type for context keys to avoid string collision
type ContextKey string
const (
// TenantIDContextKey is the context key for tenant ID
TenantIDContextKey ContextKey = "TenantID"
// TenantInfoContextKey is the context key for tenant information
TenantInfoContextKey ContextKey = "TenantInfo"
// RequestIDContextKey is the context key for request ID
RequestIDContextKey ContextKey = "RequestID"
// LoggerContextKey is the context key for logger
LoggerContextKey ContextKey = "Logger"
)
// String returns the string representation of the context key
func (c ContextKey) String() string {
return string(c)
}
+11
View File
@@ -0,0 +1,11 @@
package types
// QAPair represents a complete QA example with question, related passages and answer
type QAPair struct {
QID int // Question ID
Question string // Question text
PIDs []int // Related passage IDs
Passages []string // Passage texts
AID int // Answer ID
Answer string // Answer text
}
+33
View File
@@ -0,0 +1,33 @@
package types
// SourceType represents the type of content source
type SourceType int
const (
ChunkSourceType SourceType = iota // Source is a text chunk
PassageSourceType // Source is a passage
SummarySourceType // Source is a summary
)
// MatchType represents the type of matching algorithm
type MatchType int
const (
MatchTypeEmbedding MatchType = iota
MatchTypeKeywords
MatchTypeNearByChunk
MatchTypeHistory
MatchTypeParentChunk // 父Chunk匹配类型
MatchTypeRelationChunk // 关系Chunk匹配类型
)
// IndexInfo contains information about indexed content
type IndexInfo struct {
ID string // Unique identifier
Content string // Content text
SourceID string // ID of the source document
SourceType SourceType // Type of the source
ChunkID string // ID of the text chunk
KnowledgeID string // ID of the knowledge
KnowledgeBaseID string // ID of the knowledge base
}
+46
View File
@@ -0,0 +1,46 @@
package types
import "fmt"
// StorageQuotaExceededError represents the storage quota exceeded error
type StorageQuotaExceededError struct {
Message string
}
// Error implements the error interface
func (e *StorageQuotaExceededError) Error() string {
return e.Message
}
// NewStorageQuotaExceededError creates a storage quota exceeded error
func NewStorageQuotaExceededError() *StorageQuotaExceededError {
return &StorageQuotaExceededError{
Message: "Storage quota exceeded",
}
}
// DuplicateKnowledgeError duplicate knowledge error, contains the existing knowledge object
type DuplicateKnowledgeError struct {
Message string
Knowledge *Knowledge
}
func (e *DuplicateKnowledgeError) Error() string {
return e.Message
}
// NewDuplicateFileError creates a duplicate file error
func NewDuplicateFileError(knowledge *Knowledge) *DuplicateKnowledgeError {
return &DuplicateKnowledgeError{
Message: fmt.Sprintf("File already exists: %s", knowledge.FileName),
Knowledge: knowledge,
}
}
// NewDuplicateURLError creates a duplicate URL error
func NewDuplicateURLError(knowledge *Knowledge) *DuplicateKnowledgeError {
return &DuplicateKnowledgeError{
Message: fmt.Sprintf("URL already exists: %s", knowledge.Source),
Knowledge: knowledge,
}
}
+99
View File
@@ -0,0 +1,99 @@
package types
import (
"encoding/json"
"time"
"github.com/yanyiwu/gojieba"
)
// Jieba is a global instance of Chinese text segmentation tool
var Jieba *gojieba.Jieba = gojieba.NewJieba()
// EvaluationStatue represents the status of an evaluation task
type EvaluationStatue int
const (
EvaluationStatuePending EvaluationStatue = iota // Task is waiting to start
EvaluationStatueRunning // Task is in progress
EvaluationStatueSuccess // Task completed successfully
EvaluationStatueFailed // Task failed
)
// EvaluationTask contains information about an evaluation task
type EvaluationTask struct {
ID string `json:"id"` // Unique task ID
TenantID uint `json:"tenant_id"` // Tenant/Organization ID
DatasetID string `json:"dataset_id"` // Dataset ID for evaluation
StartTime time.Time `json:"start_time"` // Task start time
Status EvaluationStatue `json:"status"` // Current task status
ErrMsg string `json:"err_msg,omitempty"` // Error message if failed
Total int `json:"total,omitempty"` // Total items to evaluate
Finished int `json:"finished,omitempty"` // Completed items count
}
// EvaluationDetail contains detailed evaluation information
type EvaluationDetail struct {
Task *EvaluationTask `json:"task"` // Evaluation task info
Params *ChatManage `json:"params"` // Evaluation parameters
Metric *MetricResult `json:"metric,omitempty"` // Evaluation metrics
}
// String returns JSON representation of EvaluationTask
func (e *EvaluationTask) String() string {
b, _ := json.Marshal(e)
return string(b)
}
// MetricInput contains input data for metric calculation
type MetricInput struct {
RetrievalGT [][]int // Ground truth for retrieval
RetrievalIDs []int // Retrieved IDs
GeneratedTexts string // Generated text for evaluation
GeneratedGT string // Ground truth text for comparison
}
// MetricResult contains evaluation metrics
type MetricResult struct {
RetrievalMetrics RetrievalMetrics `json:"retrieval_metrics"` // Retrieval performance metrics
GenerationMetrics GenerationMetrics `json:"generation_metrics"` // Text generation quality metrics
}
// RetrievalMetrics contains metrics for retrieval evaluation
type RetrievalMetrics struct {
Precision float64 `json:"precision"` // Precision score
Recall float64 `json:"recall"` // Recall score
NDCG3 float64 `json:"ndcg3"` // Normalized Discounted Cumulative Gain at 3
NDCG10 float64 `json:"ndcg10"` // Normalized Discounted Cumulative Gain at 10
MRR float64 `json:"mrr"` // Mean Reciprocal Rank
MAP float64 `json:"map"` // Mean Average Precision
}
// GenerationMetrics contains metrics for text generation evaluation
type GenerationMetrics struct {
BLEU1 float64 `json:"bleu1"` // BLEU-1 score
BLEU2 float64 `json:"bleu2"` // BLEU-2 score
BLEU4 float64 `json:"bleu4"` // BLEU-4 score
ROUGE1 float64 `json:"rouge1"` // ROUGE-1 score
ROUGE2 float64 `json:"rouge2"` // ROUGE-2 score
ROUGEL float64 `json:"rougel"` // ROUGE-L score
}
// EvalState represents different stages of evaluation process
type EvalState int
const (
StateBegin EvalState = iota // Evaluation started
StateAfterQaPairs // After loading QA pairs
StateAfterDataset // After processing dataset
StateAfterEmbedding // After generating embeddings
StateAfterVectorSearch // After vector search
StateAfterRerank // After reranking
StateAfterComplete // After completion
StateEnd // Evaluation ended
)
+53
View File
@@ -0,0 +1,53 @@
// Package types defines the core data structures and interfaces used throughout the WeKnora system.
package types
import "context"
// Entity represents a node in the knowledge graph extracted from document chunks.
// Each entity corresponds to a meaningful concept, person, place or thing identified in the text.
type Entity struct {
ID string // Unique identifier for the entity
ChunkIDs []string // References to document chunks where this entity appears
Frequency int `json:"-"` // Number of occurrences in the corpus
Degree int `json:"-"` // Number of connections to other entities
Title string `json:"title"` // Display name of the entity
Type string `json:"type"` // Classification of the entity (e.g., person, concept, organization)
Description string `json:"description"` // Brief explanation or context about the entity
}
// Relationship represents a connection between two entities in the knowledge graph.
// It captures the semantic connection between entities identified in the document chunks.
type Relationship struct {
ID string `json:"-"` // Unique identifier for the relationship
ChunkIDs []string `json:"-"` // References to document chunks where this relationship is established
CombinedDegree int `json:"-"` // Sum of degrees of the connected entities, used for ranking
Weight float64 `json:"-"` // Strength of the relationship based on textual evidence
Source string `json:"source"` // ID of the entity where the relationship starts
Target string `json:"target"` // ID of the entity where the relationship ends
Description string `json:"description"` // Description of how these entities are related
Strength int `json:"strength"` // Normalized measure of relationship importance (1-10)
}
// GraphBuilder defines the interface for building and querying the knowledge graph.
// It provides methods to construct the graph from document chunks and retrieve related information.
type GraphBuilder interface {
// BuildGraph constructs a knowledge graph from the provided document chunks.
// It extracts entities and relationships, then builds the graph structure.
BuildGraph(ctx context.Context, chunks []*Chunk) error
// GetRelationChunks retrieves the IDs of chunks directly related to the specified chunk.
// The topK parameter limits the number of results returned, based on relationship strength.
GetRelationChunks(chunkID string, topK int) []string
// GetIndirectRelationChunks finds chunk IDs that are indirectly connected to the specified chunk.
// These are "second-degree" connections, useful for expanding the context during retrieval.
GetIndirectRelationChunks(chunkID string, topK int) []string
// GetAllEntities returns all entities currently in the knowledge graph.
// This is primarily used for visualization and diagnostics.
GetAllEntities() []*Entity
// GetAllRelationships returns all relationships currently in the knowledge graph.
// This is primarily used for visualization and diagnostics.
GetAllRelationships() []*Relationship
}
+62
View File
@@ -0,0 +1,62 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// ChunkRepository defines the interface for chunk repository operations
type ChunkRepository interface {
// CreateChunks creates chunks
CreateChunks(ctx context.Context, chunks []*types.Chunk) error
// GetChunkByID gets a chunk by id
GetChunkByID(ctx context.Context, tenantID uint, id string) (*types.Chunk, error)
// ListChunksByID lists chunks by ids
ListChunksByID(ctx context.Context, tenantID uint, ids []string) ([]*types.Chunk, error)
// ListChunksByKnowledgeID lists chunks by knowledge id
ListChunksByKnowledgeID(ctx context.Context, tenantID uint, knowledgeID string) ([]*types.Chunk, error)
// ListPagedChunksByKnowledgeID lists paged chunks by knowledge id
ListPagedChunksByKnowledgeID(
ctx context.Context,
tenantID uint,
knowledgeID string,
page *types.Pagination,
chunk_type []types.ChunkType,
) ([]*types.Chunk, int64, error)
ListChunkByParentID(ctx context.Context, tenantID uint, parentID string) ([]*types.Chunk, error)
// UpdateChunk updates a chunk
UpdateChunk(ctx context.Context, chunk *types.Chunk) error
// DeleteChunk deletes a chunk
DeleteChunk(ctx context.Context, tenantID uint, id string) error
// DeleteChunksByKnowledgeID deletes chunks by knowledge id
DeleteChunksByKnowledgeID(ctx context.Context, tenantID uint, knowledgeID string) error
// DeleteByKnowledgeList deletes all chunks for a knowledge list
DeleteByKnowledgeList(ctx context.Context, tenantID uint, knowledgeIDs []string) error
}
// ChunkService defines the interface for chunk service operations
type ChunkService interface {
// CreateChunks creates chunks
CreateChunks(ctx context.Context, chunks []*types.Chunk) error
// GetChunkByID gets a chunk by id
GetChunkByID(ctx context.Context, knowledgeID string, id string) (*types.Chunk, error)
// ListChunksByKnowledgeID lists chunks by knowledge id
ListChunksByKnowledgeID(ctx context.Context, knowledgeID string) ([]*types.Chunk, error)
// ListPagedChunksByKnowledgeID lists paged chunks by knowledge id
ListPagedChunksByKnowledgeID(
ctx context.Context,
knowledgeID string,
page *types.Pagination,
) (*types.PageResult, error)
// UpdateChunk updates a chunk
UpdateChunk(ctx context.Context, chunk *types.Chunk) error
// DeleteChunk deletes a chunk
DeleteChunk(ctx context.Context, id string) error
// DeleteChunksByKnowledgeID deletes chunks by knowledge id
DeleteChunksByKnowledgeID(ctx context.Context, knowledgeID string) error
// DeleteByKnowledgeList deletes all chunks for a knowledge list
DeleteByKnowledgeList(ctx context.Context, ids []string) error
// ListChunkByParentID lists chunks by parent id
ListChunkByParentID(ctx context.Context, tenantID uint, parentID string) ([]*types.Chunk, error)
}
+35
View File
@@ -0,0 +1,35 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// EvaluationService defines operations for evaluation tasks
type EvaluationService interface {
// Evaluation starts a new evaluation task
Evaluation(ctx context.Context, datasetID string, embeddingModelID string,
chatModelID string, rerankModelID string,
) (*types.EvaluationDetail, error)
// EvaluationResult retrieves evaluation result by task ID
EvaluationResult(ctx context.Context, taskID string) (*types.EvaluationDetail, error)
}
// Metrics defines interface for computing evaluation metrics
type Metrics interface {
// Compute calculates metric score based on input data
Compute(metricInput *types.MetricInput) float64
}
// EvalHook defines interface for evaluation process hooks
type EvalHook interface {
// Handle processes evaluation state change
Handle(ctx context.Context, state types.EvalState, index int, data interface{}) error
}
// DatasetService defines operations for dataset management
type DatasetService interface {
// GetDatasetByID retrieves QA pairs from dataset by ID
GetDatasetByID(ctx context.Context, datasetID string) ([]*types.QAPair, error)
}
+18
View File
@@ -0,0 +1,18 @@
package interfaces
import (
"context"
"io"
"mime/multipart"
)
// FileService is the interface for file services.
// FileService provides methods to save, retrieve, and delete files.
type FileService interface {
// SaveFile saves a file.
SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint, knowledgeID string) (string, error)
// GetFile retrieves a file.
GetFile(ctx context.Context, filePath string) (io.ReadCloser, error)
// DeleteFile deletes a file.
DeleteFile(ctx context.Context, filePath string) error
}
+72
View File
@@ -0,0 +1,72 @@
package interfaces
import (
"context"
"io"
"mime/multipart"
"github.com/Tencent/WeKnora/internal/types"
)
// KnowledgeService defines the interface for knowledge services.
type KnowledgeService interface {
// CreateKnowledgeFromFile creates knowledge from a file.
CreateKnowledgeFromFile(
ctx context.Context,
kbID string,
file *multipart.FileHeader,
metadata map[string]string,
) (*types.Knowledge, error)
// CreateKnowledgeFromURL creates knowledge from a URL.
CreateKnowledgeFromURL(ctx context.Context, kbID string, url string) (*types.Knowledge, error)
// CreateKnowledgeFromPassage creates knowledge from text passages.
CreateKnowledgeFromPassage(ctx context.Context, kbID string, passage []string) (*types.Knowledge, error)
// GetKnowledgeByID retrieves knowledge by ID.
GetKnowledgeByID(ctx context.Context, id string) (*types.Knowledge, error)
// GetKnowledgeBatch retrieves a batch of knowledge by IDs.
GetKnowledgeBatch(ctx context.Context, tenantID uint, ids []string) ([]*types.Knowledge, error)
// ListKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base.
ListKnowledgeByKnowledgeBaseID(ctx context.Context, kbID string) ([]*types.Knowledge, error)
// ListPagedKnowledgeByKnowledgeBaseID lists all knowledge under a knowledge base with pagination.
ListPagedKnowledgeByKnowledgeBaseID(
ctx context.Context,
kbID string,
page *types.Pagination,
) (*types.PageResult, error)
// DeleteKnowledge deletes knowledge by ID.
DeleteKnowledge(ctx context.Context, id string) error
// GetKnowledgeFile retrieves the file associated with the knowledge.
GetKnowledgeFile(ctx context.Context, id string) (io.ReadCloser, string, error)
// UpdateKnowledge updates knowledge information.
UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error
// CloneKnowledgeBase clones knowledge to another knowledge base.
CloneKnowledgeBase(ctx context.Context, srcID, dstID string) error
// UpdateImageInfo updates image information for a knowledge chunk.
UpdateImageInfo(ctx context.Context, knowledgeID string, chunkID string, imageInfo string) error
}
// KnowledgeRepository defines the interface for knowledge repositories.
type KnowledgeRepository interface {
CreateKnowledge(ctx context.Context, knowledge *types.Knowledge) error
GetKnowledgeByID(ctx context.Context, tenantID uint, id string) (*types.Knowledge, error)
ListKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint, kbID string) ([]*types.Knowledge, error)
ListPagedKnowledgeByKnowledgeBaseID(ctx context.Context,
tenantID uint, kbID string, page *types.Pagination,
) ([]*types.Knowledge, int64, error)
UpdateKnowledge(ctx context.Context, knowledge *types.Knowledge) error
DeleteKnowledge(ctx context.Context, tenantID uint, id string) error
DeleteKnowledgeList(ctx context.Context, tenantID uint, ids []string) error
GetKnowledgeBatch(ctx context.Context, tenantID uint, ids []string) ([]*types.Knowledge, error)
// CheckKnowledgeExists checks if knowledge already exists.
// For file types, check by fileHash or (fileName+fileSize).
// For URL types, check by URL.
// Returns whether it exists, the existing knowledge object (if any), and possible error.
CheckKnowledgeExists(
ctx context.Context,
tenantID uint,
kbID string,
params *types.KnowledgeCheckParams,
) (bool, *types.Knowledge, error)
// AminusB returns the difference set of A and B.
AminusB(ctx context.Context, Atenant uint, A string, Btenant uint, B string) ([]string, error)
}
+138
View File
@@ -0,0 +1,138 @@
// Package interfaces defines the interface contracts between different system components
// Through interface definitions, business logic can be decoupled from specific implementations,
// improving code testability and maintainability
// Knowledge base related interfaces are used to manage knowledge base resources and their contents
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// KnowledgeBaseService defines the knowledge base service interface
// Provides high-level operations for knowledge base creation, querying, updating, deletion, and content searching
type KnowledgeBaseService interface {
// CreateKnowledgeBase creates a new knowledge base
// Parameters:
// - ctx: Context information, carrying request tracking, user identity, etc.
// - kb: Knowledge base object containing basic information
// Returns:
// - Created knowledge base object (including automatically generated ID)
// - Possible errors such as insufficient permissions, duplicate names, etc.
CreateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) (*types.KnowledgeBase, error)
// GetKnowledgeBaseByID retrieves knowledge base information by ID
// Parameters:
// - ctx: Context information
// - id: Unique identifier of the knowledge base
// Returns:
// - Knowledge base object, if found
// - Possible errors such as not existing, insufficient permissions, etc.
GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error)
// ListKnowledgeBases lists all knowledge bases under the current tenant
// Parameters:
// - ctx: Context information, containing tenant information
// Returns:
// - List of knowledge base objects
// - Possible errors such as insufficient permissions, etc.
ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error)
// UpdateKnowledgeBase updates knowledge base information
// Parameters:
// - ctx: Context information
// - id: Unique identifier of the knowledge base
// - name: New knowledge base name
// - description: New knowledge base description
// - config: Knowledge base configuration, including chunking strategy, vectorization settings, etc.
// Returns:
// - Updated knowledge base object
// - Possible errors such as not existing, insufficient permissions, etc.
UpdateKnowledgeBase(ctx context.Context,
id string, name string, description string, config *types.KnowledgeBaseConfig,
) (*types.KnowledgeBase, error)
// DeleteKnowledgeBase deletes a knowledge base
// Parameters:
// - ctx: Context information
// - id: Unique identifier of the knowledge base
// Returns:
// - Possible errors such as not existing, insufficient permissions, etc.
DeleteKnowledgeBase(ctx context.Context, id string) error
// HybridSearch performs hybrid search (vector + keywords) in the knowledge base
// Parameters:
// - ctx: Context information
// - id: Unique identifier of the knowledge base
// - params: Search parameters, including query text, thresholds, etc.
// Returns:
// - List of search results, sorted by relevance
// - Possible errors such as not existing, insufficient permissions, search engine errors, etc.
HybridSearch(ctx context.Context, id string, params types.SearchParams) ([]*types.SearchResult, error)
// CopyKnowledgeBase copies a knowledge base
// Parameters:
// - ctx: Context information
// - sourceID: Source knowledge base ID
// - targetID: Target knowledge base ID
// Returns:
// - Copied knowledge base object
// - Possible errors such as not existing, insufficient permissions, etc.
CopyKnowledgeBase(ctx context.Context, src string, dst string) (*types.KnowledgeBase, *types.KnowledgeBase, error)
}
// KnowledgeBaseRepository defines the knowledge base repository interface
// Responsible for knowledge base data persistence and retrieval,
// serving as a bridge between the service layer and data storage
type KnowledgeBaseRepository interface {
// CreateKnowledgeBase creates a knowledge base record
// Parameters:
// - ctx: Context information
// - kb: Knowledge base object
// Returns:
// - Possible errors such as database connection failure, unique constraint conflicts, etc.
CreateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) error
// GetKnowledgeBaseByID queries a knowledge base by ID
// Parameters:
// - ctx: Context information
// - id: Knowledge base ID
// Returns:
// - Knowledge base object, if found
// - Possible errors such as record not existing, database errors, etc.
GetKnowledgeBaseByID(ctx context.Context, id string) (*types.KnowledgeBase, error)
// ListKnowledgeBases lists all knowledge bases in the system
// Parameters:
// - ctx: Context information
// Returns:
// - List of knowledge base objects
// - Possible errors such as database errors, etc.
ListKnowledgeBases(ctx context.Context) ([]*types.KnowledgeBase, error)
// ListKnowledgeBasesByTenantID lists all knowledge bases for a specific tenant
// Parameters:
// - ctx: Context information
// - tenantID: Tenant ID
// Returns:
// - List of knowledge base objects
// - Possible errors such as database errors, etc.
ListKnowledgeBasesByTenantID(ctx context.Context, tenantID uint) ([]*types.KnowledgeBase, error)
// UpdateKnowledgeBase updates a knowledge base record
// Parameters:
// - ctx: Context information
// - kb: Knowledge base object containing update information
// Returns:
// - Possible errors such as record not existing, database errors, etc.
UpdateKnowledgeBase(ctx context.Context, kb *types.KnowledgeBase) error
// DeleteKnowledgeBase deletes a knowledge base record
// Parameters:
// - ctx: Context information
// - id: Knowledge base ID
// Returns:
// - Possible errors such as record not existing, database errors, etc.
DeleteKnowledgeBase(ctx context.Context, id string) error
}
+41
View File
@@ -0,0 +1,41 @@
package interfaces
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
)
// MessageService defines the message service interface
type MessageService interface {
// 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
}
// MessageRepository defines the message repository interface
type MessageRepository interface {
MessageService
// GetFirstMessageOfUser gets the first message of a user
GetFirstMessageOfUser(ctx context.Context, sessionID string) (*types.Message, error)
}
+49
View File
@@ -0,0 +1,49 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/models/rerank"
"github.com/Tencent/WeKnora/internal/types"
)
// ModelService defines the model service interface
type ModelService interface {
// CreateModel creates a model
CreateModel(ctx context.Context, model *types.Model) error
// GetModelByID gets a model by ID
GetModelByID(ctx context.Context, id string) (*types.Model, error)
// ListModels lists all models
ListModels(ctx context.Context) ([]*types.Model, error)
// UpdateModel updates a model
UpdateModel(ctx context.Context, model *types.Model) error
// DeleteModel deletes a model
DeleteModel(ctx context.Context, id string) error
// GetEmbeddingModel gets an embedding model
GetEmbeddingModel(ctx context.Context, modelId string) (embedding.Embedder, error)
// GetRerankModel gets a rerank model
GetRerankModel(ctx context.Context, modelId string) (rerank.Reranker, error)
// GetChatModel gets a chat model
GetChatModel(ctx context.Context, modelId string) (chat.Chat, error)
}
// ModelRepository defines the model repository interface
type ModelRepository interface {
// Create creates a model
Create(ctx context.Context, model *types.Model) error
// GetByID gets a model by ID
GetByID(ctx context.Context, tenantID uint, id string) (*types.Model, error)
// List lists all models
List(
ctx context.Context,
tenantID uint,
modelType types.ModelType,
source types.ModelSource,
) ([]*types.Model, error)
// Update updates a model
Update(ctx context.Context, model *types.Model) error
// Delete deletes a model
Delete(ctx context.Context, tenantID uint, id string) error
}
+19
View File
@@ -0,0 +1,19 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// ResourceCleaner defines the resource cleaner interface
type ResourceCleaner interface {
// Register registers a resource cleanup function
Register(cleanup types.CleanupFunc)
// RegisterWithName registers a resource cleanup function with a name
RegisterWithName(name string, cleanup types.CleanupFunc)
// Cleanup executes all resource cleanup functions
Cleanup(ctx context.Context) []error
}
+109
View File
@@ -0,0 +1,109 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/types"
)
// RetrieveEngine defines the retrieve engine interface
type RetrieveEngine interface {
// EngineType gets the retrieve engine type
EngineType() types.RetrieverEngineType
// Retrieve executes the retrieve
Retrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error)
// Support gets the supported retrieve types
Support() []types.RetrieverType
}
// RetrieveEngineRepository defines the retrieve engine repository interface
type RetrieveEngineRepository interface {
// Save saves the index info
Save(ctx context.Context, indexInfo *types.IndexInfo, params map[string]any) error
// BatchSave saves the index info list
BatchSave(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) error
// EstimateStorageSize estimates the storage size
EstimateStorageSize(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) int64
// DeleteByChunkIDList deletes the index info by chunk id list
DeleteByChunkIDList(ctx context.Context, indexIDList []string, dimension int) error
// 复制索引数据
// sourceKnowledgeBaseID: 源知识库ID
// sourceToTargetChunkIDMap: 源分块ID到目标分块ID的映射关系
// targetKnowledgeBaseID: 目标知识库ID
// params: 额外参数,如向量表示等
CopyIndices(
ctx context.Context,
sourceKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
dimension int,
) error
// DeleteByKnowledgeIDList deletes the index info by knowledge id list
DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int) error
// RetrieveEngine retrieves the engine
RetrieveEngine
}
// RetrieveEngineRegistry defines the retrieve engine registry interface
type RetrieveEngineRegistry interface {
// Register registers the retrieve engine service
Register(indexService RetrieveEngineService) error
// GetRetrieveEngineService gets the retrieve engine service
GetRetrieveEngineService(engineType types.RetrieverEngineType) (RetrieveEngineService, error)
// GetAllRetrieveEngineServices gets all retrieve engine services
GetAllRetrieveEngineServices() []RetrieveEngineService
}
// RetrieveEngineService defines the retrieve engine service interface
type RetrieveEngineService interface {
// Index indexes the index info
Index(ctx context.Context,
embedder embedding.Embedder,
indexInfo *types.IndexInfo,
retrieverTypes []types.RetrieverType,
) error
// BatchIndex indexes the index info list
BatchIndex(ctx context.Context,
embedder embedding.Embedder,
indexInfoList []*types.IndexInfo,
retrieverTypes []types.RetrieverType,
) error
// EstimateStorageSize estimates the storage size
EstimateStorageSize(ctx context.Context,
embedder embedding.Embedder,
indexInfoList []*types.IndexInfo,
retrieverTypes []types.RetrieverType,
) int64
// CopyIndices 从源知识库复制索引到目标知识库,免去重新计算嵌入向量的开销
// sourceKnowledgeBaseID: 源知识库ID
// sourceToTargetChunkIDMap: 源分块ID到目标分块ID的映射关系,key为源分块ID,value为目标分块ID
// targetKnowledgeBaseID: 目标知识库ID
CopyIndices(
ctx context.Context,
sourceKnowledgeBaseID string,
sourceToTargetKBIDMap map[string]string,
sourceToTargetChunkIDMap map[string]string,
targetKnowledgeBaseID string,
dimension int,
) error
// DeleteByChunkIDList deletes the index info by chunk id list
DeleteByChunkIDList(ctx context.Context, indexIDList []string, dimension int) error
// DeleteByKnowledgeIDList deletes the index info by knowledge id list
DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int) error
// RetrieveEngine retrieves the engine
RetrieveEngine
}
+49
View File
@@ -0,0 +1,49 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// SessionService defines the session service interface
type SessionService interface {
// CreateSession creates a session
CreateSession(ctx context.Context, session *types.Session) (*types.Session, error)
// GetSession gets a session
GetSession(ctx context.Context, id string) (*types.Session, error)
// GetSessionsByTenant gets all sessions of a tenant
GetSessionsByTenant(ctx context.Context) ([]*types.Session, error)
// GetPagedSessionsByTenant gets paged sessions of a tenant
GetPagedSessionsByTenant(ctx context.Context, page *types.Pagination) (*types.PageResult, error)
// UpdateSession updates a session
UpdateSession(ctx context.Context, session *types.Session) error
// DeleteSession deletes a session
DeleteSession(ctx context.Context, id string) error
// GenerateTitle generates a title for the current conversation
GenerateTitle(ctx context.Context, sessionID string, messages []types.Message) (string, error)
// KnowledgeQA performs knowledge-based question answering
KnowledgeQA(ctx context.Context,
sessionID, query string,
) ([]*types.SearchResult, <-chan types.StreamResponse, error)
// KnowledgeQAByEvent performs knowledge-based question answering by event
KnowledgeQAByEvent(ctx context.Context, chatManage *types.ChatManage, eventList []types.EventType) error
// SearchKnowledge performs knowledge-based search, without summarization
SearchKnowledge(ctx context.Context, knowledgeBaseID, query string) ([]*types.SearchResult, error)
}
// SessionRepository defines the session repository interface
type SessionRepository interface {
// Create creates a session
Create(ctx context.Context, session *types.Session) (*types.Session, error)
// Get gets a session
Get(ctx context.Context, tenantID uint, id string) (*types.Session, error)
// GetByTenantID gets all sessions of a tenant
GetByTenantID(ctx context.Context, tenantID uint) ([]*types.Session, error)
// GetPagedByTenantID gets paged sessions of a tenant
GetPagedByTenantID(ctx context.Context, tenantID uint, page *types.Pagination) ([]*types.Session, int64, error)
// Update updates a session
Update(ctx context.Context, session *types.Session) error
// Delete deletes a session
Delete(ctx context.Context, tenantID uint, id string) error
}
@@ -0,0 +1,34 @@
package interfaces
import (
"context"
"time"
"github.com/Tencent/WeKnora/internal/types"
)
// StreamInfo stream information
type StreamInfo struct {
SessionID string // session ID
RequestID string // request ID
Query string // query content
Content string // current content
KnowledgeReferences types.References // knowledge references
LastUpdated time.Time // last updated time
IsCompleted bool // whether completed
}
// StreamManager stream manager interface
type StreamManager interface {
// RegisterStream registers a new stream
RegisterStream(ctx context.Context, sessionID, requestID, query string) error
// UpdateStream updates the stream content
UpdateStream(ctx context.Context, sessionID, requestID string, content string, references types.References) error
// CompleteStream completes the stream
CompleteStream(ctx context.Context, sessionID, requestID string) error
// GetStream gets a specific stream
GetStream(ctx context.Context, sessionID, requestID string) (*StreamInfo, error)
}
+41
View File
@@ -0,0 +1,41 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// TenantService defines the tenant service interface
type TenantService interface {
// CreateTenant creates a tenant
CreateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error)
// GetTenantByID gets a tenant by ID
GetTenantByID(ctx context.Context, id uint) (*types.Tenant, error)
// ListTenants lists all tenants
ListTenants(ctx context.Context) ([]*types.Tenant, error)
// UpdateTenant updates a tenant
UpdateTenant(ctx context.Context, tenant *types.Tenant) (*types.Tenant, error)
// DeleteTenant deletes a tenant
DeleteTenant(ctx context.Context, id uint) error
// UpdateAPIKey updates the API key
UpdateAPIKey(ctx context.Context, id uint) (string, error)
// ExtractTenantIDFromAPIKey extracts the tenant ID from the API key
ExtractTenantIDFromAPIKey(apiKey string) (uint, error)
}
// TenantRepository defines the tenant repository interface
type TenantRepository interface {
// CreateTenant creates a tenant
CreateTenant(ctx context.Context, tenant *types.Tenant) error
// GetTenantByID gets a tenant by ID
GetTenantByID(ctx context.Context, id uint) (*types.Tenant, error)
// ListTenants lists all tenants
ListTenants(ctx context.Context) ([]*types.Tenant, error)
// UpdateTenant updates a tenant
UpdateTenant(ctx context.Context, tenant *types.Tenant) error
// DeleteTenant deletes a tenant
DeleteTenant(ctx context.Context, id uint) error
// AdjustStorageUsed adjusts the storage used for a tenant
AdjustStorageUsed(ctx context.Context, tenantID uint, delta int64) error
}
+68
View File
@@ -0,0 +1,68 @@
package types
import (
"database/sql/driver"
"encoding/json"
"errors"
)
// JSON is a custom type that wraps json.RawMessage.
// Used for storing JSON data in the database.
type JSON json.RawMessage
// Scan implements the sql.Scanner interface.
func (j *JSON) Scan(value interface{}) error {
bytes, ok := value.([]byte)
if !ok {
return errors.New("type assertion to []byte failed")
}
result := json.RawMessage{}
err := json.Unmarshal(bytes, &result)
*j = JSON(result)
return err
}
// Value implements the driver.Valuer interface.
func (j JSON) Value() (driver.Value, error) {
if len(j) == 0 {
return nil, nil
}
return json.RawMessage(j).MarshalJSON()
}
// MarshalJSON implements the json.Marshaler interface.
func (j JSON) MarshalJSON() ([]byte, error) {
if len(j) == 0 {
return []byte("null"), nil
}
return j, nil
}
// UnmarshalJSON implements the json.Unmarshaler interface.
func (j *JSON) UnmarshalJSON(data []byte) error {
if j == nil {
return errors.New("JSON: UnmarshalJSON on nil pointer")
}
*j = JSON(data)
return nil
}
// ToString converts JSON to a string.
func (j JSON) ToString() string {
if len(j) == 0 {
return "{}"
}
return string(j)
}
// Map converts JSON to a map.
func (j JSON) Map() (map[string]interface{}, error) {
if len(j) == 0 {
return map[string]interface{}{}, nil
}
var m map[string]interface{}
err := json.Unmarshal(j, &m)
return m, err
}
+92
View File
@@ -0,0 +1,92 @@
package types
import (
"fmt"
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
// Knowledge represents a knowledge entity in the system.
// It contains metadata about the knowledge source, its processing status,
// and references to the physical file if applicable.
type Knowledge struct {
// Unique identifier of the knowledge
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
// Tenant ID
TenantID uint `json:"tenant_id"`
// ID of the knowledge base
KnowledgeBaseID string `json:"knowledge_base_id"`
// Type of the knowledge
Type string `json:"type"`
// Title of the knowledge
Title string `json:"title"`
// Description of the knowledge
Description string `json:"description"`
// Source of the knowledge
Source string `json:"source"`
// Parse status of the knowledge
ParseStatus string `json:"parse_status"`
// Enable status of the knowledge
EnableStatus string `json:"enable_status"`
// ID of the embedding model
EmbeddingModelID string `json:"embedding_model_id"`
// File name of the knowledge
FileName string `json:"file_name"`
// File type of the knowledge
FileType string `json:"file_type"`
// File size of the knowledge
FileSize int64 `json:"file_size"`
// File hash of the knowledge
FileHash string `json:"file_hash"`
// File path of the knowledge
FilePath string `json:"file_path"`
// Storage size of the knowledge
StorageSize int64 `json:"storage_size"`
// Metadata of the knowledge
Metadata JSON `json:"metadata" gorm:"type:json"`
// Creation time of the knowledge
CreatedAt time.Time `json:"created_at"`
// Last updated time of the knowledge
UpdatedAt time.Time `json:"updated_at"`
// Processed time of the knowledge
ProcessedAt *time.Time `json:"processed_at"`
// Error message of the knowledge
ErrorMessage string `json:"error_message"`
// Deletion time of the knowledge
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
}
// GetMetadata returns the metadata as a map[string]string.
func (k *Knowledge) GetMetadata() map[string]string {
metadata := make(map[string]string)
metadataMap, err := k.Metadata.Map()
if err != nil {
return nil
}
for k, v := range metadataMap {
metadata[k] = fmt.Sprintf("%v", v)
}
return metadata
}
// BeforeCreate hook generates a UUID for new Knowledge entities before they are created.
func (k *Knowledge) BeforeCreate(tx *gorm.DB) (err error) {
k.ID = uuid.New().String()
return nil
}
// KnowledgeCheckParams defines parameters used to check if knowledge already exists.
type KnowledgeCheckParams struct {
// File parameters
FileName string
FileSize int64
FileHash string
// URL parameters
URL string
// Text passage parameters
Passages []string
// Knowledge type
Type string
}
+95
View File
@@ -0,0 +1,95 @@
package types
import (
"database/sql/driver"
"encoding/json"
"time"
"gorm.io/gorm"
)
// KnowledgeBase represents a knowledge base
type KnowledgeBase struct {
// Unique identifier of the knowledge base
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`
// Name of the knowledge base
Name string `yaml:"name" json:"name"`
// Description of the knowledge base
Description string `yaml:"description" json:"description"`
// Tenant ID
TenantID uint `yaml:"tenant_id" json:"tenant_id"`
// Chunking configuration
ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config" gorm:"type:json"`
// Image processing configuration
ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config" gorm:"type:json"`
// ID of the embedding model
EmbeddingModelID string `yaml:"embedding_model_id" json:"embedding_model_id"`
// Summary model ID
SummaryModelID string `yaml:"summary_model_id" json:"summary_model_id"`
// Creation time of the knowledge base
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time of the knowledge base
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
// Deletion time of the knowledge base
DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"`
}
// KnowledgeBaseConfig represents the knowledge base configuration
type KnowledgeBaseConfig struct {
// Chunking configuration
ChunkingConfig ChunkingConfig `yaml:"chunking_config" json:"chunking_config"`
// Image processing configuration
ImageProcessingConfig ImageProcessingConfig `yaml:"image_processing_config" json:"image_processing_config"`
}
// ChunkingConfig represents the document splitting configuration
type ChunkingConfig struct {
// Chunk size
ChunkSize int `yaml:"chunk_size" json:"chunk_size"`
// Chunk overlap
ChunkOverlap int `yaml:"chunk_overlap" json:"chunk_overlap"`
// Separators
Separators []string `yaml:"separators" json:"separators"`
// Enable multimodal
EnableMultimodal bool `yaml:"enable_multimodal" json:"enable_multimodal"`
}
// ImageProcessingConfig represents the image processing configuration
type ImageProcessingConfig struct {
// Model ID
ModelID string `yaml:"model_id" json:"model_id"`
}
// Value implements the driver.Valuer interface, used to convert ChunkingConfig to database value
func (c ChunkingConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database value to ChunkingConfig
func (c *ChunkingConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
// Value implements the driver.Valuer interface, used to convert ImageProcessingConfig to database value
func (c ImageProcessingConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database value to ImageProcessingConfig
func (c *ImageProcessingConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
+60
View File
@@ -0,0 +1,60 @@
// Package types defines data structures and types used throughout the system
package types
import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
// History represents a conversation history entry
// Contains query-answer pairs and associated knowledge references
// Used for tracking conversation context and history
type History struct {
Query string // User query text
Answer string // System response text
CreateAt time.Time // When this history entry was created
KnowledgeReferences References // Knowledge references used in the answer
}
// Message represents a conversation message
// Each message belongs to a conversation session and can be from either user or system
// Messages can contain references to knowledge chunks used to generate responses
type Message struct {
// Unique identifier for the message
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
// ID of the session this message belongs to
SessionID string `json:"session_id"`
// Request identifier for tracking API requests
RequestID string `json:"request_id"`
// Message text content
Content string `json:"content"`
// Message role: "user", "assistant", "system"
Role string `json:"role"`
// References to knowledge chunks used in the response
KnowledgeReferences References `json:"knowledge_references" gorm:"type:json,column:knowledge_references"`
// Whether message generation is complete
IsCompleted bool `json:"is_completed"`
// Message creation timestamp
CreatedAt time.Time `json:"created_at"`
// Last update timestamp
UpdatedAt time.Time `json:"updated_at"`
// Soft delete timestamp
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
}
// BeforeCreate is a GORM hook that runs before creating a new message record
// Automatically generates a UUID for new messages and initializes knowledge references
// Parameters:
// - tx: GORM database transaction
//
// Returns:
// - error: Any error encountered during the hook execution
func (m *Message) BeforeCreate(tx *gorm.DB) (err error) {
m.ID = uuid.New().String()
if m.KnowledgeReferences == nil {
m.KnowledgeReferences = make(References, 0)
}
return nil
}
+91
View File
@@ -0,0 +1,91 @@
package types
import (
"database/sql/driver"
"encoding/json"
"time"
"gorm.io/gorm"
)
// ModelType represents the type of AI model
type ModelType string
const (
ModelTypeEmbedding ModelType = "Embedding" // Embedding model
ModelTypeRerank ModelType = "Rerank" // Rerank model
ModelTypeKnowledgeQA ModelType = "KnowledgeQA" // KnowledgeQA model
ModelTypeVLLM ModelType = "VLLM" // VLLM model
)
type ModelStatus string
const (
ModelStatusActive ModelStatus = "active" // Model is active
ModelStatusDownloading ModelStatus = "downloading" // Model is downloading
ModelStatusDownloadFailed ModelStatus = "download_failed" // Model download failed
)
// ModelSource represents the source of the model
type ModelSource string
const (
ModelSourceLocal ModelSource = "local" // Local model
ModelSourceRemote ModelSource = "remote" // Remote model
)
type EmbeddingParameters struct {
Dimension int `yaml:"dimension" json:"dimension"`
TruncatePromptTokens int `yaml:"truncate_prompt_tokens" json:"truncate_prompt_tokens"`
}
type ModelParameters struct {
BaseURL string `yaml:"base_url" json:"base_url"`
APIKey string `yaml:"api_key" json:"api_key"`
EmbeddingParameters EmbeddingParameters `yaml:"embedding_parameters" json:"embedding_parameters"`
}
// Model represents the AI model
type Model struct {
// Unique identifier of the model
ID string `yaml:"id" json:"id" gorm:"type:varchar(36);primaryKey"`
// Tenant ID
TenantID uint `yaml:"tenant_id" json:"tenant_id"`
// Name of the model
Name string `yaml:"name" json:"name"`
// Type of the model
Type ModelType `yaml:"type" json:"type"`
// Source of the model
Source ModelSource `yaml:"source" json:"source"`
// Description of the model
Description string `yaml:"description" json:"description"`
// Model parameters in JSON format
Parameters ModelParameters `yaml:"parameters" json:"parameters" gorm:"type:json"`
// Whether the model is the default model
IsDefault bool `yaml:"is_default" json:"is_default"`
// Model status, default: active, possible: downloading, download_failed
Status ModelStatus `yaml:"status" json:"status"`
// Creation time of the model
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time of the model
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
// Deletion time of the model
DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"`
}
// Value implements the driver.Valuer interface, used to convert ModelParameters to database value
func (c ModelParameters) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database value to ModelParameters
func (c *ModelParameters) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
+82
View File
@@ -0,0 +1,82 @@
package types
// RetrieverEngineType represents the type of retriever engine
type RetrieverEngineType string
// RetrieverEngineType constants
const (
PostgresRetrieverEngineType RetrieverEngineType = "postgres"
ElasticsearchRetrieverEngineType RetrieverEngineType = "elasticsearch"
InfinityRetrieverEngineType RetrieverEngineType = "infinity"
ElasticFaissRetrieverEngineType RetrieverEngineType = "elasticfaiss"
)
// RetrieverType represents the type of retriever
type RetrieverType string
// RetrieverType constants
const (
KeywordsRetrieverType RetrieverType = "keywords" // Keywords retriever
VectorRetrieverType RetrieverType = "vector" // Vector retriever
WebSearchRetrieverType RetrieverType = "websearch" // Web search retriever
)
// RetrieveParams represents the parameters for retrieval
type RetrieveParams struct {
// Query text
Query string
// Query embedding (used for vector retrieval)
Embedding []float32
// Knowledge base IDs
KnowledgeBaseIDs []string
// Excluded knowledge IDs
ExcludeKnowledgeIDs []string
// Excluded chunk IDs
ExcludeChunkIDs []string
// Number of results to return
TopK int
// Similarity threshold
Threshold float64
// Additional parameters, different retrievers may require different parameters
AdditionalParams map[string]interface{}
// Retriever type
RetrieverType RetrieverType // Retriever type
}
// RetrieverEngineParams represents the parameters for retriever engine
type RetrieverEngineParams struct {
// Retriever engine type
RetrieverEngineType RetrieverEngineType `yaml:"retriever_engine_type" json:"retriever_engine_type"`
// Retriever type
RetrieverType RetrieverType `yaml:"retriever_type" json:"retriever_type"`
}
// IndexWithScore represents the index with score
type IndexWithScore struct {
// ID
ID string
// Content
Content string
// Source ID
SourceID string
// Source type
SourceType SourceType
// Chunk ID
ChunkID string
// Knowledge ID
KnowledgeID string
// Knowledge base ID
KnowledgeBaseID string
// Score
Score float64
// Match type
MatchType MatchType
}
// RetrieveResult represents the result of retrieval
type RetrieveResult struct {
Results []*IndexWithScore // Retrieval results
RetrieverEngineType RetrieverEngineType // Retrieval source type
RetrieverType RetrieverType // Retrieval type
Error error // Retrieval error
}
+129
View File
@@ -0,0 +1,129 @@
package types
import (
"database/sql/driver"
"encoding/json"
)
// SearchResult represents the search result
type SearchResult struct {
// ID
ID string `gorm:"column:id" json:"id"`
// Content
Content string `gorm:"column:content" json:"content"`
// Knowledge ID
KnowledgeID string `gorm:"column:knowledge_id" json:"knowledge_id"`
// Chunk index
ChunkIndex int `gorm:"column:chunk_index" json:"chunk_index"`
// Knowledge title
KnowledgeTitle string `gorm:"column:knowledge_title" json:"knowledge_title"`
// Start at
StartAt int `gorm:"column:start_at" json:"start_at"`
// End at
EndAt int `gorm:"column:end_at" json:"end_at"`
// Seq
Seq int `gorm:"column:seq" json:"seq"`
// Score
Score float64 `json:"score"`
// Match type
MatchType MatchType `json:"match_type"`
// SubChunkIndex
SubChunkID []string `json:"sub_chunk_id"`
// Metadata
Metadata map[string]string `json:"metadata"`
// Chunk 类型
ChunkType string `json:"chunk_type"`
// 父 Chunk ID
ParentChunkID string `json:"parent_chunk_id"`
// 图片信息 (JSON 格式)
ImageInfo string `json:"image_info"`
// Knowledge file name
// Used for file type knowledge, contains the original file name
KnowledgeFilename string `json:"knowledge_filename"`
// Knowledge source
// Used to indicate the source of the knowledge, such as "url"
KnowledgeSource string `json:"knowledge_source"`
}
// SearchParams represents the search parameters
type SearchParams struct {
QueryText string
VectorThreshold float64
KeywordThreshold float64
MatchCount int
}
// Value implements the driver.Valuer interface, used to convert SearchResult to database value
func (c SearchResult) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database value to SearchResult
func (c *SearchResult) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
// Pagination represents the pagination parameters
type Pagination struct {
// Page
Page int `form:"page" json:"page" binding:"omitempty,min=1"`
// Page size
PageSize int `form:"page_size" json:"page_size" binding:"omitempty,min=1,max=100"`
}
// GetPage gets the page number, default is 1
func (p *Pagination) GetPage() int {
if p.Page < 1 {
return 1
}
return p.Page
}
// GetPageSize gets the page size, default is 20
func (p *Pagination) GetPageSize() int {
if p.PageSize < 1 {
return 20
}
if p.PageSize > 100 {
return 100
}
return p.PageSize
}
// Offset gets the offset for database query
func (p *Pagination) Offset() int {
return (p.GetPage() - 1) * p.GetPageSize()
}
// Limit gets the limit for database query
func (p *Pagination) Limit() int {
return p.GetPageSize()
}
// PageResult represents the pagination query result
type PageResult struct {
Total int64 `json:"total"` // Total number of records
Page int `json:"page"` // Current page number
PageSize int `json:"page_size"` // Page size
Data interface{} `json:"data"` // Data
}
// NewPageResult creates a new pagination result
func NewPageResult(total int64, page *Pagination, data interface{}) *PageResult {
return &PageResult{
Total: total,
Page: page.GetPage(),
PageSize: page.GetPageSize(),
Data: data,
}
}
+120
View File
@@ -0,0 +1,120 @@
package types
import (
"database/sql/driver"
"encoding/json"
"time"
"github.com/google/uuid"
"gorm.io/gorm"
)
// FallbackStrategy represents the fallback strategy type
type FallbackStrategy string
const (
FallbackStrategyFixed FallbackStrategy = "fixed" // Fixed response
FallbackStrategyModel FallbackStrategy = "model" // Model fallback response
)
type SummaryConfig struct {
// Max tokens
MaxTokens int `json:"max_tokens"`
// Repeat penalty
RepeatPenalty float64 `json:"repeat_penalty"`
// TopK
TopK int `json:"top_k"`
// TopP
TopP float64 `json:"top_p"`
// Frequency penalty
FrequencyPenalty float64 `json:"frequency_penalty"`
// Presence penalty
PresencePenalty float64 `json:"presence_penalty"`
// Prompt
Prompt string `json:"prompt"`
// Context template
ContextTemplate string `json:"context_template"`
// No match prefix
NoMatchPrefix string `json:"no_match_prefix"`
// Temperature
Temperature float64 `json:"temperature"`
// Seed
Seed int `json:"seed"`
// Max completion tokens
MaxCompletionTokens int `json:"max_completion_tokens"`
}
// Session represents the session
type Session struct {
// ID
ID string `json:"id" gorm:"type:varchar(36);primaryKey"`
// Title
Title string `json:"title"`
// Description
Description string `json:"description"`
// Tenant ID
TenantID uint `json:"tenant_id" gorm:"index"`
// Strategy configuration
KnowledgeBaseID string `json:"knowledge_base_id"` // 关联的知识库ID
MaxRounds int `json:"max_rounds"` // 多轮保持轮数
EnableRewrite bool `json:"enable_rewrite"` // 多轮改写开关
FallbackStrategy FallbackStrategy `json:"fallback_strategy"` // 兜底策略
FallbackResponse string `json:"fallback_response"` // 固定回复内容
EmbeddingTopK int `json:"embedding_top_k"` // 向量召回TopK
KeywordThreshold float64 `json:"keyword_threshold"` // 关键词召回阈值
VectorThreshold float64 `json:"vector_threshold"` // 向量召回阈值
RerankModelID string `json:"rerank_model_id"` // 排序模型ID
RerankTopK int `json:"rerank_top_k"` // 排序TopK
RerankThreshold float64 `json:"rerank_threshold"` // 排序阈值
SummaryModelID string `json:"summary_model_id"` // 总结模型ID
SummaryParameters *SummaryConfig `json:"summary_parameters" gorm:"type:json"` // 总结模型参数
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
// Association relationship, not stored in the database
Messages []Message `json:"-" gorm:"foreignKey:SessionID"`
}
func (s *Session) BeforeCreate(tx *gorm.DB) (err error) {
s.ID = uuid.New().String()
return nil
}
type StringArray []string
// Value implements the driver.Valuer interface, used to convert StringArray to database value
func (c StringArray) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database value to StringArray
func (c *StringArray) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
// Value implements the driver.Valuer interface, used to convert SummaryConfig to database value
func (c *SummaryConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database value to SummaryConfig
func (c *SummaryConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
+65
View File
@@ -0,0 +1,65 @@
package types
import (
"database/sql/driver"
"encoding/json"
"time"
"gorm.io/gorm"
)
// Tenant represents the tenant
type Tenant struct {
// ID
ID uint `yaml:"id" json:"id" gorm:"primaryKey"`
// Name
Name string `yaml:"name" json:"name"`
// Description
Description string `yaml:"description" json:"description"`
// API key
APIKey string `yaml:"api_key" json:"api_key"`
// Status
Status string `yaml:"status" json:"status" gorm:"default:'active'"`
// Retriever engines
RetrieverEngines RetrieverEngines `yaml:"retriever_engines" json:"retriever_engines" gorm:"type:json"`
// Business
Business string `yaml:"business" json:"business"`
// Storage quota (Bytes), default is 10GB, including vector, original file, text, index, etc.
StorageQuota int64 `yaml:"storage_quota" json:"storage_quota" gorm:"default:10737418240"`
// Storage used (Bytes)
StorageUsed int64 `yaml:"storage_used" json:"storage_used" gorm:"default:0"`
// Creation time
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time
UpdatedAt time.Time `yaml:"updated_at" json:"updated_at"`
// Deletion time
DeletedAt gorm.DeletedAt `yaml:"deleted_at" json:"deleted_at" gorm:"index"`
}
type RetrieverEngines struct {
Engines []RetrieverEngineParams `yaml:"engines" json:"engines" gorm:"type:json"`
}
func (t *Tenant) BeforeCreate(tx *gorm.DB) error {
if t.RetrieverEngines.Engines == nil {
t.RetrieverEngines.Engines = []RetrieverEngineParams{}
}
return nil
}
// Value implements the driver.Valuer interface, used to convert RetrieverEngines to database value
func (c RetrieverEngines) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database value to RetrieverEngines
func (c *RetrieverEngines) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}