feat: use language-neutral English prompts for multilingual LLM responses

Convert all LLM-facing prompts, templates, and tool output labels to
language-neutral English so the model responds in the user's input
language. Update frontend relevance/match-type mappings to match.

Output language strategy:
- User-facing: reply in user's input language
- Vector-indexed: match source document language
- LLM-internal: fixed English
This commit is contained in:
ochan.kwon
2026-03-06 20:24:23 +09:00
committed by lyingbug
parent db7cef5f17
commit edcf7116cd
28 changed files with 819 additions and 841 deletions
+16 -15
View File
@@ -518,7 +518,7 @@ func (e *AgentEngine) executeLoop(
common.PipelineError(ctx, "Agent", "final_answer_failed", map[string]interface{}{
"error": err.Error(),
})
state.FinalAnswer = "抱歉,我无法生成完整的答案。"
state.FinalAnswer = "Sorry, I was unable to generate a complete answer."
}
state.IsComplete = true
}
@@ -692,13 +692,13 @@ func (e *AgentEngine) streamReflectionToEventBus(
sessionID string,
) (string, error) {
// Simplified reflection without BuildReflectionPrompt
reflectionPrompt := fmt.Sprintf(`请评估刚才调用工具 %s 的结果,并决定下一步行动。
reflectionPrompt := fmt.Sprintf(`Evaluate the result of calling tool %s and decide the next action.
工具返回: %s
Tool returned: %s
思考:
1. 结果是否满足需求?
2. 下一步应该做什么?`, toolName, result)
Think:
1. Does the result satisfy the requirement?
2. What should be done next?`, toolName, result)
messages := []chat.Message{
{Role: "user", Content: reflectionPrompt},
@@ -853,7 +853,7 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
toolResultCount++
messages = append(messages, chat.Message{
Role: "user",
Content: fmt.Sprintf("工具 %s 返回: %s", toolCall.Name, toolCall.Result.Output),
Content: fmt.Sprintf("Tool %s returned: %s", toolCall.Name, toolCall.Result.Output),
})
logger.Debugf(ctx, "[Agent][FinalAnswer] Added tool result [Step-%d][Tool-%d]: %s (output: %d chars)",
stepIdx+1, toolIdx+1, toolCall.Name, len(toolCall.Result.Output))
@@ -864,17 +864,18 @@ func (e *AgentEngine) streamFinalAnswerToEventBus(
len(messages), toolResultCount)
// Add final answer prompt
finalPrompt := fmt.Sprintf(`基于上述工具调用结果,请为用户问题生成完整答案。
finalPrompt := fmt.Sprintf(`Based on the above tool call results, generate a complete answer for the user's question.
用户问题: %s
User question: %s
要求:
1. 基于实际检索到的内容回答
2. 清晰标注信息来源 (chunk_id, 文档名)
3. 结构化组织答案
4. 如信息不足,诚实说明
Requirements:
1. Answer based on the actually retrieved content
2. Clearly cite information sources (chunk_id, document name)
3. Organize the answer in a structured format
4. If information is insufficient, honestly state so
5. IMPORTANT: Respond in the same language as the user's question
现在请生成最终答案:`, query)
Now generate the final answer:`, query)
messages = append(messages, chat.Message{
Role: "user",
+10 -10
View File
@@ -228,18 +228,18 @@ func (t *DataAnalysisTool) executeSingleQuery(ctx context.Context, sqlQuery stri
func (t *DataAnalysisTool) formatQueryResults(results []map[string]string, query string) string {
var output strings.Builder
output.WriteString("=== DuckDB 查询结果 ===\n\n")
output.WriteString(fmt.Sprintf("执行的SQL: %s\n\n", query))
output.WriteString(fmt.Sprintf("返回 %d 行数据\n\n", len(results)))
output.WriteString("=== DuckDB Query Results ===\n\n")
output.WriteString(fmt.Sprintf("Executed SQL: %s\n\n", query))
output.WriteString(fmt.Sprintf("Returned %d rows\n\n", len(results)))
if len(results) == 0 {
output.WriteString("未找到匹配的记录。\n")
output.WriteString("No matching records found.\n")
return output.String()
}
output.WriteString("=== 数据详情 ===\n\n")
output.WriteString("=== Data Details ===\n\n")
if len(results) > 10 {
output.WriteString(fmt.Sprintf("显示了所有 %d 条记录。建议使用 LIMIT 子句限制结果数量以提高性能。\n\n", len(results)))
output.WriteString(fmt.Sprintf("Showing all %d records. Consider using a LIMIT clause to restrict the result count for better performance.\n\n", len(results)))
}
// Write each record as a separate JSON line
@@ -474,10 +474,10 @@ func (t *DataAnalysisTool) TableName(knowledge *types.Knowledge) string {
// buildSchemaDescription builds a formatted schema description
func (t *TableSchema) Description() string {
var builder strings.Builder
builder.WriteString(fmt.Sprintf("表名: %s\n", t.TableName))
builder.WriteString(fmt.Sprintf("列数: %d\n", len(t.Columns)))
builder.WriteString(fmt.Sprintf("行数: %d\n\n", t.RowCount))
builder.WriteString("列信息:\n")
builder.WriteString(fmt.Sprintf("Table name: %s\n", t.TableName))
builder.WriteString(fmt.Sprintf("Columns: %d\n", len(t.Columns)))
builder.WriteString(fmt.Sprintf("Rows: %d\n\n", t.RowCount))
builder.WriteString("Column info:\n")
for _, col := range t.Columns {
builder.WriteString(fmt.Sprintf("- %s (%s)\n", col.Name, col.Type))
+7 -7
View File
@@ -284,20 +284,20 @@ func (t *DatabaseQueryTool) formatQueryResults(
results []map[string]interface{},
query string,
) string {
output := "=== 查询结果 ===\n\n"
output += fmt.Sprintf("执行的SQL: %s\n\n", query)
output += fmt.Sprintf("返回 %d 行数据\n\n", len(results))
output := "=== Query Results ===\n\n"
output += fmt.Sprintf("Executed SQL: %s\n\n", query)
output += fmt.Sprintf("Returned %d rows\n\n", len(results))
if len(results) == 0 {
output += "未找到匹配的记录。\n"
output += "No matching records found.\n"
return output
}
output += "=== 数据详情 ===\n\n"
output += "=== Data Details ===\n\n"
// Format each row
for i, row := range results {
output += fmt.Sprintf("--- 记录 #%d ---\n", i+1)
output += fmt.Sprintf("--- Record #%d ---\n", i+1)
for _, col := range columns {
value := row[col]
// Format the value
@@ -325,7 +325,7 @@ func (t *DatabaseQueryTool) formatQueryResults(
// Add summary statistics if applicable
if len(results) > 10 {
output += fmt.Sprintf("注意: 显示了前 %d 条记录,共 %d 条。建议使用 LIMIT 子句限制结果数量。\n", len(results), len(results))
output += fmt.Sprintf("Note: Showing %d records out of %d total. Consider using a LIMIT clause to restrict the result count.\n", len(results), len(results))
}
return output
+25 -25
View File
@@ -121,7 +121,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
if err != nil {
mu.Lock()
results[id] = &docInfo{
err: fmt.Errorf("无法获取文档信息: %v", err),
err: fmt.Errorf("failed to get document info: %v", err),
}
mu.Unlock()
return
@@ -131,7 +131,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
if !t.searchTargets.ContainsKB(knowledge.KnowledgeBaseID) {
mu.Lock()
results[id] = &docInfo{
err: fmt.Errorf("知识库 %s 不可访问", knowledge.KnowledgeBaseID),
err: fmt.Errorf("knowledge base %s is not accessible", knowledge.KnowledgeBaseID),
}
mu.Unlock()
return
@@ -146,7 +146,7 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
if err != nil {
mu.Lock()
results[id] = &docInfo{
err: fmt.Errorf("无法获取文档信息: %v", err),
err: fmt.Errorf("failed to get document info: %v", err),
}
mu.Unlock()
return
@@ -180,16 +180,16 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
if len(successDocs) == 0 {
return &types.ToolResult{
Success: false,
Error: fmt.Sprintf("无法获取任何文档信息。错误: %v", errors),
Error: fmt.Sprintf("Failed to retrieve any document info. Errors: %v", errors),
}, fmt.Errorf("all document retrievals failed")
}
// Format output
output := "=== 文档信息 ===\n\n"
output += fmt.Sprintf("成功获取 %d / %d 个文档信息\n\n", len(successDocs), len(knowledgeIDs))
output := "=== Document Info ===\n\n"
output += fmt.Sprintf("Successfully retrieved %d / %d documents\n\n", len(successDocs), len(knowledgeIDs))
if len(errors) > 0 {
output += "=== 部分失败 ===\n"
output += "=== Partial Failures ===\n"
for _, errMsg := range errors {
output += fmt.Sprintf(" - %s\n", errMsg)
}
@@ -200,28 +200,28 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
for i, doc := range successDocs {
k := doc.knowledge
output += fmt.Sprintf("【文档 #%d】\n", i+1)
output += fmt.Sprintf(" ID: %s\n", k.ID)
output += fmt.Sprintf(" 标题: %s\n", k.Title)
output += fmt.Sprintf("[Document #%d]\n", i+1)
output += fmt.Sprintf(" ID: %s\n", k.ID)
output += fmt.Sprintf(" Title: %s\n", k.Title)
if k.Description != "" {
output += fmt.Sprintf(" 描述: %s\n", k.Description)
output += fmt.Sprintf(" Description: %s\n", k.Description)
}
output += fmt.Sprintf(" 来源: %s\n", formatSource(k.Type, k.Source))
output += fmt.Sprintf(" Source: %s\n", formatSource(k.Type, k.Source))
if k.FileName != "" {
output += fmt.Sprintf(" 文件名: %s\n", k.FileName)
output += fmt.Sprintf(" 文件类型: %s\n", k.FileType)
output += fmt.Sprintf(" 文件大小: %s\n", formatFileSize(k.FileSize))
output += fmt.Sprintf(" File Name: %s\n", k.FileName)
output += fmt.Sprintf(" File Type: %s\n", k.FileType)
output += fmt.Sprintf(" File Size: %s\n", formatFileSize(k.FileSize))
}
output += fmt.Sprintf(" 处理状态: %s\n", formatParseStatus(k.ParseStatus))
output += fmt.Sprintf(" 分块数量: %d 个\n", doc.chunkCount)
output += fmt.Sprintf(" Parse Status: %s\n", formatParseStatus(k.ParseStatus))
output += fmt.Sprintf(" Chunk Count: %d\n", doc.chunkCount)
if k.Metadata != nil {
if metadata, err := k.Metadata.Map(); err == nil && len(metadata) > 0 {
output += " 元数据:\n"
output += " Metadata:\n"
for key, value := range metadata {
output += fmt.Sprintf(" - %s: %v\n", key, value)
}
@@ -268,11 +268,11 @@ func (t *GetDocumentInfoTool) Execute(ctx context.Context, args json.RawMessage)
func formatSource(knowledgeType, source string) string {
switch knowledgeType {
case "file":
return "文件上传"
return "File Upload"
case "url":
return fmt.Sprintf("URL: %s", source)
case "passage":
return "文本输入"
return "Text Input"
default:
return knowledgeType
}
@@ -280,7 +280,7 @@ func formatSource(knowledgeType, source string) string {
func formatFileSize(size int64) string {
if size == 0 {
return "未知"
return "Unknown"
}
const unit = 1024
if size < unit {
@@ -297,13 +297,13 @@ func formatFileSize(size int64) string {
func formatParseStatus(status string) string {
switch status {
case "pending":
return "⏳ 待处理"
return "Pending"
case "processing":
return "🔄 处理中"
return "Processing"
case "completed", "success":
return "✅ 已完成"
return "Completed"
case "failed":
return "❌ 失败"
return "Failed"
default:
return status
}
+7 -7
View File
@@ -1178,7 +1178,7 @@ func (t *KnowledgeSearchTool) formatOutput(
}
// Add statistics and recommendations for each knowledge
output += "\n=== 检索统计与建议 ===\n\n"
output += "\n=== Retrieval Statistics ===\n\n"
for knowledgeID, retrievedChunks := range knowledgeChunkMap {
totalChunks := knowledgeTotalMap[knowledgeID]
retrievedCount := len(retrievedChunks)
@@ -1188,10 +1188,10 @@ func (t *KnowledgeSearchTool) formatOutput(
percentage := float64(retrievedCount) / float64(totalChunks) * 100
remaining := totalChunks - int64(retrievedCount)
output += fmt.Sprintf("文档: %s (%s)\n", title, knowledgeID)
output += fmt.Sprintf(" 总 Chunk 数: %d\n", totalChunks)
output += fmt.Sprintf(" 已召回: %d 个 (%.1f%%)\n", retrievedCount, percentage)
output += fmt.Sprintf(" 未召回: %d 个\n", remaining)
output += fmt.Sprintf("Document: %s (%s)\n", title, knowledgeID)
output += fmt.Sprintf(" Total Chunks: %d\n", totalChunks)
output += fmt.Sprintf(" Retrieved: %d (%.1f%%)\n", retrievedCount, percentage)
output += fmt.Sprintf(" Remaining: %d\n", remaining)
}
}
@@ -1255,10 +1255,10 @@ func (t *KnowledgeSearchTool) getEnrichedPassage(ctx context.Context, result *ty
var imageTexts []string
for _, img := range imageInfos {
if img.Caption != "" {
imageTexts = append(imageTexts, fmt.Sprintf("图片描述: %s", img.Caption))
imageTexts = append(imageTexts, fmt.Sprintf("Image Caption: %s", img.Caption))
}
if img.OCRText != "" {
imageTexts = append(imageTexts, fmt.Sprintf("图片文本: %s", img.OCRText))
imageTexts = append(imageTexts, fmt.Sprintf("Image Text: %s", img.OCRText))
}
}
+18 -18
View File
@@ -15,7 +15,7 @@ var listKnowledgeChunksTool = BaseTool{
description: `Retrieve full chunk content for a document by knowledge_id.
## Use After grep_chunks or knowledge_search:
1. grep_chunks(["keyword", "变体"]) → get knowledge_id
1. grep_chunks(["keyword", "variant"]) → get knowledge_id
2. list_knowledge_chunks(knowledge_id) → read full content
## When to Use:
@@ -245,52 +245,52 @@ func (t *ListKnowledgeChunksTool) buildOutput(
chunks []*types.Chunk,
) string {
builder := &strings.Builder{}
builder.WriteString("=== 知识文档分块 ===\n\n")
builder.WriteString("=== Knowledge Document Chunks ===\n\n")
if knowledgeTitle != "" {
fmt.Fprintf(builder, "文档: %s (%s)\n", knowledgeTitle, knowledgeID)
fmt.Fprintf(builder, "Document: %s (%s)\n", knowledgeTitle, knowledgeID)
} else {
fmt.Fprintf(builder, "文档 ID: %s\n", knowledgeID)
fmt.Fprintf(builder, "Document ID: %s\n", knowledgeID)
}
fmt.Fprintf(builder, "总分块数: %d\n", total)
fmt.Fprintf(builder, "Total chunks: %d\n", total)
if fetched == 0 {
builder.WriteString("未找到任何分块,请确认文档是否已完成解析。\n")
builder.WriteString("No chunks found. Please confirm the document has been parsed.\n")
if total > 0 {
builder.WriteString("文档存在但当前页数据为空,请检查分页参数。\n")
builder.WriteString("Document exists but the current page is empty. Please check pagination parameters.\n")
}
return builder.String()
}
fmt.Fprintf(
builder,
"本次拉取: %d 条, 检索范围: %d - %d\n\n",
"Fetched: %d chunks, range: %d - %d\n\n",
fetched,
chunks[0].ChunkIndex,
chunks[len(chunks)-1].ChunkIndex,
)
builder.WriteString("=== 分块内容预览 ===\n\n")
builder.WriteString("=== Chunk Content Preview ===\n\n")
for idx, c := range chunks {
fmt.Fprintf(builder, "Chunk #%d (Index %d)\n", idx+1, c.ChunkIndex+1)
fmt.Fprintf(builder, " chunk_id: %s\n", c.ID)
fmt.Fprintf(builder, " 类型: %s\n", c.ChunkType)
fmt.Fprintf(builder, " 内容: %s\n", summarizeContent(c.Content))
fmt.Fprintf(builder, " Type: %s\n", c.ChunkType)
fmt.Fprintf(builder, " Content: %s\n", summarizeContent(c.Content))
// 输出关联的图片信息
// Output associated image information
if c.ImageInfo != "" {
var imageInfos []types.ImageInfo
if err := json.Unmarshal([]byte(c.ImageInfo), &imageInfos); err == nil && len(imageInfos) > 0 {
fmt.Fprintf(builder, " 关联图片 (%d):\n", len(imageInfos))
fmt.Fprintf(builder, " Associated images (%d):\n", len(imageInfos))
for imgIdx, img := range imageInfos {
fmt.Fprintf(builder, " 图片 %d:\n", imgIdx+1)
fmt.Fprintf(builder, " Image %d:\n", imgIdx+1)
if img.URL != "" {
fmt.Fprintf(builder, " URL: %s\n", img.URL)
}
if img.Caption != "" {
fmt.Fprintf(builder, " 描述: %s\n", img.Caption)
fmt.Fprintf(builder, " Caption: %s\n", img.Caption)
}
if img.OCRText != "" {
fmt.Fprintf(builder, " OCR文本: %s\n", img.OCRText)
fmt.Fprintf(builder, " OCR Text: %s\n", img.OCRText)
}
}
}
@@ -299,7 +299,7 @@ func (t *ListKnowledgeChunksTool) buildOutput(
}
if int64(fetched) < total {
builder.WriteString("提示:文档仍有更多分块,可调整 offset 或多次调用以获取全部内容。\n")
builder.WriteString("Note: The document has more chunks. Adjust offset or make multiple calls to retrieve all content.\n")
}
return builder.String()
@@ -309,7 +309,7 @@ func (t *ListKnowledgeChunksTool) buildOutput(
func summarizeContent(content string) string {
cleaned := strings.TrimSpace(content)
if cleaned == "" {
return "(空内容)"
return "(empty)"
}
return strings.TrimSpace(string(cleaned))
+34 -34
View File
@@ -57,7 +57,7 @@ If KB is not configured with graph, tool will return regular search results.
// QueryKnowledgeGraphInput defines the input parameters for query knowledge graph tool
type QueryKnowledgeGraphInput struct {
KnowledgeBaseIDs []string `json:"knowledge_base_ids" jsonschema:"Array of knowledge base IDs to query"`
Query string `json:"query" jsonschema:"查询内容(实体名称或查询文本)"`
Query string `json:"query" jsonschema:"Query content (entity name or query text)"`
}
// QueryKnowledgeGraphTool queries the knowledge graph for entities and relationships
@@ -135,7 +135,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
kb, err := t.knowledgeService.GetKnowledgeBaseByID(ctx, id)
if err != nil {
mu.Lock()
kbResults[id] = &graphQueryResult{kbID: id, err: fmt.Errorf("获取知识库失败: %v", err)}
kbResults[id] = &graphQueryResult{kbID: id, err: fmt.Errorf("failed to get knowledge base: %v", err)}
mu.Unlock()
return
}
@@ -143,7 +143,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
// Check if graph extraction is enabled
if kb.ExtractConfig == nil || (len(kb.ExtractConfig.Nodes) == 0 && len(kb.ExtractConfig.Relations) == 0) {
mu.Lock()
kbResults[id] = &graphQueryResult{kbID: id, err: fmt.Errorf("未配置知识图谱抽取")}
kbResults[id] = &graphQueryResult{kbID: id, err: fmt.Errorf("graph extraction not configured")}
mu.Unlock()
return
}
@@ -152,7 +152,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
results, err := t.knowledgeService.HybridSearch(ctx, id, searchParams)
if err != nil {
mu.Lock()
kbResults[id] = &graphQueryResult{kbID: id, kb: kb, err: fmt.Errorf("查询失败: %v", err)}
kbResults[id] = &graphQueryResult{kbID: id, kb: kb, err: fmt.Errorf("query failed: %v", err)}
mu.Unlock()
return
}
@@ -206,7 +206,7 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
if len(allResults) == 0 {
return &types.ToolResult{
Success: true,
Output: "未找到相关的图谱信息。",
Output: "No relevant graph information found.",
Data: map[string]interface{}{
"knowledge_base_ids": input.KnowledgeBaseIDs,
"query": query,
@@ -218,13 +218,13 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
}
// Format output with enhanced graph information
output := "=== 知识图谱查询 ===\n\n"
output += fmt.Sprintf("📊 查询: %s\n", query)
output += fmt.Sprintf("🎯 目标知识库: %v\n", input.KnowledgeBaseIDs)
output += fmt.Sprintf("✓ 找到 %d 条相关结果(已去重)\n\n", len(allResults))
output := "=== Knowledge Graph Query ===\n\n"
output += fmt.Sprintf("📊 Query: %s\n", query)
output += fmt.Sprintf("🎯 Target Knowledge Bases: %v\n", input.KnowledgeBaseIDs)
output += fmt.Sprintf("✓ Found %d relevant results (deduplicated)\n\n", len(allResults))
if len(errors) > 0 {
output += "=== ⚠️ 部分失败 ===\n"
output += "=== ⚠️ Partial Failures ===\n"
for _, errMsg := range errors {
output += fmt.Sprintf(" - %s\n", errMsg)
}
@@ -233,16 +233,16 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
// Display graph configuration status
hasGraphConfig := false
output += "=== 📈 图谱配置状态 ===\n\n"
output += "=== 📈 Graph Configuration Status ===\n\n"
for kbID, config := range graphConfigs {
hasGraphConfig = true
output += fmt.Sprintf("知识库【%s】:\n", kbID)
output += fmt.Sprintf("Knowledge Base [%s]:\n", kbID)
nodes, _ := config["nodes"].([]interface{})
relations, _ := config["relations"].([]interface{})
if len(nodes) > 0 {
output += fmt.Sprintf(" ✓ 实体类型 (%d): ", len(nodes))
output += fmt.Sprintf(" ✓ Entity Types (%d): ", len(nodes))
nodeNames := make([]string, 0, len(nodes))
for _, n := range nodes {
if nodeMap, ok := n.(map[string]interface{}); ok {
@@ -253,11 +253,11 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
}
output += fmt.Sprintf("%v\n", nodeNames)
} else {
output += " ⚠️ 未配置实体类型\n"
output += " ⚠️ No entity types configured\n"
}
if len(relations) > 0 {
output += fmt.Sprintf(" ✓ 关系类型 (%d): ", len(relations))
output += fmt.Sprintf(" ✓ Relationship Types (%d): ", len(relations))
relNames := make([]string, 0, len(relations))
for _, r := range relations {
if relMap, ok := r.(map[string]interface{}); ok {
@@ -268,31 +268,31 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
}
output += fmt.Sprintf("%v\n", relNames)
} else {
output += " ⚠️ 未配置关系类型\n"
output += " ⚠️ No relationship types configured\n"
}
output += "\n"
}
if !hasGraphConfig {
output += "⚠️ 所查询的知识库均未配置图谱抽取\n"
output += "💡 提示: 需要在知识库设置中配置实体和关系类型\n\n"
output += "⚠️ None of the queried knowledge bases have graph extraction configured\n"
output += "💡 Hint: Configure entity and relationship types in knowledge base settings\n\n"
}
// Display result counts by KB
if len(kbCounts) > 0 {
output += "=== 📚 知识库覆盖 ===\n"
output += "=== 📚 Knowledge Base Coverage ===\n"
for kbID, count := range kbCounts {
output += fmt.Sprintf(" - %s: %d 条结果\n", kbID, count)
output += fmt.Sprintf(" - %s: %d results\n", kbID, count)
}
output += "\n"
}
// Display search results
output += "=== 🔍 查询结果 ===\n\n"
output += "=== 🔍 Query Results ===\n\n"
if !hasGraphConfig {
output += "💡 当前返回相关文档片段(知识库未配置图谱)\n\n"
output += "💡 Returning relevant document chunks (knowledge base has no graph configuration)\n\n"
} else {
output += "💡 基于图谱配置的相关内容检索\n\n"
output += "💡 Content retrieval based on graph configuration\n\n"
}
formattedResults := make([]map[string]interface{}, 0, len(allResults))
@@ -305,15 +305,15 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
if i > 0 {
output += "\n"
}
output += fmt.Sprintf("【来源文档: %s】\n\n", result.KnowledgeTitle)
output += fmt.Sprintf("[Source Document: %s]\n\n", result.KnowledgeTitle)
}
relevanceLevel := GetRelevanceLevel(result.Score)
output += fmt.Sprintf("结果 #%d:\n", i+1)
output += fmt.Sprintf(" 📍 相关度: %.2f (%s)\n", result.Score, relevanceLevel)
output += fmt.Sprintf(" 🔗 匹配方式: %s\n", FormatMatchType(result.MatchType))
output += fmt.Sprintf(" 📄 内容: %s\n", result.Content)
output += fmt.Sprintf("Result #%d:\n", i+1)
output += fmt.Sprintf(" 📍 Relevance: %.2f (%s)\n", result.Score, relevanceLevel)
output += fmt.Sprintf(" 🔗 Match Type: %s\n", FormatMatchType(result.MatchType))
output += fmt.Sprintf(" 📄 Content: %s\n", result.Content)
output += fmt.Sprintf(" 🆔 chunk_id: %s\n\n", result.ID)
formattedResults = append(formattedResults, map[string]interface{}{
@@ -328,14 +328,14 @@ func (t *QueryKnowledgeGraphTool) Execute(ctx context.Context, args json.RawMess
})
}
output += "=== 💡 使用提示 ===\n"
output += "- ✓ 结果已跨知识库去重并按相关度排序\n"
output += "- ✓ 使用 get_chunk_detail 获取完整内容\n"
output += "- ✓ 使用 list_knowledge_chunks 探索上下文\n"
output += "=== 💡 Tips ===\n"
output += "- ✓ Results are deduplicated across knowledge bases and sorted by relevance\n"
output += "- ✓ Use get_chunk_detail to get full content\n"
output += "- ✓ Use list_knowledge_chunks to explore context\n"
if !hasGraphConfig {
output += "- ⚠️ 配置图谱抽取以获得更精准的实体关系结果\n"
output += "- ⚠️ Configure graph extraction for more precise entity-relationship results\n"
}
output += "- ⏳ 完整的图查询语言(Cypher)支持开发中\n"
output += "- ⏳ Full graph query language (Cypher) support is under development\n"
// Build structured graph data for frontend visualization
graphData := buildGraphVisualizationData(allResults, graphConfigs)
+30 -30
View File
@@ -173,7 +173,7 @@ func (t *TodoWriteTool) Execute(ctx context.Context, args json.RawMessage) (*typ
}
if input.Task == "" {
input.Task = "未提供任务描述"
input.Task = "No task description provided"
}
// Parse plan steps
@@ -227,17 +227,17 @@ func getStringArrayField(m map[string]interface{}, key string) []string {
// generatePlanOutput generates a formatted plan output
func generatePlanOutput(task string, steps []PlanStep) string {
output := "计划已创建\n\n"
output += fmt.Sprintf("**任务**: %s\n\n", task)
output := "Plan created\n\n"
output += fmt.Sprintf("**Task**: %s\n\n", task)
if len(steps) == 0 {
output += "注意:未提供具体步骤。建议创建3-7个检索任务以系统化研究。\n\n"
output += "建议的检索流程(专注于检索任务,不包含总结):\n"
output += "1. 使用 grep_chunks 搜索关键词定位相关文档\n"
output += "2. 使用 knowledge_search 进行语义搜索获取相关内容\n"
output += "3. 使用 list_knowledge_chunks 获取关键文档的完整内容\n"
output += "4. 使用 web_search 获取补充信息(如需要)\n"
output += "\n注意:总结和综合由 thinking 工具处理,不要在此处添加总结任务。\n"
output += "Note: No specific steps provided. It is recommended to create 3-7 retrieval tasks for systematic research.\n\n"
output += "Suggested retrieval workflow (focused on retrieval tasks, excluding summarization):\n"
output += "1. Use grep_chunks to search keywords and locate relevant documents\n"
output += "2. Use knowledge_search for semantic search to retrieve relevant content\n"
output += "3. Use list_knowledge_chunks to get the full content of key documents\n"
output += "4. Use web_search to get supplementary information (if needed)\n"
output += "\nNote: Summarization and synthesis are handled by the thinking tool. Do not add summarization tasks here.\n"
return output
}
@@ -258,7 +258,7 @@ func generatePlanOutput(task string, steps []PlanStep) string {
totalCount := len(steps)
remainingCount := pendingCount + inProgressCount
output += "**计划步骤**:\n\n"
output += "**Plan Steps**:\n\n"
// Display all steps in order
for i, step := range steps {
@@ -266,32 +266,32 @@ func generatePlanOutput(task string, steps []PlanStep) string {
}
// Add summary and emphasis on remaining tasks
output += "\n=== 任务进度 ===\n"
output += fmt.Sprintf("总计: %d 个任务\n", totalCount)
output += fmt.Sprintf("✅ 已完成: %d 个\n", completedCount)
output += fmt.Sprintf("🔄 进行中: %d 个\n", inProgressCount)
output += fmt.Sprintf("⏳ 待处理: %d 个\n", pendingCount)
output += "\n=== Task Progress ===\n"
output += fmt.Sprintf("Total: %d tasks\n", totalCount)
output += fmt.Sprintf("✅ Completed: %d\n", completedCount)
output += fmt.Sprintf("🔄 In Progress: %d\n", inProgressCount)
output += fmt.Sprintf("⏳ Pending: %d\n", pendingCount)
output += "\n=== ⚠️ 重要提醒 ===\n"
output += "\n=== ⚠️ Important Reminder ===\n"
if remainingCount > 0 {
output += fmt.Sprintf("**还有 %d 个任务未完成!**\n\n", remainingCount)
output += "**必须完成所有任务后才能总结或得出结论。**\n\n"
output += "下一步操作:\n"
output += fmt.Sprintf("**%d tasks remaining!**\n\n", remainingCount)
output += "**All tasks must be completed before summarizing or drawing conclusions.**\n\n"
output += "Next steps:\n"
if inProgressCount > 0 {
output += "- 继续完成当前进行中的任务\n"
output += "- Continue completing tasks currently in progress\n"
}
if pendingCount > 0 {
output += fmt.Sprintf("- 开始处理 %d 个待处理任务\n", pendingCount)
output += "- 按顺序完成每个任务,不要跳过\n"
output += fmt.Sprintf("- Start processing %d pending tasks\n", pendingCount)
output += "- Complete each task in order, do not skip\n"
}
output += "- 完成每个任务后,更新 todo_write 标记为 completed\n"
output += "- 只有在所有任务完成后,才能生成最终总结\n"
output += "- After completing each task, update todo_write to mark it as completed\n"
output += "- Only generate the final summary after all tasks are completed\n"
} else {
output += "✅ **所有任务已完成!**\n\n"
output += "现在可以:\n"
output += "- 综合所有任务的发现\n"
output += "- 生成完整的最终答案或报告\n"
output += "- 确保所有方面都已充分研究\n"
output += "✅ **All tasks completed!**\n\n"
output += "You can now:\n"
output += "- Synthesize findings from all tasks\n"
output += "- Generate a complete final answer or report\n"
output += "- Ensure all aspects have been thoroughly researched\n"
}
return output
+12 -12
View File
@@ -52,13 +52,13 @@ type ToolExecutor interface {
func GetRelevanceLevel(score float64) string {
switch {
case score >= 0.8:
return "高相关"
return "High Relevance"
case score >= 0.6:
return "中相关"
return "Medium Relevance"
case score >= 0.4:
return "低相关"
return "Low Relevance"
default:
return "弱相关"
return "Weak Relevance"
}
}
@@ -66,20 +66,20 @@ func GetRelevanceLevel(score float64) string {
func FormatMatchType(mt types.MatchType) string {
switch mt {
case types.MatchTypeEmbedding:
return "向量匹配"
return "Vector Match"
case types.MatchTypeKeywords:
return "关键词匹配"
return "Keyword Match"
case types.MatchTypeNearByChunk:
return "相邻块匹配"
return "Adjacent Chunk Match"
case types.MatchTypeHistory:
return "历史匹配"
return "History Match"
case types.MatchTypeParentChunk:
return "父块匹配"
return "Parent Chunk Match"
case types.MatchTypeRelationChunk:
return "关系块匹配"
return "Relation Chunk Match"
case types.MatchTypeGraph:
return "图谱匹配"
return "Graph Match"
default:
return fmt.Sprintf("未知类型(%d)", mt)
return fmt.Sprintf("Unknown Type(%d)", mt)
}
}
+9 -9
View File
@@ -45,13 +45,13 @@ var webFetchTool = BaseTool{
// WebFetchInput defines the input parameters for web fetch tool
type WebFetchInput struct {
Items []WebFetchItem `json:"items" jsonschema:"批量抓取任务,每项包含 url 与 prompt"`
Items []WebFetchItem `json:"items" jsonschema:"Batch fetch tasks, each containing a url and prompt"`
}
// WebFetchItem represents a single web fetch task
type WebFetchItem struct {
URL string `json:"url" jsonschema:"待抓取的网页 URL,需来自 web_search 结果"`
Prompt string `json:"prompt" jsonschema:"分析该网页内容时使用的提示词"`
URL string `json:"url" jsonschema:"URL of the web page to fetch, should come from web_search results"`
Prompt string `json:"prompt" jsonschema:"Prompt for analyzing the fetched web page content"`
}
// webFetchParams is the parameters for the web fetch tool
@@ -147,7 +147,7 @@ func (t *WebFetchTool) Execute(ctx context.Context, args json.RawMessage) (*type
"prompt": p.Prompt,
"error": err.Error(),
},
output: fmt.Sprintf("URL: %s\n错误: %v\n\n", p.URL, err),
output: fmt.Sprintf("URL: %s\nError: %v\n\n", p.URL, err),
}
return
}
@@ -176,7 +176,7 @@ func (t *WebFetchTool) Execute(ctx context.Context, args json.RawMessage) (*type
if firstErr == nil {
firstErr = fmt.Errorf("fetch item %d returned nil", idx)
}
builder.WriteString(fmt.Sprintf("#%d: 无结果(内部错误)\n\n", idx+1))
builder.WriteString(fmt.Sprintf("#%d: No result (internal error)\n\n", idx+1))
continue
}
@@ -317,7 +317,7 @@ func (t *WebFetchTool) executeFetch(
htmlContent, method, err := t.fetchHTMLContent(ctx, vp)
if err != nil {
logger.Errorf(ctx, "[Tool][WebFetch] 获取页面失败 url=%s err=%v", vp.URL, err)
return fmt.Sprintf("URL: %s\n错误: %v\n", displayURL, err),
return fmt.Sprintf("URL: %s\nError: %v\n", displayURL, err),
map[string]interface{}{
"url": displayURL,
"prompt": vp.Prompt,
@@ -364,11 +364,11 @@ func (t *WebFetchTool) processWithLLM(ctx context.Context, params webFetchParams
return "", fmt.Errorf("chat model not available for web_fetch")
}
systemMessage := "你是一名擅长阅读网页内容的智能助手,请根据提供的网页文本回答用户需求,严禁编造未在文本中出现的信息。"
userTemplate := `用户请求:
systemMessage := "You are an intelligent assistant skilled at reading web page content. Answer the user's request based on the provided web page text. Never fabricate information that does not appear in the text."
userTemplate := `User request:
%s
网页内容:
Web page content:
%s`
messages := []chat.Message{
@@ -71,31 +71,31 @@ func (p *PluginIntoChatMessage) OnEvent(ctx context.Context,
pipelineWarn(ctx, "IntoChatMessage", "invalid_query", map[string]interface{}{
"session_id": chatManage.SessionID,
})
return ErrTemplateExecute.WithError(fmt.Errorf("用户查询包含非法内容"))
return ErrTemplateExecute.WithError(fmt.Errorf("user query contains invalid content"))
}
// Prepare weekday names
weekdayName := []string{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}
weekdayName := []string{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
var contextsBuilder strings.Builder
// Build contexts string based on FAQ priority strategy
if chatManage.FAQPriorityEnabled && len(faqResults) > 0 {
// Build structured context with FAQ prioritization
contextsBuilder.WriteString("### 资料来源 1:标准问答库 (FAQ)\n")
contextsBuilder.WriteString("【高置信度 - 请优先参考】\n")
contextsBuilder.WriteString("### Source 1: FAQ Knowledge Base\n")
contextsBuilder.WriteString("[High Confidence - Prioritize these results]\n")
for i, result := range faqResults {
passage := getEnrichedPassageForChat(ctx, result)
if hasHighConfidenceFAQ && i == 0 {
contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] ⭐ 精准匹配: %s\n", i+1, passage))
contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] Exact Match: %s\n", i+1, passage))
} else {
contextsBuilder.WriteString(fmt.Sprintf("[FAQ-%d] %s\n", i+1, passage))
}
}
if len(docResults) > 0 {
contextsBuilder.WriteString("\n### 资料来源 2:参考文档\n")
contextsBuilder.WriteString("【补充资料 - 仅在FAQ无法解答时参考】\n")
contextsBuilder.WriteString("\n### Source 2: Reference Documents\n")
contextsBuilder.WriteString("[Supplementary - Use only when FAQ cannot answer the question]\n")
for i, result := range docResults {
passage := getEnrichedPassageForChat(ctx, result)
contextsBuilder.WriteString(fmt.Sprintf("[DOC-%d] %s\n", i+1, passage))
@@ -208,10 +208,10 @@ func enrichContentWithImageInfo(ctx context.Context, content string, imageInfoJS
if found && imgInfo != nil {
replacement := match[0] + "\n"
if imgInfo.Caption != "" {
replacement += fmt.Sprintf("图片描述: %s\n", imgInfo.Caption)
replacement += fmt.Sprintf("Image Caption: %s\n", imgInfo.Caption)
}
if imgInfo.OCRText != "" {
replacement += fmt.Sprintf("图片文本: %s\n", imgInfo.OCRText)
replacement += fmt.Sprintf("Image Text: %s\n", imgInfo.OCRText)
}
content = strings.Replace(content, match[0], replacement, 1)
}
@@ -227,10 +227,10 @@ func enrichContentWithImageInfo(ctx context.Context, content string, imageInfoJS
var imgTexts []string
if imgInfo.Caption != "" {
imgTexts = append(imgTexts, fmt.Sprintf("图片 %s 的描述信息: %s", imgInfo.URL, imgInfo.Caption))
imgTexts = append(imgTexts, fmt.Sprintf("Image %s caption: %s", imgInfo.URL, imgInfo.Caption))
}
if imgInfo.OCRText != "" {
imgTexts = append(imgTexts, fmt.Sprintf("图片 %s 的文本: %s", imgInfo.URL, imgInfo.OCRText))
imgTexts = append(imgTexts, fmt.Sprintf("Image %s text: %s", imgInfo.URL, imgInfo.OCRText))
}
if len(imgTexts) > 0 {
@@ -243,7 +243,7 @@ func enrichContentWithImageInfo(ctx context.Context, content string, imageInfoJS
if content != "" {
content += "\n\n"
}
content += "附加图片信息:\n" + strings.Join(additionalImageTexts, "\n")
content += "Additional Image Info:\n" + strings.Join(additionalImageTexts, "\n")
}
pipelineInfo(ctx, "IntoChatMessage", "image_enrich_summary", map[string]interface{}{
@@ -218,9 +218,9 @@ func formatConversationHistory(historyList []*types.History) string {
var builder strings.Builder
for _, h := range historyList {
builder.WriteString("------BEGIN------\n")
builder.WriteString("用户的问题是:")
builder.WriteString("User question: ")
builder.WriteString(h.Query)
builder.WriteString("\n助手的回答是:")
builder.WriteString("\nAssistant answer: ")
builder.WriteString(h.Answer)
builder.WriteString("\n------END------\n")
}
+39 -37
View File
@@ -23,58 +23,60 @@ import (
)
const (
// tableDescriptionPromptTemplate 表格描述生成的 prompt 模板
tableDescriptionPromptTemplate = `你是一个数据分析专家。请根据以下表格的结构信息和数据样本,生成一段简洁的表格元数据描述(200-300字)。
// tableDescriptionPromptTemplate is the prompt template for generating table descriptions
tableDescriptionPromptTemplate = `You are a data analysis expert. Based on the following table structure information and data samples, generate a concise table metadata description (200-300 words).
表名: %s
Table name: %s
%s
%s
请从以下维度描述这个表格:
1. **数据主题**:这个表格记录的是什么类型的数据?(如:用户信息、销售记录、日志数据等)
2. **核心字段**:列出3-5个最重要的字段及其含义
3. **数据规模**:总行数和列数
4. **业务场景**:这个表格可能用于什么业务分析或应用场景?
5. **关键特征**:数据有什么显著特点?(如:包含地理位置、有分类标签、存在层级关系等)
Please describe the table from the following dimensions:
1. **Data Subject**: What type of data does this table record? (e.g., user information, sales records, log data, etc.)
2. **Core Fields**: List 3-5 most important fields and their meanings
3. **Data Scale**: Total number of rows and columns
4. **Business Scenarios**: What business analysis or application scenarios might this table be used for?
5. **Key Characteristics**: What notable features does the data have? (e.g., contains geographic locations, has category labels, has hierarchical relationships, etc.)
**重要提示**:
- 不要输出具体的数据值或样本内容
- 使用概括性的描述,让用户能快速判断这个表格是否包含他们需要的信息
- 用简洁专业的语言,便于检索和理解`
**Important Notes**:
- Do not output specific data values or sample content
- Use general descriptions so users can quickly determine if this table contains the information they need
- Use concise and professional language for easy retrieval and understanding
- Write the description in the same language as the data content`
// columnDescriptionsPromptTemplate 列描述生成的 prompt 模板
columnDescriptionsPromptTemplate = `你是一个数据分析专家。请根据以下表格的结构信息和数据样本,为每一列生成结构化的描述信息。
// columnDescriptionsPromptTemplate is the prompt template for generating column descriptions
columnDescriptionsPromptTemplate = `You are a data analysis expert. Based on the following table structure information and data samples, generate structured description information for each column.
表名: %s
Table name: %s
%s
%s
请为每一列生成详细的描述,包含以下信息:
1. **字段含义**:这一列存储的是什么信息?(如:用户ID、订单金额、创建时间等)
2. **数据类型**:数据的类型和格式(如:整数、字符串、日期时间、布尔值等)
3. **业务用途**:这个字段在业务中的作用(如:用于用户识别、金额计算、时间排序等)
4. **数据特征**:数据的显著特点(如:唯一标识、可为空、有枚举值、有单位等)
Please generate a detailed description for each column, including the following information:
1. **Field Meaning**: What information does this column store? (e.g., user ID, order amount, creation time, etc.)
2. **Data Type**: The type and format of the data (e.g., integer, string, datetime, boolean, etc.)
3. **Business Purpose**: The role of this field in business (e.g., for user identification, amount calculation, time sorting, etc.)
4. **Data Characteristics**: Notable features of the data (e.g., unique identifier, nullable, has enum values, has units, etc.)
请按以下格式输出(每列一个段落):
Please output in the following format (one paragraph per column):
**列名1** (数据类型)
- 字段含义:xxx
- 业务用途:xxx
- 数据特征:xxx
**Column1** (data type)
- Field Meaning: xxx
- Business Purpose: xxx
- Data Characteristics: xxx
**列名2** (数据类型)
- 字段含义:xxx
- 业务用途:xxx
- 数据特征:xxx
**Column2** (data type)
- Field Meaning: xxx
- Business Purpose: xxx
- Data Characteristics: xxx
**重要提示**:
- 不要输出具体的数据值,只描述字段的元信息
- 使用清晰的业务术语,便于用户理解和搜索
- 如果从样本数据中能推断出枚举值范围,可以概括说明(如:状态字段包含待处理/进行中/已完成等状态)`
**Important Notes**:
- Do not output specific data values, only describe the field metadata
- Use clear business terms for easy user understanding and search
- If enum value ranges can be inferred from sample data, provide a summary (e.g., status field contains pending/in-progress/completed states)
- Write descriptions in the same language as the data content`
)
// NewChunkExtractTask creates a new chunk extract task
@@ -612,7 +614,7 @@ func (s *DataTableSummaryService) generateTableDescription(ctx context.Context,
return "", fmt.Errorf("failed to generate table description: %w", err)
}
return fmt.Sprintf("# 表格摘要\n\n表名: %s\n\n%s", tableName, response.Content), nil
return fmt.Sprintf("# Table Summary\n\nTable name: %s\n\n%s", tableName, response.Content), nil
}
// generateColumnDescriptions generates descriptions for each column in batch
@@ -634,13 +636,13 @@ func (s *DataTableSummaryService) generateColumnDescriptions(ctx context.Context
return "", fmt.Errorf("failed to generate column descriptions: %w", err)
}
return fmt.Sprintf("# 表格列信息\n\n表名: %s\n\n%s", tableName, response.Content), nil
return fmt.Sprintf("# Table Column Information\n\nTable name: %s\n\n%s", tableName, response.Content), nil
}
// buildSampleDataDescription builds a formatted sample data description
func (s *DataTableSummaryService) buildSampleDataDescription(sampleData *types.ToolResult, maxRows int) string {
var builder strings.Builder
builder.WriteString(fmt.Sprintf("前%d行数据示例:\n", maxRows))
builder.WriteString(fmt.Sprintf("Sample data (first %d rows):\n", maxRows))
rows, ok := sampleData.Data["rows"].([]map[string]interface{})
if !ok {
+1 -1
View File
@@ -992,7 +992,7 @@ func (b *graphBuilder) generateKnowledgeGraphDiagram(ctx context.Context) string
// only draw if there are multiple entities or at least one relationship in the subgraph
if hasRelations {
subgraphCount++
sb.WriteString(fmt.Sprintf("\n subgraph 子图%d\n", subgraphCount))
sb.WriteString(fmt.Sprintf("\n subgraph Subgraph%d\n", subgraphCount))
// add all entities in this subgraph
entitiesInComponent := make(map[string]bool)
@@ -22,14 +22,14 @@ import (
)
const (
vlmOCRPrompt = "请提取这张文档图片中的所有正文内容,用纯 Markdown 格式输出。要求:\n" +
"1. 忽略页眉、页脚\n" +
"2. 表格使用 Markdown 表格语法\n" +
"3. 公式使用 LaTeX 格式(用 $ 或 $$ 包裹)\n" +
"4. 按照原文阅读顺序组织\n" +
"5. 只输出提取到的文本内容,不要添加任何 HTML 标签\n" +
"如果图片中没有可识别的文字内容,请回复:无文字内容。"
vlmCaptionPrompt = "简单凝炼的描述图片的主要内容"
vlmOCRPrompt = "Extract all body text content from this document image and output in pure Markdown format. Requirements:\n" +
"1. Ignore headers and footers\n" +
"2. Use Markdown table syntax for tables\n" +
"3. Use LaTeX format for formulas (wrapped with $ or $$)\n" +
"4. Organize content in the original reading order\n" +
"5. Only output extracted text content, do not add any HTML tags\n" +
"If there is no recognizable text content in the image, reply: No text content."
vlmCaptionPrompt = "Provide a brief and concise description of the main content of the image"
)
// ImageMultimodalService handles image:multimodal asynq tasks.
+35 -29
View File
@@ -1809,10 +1809,10 @@ func (s *knowledgeService) getSummary(ctx context.Context,
var imageAnnotations string
for _, img := range allImageInfos {
if img.Caption != "" {
imageAnnotations += fmt.Sprintf("\n[图片描述: %s]", img.Caption)
imageAnnotations += fmt.Sprintf("\n[Image Description: %s]", img.Caption)
}
if img.OCRText != "" {
imageAnnotations += fmt.Sprintf("\n[图片文字: %s]", img.OCRText)
imageAnnotations += fmt.Sprintf("\n[Image OCR Text: %s]", img.OCRText)
}
}
@@ -1829,15 +1829,15 @@ func (s *knowledgeService) getSummary(ctx context.Context,
// Add knowledge metadata if available
if knowledge != nil {
metadataIntro := fmt.Sprintf("文档类型: %s\n文件名称: %s\n", knowledge.FileType, knowledge.FileName)
metadataIntro := fmt.Sprintf("Document Type: %s\nFile Name: %s\n", knowledge.FileType, knowledge.FileName)
// Add additional metadata if available
if knowledge.Type != "" {
metadataIntro += fmt.Sprintf("知识类型: %s\n", knowledge.Type)
metadataIntro += fmt.Sprintf("Knowledge Type: %s\n", knowledge.Type)
}
// Prepend metadata to content
contentWithMetadata = metadataIntro + "\n内容:\n" + contentWithMetadata
contentWithMetadata = metadataIntro + "\nContent:\n" + contentWithMetadata
}
// Generate summary using AI model
@@ -2035,7 +2035,7 @@ func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asyn
TenantID: knowledge.TenantID,
KnowledgeID: knowledge.ID,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
Content: fmt.Sprintf("# 文档名称\n%s\n\n# 摘要\n%s", knowledge.FileName, summary),
Content: fmt.Sprintf("# Document\n%s\n\n# Summary\n%s", knowledge.FileName, summary),
ChunkIndex: maxChunkIndex + 1,
IsEnabled: true,
CreatedAt: time.Now(),
@@ -2282,12 +2282,12 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
// Build context section
var contextSection string
if prevContent != "" || nextContent != "" {
contextSection = "## 上下文信息(仅供参考,帮助理解主要内容)\n"
contextSection = "## Context Information (for reference only, to help understand the main content)\n"
if prevContent != "" {
contextSection += fmt.Sprintf("【前文】%s\n", prevContent)
contextSection += fmt.Sprintf("[Preceding Context] %s\n", prevContent)
}
if nextContent != "" {
contextSection += fmt.Sprintf("【后文】%s\n", nextContent)
contextSection += fmt.Sprintf("[Following Context] %s\n", nextContent)
}
contextSection += "\n"
}
@@ -2335,32 +2335,38 @@ func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
}
// Default prompt for question generation with context support
const defaultQuestionGenerationPrompt = `你是一个专业的问题生成助手。你的任务是根据给定的【主要内容】生成用户可能会问的相关问题。
const defaultQuestionGenerationPrompt = `You are a professional question generation assistant. Your task is to generate related questions that users might ask based on the given [Main Content].
{{context}}
## 主要内容(请基于此内容生成问题)
文档名称:{{doc_name}}
文档内容:
## Main Content (generate questions based on this content)
Document name: {{doc_name}}
Document content:
{{content}}
## 核心要求
- 生成的问题必须与【主要内容】直接相关
- 问题中禁止使用任何代词或指代词(如"它"、"这个"、"该文档"、"本文"、"文中"、"其"等),必须用具体名称替代
- 问题必须是完整独立的,脱离上下文也能被理解
- 问题应该是用户在实际场景中可能会提出的自然问题
- 问题应该多样化,覆盖内容的不同方面
- 每个问题应该简洁明了,长度控制在30字以内
- 生成的问题数量为 {{question_count}} 个
## Core Requirements
- Generated questions must be directly related to the [Main Content]
- Questions must NOT use any pronouns or referential words (such as "it", "this", "that document", "this article", "the text", "its", etc.); use specific names instead
- Questions must be complete and self-contained, understandable without additional context
- Questions should be natural questions that users would likely ask in real scenarios
- Questions should be diverse, covering different aspects of the content
- Each question should be concise and clear, within 30 words
- Generate {{question_count}} questions
## 问题类型建议
- 定义类:什么是...?...是什么?
- 原因类:为什么...?...的原因是什么?
- 方法类:如何...?怎样...?
- 比较类:...和...有什么区别?
- 应用类:...可以用于什么场景?
## Suggested Question Types
- Definition: What is...? What does... mean?
- Reason: Why...? What is the reason for...?
- Method: How to...? What is the way to...?
- Comparison: What is the difference between... and...?
- Application: What scenarios can... be used for?
## 输出格式
直接输出问题列表,每行一个问题,不要有序号或其他前缀。`
## Output Format
Output the question list directly, one question per line, without numbering or other prefixes.
## CRITICAL: Language Rule
- Generate questions in the SAME LANGUAGE as the source document
- If the document is in Korean, generate questions in Korean
- If the document is in English, generate questions in English
- If the document is in Chinese, generate questions in Chinese`
// GetKnowledgeFile retrieves the physical file associated with a knowledge entry
func (s *knowledgeService) GetKnowledgeFile(ctx context.Context, id string) (io.ReadCloser, string, error) {
@@ -16,6 +16,7 @@ var (
"无文字内容",
"无法识别",
"no text",
"no text content",
"no content",
"empty",
"图片中没有文字",
@@ -94,8 +95,11 @@ func ocrHTMLToMarkdown(content string) string {
// isKnownEmptyReply checks whether the text matches a known "no content"
// reply pattern that VLM models produce when the image has no text.
// Trailing punctuation (., !, ?) is stripped before comparison so that
// responses like "No text content." still match "no text content".
func isKnownEmptyReply(text string) bool {
lower := strings.ToLower(strings.TrimSpace(text))
lower = strings.TrimRight(lower, ".!?。!?")
for _, phrase := range knownEmptyReplies {
if lower == strings.ToLower(phrase) {
return true
+9 -9
View File
@@ -241,19 +241,19 @@ func (a *CustomAgent) IsAgentMode() bool {
func GetBuiltinQuickAnswerAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinQuickAnswerID,
Name: "快速问答",
Description: "基于知识库的 RAG 问答,快速准确地回答问题",
Name: "Quick Answer",
Description: "Knowledge base RAG Q&A for fast and accurate answers",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
AgentMode: AgentModeQuickAnswer,
SystemPrompt: "",
ContextTemplate: `请根据以下参考资料回答用户问题。
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}}
用户问题:{{query}}`,
User question: {{query}}`,
Temperature: 0.7,
MaxCompletionTokens: 2048,
WebSearchEnabled: true,
@@ -284,8 +284,8 @@ func GetBuiltinQuickAnswerAgent(tenantID uint64) *CustomAgent {
func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinSmartReasoningID,
Name: "智能推理",
Description: "ReAct 推理框架,支持多步思考和工具调用",
Name: "Smart Reasoning",
Description: "ReAct reasoning framework with multi-step thinking and tool calling",
IsBuiltin: true,
TenantID: tenantID,
Config: CustomAgentConfig{
@@ -321,8 +321,8 @@ func GetBuiltinSmartReasoningAgent(tenantID uint64) *CustomAgent {
func GetBuiltinDataAnalystAgent(tenantID uint64) *CustomAgent {
return &CustomAgent{
ID: BuiltinDataAnalystID,
Name: "数据分析师",
Description: "专业数据分析智能体,支持 CSV/Excel 文件的 SQL 查询与统计分析",
Name: "Data Analyst",
Description: "Professional data analysis agent with SQL query and statistical analysis for CSV/Excel files",
Avatar: "📊",
IsBuiltin: true,
TenantID: tenantID,