Merge upstream main and resolve conflicts

This commit is contained in:
Mao Meng
2026-04-14 14:13:00 +08:00
185 changed files with 13886 additions and 1507 deletions
+11 -9
View File
@@ -49,12 +49,13 @@ type PipelineRequest struct {
Attachments MessageAttachments `json:"-"`
// Misc request-scoped config
TenantID uint64 `json:"-"`
WebSearchEnabled bool `json:"-"`
WebSearchProviderID string `json:"-"` // Resolved from agent config or tenant default
WebFetchEnabled bool `json:"-"` // Auto-fetch full page content for web search results after rerank
WebFetchTopN int `json:"-"` // Max pages to fetch (default 3)
Language string `json:"-"`
TenantID uint64 `json:"-"`
WebSearchEnabled bool `json:"-"`
WebSearchProviderID string `json:"-"` // Resolved from agent config or tenant default
WebSearchMaxResults int `json:"-"` // Resolved from agent config or tenant default
WebFetchEnabled bool `json:"-"` // Auto-fetch full page content for web search results after rerank
WebFetchTopN int `json:"-"` // Max pages to fetch (default 3)
Language string `json:"-"`
}
// QueryIntent represents the classified intent of a user query.
@@ -191,9 +192,10 @@ func (c *ChatManage) Clone() *ChatManage {
Attachments: append(MessageAttachments(nil), c.Attachments...),
TenantID: c.TenantID,
WebSearchEnabled: c.WebSearchEnabled,
WebSearchProviderID: c.WebSearchProviderID,
WebFetchEnabled: c.WebFetchEnabled,
WebFetchTopN: c.WebFetchTopN,
WebSearchProviderID: c.WebSearchProviderID,
WebSearchMaxResults: c.WebSearchMaxResults,
WebFetchEnabled: c.WebFetchEnabled,
WebFetchTopN: c.WebFetchTopN,
Language: c.Language,
},
PipelineState: PipelineState{
+26
View File
@@ -20,6 +20,12 @@ const (
ChunkTypeImageOCR ChunkType = "image_ocr"
// ChunkTypeImageCaption 表示图片描述的 Chunk
ChunkTypeImageCaption ChunkType = "image_caption"
// ChunkTypeVideoFrame 表示视频帧分析内容的 Chunk
ChunkTypeVideoFrame ChunkType = "video_frame"
// ChunkTypeVideoCaption 表示视频整体描述的 Chunk
ChunkTypeVideoCaption ChunkType = "video_caption"
// ChunkTypeVideoASR 表示视频音频转录的 Chunk
ChunkTypeVideoASR ChunkType = "video_asr"
// ChunkTypeSummary 表示摘要类型的 Chunk
ChunkTypeSummary = "summary"
// ChunkTypeEntity 表示实体类型的 Chunk
@@ -95,6 +101,24 @@ type ImageInfo struct {
OCRText string `json:"ocr_text"`
}
// VideoInfo 表示与 Chunk 关联的视频信息
type VideoInfo struct {
// 视频URL
URL string `json:"url" gorm:"type:text"`
// 帧数量
FrameCount int `json:"frame_count"`
// 是否有VLM分析
HasVLMAnalysis bool `json:"has_vlm_analysis"`
// 是否有ASR转录
HasASR bool `json:"has_asr"`
// 视频摘要
VideoSummary string `json:"video_summary"`
// ASR转录文本
ASRText string `json:"asr_text"`
// 帧描述列表
FrameDescriptions []string `json:"frame_descriptions"`
}
// Chunk represents a document chunk
// Chunks are meaningful text segments extracted from original documents
// and are the basic units of knowledge base retrieval
@@ -147,6 +171,8 @@ type Chunk struct {
ContentHash string `json:"content_hash" gorm:"type:varchar(64);index"`
// 图片信息,存储为 JSON
ImageInfo string `json:"image_info" gorm:"type:text"`
// 视频信息,存储为 JSON
VideoInfo string `json:"video_info" gorm:"type:text"`
// Chunk creation time
CreatedAt time.Time `json:"created_at"`
// Chunk last update time
+2
View File
@@ -22,6 +22,8 @@ type ReadResult struct {
Error string
IsAudio bool // true when the result contains raw audio data needing ASR transcription
AudioData []byte // raw audio bytes for ASR processing
IsVideo bool // true when the result contains raw video data needing multimodal processing
VideoData []byte // raw video bytes for video multimodal processing
}
// ImageRef represents an image reference extracted from the document.
+21 -6
View File
@@ -13,6 +13,7 @@ const (
TypeKnowledgeMove = "knowledge:move" // 知识移动任务
TypeDataTableSummary = "datatable:summary" // 表格摘要任务
TypeImageMultimodal = "image:multimodal" // 图片多模态处理任务(OCR + VLM Caption)
TypeVideoMultimodal = "video:multimodal" // 视频多模态处理任务(抽帧 + VLM + ASR)
TypeManualProcess = "manual:process" // 手工知识更新任务(cleanup + 重新索引)
TypeDataSourceSync = "datasource:sync" // 数据源同步任务
)
@@ -121,7 +122,7 @@ type KnowledgeMoveProgress struct {
SourceKBID string `json:"source_kb_id"`
TargetKBID string `json:"target_kb_id"`
Status KBCloneTaskStatus `json:"status"`
Progress int `json:"progress"` // 0-100
Progress int `json:"progress"` // 0-100
Total int `json:"total"` // 总知识数
Processed int `json:"processed"` // 已处理数
Failed int `json:"failed"` // 失败数
@@ -138,8 +139,8 @@ type ManualProcessPayload struct {
TenantID uint64 `json:"tenant_id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
Content string `json:"content"` // cleaned markdown content
NeedCleanup bool `json:"need_cleanup"` // true for update, false for create
Content string `json:"content"` // cleaned markdown content
NeedCleanup bool `json:"need_cleanup"` // true for update, false for create
}
// ImageMultimodalPayload represents the image multimodal processing task payload.
@@ -147,14 +148,28 @@ type ImageMultimodalPayload struct {
TenantID uint64 `json:"tenant_id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
ChunkID string `json:"chunk_id"` // parent text chunk
ImageURL string `json:"image_url"` // provider:// URL (e.g. local://..., minio://...)
ImageLocalPath string `json:"image_local_path"` // deprecated: kept for backward compat with in-flight tasks
ChunkID string `json:"chunk_id"` // parent text chunk
ImageURL string `json:"image_url"` // provider:// URL (e.g. local://..., minio://...)
ImageLocalPath string `json:"image_local_path"` // deprecated: kept for backward compat with in-flight tasks
EnableOCR bool `json:"enable_ocr"`
EnableCaption bool `json:"enable_caption"`
Language string `json:"language,omitempty"` // Request locale for {{language}} in prompt templates
}
// VideoMultimodalPayload represents the video multimodal processing task payload.
type VideoMultimodalPayload struct {
TenantID uint64 `json:"tenant_id"`
KnowledgeID string `json:"knowledge_id"`
KnowledgeBaseID string `json:"knowledge_base_id"`
ChunkID string `json:"chunk_id"` // parent text chunk
VideoURL string `json:"video_url"` // provider:// URL (e.g. local://..., minio://...)
VideoLocalPath string `json:"video_local_path"` // deprecated: kept for backward compat with in-flight tasks
EnableVLM bool `json:"enable_vlm"` // enable VLM frame analysis
EnableASR bool `json:"enable_asr"` // enable ASR audio transcription
Language string `json:"language,omitempty"` // Request locale for {{language}} in prompt templates
MaxFrames int `json:"max_frames,omitempty"` // optional: max frames to extract, 0 = no limit
}
// KBCloneTaskStatus represents the status of a knowledge base clone task
type KBCloneTaskStatus string
+2
View File
@@ -28,6 +28,8 @@ type TenantService interface {
SearchTenants(ctx context.Context, keyword string, tenantID uint64, page, pageSize int) ([]*types.Tenant, int64, error)
// GetTenantByIDForUser gets a tenant by ID with permission check
GetTenantByIDForUser(ctx context.Context, tenantID uint64, userID string) (*types.Tenant, error)
// GetTenantByAPIKey gets a tenant by API key
GetDocreaderCredentials(ctx context.Context) *types.DocreaderCredentials
}
// TenantRepository defines the tenant repository interface
+18
View File
@@ -6,6 +6,22 @@ import (
"github.com/Tencent/WeKnora/internal/types"
)
// VectorStoreService defines the service interface for vector store management.
// Tenant isolation is enforced by the handler layer (getOwnedStore pattern).
type VectorStoreService interface {
// CreateStore validates and creates a new vector store.
CreateStore(ctx context.Context, store *types.VectorStore) error
// UpdateStore updates an existing vector store (name only).
UpdateStore(ctx context.Context, store *types.VectorStore) error
// DeleteStore deletes a vector store by tenant + id.
DeleteStore(ctx context.Context, tenantID uint64, id string) error
// TestConnection tests connectivity to a vector database.
// Returns the detected server version on success (e.g., "7.10.1"), empty string if unknown.
TestConnection(ctx context.Context, engineType types.RetrieverEngineType, config types.ConnectionConfig) (string, error)
// SaveDetectedVersion updates the connection_config.version for a stored vector store.
SaveDetectedVersion(ctx context.Context, store *types.VectorStore, version string) error
}
// VectorStoreRepository defines the repository interface for VectorStore CRUD.
type VectorStoreRepository interface {
// Create creates a new vector store
@@ -16,6 +32,8 @@ type VectorStoreRepository interface {
List(ctx context.Context, tenantID uint64) ([]*types.VectorStore, error)
// Update updates a vector store (only mutable fields: name)
Update(ctx context.Context, store *types.VectorStore) error
// UpdateConnectionConfig updates only the connection_config column
UpdateConnectionConfig(ctx context.Context, store *types.VectorStore) error
// Delete soft-deletes a vector store
Delete(ctx context.Context, tenantID uint64, id string) error
// ExistsByEndpointAndIndex checks if a store with the same endpoint and index already exists
+15
View File
@@ -0,0 +1,15 @@
package interfaces
import (
"context"
"github.com/Tencent/WeKnora/internal/types"
)
// WeKnoraCloudService 处理 WeKnoraCloud 厂商的初始化逻辑
type WeKnoraCloudService interface {
Initialize(ctx context.Context, appID, appSecret string) (*types.InitializeResult, error)
// CheckStatus 检查当前租户的 WeKnoraCloud 凭证是否可正常解密
// needsReinit=true 表示加密状态已损坏(salt 变更等),需要用户重新填写凭证
CheckStatus(ctx context.Context) (*types.WeKnoraCloudStatusResult, error)
}
+18 -3
View File
@@ -12,9 +12,24 @@ 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")
if value == nil {
*j = nil
return nil
}
var bytes []byte
switch v := value.(type) {
case []byte:
bytes = v
case string:
bytes = []byte(v)
default:
return errors.New("type assertion to []byte or string failed")
}
if len(bytes) == 0 {
*j = nil
return nil
}
result := json.RawMessage{}
+2 -2
View File
@@ -152,7 +152,7 @@ func (c ChunkingConfig) ResolveParserEngine(fileType string) string {
// StorageProviderConfig stores the KB-level storage provider selection.
// Credentials are managed at the tenant level (StorageEngineConfig).
type StorageProviderConfig struct {
Provider string `yaml:"provider" json:"provider"` // "local", "minio", "cos", "tos"
Provider string `yaml:"provider" json:"provider"` // "local", "minio", "cos", "tos", "s3", "oss"
}
func (c StorageProviderConfig) Value() (driver.Value, error) {
@@ -266,7 +266,7 @@ func InferStorageFromFilePath(filePath string) string {
// e.g. "minio://bucket/key" → "minio", "local://tenant/file.pdf" → "local"
// Returns "" if the path does not use a known provider scheme.
func ParseProviderScheme(filePath string) string {
for _, provider := range []string{"local", "minio", "cos", "tos", "s3"} {
for _, provider := range []string{"local", "minio", "cos", "tos", "s3", "oss"} {
if strings.HasPrefix(filePath, provider+"://") {
return provider
}
+4
View File
@@ -50,6 +50,7 @@ const (
ModelSourceOpenRouter ModelSource = "openrouter" // OpenRouter model
ModelSourceNvidia ModelSource = "nvidia" // NVIDIA model
ModelSourceNovita ModelSource = "novita" // Novita AI model
ModelSourceAzureOpenAI ModelSource = "azure_openai" // Azure OpenAI model
)
// EmbeddingParameters represents the embedding parameters for a model
@@ -67,6 +68,9 @@ type ModelParameters struct {
Provider string `yaml:"provider" json:"provider"` // Provider identifier: openai, aliyun, zhipu, generic
ExtraConfig map[string]string `yaml:"extra_config" json:"extra_config"` // Provider-specific configuration
SupportsVision bool `yaml:"supports_vision" json:"supports_vision"` // Whether the model accepts image/multimodal input
// WeKnoraCloud 厂商专用凭证
AppID string `yaml:"app_id,omitempty" json:"app_id,omitempty"`
AppSecret string `yaml:"app_secret,omitempty" json:"app_secret,omitempty"` // AES-256 加密存储,实际承载上游 API Key
}
// Model represents the AI model
+24 -3
View File
@@ -233,7 +233,11 @@ func (c *ConversationConfig) Scan(value interface{}) error {
// ParserEngineConfig holds tenant-level overrides for document parser engines (e.g. MinerU endpoint, API key).
// These values take precedence over environment variables when parsing documents.
type ParserEngineConfig struct {
DocReaderAddr string `json:"docreader_addr"` // 文档解析服务地址
DocReaderAddr string `json:"docreader_addr"` // 文档解析服务地址
// docreader 凭证
DocreaderAppID string `json:"docreader_app_id,omitempty"`
DocreaderAPIKey string `json:"docreader_api_key,omitempty"`
MinerUEndpoint string `json:"mineru_endpoint"` // MinerU 自建服务端点
MinerUAPIKey string `json:"mineru_api_key"` // MinerU 云 API Key
@@ -259,6 +263,9 @@ func (c *ParserEngineConfig) ToOverridesMap() map[string]string {
return nil
}
m := make(map[string]string)
if c.DocReaderAddr != "" {
m["docreader_addr"] = c.DocReaderAddr
}
if c.MinerUEndpoint != "" {
m["mineru_endpoint"] = c.MinerUEndpoint
}
@@ -321,15 +328,16 @@ func (c *ParserEngineConfig) Scan(value interface{}) error {
return json.Unmarshal(b, c)
}
// StorageEngineConfig holds tenant-level storage engine parameters for Local, MinIO, COS, TOS, and S3.
// StorageEngineConfig holds tenant-level storage engine parameters for Local, MinIO, COS, TOS, S3, and OSS.
// Knowledge bases select which provider to use; parameters are read from here.
type StorageEngineConfig struct {
DefaultProvider string `json:"default_provider"` // "local", "minio", "cos", "tos", "s3"
DefaultProvider string `json:"default_provider"` // "local", "minio", "cos", "tos", "s3", "oss"
Local *LocalEngineConfig `json:"local,omitempty"`
MinIO *MinIOEngineConfig `json:"minio,omitempty"`
COS *COSEngineConfig `json:"cos,omitempty"`
TOS *TOSEngineConfig `json:"tos,omitempty"`
S3 *S3EngineConfig `json:"s3,omitempty"`
OSS *OSSEngineConfig `json:"oss,omitempty"`
}
// LocalEngineConfig is for local file system storage (single-machine deployment only).
@@ -379,6 +387,19 @@ type S3EngineConfig struct {
PathPrefix string `json:"path_prefix"`
}
// OSSEngineConfig is for Alibaba Cloud OSS (对象存储服务).
type OSSEngineConfig struct {
Endpoint string `json:"endpoint"`
Region string `json:"region"`
AccessKey string `json:"access_key"`
SecretKey string `json:"secret_key"`
BucketName string `json:"bucket_name"`
PathPrefix string `json:"path_prefix"`
UseTempBucket bool `json:"use_temp_bucket"`
TempBucketName string `json:"temp_bucket_name"`
TempRegion string `json:"temp_region"`
}
// Value implements the driver.Valuer interface for StorageEngineConfig
func (c *StorageEngineConfig) Value() (driver.Value, error) {
if c == nil {
+266
View File
@@ -4,6 +4,7 @@ import (
"database/sql/driver"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/errors"
@@ -12,6 +13,18 @@ import (
"gorm.io/gorm"
)
// EnvStoreIDPrefix is the prefix for virtual env store IDs.
const EnvStoreIDPrefix = "__env_"
// IsEnvStoreID checks if the given ID is an env store virtual ID.
func IsEnvStoreID(id string) bool {
return strings.HasPrefix(id, EnvStoreIDPrefix)
}
// EnvLookupFunc is a function type for looking up environment variables.
// In production: os.Getenv, in tests: custom lookup function.
type EnvLookupFunc func(string) string
// VectorStore represents a configured vector database instance for a tenant.
// Each tenant can register multiple VectorStore entries (even of the same engine type)
// to support multi-store scenarios (e.g., ES-hot + ES-warm clusters).
@@ -100,6 +113,9 @@ type ConnectionConfig struct {
Scheme string `yaml:"scheme" json:"scheme,omitempty"`
// Postgres
UseDefaultConnection bool `yaml:"use_default_connection" json:"use_default_connection,omitempty"`
// Version is the detected server version (e.g., "7.10.1", "16.2", "1.12.6").
// Auto-populated by TestConnection on successful connectivity check.
Version string `yaml:"version" json:"version,omitempty"`
}
// Value implements the driver.Valuer interface.
@@ -237,3 +253,253 @@ func (c IndexConfig) GetIndexNameOrDefault(engineType RetrieverEngineType) strin
return c.IndexName
}
}
// ---------------------------------------------------------------------------
// VectorStoreResponse — API response DTO
// ---------------------------------------------------------------------------
// VectorStoreResponse is the API response DTO for vector store.
// Wraps VectorStore with additional metadata (source, readonly).
type VectorStoreResponse struct {
VectorStore
Source string `json:"source"` // "env" or "user"
ReadOnly bool `json:"readonly"` // env stores are read-only
}
// NewVectorStoreResponse creates a response DTO from a VectorStore
// with sensitive fields masked.
func NewVectorStoreResponse(store *VectorStore, source string, readonly bool) VectorStoreResponse {
masked := *store
masked.ConnectionConfig = store.ConnectionConfig.MaskSensitiveFields()
return VectorStoreResponse{
VectorStore: masked,
Source: source,
ReadOnly: readonly,
}
}
// ---------------------------------------------------------------------------
// VectorStore type metadata — for /types endpoint
// ---------------------------------------------------------------------------
// VectorStoreTypeInfo describes a supported engine type and its configuration schema.
type VectorStoreTypeInfo struct {
Type string `json:"type"`
DisplayName string `json:"display_name"`
ConnectionFields []VectorStoreFieldInfo `json:"connection_fields"`
IndexFields []VectorStoreFieldInfo `json:"index_fields,omitempty"`
}
// VectorStoreFieldInfo describes a single configuration field.
type VectorStoreFieldInfo struct {
Name string `json:"name"`
Type string `json:"type"` // "string", "number", "boolean"
Required bool `json:"required"`
Sensitive bool `json:"sensitive,omitempty"`
Default any `json:"default,omitempty"`
Description string `json:"description,omitempty"`
}
// GetVectorStoreTypes returns metadata for all supported engine types.
func GetVectorStoreTypes() []VectorStoreTypeInfo {
return []VectorStoreTypeInfo{
{
Type: "elasticsearch",
DisplayName: "Elasticsearch (Keywords + Vector)",
ConnectionFields: []VectorStoreFieldInfo{
{Name: "addr", Type: "string", Required: true, Description: "Elasticsearch URL (e.g., http://localhost:9200)"},
{Name: "username", Type: "string", Required: false},
{Name: "password", Type: "string", Required: false, Sensitive: true},
},
IndexFields: []VectorStoreFieldInfo{
{Name: "index_name", Type: "string", Required: false, Default: "xwrag_default"},
{Name: "number_of_shards", Type: "number", Required: false},
{Name: "number_of_replicas", Type: "number", Required: false},
},
},
{
Type: "postgres",
DisplayName: "PostgreSQL (Keywords + Vector)",
ConnectionFields: []VectorStoreFieldInfo{
{Name: "use_default_connection", Type: "boolean", Required: false, Default: true,
Description: "Use the application's default database connection"},
{Name: "addr", Type: "string", Required: false,
Description: "PostgreSQL connection string (required if use_default_connection is false)"},
{Name: "username", Type: "string", Required: false},
{Name: "password", Type: "string", Required: false, Sensitive: true},
},
},
{
Type: "qdrant",
DisplayName: "Qdrant (Keywords + Vector)",
ConnectionFields: []VectorStoreFieldInfo{
{Name: "host", Type: "string", Required: true, Description: "Qdrant host"},
{Name: "port", Type: "number", Required: false, Default: 6334},
{Name: "api_key", Type: "string", Required: false, Sensitive: true},
{Name: "use_tls", Type: "boolean", Required: false, Default: false},
},
IndexFields: []VectorStoreFieldInfo{
{Name: "collection_prefix", Type: "string", Required: false, Default: "weknora_embeddings"},
},
},
{
Type: "milvus",
DisplayName: "Milvus (Keywords + Vector)",
ConnectionFields: []VectorStoreFieldInfo{
{Name: "addr", Type: "string", Required: true, Description: "Milvus address (e.g., localhost:19530)"},
{Name: "username", Type: "string", Required: false},
{Name: "password", Type: "string", Required: false, Sensitive: true},
},
IndexFields: []VectorStoreFieldInfo{
{Name: "collection_name", Type: "string", Required: false, Default: "weknora_embeddings"},
},
},
{
Type: "weaviate",
DisplayName: "Weaviate (Keywords + Vector)",
ConnectionFields: []VectorStoreFieldInfo{
{Name: "host", Type: "string", Required: true, Description: "Weaviate host (e.g., weaviate:8080)"},
{Name: "grpc_address", Type: "string", Required: false, Default: "weaviate:50051"},
{Name: "scheme", Type: "string", Required: false, Default: "http"},
{Name: "api_key", Type: "string", Required: false, Sensitive: true},
},
IndexFields: []VectorStoreFieldInfo{
{Name: "collection_prefix", Type: "string", Required: false, Default: "WeKnora"},
},
},
{
Type: "sqlite",
DisplayName: "SQLite (Keywords + Vector)",
ConnectionFields: []VectorStoreFieldInfo{},
},
}
}
// ---------------------------------------------------------------------------
// BuildEnvVectorStores — virtual stores from RETRIEVE_DRIVER env var
// ---------------------------------------------------------------------------
// BuildEnvVectorStores builds virtual VectorStore entries from RETRIEVE_DRIVER.
// Returns []VectorStore (not VectorStoreResponse) so that business logic (e.g.,
// duplicate checking) can use them directly. API responses should wrap them
// via NewVectorStoreResponse.
//
// Pure function — does not call os.Getenv directly.
//
// Usage:
//
// types.BuildEnvVectorStores(os.Getenv("RETRIEVE_DRIVER"), os.Getenv)
func BuildEnvVectorStores(retrieveDriver string, envLookup EnvLookupFunc) []VectorStore {
if retrieveDriver == "" {
return nil
}
drivers := strings.Split(retrieveDriver, ",")
var stores []VectorStore
for _, driver := range drivers {
driver = strings.TrimSpace(driver)
if driver == "" {
continue
}
store := buildEnvStoreForDriver(driver, envLookup)
if store != nil {
stores = append(stores, *store)
}
}
return stores
}
// FindEnvVectorStore finds a specific env store by its virtual ID.
func FindEnvVectorStore(retrieveDriver string, envLookup EnvLookupFunc, id string) *VectorStore {
for _, s := range BuildEnvVectorStores(retrieveDriver, envLookup) {
if s.ID == id {
return &s
}
}
return nil
}
func buildEnvStoreForDriver(driver string, envLookup EnvLookupFunc) *VectorStore {
switch driver {
case "postgres":
return &VectorStore{
ID: "__env_postgres__",
Name: "postgres (env)",
EngineType: PostgresRetrieverEngineType,
ConnectionConfig: ConnectionConfig{
UseDefaultConnection: true,
},
}
case "sqlite":
return &VectorStore{
ID: "__env_sqlite__",
Name: "sqlite (env)",
EngineType: SQLiteRetrieverEngineType,
}
case "elasticsearch_v8":
return &VectorStore{
ID: "__env_elasticsearch_v8__",
Name: "elasticsearch v8 (env)",
EngineType: ElasticsearchRetrieverEngineType,
ConnectionConfig: ConnectionConfig{
Addr: envLookup("ELASTICSEARCH_ADDR"),
Username: envLookup("ELASTICSEARCH_USERNAME"),
Password: envLookup("ELASTICSEARCH_PASSWORD"),
},
IndexConfig: IndexConfig{
IndexName: envLookup("ELASTICSEARCH_INDEX"),
},
}
case "elasticsearch_v7":
return &VectorStore{
ID: "__env_elasticsearch_v7__",
Name: "elasticsearch v7 (env)",
EngineType: ElasticsearchRetrieverEngineType,
ConnectionConfig: ConnectionConfig{
Addr: envLookup("ELASTICSEARCH_ADDR"),
Username: envLookup("ELASTICSEARCH_USERNAME"),
Password: envLookup("ELASTICSEARCH_PASSWORD"),
},
IndexConfig: IndexConfig{
IndexName: envLookup("ELASTICSEARCH_INDEX"),
},
}
case "qdrant":
return &VectorStore{
ID: "__env_qdrant__",
Name: "qdrant (env)",
EngineType: QdrantRetrieverEngineType,
ConnectionConfig: ConnectionConfig{
Host: envLookup("QDRANT_HOST"),
APIKey: envLookup("QDRANT_API_KEY"),
},
}
case "milvus":
return &VectorStore{
ID: "__env_milvus__",
Name: "milvus (env)",
EngineType: MilvusRetrieverEngineType,
ConnectionConfig: ConnectionConfig{
Addr: envLookup("MILVUS_ADDRESS"),
Username: envLookup("MILVUS_USERNAME"),
Password: envLookup("MILVUS_PASSWORD"),
},
}
case "weaviate":
return &VectorStore{
ID: "__env_weaviate__",
Name: "weaviate (env)",
EngineType: WeaviateRetrieverEngineType,
ConnectionConfig: ConnectionConfig{
Host: envLookup("WEAVIATE_HOST"),
GrpcAddress: envLookup("WEAVIATE_GRPC_ADDRESS"),
Scheme: envLookup("WEAVIATE_SCHEME"),
APIKey: envLookup("WEAVIATE_API_KEY"),
},
}
default:
return nil
}
}
+239
View File
@@ -10,6 +10,245 @@ import (
"gorm.io/gorm"
)
// ---------------------------------------------------------------------------
// PR2 additions: env store builder, response DTO, types metadata
// ---------------------------------------------------------------------------
// mockEnvLookup creates a simple env lookup function from a map.
func mockEnvLookup(env map[string]string) EnvLookupFunc {
return func(key string) string {
return env[key]
}
}
func TestIsEnvStoreID(t *testing.T) {
tests := []struct {
name string
id string
expected bool
}{
{"env postgres ID", "__env_postgres__", true},
{"env elasticsearch ID", "__env_elasticsearch_v8__", true},
{"env prefix only", "__env_", true},
{"UUID ID", "550e8400-e29b-41d4-a716-446655440000", false},
{"empty string", "", false},
{"similar but not prefix", "_env_postgres__", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equal(t, tt.expected, IsEnvStoreID(tt.id))
})
}
}
func TestBuildEnvVectorStores(t *testing.T) {
envMap := map[string]string{
"ELASTICSEARCH_ADDR": "http://es:9200",
"ELASTICSEARCH_USERNAME": "elastic",
"ELASTICSEARCH_PASSWORD": "secret",
"ELASTICSEARCH_INDEX": "my_index",
"QDRANT_HOST": "qdrant-host",
"QDRANT_API_KEY": "qd-key",
"MILVUS_ADDRESS": "milvus:19530",
"WEAVIATE_HOST": "weaviate:8080",
}
lookup := mockEnvLookup(envMap)
t.Run("empty RETRIEVE_DRIVER returns nil", func(t *testing.T) {
stores := BuildEnvVectorStores("", lookup)
assert.Nil(t, stores)
})
t.Run("single driver postgres", func(t *testing.T) {
stores := BuildEnvVectorStores("postgres", lookup)
require.Len(t, stores, 1)
assert.Equal(t, "__env_postgres__", stores[0].ID)
assert.Equal(t, "postgres (env)", stores[0].Name)
assert.Equal(t, PostgresRetrieverEngineType, stores[0].EngineType)
assert.True(t, stores[0].ConnectionConfig.UseDefaultConnection)
})
t.Run("multiple drivers", func(t *testing.T) {
stores := BuildEnvVectorStores("postgres,elasticsearch_v8", lookup)
require.Len(t, stores, 2)
assert.Equal(t, "__env_postgres__", stores[0].ID)
assert.Equal(t, "__env_elasticsearch_v8__", stores[1].ID)
assert.Equal(t, "http://es:9200", stores[1].ConnectionConfig.Addr)
assert.Equal(t, "elastic", stores[1].ConnectionConfig.Username)
assert.Equal(t, "secret", stores[1].ConnectionConfig.Password) // unmasked
assert.Equal(t, "my_index", stores[1].IndexConfig.IndexName)
})
t.Run("env store retains raw password (not masked)", func(t *testing.T) {
stores := BuildEnvVectorStores("elasticsearch_v8", lookup)
require.Len(t, stores, 1)
assert.Equal(t, "secret", stores[0].ConnectionConfig.Password)
})
t.Run("unknown driver is skipped", func(t *testing.T) {
stores := BuildEnvVectorStores("postgres,unknown_db", lookup)
require.Len(t, stores, 1)
assert.Equal(t, "__env_postgres__", stores[0].ID)
})
t.Run("whitespace trimmed", func(t *testing.T) {
stores := BuildEnvVectorStores(" postgres , elasticsearch_v8 ", lookup)
require.Len(t, stores, 2)
})
t.Run("all supported drivers", func(t *testing.T) {
stores := BuildEnvVectorStores("postgres,sqlite,elasticsearch_v8,elasticsearch_v7,qdrant,milvus,weaviate", lookup)
require.Len(t, stores, 7)
ids := make([]string, len(stores))
for i, s := range stores {
ids[i] = s.ID
}
assert.Contains(t, ids, "__env_postgres__")
assert.Contains(t, ids, "__env_sqlite__")
assert.Contains(t, ids, "__env_elasticsearch_v8__")
assert.Contains(t, ids, "__env_elasticsearch_v7__")
assert.Contains(t, ids, "__env_qdrant__")
assert.Contains(t, ids, "__env_milvus__")
assert.Contains(t, ids, "__env_weaviate__")
})
t.Run("qdrant env store", func(t *testing.T) {
stores := BuildEnvVectorStores("qdrant", lookup)
require.Len(t, stores, 1)
assert.Equal(t, "qdrant-host", stores[0].ConnectionConfig.Host)
assert.Equal(t, "qd-key", stores[0].ConnectionConfig.APIKey)
})
t.Run("milvus env store", func(t *testing.T) {
stores := BuildEnvVectorStores("milvus", lookup)
require.Len(t, stores, 1)
assert.Equal(t, "milvus:19530", stores[0].ConnectionConfig.Addr)
})
t.Run("weaviate env store", func(t *testing.T) {
stores := BuildEnvVectorStores("weaviate", lookup)
require.Len(t, stores, 1)
assert.Equal(t, "weaviate:8080", stores[0].ConnectionConfig.Host)
})
}
func TestFindEnvVectorStore(t *testing.T) {
lookup := mockEnvLookup(map[string]string{})
t.Run("found", func(t *testing.T) {
store := FindEnvVectorStore("postgres", lookup, "__env_postgres__")
require.NotNil(t, store)
assert.Equal(t, "__env_postgres__", store.ID)
})
t.Run("not found", func(t *testing.T) {
store := FindEnvVectorStore("postgres", lookup, "__env_unknown__")
assert.Nil(t, store)
})
t.Run("empty driver returns nil", func(t *testing.T) {
store := FindEnvVectorStore("", lookup, "__env_postgres__")
assert.Nil(t, store)
})
}
func TestNewVectorStoreResponse(t *testing.T) {
store := &VectorStore{
ID: "test-id",
Name: "test-store",
EngineType: ElasticsearchRetrieverEngineType,
ConnectionConfig: ConnectionConfig{
Addr: "http://es:9200",
Password: "secret",
APIKey: "my-api-key",
},
}
t.Run("masks sensitive fields", func(t *testing.T) {
resp := NewVectorStoreResponse(store, "user", false)
assert.Equal(t, "***", resp.ConnectionConfig.Password)
assert.Equal(t, "***", resp.ConnectionConfig.APIKey)
assert.Equal(t, "http://es:9200", resp.ConnectionConfig.Addr) // non-sensitive preserved
})
t.Run("preserves source and readonly", func(t *testing.T) {
resp := NewVectorStoreResponse(store, "env", true)
assert.Equal(t, "env", resp.Source)
assert.True(t, resp.ReadOnly)
})
t.Run("does not mutate original store", func(t *testing.T) {
_ = NewVectorStoreResponse(store, "user", false)
assert.Equal(t, "secret", store.ConnectionConfig.Password)
assert.Equal(t, "my-api-key", store.ConnectionConfig.APIKey)
})
t.Run("empty sensitive fields not masked to ***", func(t *testing.T) {
noSecret := &VectorStore{
ID: "test-id",
ConnectionConfig: ConnectionConfig{Addr: "http://es:9200"},
}
resp := NewVectorStoreResponse(noSecret, "user", false)
assert.Equal(t, "", resp.ConnectionConfig.Password)
assert.Equal(t, "", resp.ConnectionConfig.APIKey)
})
}
func TestGetVectorStoreTypes(t *testing.T) {
types := GetVectorStoreTypes()
t.Run("returns 6 engine types", func(t *testing.T) {
assert.Len(t, types, 6)
})
t.Run("type names match engine constants", func(t *testing.T) {
typeNames := make([]string, len(types))
for i, typ := range types {
typeNames[i] = typ.Type
}
assert.Contains(t, typeNames, "elasticsearch")
assert.Contains(t, typeNames, "postgres")
assert.Contains(t, typeNames, "qdrant")
assert.Contains(t, typeNames, "milvus")
assert.Contains(t, typeNames, "weaviate")
assert.Contains(t, typeNames, "sqlite")
})
t.Run("elasticsearch has connection and index fields", func(t *testing.T) {
var esType VectorStoreTypeInfo
for _, typ := range types {
if typ.Type == "elasticsearch" {
esType = typ
break
}
}
assert.NotEmpty(t, esType.ConnectionFields)
assert.NotEmpty(t, esType.IndexFields)
// Check sensitive field marking
var passwordField VectorStoreFieldInfo
for _, f := range esType.ConnectionFields {
if f.Name == "password" {
passwordField = f
break
}
}
assert.True(t, passwordField.Sensitive)
})
t.Run("sqlite has no connection fields", func(t *testing.T) {
var sqliteType VectorStoreTypeInfo
for _, typ := range types {
if typ.Type == "sqlite" {
sqliteType = typ
break
}
}
assert.Empty(t, sqliteType.ConnectionFields)
})
}
// testAESKey is a 32-byte key for testing AES-GCM encryption.
const testAESKey = "01234567890123456789012345678901"
+16
View File
@@ -18,6 +18,8 @@ const (
WebSearchProviderTypeGoogle WebSearchProviderType = "google"
WebSearchProviderTypeDuckDuckGo WebSearchProviderType = "duckduckgo"
WebSearchProviderTypeTavily WebSearchProviderType = "tavily"
WebSearchProviderTypeOllama WebSearchProviderType = "ollama"
WebSearchProviderTypeBaidu WebSearchProviderType = "baidu"
)
// WebSearchProviderEntity represents a configured web search provider instance for a tenant.
@@ -153,5 +155,19 @@ func GetWebSearchProviderTypes() []WebSearchProviderTypeInfo {
Description: "Tavily Search API (requires API key)",
DocsURL: "https://tavily.com/",
},
{
ID: "ollama",
Name: "Ollama Web Search",
RequiresAPIKey: true,
Description: "Ollama Cloud web search (requires Ollama API key)",
DocsURL: "https://docs.ollama.com/capabilities/web-search",
},
{
ID: "baidu",
Name: "Baidu",
RequiresAPIKey: true,
Description: "Baidu AI Search (requires API key from Baidu Cloud)",
DocsURL: "https://cloud.baidu.com/doc/AppBuilder/s/qlvEcai0p",
},
}
}
+25
View File
@@ -0,0 +1,25 @@
package types
// WeKnoraCloudStatusResult 状态检查结果
type WeKnoraCloudStatusResult struct {
HasModels bool `json:"has_models"` // 是否已配置 WeKnoraCloud 模型
NeedsReinit bool `json:"needs_reinit"` // 是否需要重新初始化(凭证损坏)
Reason string `json:"reason,omitempty"` // 需要重新初始化的原因
}
// InitializeResult 返回每个模型的操作结果
type InitializeResult struct {
Models []ModelAction `json:"models"`
}
// ModelAction 单个模型的操作结果
type ModelAction struct {
Name string `json:"name"`
Type string `json:"type"`
Action string `json:"action"` // "created" | "updated"
}
type DocreaderCredentials struct {
AppID string
APIKey string
}