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
+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{