feat: Introduce conversation configuration management and localization updates

- Added new ConversationConfig interface and API endpoints for retrieving and updating conversation settings.
- Enhanced AgentSettings.vue to include UI for configuring conversation parameters such as prompt, context template, temperature, and max tokens.
- Updated localization files in English and Chinese to include new strings for conversation settings.
- Implemented logic to load and save conversation configuration for tenants, ensuring defaults are applied when no specific configuration exists.
This commit is contained in:
wizardchen
2025-11-17 15:33:43 +08:00
parent a886106917
commit 1f5e445eaa
14 changed files with 913 additions and 175 deletions
+62 -21
View File
@@ -43,19 +43,23 @@ func formatDocSummary(summary string, maxLen int) string {
// RecentDocInfo contains brief information about a recently added document
type RecentDocInfo struct {
KnowledgeID string
Title string
Description string
FileName string
FileSize int64
Type string
CreatedAt string // Formatted time string
KnowledgeID string
Title string
Description string
FileName string
FileSize int64
Type string
CreatedAt string // Formatted time string
FAQStandardQuestion string
FAQSimilarQuestions []string
FAQAnswers []string
}
// KnowledgeBaseInfo contains essential information about a knowledge base for agent prompt
type KnowledgeBaseInfo struct {
ID string
Name string
Type string // Knowledge base type: "document" or "faq"
Description string
DocCount int
RecentDocs []RecentDocInfo // Recently added documents (up to 10)
@@ -98,30 +102,67 @@ func formatKnowledgeBaseList(kbInfos []*KnowledgeBaseInfo) string {
var builder strings.Builder
builder.WriteString("\n")
for i, kb := range kbInfos {
// Display knowledge base name and ID
builder.WriteString(fmt.Sprintf("%d. **%s** (knowledge_base_id: `%s`)\n", i+1, kb.Name, kb.ID))
// Display knowledge base type
kbType := kb.Type
if kbType == "" {
kbType = "document" // Default type
}
builder.WriteString(fmt.Sprintf(" - Type: %s\n", kbType))
if kb.Description != "" {
builder.WriteString(fmt.Sprintf(" - Description: %s\n", kb.Description))
}
builder.WriteString(fmt.Sprintf(" - Document count: %d\n", kb.DocCount))
// Display recent documents if available
// For FAQ type knowledge bases, adjust the display format
if len(kb.RecentDocs) > 0 {
builder.WriteString(" - Recently added documents:\n\n")
builder.WriteString(" | # | Document Name | Type | Created At | Knowledge ID | File Size | Summary |\n")
builder.WriteString(" |---|---------------|------|------------|--------------|----------|---------|\n")
for j, doc := range kb.RecentDocs {
if j >= 10 { // Limit to 10 documents
break
if kbType == "faq" {
// FAQ knowledge base: show Q&A pairs in a more compact format
builder.WriteString(" - Recent FAQ entries:\n\n")
builder.WriteString(" | # | Standard Question | Similar Questions | Answers | Entry ID | Created At |\n")
builder.WriteString(" |---|-------------------|-------------------|---------|----------|------------|\n")
for j, doc := range kb.RecentDocs {
if j >= 10 { // Limit to 10 documents
break
}
question := doc.FAQStandardQuestion
if question == "" {
question = doc.FileName
}
similar := "-"
if len(doc.FAQSimilarQuestions) > 0 {
similar = strings.Join(doc.FAQSimilarQuestions, "; ")
}
answers := "-"
if len(doc.FAQAnswers) > 0 {
answers = strings.Join(doc.FAQAnswers, " | ")
}
builder.WriteString(fmt.Sprintf(" | %d | %s | %s | %s | `%s` | %s |\n",
j+1, question, similar, answers, doc.KnowledgeID, doc.CreatedAt))
}
docName := doc.Title
if docName == "" {
docName = doc.FileName
} else {
// Document knowledge base: show documents in standard format
builder.WriteString(" - Recently added documents:\n\n")
builder.WriteString(" | # | Document Name | Type | Created At | Knowledge ID | File Size | Summary |\n")
builder.WriteString(" |---|---------------|------|------------|--------------|----------|---------|\n")
for j, doc := range kb.RecentDocs {
if j >= 10 { // Limit to 10 documents
break
}
docName := doc.Title
if docName == "" {
docName = doc.FileName
}
// Format file size
fileSize := formatFileSize(doc.FileSize)
summary := formatDocSummary(doc.Description, 120)
builder.WriteString(fmt.Sprintf(" | %d | %s | %s | %s | `%s` | %s | %s |\n",
j+1, docName, doc.Type, doc.CreatedAt, doc.KnowledgeID, fileSize, summary))
}
// Format file size
fileSize := formatFileSize(doc.FileSize)
summary := formatDocSummary(doc.Description, 120)
builder.WriteString(fmt.Sprintf(" | %d | %s | %s | %s | `%s` | %s | %s |\n",
j+1, docName, doc.Type, doc.CreatedAt, doc.KnowledgeID, fileSize, summary))
}
builder.WriteString("\n")
}
+173 -28
View File
@@ -19,14 +19,17 @@ import (
// searchResultWithMeta wraps search result with metadata about which query matched it
type searchResultWithMeta struct {
*types.SearchResult
SourceQuery string
QueryType string // "vector" or "keyword"
SourceQuery string
QueryType string // "vector" or "keyword"
KnowledgeBaseID string // ID of the knowledge base this result came from
KnowledgeBaseType string // Type of the knowledge base (document, faq, etc.)
}
// KnowledgeSearchTool searches knowledge bases with flexible query modes
type KnowledgeSearchTool struct {
BaseTool
knowledgeService interfaces.KnowledgeBaseService
chunkService interfaces.ChunkService
tenantID uint
allowedKBs []string
rerankModel rerank.Reranker
@@ -36,6 +39,7 @@ type KnowledgeSearchTool struct {
// NewKnowledgeSearchTool creates a new knowledge search tool
func NewKnowledgeSearchTool(
knowledgeService interfaces.KnowledgeBaseService,
chunkService interfaces.ChunkService,
tenantID uint,
allowedKBs []string,
rerankModel rerank.Reranker,
@@ -110,6 +114,7 @@ func NewKnowledgeSearchTool(
return &KnowledgeSearchTool{
BaseTool: NewBaseTool("knowledge_search", description),
knowledgeService: knowledgeService,
chunkService: chunkService,
tenantID: tenantID,
allowedKBs: allowedKBs,
rerankModel: rerankModel,
@@ -327,8 +332,10 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
// Execute concurrent search
logger.Infof(ctx, "[Tool][KnowledgeSearch] Starting concurrent search across %d KBs", len(kbIDs))
kbTypeMap := t.getKnowledgeBaseTypes(ctx, kbIDs)
allResults := t.concurrentSearch(ctx, vectorQueries, keywordQueries, kbIDs,
topK, vectorThreshold, keywordThreshold)
topK, vectorThreshold, keywordThreshold, kbTypeMap)
logger.Infof(ctx, "[Tool][KnowledgeSearch] Concurrent search completed: %d raw results", len(allResults))
// Filter by knowledge_ids if provided
@@ -432,7 +439,7 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
// Build output
logger.Infof(ctx, "[Tool][KnowledgeSearch] Formatting output with %d final results", len(deduplicatedResults))
result, err := t.formatOutput(deduplicatedResults, vectorQueries, keywordQueries,
result, err := t.formatOutput(ctx, deduplicatedResults, vectorQueries, keywordQueries,
kbIDs, len(allResults), vectorThreshold, keywordThreshold, knowledgeIDsFilter, singleQuery)
if err != nil {
logger.Errorf(ctx, "[Tool][KnowledgeSearch] Failed to format output: %v", err)
@@ -443,6 +450,30 @@ func (t *KnowledgeSearchTool) Execute(ctx context.Context, args map[string]inter
return result, nil
}
// getKnowledgeBaseTypes fetches knowledge base types for the given IDs
func (t *KnowledgeSearchTool) getKnowledgeBaseTypes(ctx context.Context, kbIDs []string) map[string]string {
kbTypeMap := make(map[string]string, len(kbIDs))
for _, kbID := range kbIDs {
if kbID == "" {
continue
}
if _, exists := kbTypeMap[kbID]; exists {
continue
}
kb, err := t.knowledgeService.GetKnowledgeBaseByID(ctx, kbID)
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to fetch knowledge base %s info: %v", kbID, err)
continue
}
kbTypeMap[kbID] = kb.Type
}
return kbTypeMap
}
// concurrentSearch executes vector and keyword searches concurrently
func (t *KnowledgeSearchTool) concurrentSearch(
ctx context.Context,
@@ -450,6 +481,7 @@ func (t *KnowledgeSearchTool) concurrentSearch(
kbsToSearch []string,
topK int,
vectorThreshold, keywordThreshold float64,
kbTypeMap map[string]string,
) []*searchResultWithMeta {
var wg sync.WaitGroup
var mu sync.Mutex
@@ -461,7 +493,7 @@ func (t *KnowledgeSearchTool) concurrentSearch(
go func() {
defer wg.Done()
results := t.searchWithQueries(ctx, vectorQueries, kbsToSearch, topK,
vectorThreshold, 1.0, "vector")
vectorThreshold, 1.0, "vector", kbTypeMap)
mu.Lock()
allResults = append(allResults, results...)
mu.Unlock()
@@ -474,7 +506,7 @@ func (t *KnowledgeSearchTool) concurrentSearch(
go func() {
defer wg.Done()
results := t.searchWithQueries(ctx, keywordQueries, kbsToSearch, topK,
1.0, keywordThreshold, "keyword")
1.0, keywordThreshold, "keyword", kbTypeMap)
mu.Lock()
allResults = append(allResults, results...)
mu.Unlock()
@@ -493,6 +525,7 @@ func (t *KnowledgeSearchTool) searchWithQueries(
topK int,
vectorThreshold, keywordThreshold float64,
queryType string,
kbTypeMap map[string]string,
) []*searchResultWithMeta {
var wg sync.WaitGroup
var mu sync.Mutex
@@ -503,7 +536,7 @@ func (t *KnowledgeSearchTool) searchWithQueries(
go func(q string) {
defer wg.Done()
results := t.searchSingleQuery(ctx, q, kbsToSearch, topK,
vectorThreshold, keywordThreshold, queryType)
vectorThreshold, keywordThreshold, queryType, kbTypeMap)
mu.Lock()
allResults = append(allResults, results...)
mu.Unlock()
@@ -522,6 +555,7 @@ func (t *KnowledgeSearchTool) searchSingleQuery(
topK int,
vectorThreshold, keywordThreshold float64,
queryType string,
kbTypeMap map[string]string,
) []*searchResultWithMeta {
var wg sync.WaitGroup
var mu sync.Mutex
@@ -549,9 +583,11 @@ func (t *KnowledgeSearchTool) searchSingleQuery(
mu.Lock()
for _, r := range kbResults {
results = append(results, &searchResultWithMeta{
SearchResult: r,
SourceQuery: query,
QueryType: queryType,
SearchResult: r,
SourceQuery: query,
QueryType: queryType,
KnowledgeBaseID: kb,
KnowledgeBaseType: kbTypeMap[kb],
})
}
mu.Unlock()
@@ -594,18 +630,85 @@ func (t *KnowledgeSearchTool) rerankResults(
query string,
results []*searchResultWithMeta,
) ([]*searchResultWithMeta, error) {
// If chatModel is available, use LLM-based prompt scoring
if t.chatModel != nil {
return t.rerankWithLLM(ctx, query, results)
// Separate FAQ and non-FAQ results. FAQ results keep original scores.
faqResults := make([]*searchResultWithMeta, 0)
nonFAQResults := make([]*searchResultWithMeta, 0, len(results))
for _, result := range results {
if result.KnowledgeBaseType == types.KnowledgeBaseTypeFAQ {
faqResults = append(faqResults, result)
} else {
nonFAQResults = append(nonFAQResults, result)
}
}
// Fallback to rerank model if available
if t.rerankModel != nil {
return t.rerankWithModel(ctx, query, results)
// If there are no non-FAQ results, return original list (already all FAQ)
if len(nonFAQResults) == 0 {
return results, nil
}
// No reranking available, return original results
return results, nil
var (
rerankedNonFAQ []*searchResultWithMeta
err error
)
// Apply reranking only to non-FAQ results
switch {
case t.chatModel != nil:
rerankedNonFAQ, err = t.rerankWithLLM(ctx, query, nonFAQResults)
case t.rerankModel != nil:
rerankedNonFAQ, err = t.rerankWithModel(ctx, query, nonFAQResults)
default:
rerankedNonFAQ = nonFAQResults
}
if err != nil {
return nil, err
}
// Combine FAQ results (with original order) and reranked non-FAQ results
combined := make([]*searchResultWithMeta, 0, len(results))
combined = append(combined, faqResults...)
combined = append(combined, rerankedNonFAQ...)
// Sort by score (descending) to keep consistent output order
sort.Slice(combined, func(i, j int) bool {
return combined[i].Score > combined[j].Score
})
return combined, nil
}
func (t *KnowledgeSearchTool) getFAQMetadata(
ctx context.Context,
chunkID string,
cache map[string]*types.FAQChunkMetadata,
) (*types.FAQChunkMetadata, error) {
if chunkID == "" || t.chunkService == nil {
return nil, nil
}
if meta, ok := cache[chunkID]; ok {
return meta, nil
}
chunk, err := t.chunkService.GetChunkByID(ctx, chunkID)
if err != nil {
cache[chunkID] = nil
return nil, err
}
if chunk == nil {
cache[chunkID] = nil
return nil, nil
}
meta, err := chunk.FAQMetadata()
if err != nil {
cache[chunkID] = nil
return nil, err
}
cache[chunkID] = meta
return meta, nil
}
// rerankWithLLM uses LLM prompt to score and rerank search results
@@ -906,6 +1009,7 @@ func (t *KnowledgeSearchTool) deduplicateResults(results []*searchResultWithMeta
// formatOutput formats the search results for display
func (t *KnowledgeSearchTool) formatOutput(
ctx context.Context,
results []*searchResultWithMeta,
vectorQueries, keywordQueries []string,
kbsToSearch []string,
@@ -992,7 +1096,19 @@ func (t *KnowledgeSearchTool) formatOutput(
formattedResults := make([]map[string]interface{}, 0, len(results))
currentKB := ""
faqMetadataCache := make(map[string]*types.FAQChunkMetadata)
for i, result := range results {
var faqMeta *types.FAQChunkMetadata
if result.KnowledgeBaseType == types.KnowledgeBaseTypeFAQ {
meta, err := t.getFAQMetadata(ctx, result.ID, faqMetadataCache)
if err != nil {
logger.Warnf(ctx, "[Tool][KnowledgeSearch] Failed to load FAQ metadata for chunk %s: %v", result.ID, err)
} else {
faqMeta = meta
}
}
// Group by knowledge base
if result.KnowledgeID != currentKB {
currentKB = result.KnowledgeID
@@ -1013,18 +1129,47 @@ func (t *KnowledgeSearchTool) formatOutput(
output += fmt.Sprintf(" Content: %s\n", result.Content)
output += fmt.Sprintf(" [chunk_id: %s - full content included above]\n", result.ID)
if faqMeta != nil {
if faqMeta.StandardQuestion != "" {
output += fmt.Sprintf(" FAQ Standard Question: %s\n", faqMeta.StandardQuestion)
}
if len(faqMeta.SimilarQuestions) > 0 {
output += fmt.Sprintf(" FAQ Similar Questions: %s\n", strings.Join(faqMeta.SimilarQuestions, "; "))
}
if len(faqMeta.Answers) > 0 {
output += " FAQ Answers:\n"
for _, ans := range faqMeta.Answers {
output += fmt.Sprintf(" - %s\n", ans)
}
}
}
formattedResults = append(formattedResults, map[string]interface{}{
"result_index": i + 1,
"chunk_id": result.ID,
"content": result.Content,
"score": result.Score,
"relevance_level": relevanceLevel,
"knowledge_id": result.KnowledgeID,
"knowledge_title": result.KnowledgeTitle,
"match_type": result.MatchType,
"source_query": result.SourceQuery,
"query_type": result.QueryType,
"result_index": i + 1,
"chunk_id": result.ID,
"content": result.Content,
"score": result.Score,
"relevance_level": relevanceLevel,
"knowledge_id": result.KnowledgeID,
"knowledge_title": result.KnowledgeTitle,
"match_type": result.MatchType,
"source_query": result.SourceQuery,
"query_type": result.QueryType,
"knowledge_base_type": result.KnowledgeBaseType,
})
last := formattedResults[len(formattedResults)-1]
if faqMeta != nil {
if faqMeta.StandardQuestion != "" {
last["faq_standard_question"] = faqMeta.StandardQuestion
}
if len(faqMeta.SimilarQuestions) > 0 {
last["faq_similar_questions"] = faqMeta.SimilarQuestions
}
if len(faqMeta.Answers) > 0 {
last["faq_answers"] = faqMeta.Answers
}
}
}
// // Add usage guidance
+68 -24
View File
@@ -208,7 +208,15 @@ func (s *agentService) registerTools(
case "todo_write":
registry.RegisterTool(tools.NewTodoWriteTool())
case "knowledge_search":
registry.RegisterTool(tools.NewKnowledgeSearchTool(s.knowledgeBaseService, tenantID, config.KnowledgeBases, rerankModel, chatModel))
registry.RegisterTool(
tools.NewKnowledgeSearchTool(
s.knowledgeBaseService,
s.chunkService,
tenantID,
config.KnowledgeBases,
rerankModel,
chatModel,
))
case "get_related_chunks":
registry.RegisterTool(tools.NewGetRelatedChunksTool(s.chunkService, s.knowledgeBaseService))
case "query_knowledge_graph":
@@ -283,6 +291,7 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
kbInfos = append(kbInfos, &agent.KnowledgeBaseInfo{
ID: kbID,
Name: kbID,
Type: "document", // Default type
Description: "",
DocCount: 0,
RecentDocs: []agent.RecentDocInfo{},
@@ -294,37 +303,72 @@ func (s *agentService) getKnowledgeBaseInfos(ctx context.Context, kbIDs []string
docCount := 0
recentDocs := []agent.RecentDocInfo{}
// Get recent documents using paged query (first 10, assumed to be sorted by created_at desc)
pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{
Page: 1,
PageSize: 10,
})
if err == nil && pageResult != nil {
docCount = int(pageResult.Total)
// Convert to Knowledge slice
if knowledges, ok := pageResult.Data.([]*types.Knowledge); ok {
for _, k := range knowledges {
if len(recentDocs) >= 10 {
break
if kb.Type == types.KnowledgeBaseTypeFAQ {
pageResult, err := s.knowledgeService.ListFAQEntries(ctx, kbID, &types.Pagination{
Page: 1,
PageSize: 10,
})
if err == nil && pageResult != nil {
docCount = int(pageResult.Total)
if entries, ok := pageResult.Data.([]*types.FAQEntry); ok {
for _, entry := range entries {
if len(recentDocs) >= 10 {
break
}
recentDocs = append(recentDocs, agent.RecentDocInfo{
KnowledgeID: entry.ChunkID,
Title: entry.StandardQuestion,
Type: string(types.ChunkTypeFAQ),
CreatedAt: entry.CreatedAt.Format("2006-01-02"),
FAQStandardQuestion: entry.StandardQuestion,
FAQSimilarQuestions: entry.SimilarQuestions,
FAQAnswers: entry.Answers,
})
}
}
} else if err != nil {
logger.Warnf(ctx, "Failed to list FAQ entries for %s: %v", kbID, err)
}
}
// Fallback to generic knowledge listing when not FAQ or FAQ retrieval failed
if kb.Type != types.KnowledgeBaseTypeFAQ || len(recentDocs) == 0 {
pageResult, err := s.knowledgeService.ListPagedKnowledgeByKnowledgeBaseID(ctx, kbID, &types.Pagination{
Page: 1,
PageSize: 10,
})
if err == nil && pageResult != nil {
docCount = int(pageResult.Total)
// Convert to Knowledge slice
if knowledges, ok := pageResult.Data.([]*types.Knowledge); ok {
for _, k := range knowledges {
if len(recentDocs) >= 10 {
break
}
recentDocs = append(recentDocs, agent.RecentDocInfo{
KnowledgeID: k.ID,
Title: k.Title,
Description: k.Description,
FileName: k.FileName,
Type: k.FileType,
CreatedAt: k.CreatedAt.Format("2006-01-02"),
FileSize: k.FileSize,
})
}
recentDocs = append(recentDocs, agent.RecentDocInfo{
KnowledgeID: k.ID,
Title: k.Title,
Description: k.Description,
FileName: k.FileName,
Type: k.FileType,
CreatedAt: k.CreatedAt.Format("2006-01-02"),
FileSize: k.FileSize,
})
}
}
}
kbType := kb.Type
if kbType == "" {
kbType = "document" // Default type
}
kbInfos = append(kbInfos, &agent.KnowledgeBaseInfo{
ID: kb.ID,
Name: kb.Name,
Type: kbType,
Description: kb.Description,
DocCount: docCount,
RecentDocs: recentDocs,
+3 -3
View File
@@ -97,9 +97,9 @@ func (h *Handler) CreateSession(c *gin.Context) {
if request.SessionStrategy.SummaryParameters != nil {
createdSession.SummaryParameters = request.SessionStrategy.SummaryParameters
} else {
createdSession.SummaryParameters = h.createDefaultSummaryConfig()
createdSession.SummaryParameters = h.createDefaultSummaryConfig(ctx)
}
h.fillSummaryConfigDefaults(createdSession.SummaryParameters)
h.fillSummaryConfigDefaults(ctx, createdSession.SummaryParameters)
logger.Debug(ctx, "Custom session strategy set")
} else {
@@ -113,7 +113,7 @@ func (h *Handler) CreateSession(c *gin.Context) {
createdSession.VectorThreshold = h.config.Conversation.VectorThreshold
createdSession.RerankThreshold = h.config.Conversation.RerankThreshold
createdSession.RerankTopK = h.config.Conversation.RerankTopK
createdSession.SummaryParameters = h.createDefaultSummaryConfig()
createdSession.SummaryParameters = h.createDefaultSummaryConfig(ctx)
logger.Debug(ctx, "Using default session strategy")
}
+68 -6
View File
@@ -162,8 +162,13 @@ func getFloat64(m map[string]interface{}, key string) float64 {
}
// createDefaultSummaryConfig creates a default summary configuration from config
func (h *Handler) createDefaultSummaryConfig() *types.SummaryConfig {
return &types.SummaryConfig{
// It prioritizes tenant-level ConversationConfig, then falls back to config.yaml defaults
func (h *Handler) createDefaultSummaryConfig(ctx context.Context) *types.SummaryConfig {
// Try to get tenant from context
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
// Initialize with config.yaml defaults
cfg := &types.SummaryConfig{
MaxTokens: h.config.Conversation.Summary.MaxTokens,
TopP: h.config.Conversation.Summary.TopP,
TopK: h.config.Conversation.Summary.TopK,
@@ -177,17 +182,74 @@ func (h *Handler) createDefaultSummaryConfig() *types.SummaryConfig {
Seed: h.config.Conversation.Summary.Seed,
MaxCompletionTokens: h.config.Conversation.Summary.MaxCompletionTokens,
}
// Override with tenant-level conversation config if available
if tenant != nil && tenant.ConversationConfig != nil {
if tenant.ConversationConfig.Prompt != "" {
cfg.Prompt = tenant.ConversationConfig.Prompt
}
if tenant.ConversationConfig.ContextTemplate != "" {
cfg.ContextTemplate = tenant.ConversationConfig.ContextTemplate
}
if tenant.ConversationConfig.Temperature > 0 {
cfg.Temperature = tenant.ConversationConfig.Temperature
}
if tenant.ConversationConfig.MaxTokens > 0 {
cfg.MaxTokens = tenant.ConversationConfig.MaxTokens
}
}
return cfg
}
// fillSummaryConfigDefaults fills missing fields in summary config with defaults
func (h *Handler) fillSummaryConfigDefaults(config *types.SummaryConfig) {
// It prioritizes tenant-level ConversationConfig, then falls back to config.yaml defaults
func (h *Handler) fillSummaryConfigDefaults(ctx context.Context, config *types.SummaryConfig) {
// Try to get tenant from context
tenant, _ := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
// Determine default values: tenant config first, then config.yaml
var defaultPrompt, defaultContextTemplate, defaultNoMatchPrefix string
var defaultTemperature float64
var defaultMaxTokens int
if tenant != nil && tenant.ConversationConfig != nil {
// Use tenant-level config as defaults
defaultPrompt = tenant.ConversationConfig.Prompt
defaultContextTemplate = tenant.ConversationConfig.ContextTemplate
defaultTemperature = tenant.ConversationConfig.Temperature
defaultMaxTokens = tenant.ConversationConfig.MaxTokens
}
// Fall back to config.yaml if tenant config is empty
if defaultPrompt == "" {
defaultPrompt = h.config.Conversation.Summary.Prompt
}
if defaultContextTemplate == "" {
defaultContextTemplate = h.config.Conversation.Summary.ContextTemplate
}
if defaultTemperature == 0 {
defaultTemperature = h.config.Conversation.Summary.Temperature
}
if defaultMaxTokens == 0 {
defaultMaxTokens = h.config.Conversation.Summary.MaxTokens
}
defaultNoMatchPrefix = h.config.Conversation.Summary.NoMatchPrefix
// Fill missing fields
if config.Prompt == "" {
config.Prompt = h.config.Conversation.Summary.Prompt
config.Prompt = defaultPrompt
}
if config.ContextTemplate == "" {
config.ContextTemplate = h.config.Conversation.Summary.ContextTemplate
config.ContextTemplate = defaultContextTemplate
}
if config.Temperature == 0 {
config.Temperature = defaultTemperature
}
if config.MaxTokens == 0 {
config.MaxTokens = defaultMaxTokens
}
if config.NoMatchPrefix == "" {
config.NoMatchPrefix = h.config.Conversation.Summary.NoMatchPrefix
config.NoMatchPrefix = defaultNoMatchPrefix
}
}
+110 -1
View File
@@ -8,6 +8,7 @@ import (
"github.com/Tencent/WeKnora/internal/agent"
agenttools "github.com/Tencent/WeKnora/internal/agent/tools"
"github.com/Tencent/WeKnora/internal/config"
"github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
@@ -19,16 +20,19 @@ import (
// through the REST API endpoints
type TenantHandler struct {
service interfaces.TenantService
config *config.Config
}
// NewTenantHandler creates a new tenant handler instance with the provided service
// Parameters:
// - service: An implementation of the TenantService interface for business logic
// - config: Application configuration
//
// Returns a pointer to the newly created TenantHandler
func NewTenantHandler(service interfaces.TenantService) *TenantHandler {
func NewTenantHandler(service interfaces.TenantService, config *config.Config) *TenantHandler {
return &TenantHandler{
service: service,
config: config,
}
}
@@ -410,6 +414,9 @@ func (h *TenantHandler) GetTenantKV(c *gin.Context) {
case "web-search-config":
h.GetTenantWebSearchConfig(c)
return
case "conversation-config":
h.GetTenantConversationConfig(c)
return
default:
logger.Info(ctx, "KV key not supported", "key", key)
c.Error(errors.NewBadRequestError("unsupported key"))
@@ -430,6 +437,9 @@ func (h *TenantHandler) UpdateTenantKV(c *gin.Context) {
case "web-search-config":
h.updateTenantWebSearchConfigInternal(c)
return
case "conversation-config":
h.updateTenantConversationConfigInternal(c)
return
default:
logger.Info(ctx, "KV key not supported", "key", key)
c.Error(errors.NewBadRequestError("unsupported key"))
@@ -499,3 +509,102 @@ func (h *TenantHandler) GetTenantWebSearchConfig(c *gin.Context) {
"data": tenant.WebSearchConfig,
})
}
// GetTenantConversationConfig retrieves the conversation configuration for a tenant
// This is the global conversation configuration that applies to normal mode sessions by default
func (h *TenantHandler) GetTenantConversationConfig(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start retrieving tenant conversation config")
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
return
}
// If tenant has no conversation config, return defaults from config.yaml
if tenant.ConversationConfig == nil {
logger.Info(ctx, "Tenant has no conversation config, returning defaults")
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"prompt": h.config.Conversation.Summary.Prompt,
"context_template": h.config.Conversation.Summary.ContextTemplate,
"temperature": h.config.Conversation.Summary.Temperature,
"max_tokens": h.config.Conversation.Summary.MaxTokens,
},
})
return
}
logger.Infof(ctx, "Retrieved tenant conversation config successfully, Tenant ID: %d", tenant.ID)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"prompt": tenant.ConversationConfig.Prompt,
"context_template": tenant.ConversationConfig.ContextTemplate,
"temperature": tenant.ConversationConfig.Temperature,
"max_tokens": tenant.ConversationConfig.MaxTokens,
},
})
}
// updateTenantConversationConfigInternal updates the conversation configuration for a tenant
// This sets the global conversation configuration for normal mode sessions in this tenant
func (h *TenantHandler) updateTenantConversationConfigInternal(c *gin.Context) {
ctx := c.Request.Context()
logger.Info(ctx, "Start updating tenant conversation config")
var req types.ConversationConfig
if err := c.ShouldBindJSON(&req); err != nil {
logger.Error(ctx, "Failed to parse request parameters", err)
c.Error(errors.NewValidationError("Invalid request data").WithDetails(err.Error()))
return
}
// Validate configuration
if req.Temperature < 0 || req.Temperature > 2 {
c.Error(errors.NewBadRequestError("temperature must be between 0 and 2"))
return
}
if req.MaxTokens <= 0 || req.MaxTokens > 100000 {
c.Error(errors.NewBadRequestError("max_tokens must be between 1 and 100000"))
return
}
// Get existing tenant
tenant := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
if tenant == nil {
logger.Error(ctx, "Tenant is empty")
c.Error(errors.NewBadRequestError("Tenant is empty"))
return
}
// Update conversation configuration
tenant.ConversationConfig = &req
updatedTenant, err := h.service.UpdateTenant(ctx, tenant)
if err != nil {
if appErr, ok := errors.IsAppError(err); ok {
logger.Error(ctx, "Failed to update tenant: application error", appErr)
c.Error(appErr)
} else {
logger.ErrorWithFields(ctx, err, nil)
c.Error(errors.NewInternalServerError("Failed to update tenant conversation config").WithDetails(err.Error()))
}
return
}
logger.Infof(ctx, "Tenant conversation config updated successfully, Tenant ID: %d", tenant.ID)
c.JSON(http.StatusOK, gin.H{
"success": true,
"data": gin.H{
"prompt": updatedTenant.ConversationConfig.Prompt,
"context_template": updatedTenant.ConversationConfig.ContextTemplate,
"temperature": updatedTenant.ConversationConfig.Temperature,
"max_tokens": updatedTenant.ConversationConfig.MaxTokens,
},
"message": "Conversation configuration updated successfully",
})
}
+34
View File
@@ -34,6 +34,8 @@ type Tenant struct {
ContextConfig *ContextConfig `yaml:"context_config" json:"context_config" gorm:"type:jsonb"`
// Global WebSearch configuration for this tenant
WebSearchConfig *WebSearchConfig `yaml:"web_search_config" json:"web_search_config" gorm:"type:jsonb"`
// Global Conversation configuration for this tenant (default for normal mode sessions)
ConversationConfig *ConversationConfig `yaml:"conversation_config" json:"conversation_config" gorm:"type:jsonb"`
// Creation time
CreatedAt time.Time `yaml:"created_at" json:"created_at"`
// Last updated time
@@ -69,3 +71,35 @@ func (c *RetrieverEngines) Scan(value interface{}) error {
}
return json.Unmarshal(b, c)
}
// ConversationConfig represents the conversation configuration for normal mode
type ConversationConfig struct {
// Prompt is the system prompt
Prompt string `json:"prompt"`
// ContextTemplate is the prompt template for summarizing retrieval results
ContextTemplate string `json:"context_template"`
// Temperature controls the randomness of the model output
Temperature float64 `json:"temperature"`
// MaxTokens is the maximum number of tokens to generate
MaxTokens int `json:"max_tokens"`
}
// Value implements the driver.Valuer interface, used to convert ConversationConfig to database value
func (c *ConversationConfig) Value() (driver.Value, error) {
if c == nil {
return nil, nil
}
return json.Marshal(c)
}
// Scan implements the sql.Scanner interface, used to convert database value to ConversationConfig
func (c *ConversationConfig) Scan(value interface{}) error {
if value == nil {
return nil
}
b, ok := value.([]byte)
if !ok {
return nil
}
return json.Unmarshal(b, c)
}