feat: enhance localization and configuration support

- Added timezone and language settings to the environment configuration.
- Introduced built-in agent configurations with multilingual support for various agents.
- Updated Docker Compose to utilize new environment variables for timezone and language.
- Created new prompt templates for question generation, summary generation, and keywords extraction.
This commit is contained in:
wizardchen
2026-03-17 15:33:19 +08:00
committed by lyingbug
parent 09d9fe5ddb
commit 139a9c40ff
54 changed files with 2524 additions and 1482 deletions
+239
View File
@@ -0,0 +1,239 @@
package types
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"gopkg.in/yaml.v3"
)
// ---------------------------------------------------------------------------
// YAML data structures for config/builtin_agents.yaml
// ---------------------------------------------------------------------------
// BuiltinAgentI18n holds localised name and description for a single locale.
type BuiltinAgentI18n struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
}
// BuiltinAgentEntry is one entry in the builtin_agents list in YAML.
type BuiltinAgentEntry struct {
ID string `yaml:"id"`
Avatar string `yaml:"avatar"`
IsBuiltin bool `yaml:"is_builtin"`
I18n map[string]BuiltinAgentI18n `yaml:"i18n"`
Config CustomAgentConfig `yaml:"config"`
}
// builtinAgentsFile is the top-level YAML structure.
type builtinAgentsFile struct {
BuiltinAgents []BuiltinAgentEntry `yaml:"builtin_agents"`
}
// ---------------------------------------------------------------------------
// Global registry (populated from YAML at startup)
// ---------------------------------------------------------------------------
var (
builtinAgentEntries map[string]*BuiltinAgentEntry // keyed by agent ID
builtinAgentEntriesMu sync.RWMutex
builtinAgentEntriesOnce sync.Once
)
// LoadBuiltinAgentsConfig loads built-in agent definitions from the given
// config directory (e.g. "./config"). The file must be named "builtin_agents.yaml".
// This should be called once at startup, after config.LoadConfig determines
// the config directory.
//
// If the file does not exist, the function is a no-op and the hard-coded
// defaults in BuiltinAgentRegistry remain effective.
func LoadBuiltinAgentsConfig(configDir string) error {
var loadErr error
builtinAgentEntriesOnce.Do(func() {
filePath := filepath.Join(configDir, "builtin_agents.yaml")
data, err := os.ReadFile(filePath)
if err != nil {
if os.IsNotExist(err) {
// File not found – perfectly fine, keep using hard-coded defaults.
return
}
loadErr = fmt.Errorf("read builtin_agents.yaml: %w", err)
return
}
var file builtinAgentsFile
if err := yaml.Unmarshal(data, &file); err != nil {
loadErr = fmt.Errorf("parse builtin_agents.yaml: %w", err)
return
}
builtinAgentEntriesMu.Lock()
defer builtinAgentEntriesMu.Unlock()
builtinAgentEntries = make(map[string]*BuiltinAgentEntry, len(file.BuiltinAgents))
for i := range file.BuiltinAgents {
entry := &file.BuiltinAgents[i]
builtinAgentEntries[entry.ID] = entry
}
// Rebuild the BuiltinAgentRegistry so that IsBuiltinAgentID / GetBuiltinAgent
// continue to work transparently.
rebuildRegistryFromConfig()
})
return loadErr
}
// rebuildRegistryFromConfig replaces the BuiltinAgentRegistry entries with
// factory functions that read from the YAML-loaded config. Must be called
// while builtinAgentEntriesMu is held.
func rebuildRegistryFromConfig() {
for id := range builtinAgentEntries {
agentID := id // capture for closure
BuiltinAgentRegistry[agentID] = func(tenantID uint64) *CustomAgent {
return buildAgentFromEntry(agentID, tenantID, "")
}
}
}
// ---------------------------------------------------------------------------
// Public API — context-aware, i18n-capable
// ---------------------------------------------------------------------------
// GetBuiltinAgentWithContext returns a built-in agent whose Name and
// Description are localised according to the language in ctx.
// Falls back to GetBuiltinAgent (default locale) when no YAML config is loaded.
func GetBuiltinAgentWithContext(ctx context.Context, id string, tenantID uint64) *CustomAgent {
locale := localeFromCtx(ctx)
builtinAgentEntriesMu.RLock()
entry, ok := builtinAgentEntries[id]
builtinAgentEntriesMu.RUnlock()
if !ok || entry == nil {
// No YAML entry — fall back to hard-coded factory.
if factory, exists := BuiltinAgentRegistry[id]; exists {
return factory(tenantID)
}
return nil
}
return buildAgentFromEntry(id, tenantID, locale)
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
// buildAgentFromEntry constructs a *CustomAgent from a BuiltinAgentEntry.
// locale can be "" to use the "default" locale.
func buildAgentFromEntry(id string, tenantID uint64, locale string) *CustomAgent {
builtinAgentEntriesMu.RLock()
entry, ok := builtinAgentEntries[id]
builtinAgentEntriesMu.RUnlock()
if !ok || entry == nil {
return nil
}
i18n := resolveI18n(entry.I18n, locale)
agent := &CustomAgent{
ID: entry.ID,
Name: i18n.Name,
Description: i18n.Description,
Avatar: entry.Avatar,
IsBuiltin: entry.IsBuiltin,
TenantID: tenantID,
Config: entry.Config, // value copy
}
agent.EnsureDefaults()
return agent
}
// resolveI18n picks the best locale match from the i18n map.
// Priority: exact match → language-only match → "default" → first entry.
func resolveI18n(m map[string]BuiltinAgentI18n, locale string) BuiltinAgentI18n {
if len(m) == 0 {
return BuiltinAgentI18n{}
}
// 1. Exact match (e.g. "zh-CN")
if v, ok := m[locale]; ok {
return v
}
// 2. Language-only match (e.g. "zh-CN" → try "zh")
if idx := strings.IndexAny(locale, "-_"); idx > 0 {
lang := locale[:idx]
if v, ok := m[lang]; ok {
return v
}
// Also try matching entries that start with the same language prefix
for k, v := range m {
if strings.HasPrefix(k, lang) {
return v
}
}
}
// 3. "default" key
if v, ok := m["default"]; ok {
return v
}
// 4. First available entry
for _, v := range m {
return v
}
return BuiltinAgentI18n{}
}
// localeFromCtx extracts the locale string from ctx, falling back to "".
func localeFromCtx(ctx context.Context) string {
if ctx == nil {
return ""
}
lang, _ := LanguageFromContext(ctx)
return lang
}
// ResolveBuiltinAgentPromptRefs iterates over all builtin agent entries and
// resolves system_prompt_id / context_template_id references by calling the
// provided resolver function. The resolver takes a template ID and returns
// the template content string (empty string if not found).
//
// This must be called after both LoadBuiltinAgentsConfig and prompt template
// loading have completed.
func ResolveBuiltinAgentPromptRefs(resolver func(id string) string) {
builtinAgentEntriesMu.Lock()
defer builtinAgentEntriesMu.Unlock()
for _, entry := range builtinAgentEntries {
if entry == nil {
continue
}
// Resolve system_prompt_id → SystemPrompt
if entry.Config.SystemPromptID != "" && entry.Config.SystemPrompt == "" {
if content := resolver(entry.Config.SystemPromptID); content != "" {
entry.Config.SystemPrompt = content
} else {
fmt.Printf("Warning: builtin agent %q references system_prompt_id %q but template not found\n",
entry.ID, entry.Config.SystemPromptID)
}
}
// Resolve context_template_id → ContextTemplate
if entry.Config.ContextTemplateID != "" && entry.Config.ContextTemplate == "" {
if content := resolver(entry.Config.ContextTemplateID); content != "" {
entry.Config.ContextTemplate = content
} else {
fmt.Printf("Warning: builtin agent %q references context_template_id %q but template not found\n",
entry.ID, entry.Config.ContextTemplateID)
}
}
}
}
+2
View File
@@ -68,6 +68,7 @@ type ChatManage struct {
VLMModelID string `json:"-"` // Agent-configured VLM model ID for image analysis
ChatModelSupportsVision bool `json:"-"` // Whether the chat model accepts multimodal/image input
SkipKBSearch bool `json:"-"` // Set by rewrite intent classification: true = skip KB retrieval
Language string `json:"-"` // User language name for prompt placeholder (e.g. "Chinese (Simplified)", "English")
}
// Clone creates a deep copy of the ChatManage object
@@ -143,6 +144,7 @@ func (c *ChatManage) Clone() *ChatManage {
VLMModelID: c.VLMModelID,
ChatModelSupportsVision: c.ChatModelSupportsVision,
SkipKBSearch: c.SkipKBSearch,
Language: c.Language,
}
}
+2
View File
@@ -21,6 +21,8 @@ const (
SessionTenantIDContextKey ContextKey = "SessionTenantID"
// EmbedQueryContextKey is the context key for embedding query text
EmbedQueryContextKey ContextKey = "EmbedQuery"
// LanguageContextKey is the context key for user language preference (e.g. "zh-CN", "en-US")
LanguageContextKey ContextKey = "Language"
)
// String returns the string representation of the context key
+46
View File
@@ -45,3 +45,49 @@ func SessionTenantIDFromContext(ctx context.Context) (uint64, bool) {
}
return TenantIDFromContext(ctx)
}
// LanguageFromContext extracts the language locale string from ctx (e.g. "zh-CN", "en-US").
// Returns ("en-US", false) when the key is absent.
func LanguageFromContext(ctx context.Context) (string, bool) {
v, ok := ctx.Value(LanguageContextKey).(string)
return v, ok && v != ""
}
// LanguageNameFromContext returns the human-readable language name for use in prompts.
// e.g. "zh-CN" -> "Chinese (Simplified)", "en-US" -> "English", "ko-KR" -> "Korean"
func LanguageNameFromContext(ctx context.Context) string {
lang, ok := LanguageFromContext(ctx)
if !ok {
lang = "en-US"
}
return LanguageLocaleName(lang)
}
// LanguageLocaleName maps a locale code to a human-readable language name for LLM prompts.
func LanguageLocaleName(locale string) string {
switch locale {
case "zh-CN", "zh", "zh-Hans":
return "Chinese (Simplified)"
case "zh-TW", "zh-HK", "zh-Hant":
return "Chinese (Traditional)"
case "en-US", "en", "en-GB":
return "English"
case "ko-KR", "ko":
return "Korean"
case "ja-JP", "ja":
return "Japanese"
case "ru-RU", "ru":
return "Russian"
case "fr-FR", "fr":
return "French"
case "de-DE", "de":
return "German"
case "es-ES", "es":
return "Spanish"
case "pt-BR", "pt":
return "Portuguese"
default:
// For unknown locales, return the locale itself
return locale
}
}
+10 -173
View File
@@ -67,8 +67,14 @@ type CustomAgentConfig struct {
AgentMode string `yaml:"agent_mode" json:"agent_mode"`
// System prompt for the agent (unified prompt, uses web_search_status placeholder for dynamic behavior)
SystemPrompt string `yaml:"system_prompt" json:"system_prompt"`
// SystemPromptID references a template ID in prompt_templates/ YAML files.
// If set and SystemPrompt is empty, the template content will be resolved at startup.
SystemPromptID string `yaml:"system_prompt_id" json:"system_prompt_id,omitempty"`
// Context template for normal mode (how to format retrieved chunks)
ContextTemplate string `yaml:"context_template" json:"context_template"`
// ContextTemplateID references a template ID in prompt_templates/ YAML files.
// If set and ContextTemplate is empty, the template content will be resolved at startup.
ContextTemplateID string `yaml:"context_template_id" json:"context_template_id,omitempty"`
// ===== Model Settings =====
// Model ID to use for conversations
@@ -251,179 +257,10 @@ func (a *CustomAgent) IsAgentMode() bool {
return a.Config.AgentMode == AgentModeSmartReasoning
}
// GetBuiltinQuickAnswerAgent returns the built-in quick answer (RAG) mode agent
func GetBuiltinQuickAnswerAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinQuickAnswerID,
Name: "Quick Answer",
Description: "Knowledge base RAG Q&A for fast and accurate answers",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeQuickAnswer,
SystemPrompt: "",
ContextTemplate: `Answer the user's question based on the following reference materials. IMPORTANT: Always respond in the same language as the user's question.
Reference materials:
{{contexts}}
User question: {{query}}`,
Temperature: 0.7,
MaxCompletionTokens: 2048,
WebSearchEnabled: true,
WebSearchMaxResults: 5,
MultiTurnEnabled: true,
HistoryTurns: 5,
KBSelectionMode: "all",
RetrieveKBOnlyWhenMentioned: false, // Default: retrieve KB based on KBSelectionMode
// FAQ strategy
FAQPriorityEnabled: true,
FAQDirectAnswerThreshold: 0.9,
FAQScoreBoost: 1.2,
// Retrieval strategy
EmbeddingTopK: 10,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 10,
RerankThreshold: 0.3,
// Advanced settings
EnableQueryExpansion: true,
EnableRewrite: true,
FallbackStrategy: "model",
},
}
}
// GetBuiltinSmartReasoningAgent returns the built-in smart reasoning (ReAct) mode agent
func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinSmartReasoningID,
Name: "Smart Reasoning",
Description: "ReAct reasoning framework with multi-step thinking and tool calling",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeSmartReasoning,
SystemPrompt: "",
Temperature: 0.7,
MaxCompletionTokens: 2048,
MaxIterations: 50,
KBSelectionMode: "all",
RetrieveKBOnlyWhenMentioned: false, // Default: retrieve KB based on KBSelectionMode
AllowedTools: []string{"thinking", "todo_write", "knowledge_search", "grep_chunks", "list_knowledge_chunks", "query_knowledge_graph", "get_document_info"},
WebSearchEnabled: true,
WebSearchMaxResults: 5,
ReflectionEnabled: false,
MultiTurnEnabled: true,
HistoryTurns: 5,
// FAQ strategy
FAQPriorityEnabled: true,
FAQDirectAnswerThreshold: 0.9,
FAQScoreBoost: 1.2,
// Retrieval strategy
EmbeddingTopK: 10,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 10,
RerankThreshold: 0.3,
},
}
}
// GetBuiltinDataAnalystAgent returns the built-in data analyst agent
// This agent specializes in analyzing CSV/Excel data using SQL queries via DuckDB
func GetBuiltinDataAnalystAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinDataAnalystID,
Name: "Data Analyst",
Description: "Professional data analysis agent with SQL query and statistical analysis for CSV/Excel files",
Avatar: "📊",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeSmartReasoning,
SystemPrompt: `### Role
You are WeKnora Data Analyst, an intelligent data analysis assistant powered by DuckDB. You specialize in analyzing structured data from CSV and Excel files using SQL queries.
### Mission
Help users explore, analyze, and derive insights from their tabular data through intelligent SQL query generation and execution.
### Critical Constraints
1. **Schema First:** ALWAYS call data_schema before writing any SQL query to understand the table structure.
2. **Read-Only:** Only SELECT queries allowed. INSERT, UPDATE, DELETE, CREATE, DROP are forbidden.
3. **Iterative Refinement:** If a query fails, analyze the error and refine your approach.
### Workflow
1. **Understand:** Call data_schema to get table name, columns, types, and row count.
2. **Plan:** For complex questions, use todo_write to break into sub-queries.
3. **Query:** Call data_analysis with the knowledge_id and SQL query.
4. **Analyze:** Interpret results and provide insights.
### SQL Best Practices for DuckDB
- Use double quotes for identifiers: SELECT "Column Name" FROM "table_name"
- Aggregate functions: COUNT(*), SUM(), AVG(), MIN(), MAX(), MEDIAN(), STDDEV()
- String matching: LIKE, ILIKE (case-insensitive), REGEXP
- Use LIMIT to prevent overwhelming output (default to 100 rows max)
### Tool Guidelines
- **data_schema:** ALWAYS use first. Required before any query.
- **data_analysis:** Execute SQL queries. Only SELECT queries allowed.
- **thinking:** Plan complex analyses, debug query issues.
- **todo_write:** Track multi-step analysis tasks.
### Output Standards
- Present results in well-formatted tables or summaries
- Provide actionable insights, not just raw numbers
- Relate findings back to the user's original question
Current Time: {{current_time}}
`,
Temperature: 0.3, // Lower temperature for precise SQL generation
MaxCompletionTokens: 4096,
MaxIterations: 30,
KBSelectionMode: "all",
RetrieveKBOnlyWhenMentioned: false, // Default: retrieve KB based on KBSelectionMode
// Only support CSV and Excel files for data analysis
// Use standard values (xlsx), backend will auto-include xls via alias
SupportedFileTypes: []string{"csv", "xlsx"},
// Core tools for data analysis
AllowedTools: []string{
"thinking",
"todo_write",
"data_schema", // Get table schema information
"data_analysis", // Execute SQL queries on data
},
WebSearchEnabled: false, // Data analysis doesn't need web search
WebSearchMaxResults: 0,
ReflectionEnabled: true, // Enable reflection for query optimization
MultiTurnEnabled: true,
HistoryTurns: 10, // More history for iterative analysis
// Retrieval strategy (minimal, as we focus on data tools)
EmbeddingTopK: 5,
KeywordThreshold: 0.3,
VectorThreshold: 0.5,
RerankTopK: 5,
RerankThreshold: 0.3,
},
}
}
// Deprecated: Use GetBuiltinQuickAnswerAgent instead
func GetBuiltinNormalAgent(tenantID uint64) *CustomAgent {
return GetBuiltinQuickAnswerAgent(tenantID)
}
// Deprecated: Use GetBuiltinSmartReasoningAgent instead
func GetBuiltinAgentAgent(tenantID uint64) *CustomAgent {
return GetBuiltinSmartReasoningAgent(tenantID)
}
// BuiltinAgentRegistry provides a registry of all built-in agents for easy extension
var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{
BuiltinQuickAnswerID: GetBuiltinQuickAnswerAgent,
BuiltinSmartReasoningID: GetBuiltinSmartReasoningAgent,
BuiltinDataAnalystID: GetBuiltinDataAnalystAgent,
}
// BuiltinAgentRegistry provides a registry of all built-in agents.
// It is initialised empty and populated by LoadBuiltinAgentsConfig from
// config/builtin_agents.yaml at startup via rebuildRegistryFromConfig.
var BuiltinAgentRegistry = map[string]func(uint64) *CustomAgent{}
// builtinAgentIDsOrdered defines the fixed display order of built-in agents
var builtinAgentIDsOrdered = []string{
+62
View File
@@ -1,5 +1,10 @@
package types
import (
"strings"
"time"
)
// PromptPlaceholder represents a placeholder that can be used in prompt templates
type PromptPlaceholder struct {
// Name is the placeholder name (without braces), e.g., "query"
@@ -86,6 +91,12 @@ var (
Label: "网络搜索状态",
Description: "网络搜索工具是否启用的状态(Enabled 或 Disabled)",
}
PlaceholderLanguage = PromptPlaceholder{
Name: "language",
Label: "用户语言",
Description: "用户界面的语言偏好,如 Chinese (Simplified)、English、Korean 等,用于控制 LLM 回答语言",
}
)
// PlaceholdersByField returns the available placeholders for a specific prompt field type
@@ -98,6 +109,7 @@ func PlaceholdersByField(fieldType PromptFieldType) []PromptPlaceholder {
PlaceholderContexts,
PlaceholderCurrentTime,
PlaceholderCurrentWeek,
PlaceholderLanguage,
}
case PromptFieldAgentSystemPrompt:
// Agent mode system prompt
@@ -105,6 +117,7 @@ func PlaceholdersByField(fieldType PromptFieldType) []PromptPlaceholder {
PlaceholderKnowledgeBases,
PlaceholderWebSearchStatus,
PlaceholderCurrentTime,
PlaceholderLanguage,
}
case PromptFieldContextTemplate:
return []PromptPlaceholder{
@@ -112,6 +125,7 @@ func PlaceholdersByField(fieldType PromptFieldType) []PromptPlaceholder {
PlaceholderContexts,
PlaceholderCurrentTime,
PlaceholderCurrentWeek,
PlaceholderLanguage,
}
case PromptFieldRewriteSystemPrompt:
// Rewrite system prompt supports same placeholders as rewrite user prompt
@@ -120,6 +134,7 @@ func PlaceholdersByField(fieldType PromptFieldType) []PromptPlaceholder {
PlaceholderConversation,
PlaceholderCurrentTime,
PlaceholderYesterday,
PlaceholderLanguage,
}
case PromptFieldRewritePrompt:
return []PromptPlaceholder{
@@ -127,10 +142,12 @@ func PlaceholdersByField(fieldType PromptFieldType) []PromptPlaceholder {
PlaceholderConversation,
PlaceholderCurrentTime,
PlaceholderYesterday,
PlaceholderLanguage,
}
case PromptFieldFallbackPrompt:
return []PromptPlaceholder{
PlaceholderQuery,
PlaceholderLanguage,
}
default:
return []PromptPlaceholder{}
@@ -149,6 +166,7 @@ func AllPlaceholders() []PromptPlaceholder {
PlaceholderAnswer,
PlaceholderKnowledgeBases,
PlaceholderWebSearchStatus,
PlaceholderLanguage,
}
}
@@ -163,3 +181,47 @@ func PlaceholderMap() map[PromptFieldType][]PromptPlaceholder {
PromptFieldFallbackPrompt: PlaceholdersByField(PromptFieldFallbackPrompt),
}
}
// ---------------------------------------------------------------------------
// Unified prompt placeholder rendering
// ---------------------------------------------------------------------------
// PlaceholderValues is a map of placeholder names (without braces) to their
// replacement values. Example: {"query": "How to use?", "language": "English"}
type PlaceholderValues map[string]string
// RenderPromptPlaceholders replaces all {{key}} occurrences in template with
// the corresponding values from vals. Unknown placeholders are left untouched.
//
// Built-in auto-values (filled when not supplied explicitly):
// - {{current_time}} -> time.Now().Format("2006-01-02 15:04:05")
// - {{current_week}} -> current weekday name
// - {{yesterday}} -> yesterday's date (2006-01-02)
func RenderPromptPlaceholders(template string, vals PlaceholderValues) string {
if template == "" {
return ""
}
// Populate auto-generated values when callers don't supply them.
autoFill := func(key, value string) {
if _, exists := vals[key]; !exists {
if strings.Contains(template, "{{"+key+"}}") {
vals[key] = value
}
}
}
now := time.Now()
autoFill("current_time", now.Format("2006-01-02 15:04:05"))
autoFill("current_week", now.Weekday().String())
autoFill("yesterday", now.AddDate(0, 0, -1).Format("2006-01-02"))
result := template
for key, value := range vals {
placeholder := "{{" + key + "}}"
if strings.Contains(result, placeholder) {
result = strings.ReplaceAll(result, placeholder, value)
}
}
return result
}