feat: Added web page for configuring model information

This commit is contained in:
wizardchen
2025-08-10 17:04:39 +08:00
committed by lyingbug
parent 4498442fcc
commit bdabed6bfa
43 changed files with 5689 additions and 338 deletions
+52 -1
View File
@@ -19,6 +19,7 @@ import (
"github.com/Tencent/WeKnora/internal/application/service/retriever"
"github.com/Tencent/WeKnora/internal/config"
werrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/utils"
@@ -105,6 +106,28 @@ func (s *knowledgeService) CreateKnowledgeFromFile(ctx context.Context,
return nil, err
}
// 检查多模态配置完整性 - 只在图片文件时校验
// 检查是否为图片文件
if !IsImageType(getFileType(file.Filename)) {
logger.Info(ctx, "Non-image file with multimodal enabled, skipping COS/VLM validation")
} else {
// 检查COS配置
if kb.COSConfig.SecretID == "" || kb.COSConfig.SecretKey == "" ||
kb.COSConfig.Region == "" || kb.COSConfig.BucketName == "" ||
kb.COSConfig.AppID == "" {
logger.Error(ctx, "COS configuration incomplete for image multimodal processing")
return nil, werrors.NewBadRequestError("上传图片文件需要完整的COS配置信息")
}
// 检查VLM配置
if kb.VLMConfig.ModelName == "" || kb.VLMConfig.BaseURL == "" {
logger.Error(ctx, "VLM configuration incomplete for image multimodal processing")
return nil, werrors.NewBadRequestError("上传图片文件需要完整的VLM配置信息")
}
logger.Info(ctx, "Image multimodal configuration validation passed")
}
// Validate file type
logger.Infof(ctx, "Checking file type: %s", file.Filename)
if !isValidFileType(file.Filename) {
@@ -647,6 +670,20 @@ func (s *knowledgeService) processDocument(ctx context.Context,
ChunkOverlap: int32(kb.ChunkingConfig.ChunkOverlap),
Separators: kb.ChunkingConfig.Separators,
EnableMultimodal: enableMultimodel,
CosConfig: &proto.COSConfig{
SecretId: kb.COSConfig.SecretID,
SecretKey: kb.COSConfig.SecretKey,
Region: kb.COSConfig.Region,
BucketName: kb.COSConfig.BucketName,
AppId: kb.COSConfig.AppID,
PathPrefix: kb.COSConfig.PathPrefix,
},
VlmConfig: &proto.VLMConfig{
ModelName: kb.VLMConfig.ModelName,
BaseUrl: kb.VLMConfig.BaseURL,
ApiKey: kb.VLMConfig.APIKey,
InterfaceType: kb.VLMConfig.InterfaceType,
},
},
RequestId: ctx.Value(types.RequestIDContextKey).(string),
})
@@ -687,6 +724,20 @@ func (s *knowledgeService) processDocumentFromURL(ctx context.Context,
ChunkOverlap: int32(kb.ChunkingConfig.ChunkOverlap),
Separators: kb.ChunkingConfig.Separators,
EnableMultimodal: enableMultimodel,
CosConfig: &proto.COSConfig{
SecretId: kb.COSConfig.SecretID,
SecretKey: kb.COSConfig.SecretKey,
Region: kb.COSConfig.Region,
BucketName: kb.COSConfig.BucketName,
AppId: kb.COSConfig.AppID,
PathPrefix: kb.COSConfig.PathPrefix,
},
VlmConfig: &proto.VLMConfig{
ModelName: kb.VLMConfig.ModelName,
BaseUrl: kb.VLMConfig.BaseURL,
ApiKey: kb.VLMConfig.APIKey,
InterfaceType: kb.VLMConfig.InterfaceType,
},
},
RequestId: ctx.Value(types.RequestIDContextKey).(string),
})
@@ -1145,7 +1196,7 @@ func (s *knowledgeService) getSummary(ctx context.Context,
chunkContents = chunkContents + imageAnnotations
}
if len(chunkContents) < 30 {
if len(chunkContents) < 300 {
return chunkContents, nil
}
@@ -47,7 +47,9 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context,
kb *types.KnowledgeBase,
) (*types.KnowledgeBase, error) {
// Generate UUID and set creation timestamps
kb.ID = uuid.New().String()
if kb.ID == "" {
kb.ID = uuid.New().String()
}
kb.CreatedAt = time.Now()
kb.TenantID = ctx.Value(types.TenantIDContextKey).(uint)
kb.UpdatedAt = time.Now()
@@ -245,6 +247,9 @@ func (s *knowledgeBaseService) CopyKnowledgeBase(ctx context.Context,
ImageProcessingConfig: sourceKB.ImageProcessingConfig,
EmbeddingModelID: sourceKB.EmbeddingModelID,
SummaryModelID: sourceKB.SummaryModelID,
RerankModelID: sourceKB.RerankModelID,
VLMModelID: sourceKB.VLMModelID,
COSConfig: sourceKB.COSConfig,
}
if err := s.repo.CreateKnowledgeBase(ctx, targetKB); err != nil {
return nil, nil, err
@@ -144,6 +144,7 @@ func (s *TestDataService) initKnowledgeBase(ctx context.Context) error {
},
EmbeddingModelID: s.EmbedModel.GetModelID(),
SummaryModelID: s.LLMModel.GetModelID(),
RerankModelID: s.RerankModel.GetModelID(),
}
// 初始化测试知识库
+1
View File
@@ -115,6 +115,7 @@ func BuildContainer(container *dig.Container) *dig.Container {
must(container.Provide(handler.NewTestDataHandler))
must(container.Provide(handler.NewModelHandler))
must(container.Provide(handler.NewEvaluationHandler))
must(container.Provide(handler.NewInitializationHandler))
// Router configuration
must(container.Provide(router.NewRouter))
File diff suppressed because it is too large Load Diff
+4
View File
@@ -135,6 +135,10 @@ func (h *KnowledgeHandler) CreateKnowledgeFromFile(c *gin.Context) {
if h.handleDuplicateKnowledgeError(c, err, knowledge, "file") {
return
}
if appErr, ok := errors.IsAppError(err); ok {
c.Error(appErr)
return
}
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
return
+24 -24
View File
@@ -18,11 +18,12 @@ import (
// SessionHandler handles all HTTP requests related to conversation sessions
type SessionHandler struct {
messageService interfaces.MessageService // Service for managing messages
sessionService interfaces.SessionService // Service for managing sessions
streamManager interfaces.StreamManager // Manager for handling streaming responses
config *config.Config // Application configuration
testDataService *service.TestDataService // Service for test data (models, etc.)
messageService interfaces.MessageService // Service for managing messages
sessionService interfaces.SessionService // Service for managing sessions
streamManager interfaces.StreamManager // Manager for handling streaming responses
config *config.Config // Application configuration
testDataService *service.TestDataService // Service for test data (models, etc.)
knowledgebaseService interfaces.KnowledgeBaseService
}
// NewSessionHandler creates a new instance of SessionHandler with all necessary dependencies
@@ -32,13 +33,15 @@ func NewSessionHandler(
streamManager interfaces.StreamManager,
config *config.Config,
testDataService *service.TestDataService,
knowledgebaseService interfaces.KnowledgeBaseService,
) *SessionHandler {
return &SessionHandler{
sessionService: sessionService,
messageService: messageService,
streamManager: streamManager,
config: config,
testDataService: testDataService,
sessionService: sessionService,
messageService: messageService,
streamManager: streamManager,
config: config,
testDataService: testDataService,
knowledgebaseService: knowledgebaseService,
}
}
@@ -191,27 +194,24 @@ func (h *SessionHandler) CreateSession(c *gin.Context) {
logger.Debug(ctx, "Using default session strategy")
}
// Get model IDs from test data service if not provided
kb, err := h.knowledgebaseService.GetKnowledgeBaseByID(ctx, request.KnowledgeBaseID)
if err != nil {
logger.Error(ctx, "Failed to get knowledge base", err)
c.Error(errors.NewInternalServerError(err.Error()))
return
}
// Get model IDs from knowledge base if not provided
if createdSession.SummaryModelID == "" {
if h.testDataService != nil {
createdSession.SummaryModelID = h.testDataService.LLMModel.GetModelID()
logger.Debug(ctx, "Using summary model ID from test data service")
} else {
logger.Error(ctx, "Summary model ID is empty and cannot get default value")
c.Error(errors.NewBadRequestError("Summary model ID cannot be empty"))
return
}
createdSession.SummaryModelID = kb.SummaryModelID
}
if createdSession.RerankModelID == "" {
if h.testDataService != nil && h.testDataService.RerankModel != nil {
createdSession.RerankModelID = h.testDataService.RerankModel.GetModelID()
logger.Debug(ctx, "Using rerank model ID from test data service")
}
createdSession.RerankModelID = kb.RerankModelID
}
// Call service to create session
logger.Infof(ctx, "Calling session service to create session")
createdSession, err := h.sessionService.CreateSession(ctx, createdSession)
createdSession, err = h.sessionService.CreateSession(ctx, createdSession)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError(err.Error()))
+5 -13
View File
@@ -4,7 +4,6 @@ import (
"errors"
"net/http"
"os"
"strconv"
"github.com/gin-gonic/gin"
@@ -65,26 +64,19 @@ func (h *TestDataHandler) GetTestData(c *gin.Context) {
return
}
tenantID := os.Getenv("INIT_TEST_TENANT_ID")
logger.Debugf(ctx, "Test tenant ID environment variable: %s", tenantID)
tenantIDUint, err := strconv.ParseUint(tenantID, 10, 64)
if err != nil {
logger.Errorf(ctx, "Failed to parse tenant ID: %s", tenantID)
c.Error(err)
return
}
tenantID := uint(types.InitDefaultTenantID)
logger.Debugf(ctx, "Test tenant ID environment variable: %d", tenantID)
// Retrieve the test tenant data
logger.Infof(ctx, "Retrieving test tenant, ID: %d", tenantIDUint)
tenant, err := h.tenantService.GetTenantByID(ctx, uint(tenantIDUint))
logger.Infof(ctx, "Retrieving test tenant, ID: %d", tenantID)
tenant, err := h.tenantService.GetTenantByID(ctx, tenantID)
if err != nil {
logger.ErrorWithFields(ctx, err, nil)
c.Error(err)
return
}
knowledgeBaseID := os.Getenv("INIT_TEST_KNOWLEDGE_BASE_ID")
knowledgeBaseID := types.InitDefaultKnowledgeBaseID
logger.Debugf(ctx, "Test knowledge base ID environment variable: %s", knowledgeBaseID)
// Retrieve the test knowledge base data
+10 -3
View File
@@ -6,6 +6,7 @@ import (
"log"
"net/http"
"slices"
"strings"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/types"
@@ -15,14 +16,20 @@ import (
// 无需认证的API列表
var noAuthAPI = map[string][]string{
"/api/v1/test-data": {"GET"},
"/api/v1/tenants": {"POST"},
"/api/v1/test-data": {"GET"},
"/api/v1/tenants": {"POST"},
"/api/v1/initialization/*": {"GET", "POST"},
}
// 检查请求是否在无需认证的API列表中
func isNoAuthAPI(path string, method string) bool {
for api, methods := range noAuthAPI {
if api == path && slices.Contains(methods, method) {
// 如果以*结尾,按照前缀匹配,否则按照全路径匹配
if strings.HasSuffix(api, "*") {
if strings.HasPrefix(path, strings.TrimSuffix(api, "*")) && slices.Contains(methods, method) {
return true
}
} else if path == api && slices.Contains(methods, method) {
return true
}
}
+3 -1
View File
@@ -63,7 +63,9 @@ func (c *OllamaChat) buildChatRequest(messages []Message, opts *ChatOptions, isS
chatReq.Options["num_predict"] = opts.MaxTokens
}
if opts.Thinking != nil {
chatReq.Options["think"] = *opts.Thinking
chatReq.Think = &ollamaapi.ThinkValue{
Value: *opts.Thinking,
}
}
}
+5
View File
@@ -309,3 +309,8 @@ func (s *OllamaService) Generate(ctx context.Context, req *api.GenerateRequest,
// Use official client Generate method
return s.client.Generate(ctx, req, fn)
}
// GetClient returns the underlying ollama client for advanced operations
func (s *OllamaService) GetClient() *api.Client {
return s.client
}
+29 -11
View File
@@ -17,17 +17,18 @@ import (
type RouterParams struct {
dig.In
Config *config.Config
KBHandler *handler.KnowledgeBaseHandler
KnowledgeHandler *handler.KnowledgeHandler
TenantHandler *handler.TenantHandler
TenantService interfaces.TenantService
ChunkHandler *handler.ChunkHandler
SessionHandler *handler.SessionHandler
MessageHandler *handler.MessageHandler
TestDataHandler *handler.TestDataHandler
ModelHandler *handler.ModelHandler
EvaluationHandler *handler.EvaluationHandler
Config *config.Config
KBHandler *handler.KnowledgeBaseHandler
KnowledgeHandler *handler.KnowledgeHandler
TenantHandler *handler.TenantHandler
TenantService interfaces.TenantService
ChunkHandler *handler.ChunkHandler
SessionHandler *handler.SessionHandler
MessageHandler *handler.MessageHandler
TestDataHandler *handler.TestDataHandler
ModelHandler *handler.ModelHandler
EvaluationHandler *handler.EvaluationHandler
InitializationHandler *handler.InitializationHandler
}
// NewRouter 创建新的路由
@@ -62,6 +63,23 @@ func NewRouter(params RouterParams) *gin.Engine {
// 测试数据接口(不需要认证)
r.GET("/api/v1/test-data", params.TestDataHandler.GetTestData)
// 初始化接口(不需要认证)
r.GET("/api/v1/initialization/status", params.InitializationHandler.CheckStatus)
r.GET("/api/v1/initialization/config", params.InitializationHandler.GetCurrentConfig)
r.POST("/api/v1/initialization/initialize", params.InitializationHandler.Initialize)
// Ollama相关接口(不需要认证)
r.GET("/api/v1/initialization/ollama/status", params.InitializationHandler.CheckOllamaStatus)
r.POST("/api/v1/initialization/ollama/models/check", params.InitializationHandler.CheckOllamaModels)
r.POST("/api/v1/initialization/ollama/models/download", params.InitializationHandler.DownloadOllamaModel)
r.GET("/api/v1/initialization/ollama/download/progress/:taskId", params.InitializationHandler.GetDownloadProgress)
r.GET("/api/v1/initialization/ollama/download/tasks", params.InitializationHandler.ListDownloadTasks)
// 远程API相关接口(不需要认证)
r.POST("/api/v1/initialization/remote/check", params.InitializationHandler.CheckRemoteModel)
r.POST("/api/v1/initialization/rerank/check", params.InitializationHandler.CheckRerankModel)
r.POST("/api/v1/initialization/multimodal/test", params.InitializationHandler.TestMultimodalFunction)
// 需要认证的API路由
v1 := r.Group("/api/v1")
{
+72
View File
@@ -8,6 +8,10 @@ import (
"gorm.io/gorm"
)
const (
InitDefaultKnowledgeBaseID = "kb-00000001"
)
// KnowledgeBase represents a knowledge base
type KnowledgeBase struct {
// Unique identifier of the knowledge base
@@ -26,6 +30,14 @@ type KnowledgeBase struct {
EmbeddingModelID string `yaml:"embedding_model_id" json:"embedding_model_id"`
// Summary model ID
SummaryModelID string `yaml:"summary_model_id" json:"summary_model_id"`
// Rerank model ID
RerankModelID string `yaml:"rerank_model_id" json:"rerank_model_id"`
// VLM model ID
VLMModelID string `yaml:"vlm_model_id" json:"vlm_model_id"`
// VLM config
VLMConfig VLMConfig `yaml:"vlm_config" json:"vlm_config" gorm:"type:json"`
// COS config
COSConfig COSConfig `yaml:"cos_config" json:"cos_config" gorm:"type:json"`
// Creation time of the knowledge base
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time of the knowledge base
@@ -54,6 +66,37 @@ type ChunkingConfig struct {
EnableMultimodal bool `yaml:"enable_multimodal" json:"enable_multimodal"`
}
// COSConfig represents the COS configuration
type COSConfig struct {
// Secret ID
SecretID string `yaml:"secret_id" json:"secret_id"`
// Secret Key
SecretKey string `yaml:"secret_key" json:"secret_key"`
// Region
Region string `yaml:"region" json:"region"`
// Bucket Name
BucketName string `yaml:"bucket_name" json:"bucket_name"`
// App ID
AppID string `yaml:"app_id" json:"app_id"`
// Path Prefix
PathPrefix string `yaml:"path_prefix" json:"path_prefix"`
}
func (c *COSConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
func (c *COSConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
// ImageProcessingConfig represents the image processing configuration
type ImageProcessingConfig struct {
// Model ID
@@ -93,3 +136,32 @@ func (c *ImageProcessingConfig) Scan(value interface{}) error {
}
return json.Unmarshal(b, c)
}
// VLMConfig represents the VLM configuration
type VLMConfig struct {
// Model Name
ModelName string `yaml:"model_name" json:"model_name"`
// Base URL
BaseURL string `yaml:"base_url" json:"base_url"`
// API Key
APIKey string `yaml:"api_key" json:"api_key"`
// Interface Type: "ollama" or "openai"
InterfaceType string `yaml:"interface_type" json:"interface_type"`
}
// Value implements the driver.Valuer interface, used to convert VLMConfig to database value
func (c VLMConfig) Value() (driver.Value, error) {
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database value to VLMConfig
func (c *VLMConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}
+4
View File
@@ -8,6 +8,10 @@ import (
"gorm.io/gorm"
)
const (
InitDefaultTenantID uint = 1
)
// Tenant represents the tenant
type Tenant struct {
// ID