feat: Add Wiki Researcher agent and system prompt for enhanced knowledge retrieval

- Introduced a new built-in agent, "Wiki Researcher," designed for navigating and answering questions based on Wiki knowledge bases, complete with multilingual support.
- Added a corresponding system prompt that outlines the agent's role, mission, and workflow for effective knowledge graph traversal.
- Updated the agent configuration to include specific tools and parameters tailored for the Wiki Researcher, enhancing its functionality and user interaction.
- Removed deprecated wiki tools from the agent service to streamline the toolset and improve performance.

These changes significantly enhance the capabilities of the agent system, providing users with a specialized tool for in-depth research and information retrieval from Wiki sources.
This commit is contained in:
wizardchen
2026-04-09 21:31:37 +08:00
parent a75233c90f
commit 4715b10642
10 changed files with 191 additions and 362 deletions
-37
View File
@@ -208,43 +208,6 @@ const WikiLogEntryTemplate = `## [{{.Date}}] {{.Operation}} | {{.Title}}
- **Summary**: {{.Summary}}
`
// WikiAgentSystemPromptAddendum is appended to the Agent system prompt when
// wiki knowledge bases are detected among the search targets.
// It tells the LLM how and when to use wiki tools.
const WikiAgentSystemPromptAddendum = `
### Wiki Knowledge Base Guidelines
You have access to a **Wiki Knowledge Base** — a persistent, interlinked collection of LLM-generated Markdown pages. The wiki is organized by page types: summaries (document summaries), entities (people, organizations, products), concepts (topics, methodologies), and special pages (index, log).
#### Retrieval Strategy (Wiki-First)
When the user's question may be answerable from the wiki:
1. **Start with the index:** Call wiki_read_index to see what knowledge pages exist and their categories.
2. **Search if needed:** Call wiki_search with keywords to find relevant pages.
3. **Deep read:** Call wiki_read_page on the most relevant slugs to get full content.
4. **Follow links:** Wiki pages contain [[slug]] cross-references. Follow them to gather related context (1-2 hops).
5. **Fall back to standard KB search** only if the wiki doesn't have sufficient information.
#### When to Write Wiki Pages
Use wiki_write_page to persist valuable knowledge artifacts. Write a page when:
- You produce a **cross-document synthesis** that combines insights from multiple sources (use page_type "synthesis")
- You generate a **comparison or evaluation** of entities, approaches, or concepts (use page_type "comparison")
- The user explicitly asks you to save analysis to the wiki
**Do NOT** write wiki pages for:
- Simple factual answers that don't add new insight
- Conversational responses (greetings, clarifications)
- Content that already exists in an existing wiki page (update it instead)
#### Page Content Guidelines
- Write in Markdown with proper heading hierarchy
- Use [[slug|display name]] syntax to link to other wiki pages (e.g. [[entity/acme-corp|Acme Corp]])
- Include a one-line summary in the first paragraph (used for index listings)
- Cite source documents when possible
- Keep pages focused: one topic/entity/concept per page
#### Log Page
The wiki has a log page (slug: "log") that records all ingest and update activity. Read it when the user asks about recent changes, update history, or what's new in the knowledge base.
`
// WikiDeduplicationPrompt asks the LLM to identify duplicate entities/concepts
// between newly extracted items and existing wiki pages.
+2 -8
View File
@@ -23,11 +23,8 @@ const (
ToolExecuteSkillScript = "execute_skill_script"
ToolReadSkill = "read_skill"
// Wiki-related tools (only available when wiki KBs are in scope)
ToolWikiReadPage = "wiki_read_page"
ToolWikiWritePage = "wiki_write_page"
ToolWikiSearch = "wiki_search"
ToolWikiReadIndex = "wiki_read_index"
ToolWikiLint = "wiki_lint"
ToolWikiReadPage = "wiki_read_page"
ToolWikiSearch = "wiki_search"
)
// AvailableTool defines a simple tool metadata used by settings APIs.
@@ -55,10 +52,7 @@ func AvailableToolDefinitions() []AvailableTool {
{Name: ToolExecuteSkillScript, Label: "执行技能脚本", Description: "在沙箱环境中执行技能脚本"},
{Name: ToolFinalAnswer, Label: "提交最终回答", Description: "提交最终回答给用户"},
{Name: ToolWikiReadPage, Label: "读取Wiki页面", Description: "读取指定的Wiki页面内容"},
{Name: ToolWikiWritePage, Label: "写入Wiki页面", Description: "创建或更新Wiki页面"},
{Name: ToolWikiSearch, Label: "搜索Wiki", Description: "在Wiki中搜索页面"},
{Name: ToolWikiReadIndex, Label: "读取Wiki索引", Description: "读取Wiki索引目录"},
{Name: ToolWikiLint, Label: "Wiki健康检查", Description: "检查Wiki健康状况"},
}
}
+49 -289
View File
@@ -8,7 +8,6 @@ import (
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/google/uuid"
)
// ---- wiki_read_page ----
@@ -62,10 +61,51 @@ func (t *wikiReadPageTool) Execute(ctx context.Context, args json.RawMessage) (*
for _, kbID := range kbIDs {
page, err := t.wikiService.GetPageBySlug(ctx, kbID, params.Slug)
if err == nil && page != nil {
output := fmt.Sprintf("# %s\n**Type**: %s | **Version**: %d | **Updated**: %s\n**Links to**: %s\n**Linked from**: %s\n\n---\n\n%s",
page.Title, page.PageType, page.Version, page.UpdatedAt.Format("2006-01-02"),
strings.Join(page.OutLinks, ", "),
strings.Join(page.InLinks, ", "),
// Resolve OutLinks summaries to provide 1-hop context
var outLinksDesc []string
if len(page.OutLinks) > 0 {
for _, outSlug := range page.OutLinks {
if linkPage, err := t.wikiService.GetPageBySlug(ctx, kbID, outSlug); err == nil && linkPage != nil {
outLinksDesc = append(outLinksDesc, fmt.Sprintf("[[%s]] (%s)", outSlug, linkPage.Summary))
} else {
outLinksDesc = append(outLinksDesc, fmt.Sprintf("[[%s]]", outSlug))
}
}
} else {
outLinksDesc = []string{"(none)"}
}
// Resolve InLinks summaries to provide reverse 1-hop context
var inLinksDesc []string
if len(page.InLinks) > 0 {
for _, inSlug := range page.InLinks {
if linkPage, err := t.wikiService.GetPageBySlug(ctx, kbID, inSlug); err == nil && linkPage != nil {
inLinksDesc = append(inLinksDesc, fmt.Sprintf("[[%s]] (%s)", inSlug, linkPage.Summary))
} else {
inLinksDesc = append(inLinksDesc, fmt.Sprintf("[[%s]]", inSlug))
}
}
} else {
inLinksDesc = []string{"(none)"}
}
output := fmt.Sprintf(`<wiki_page>
<metadata>
<title>%s</title>
<slug>%s</slug>
<type>%s</type>
</metadata>
<relationships>
<links_to>%s</links_to>
<linked_from>%s</linked_from>
</relationships>
<content>
%s
</content>
</wiki_page>`,
page.Title, page.Slug, page.PageType,
strings.Join(outLinksDesc, ", "),
strings.Join(inLinksDesc, ", "),
page.Content,
)
return &types.ToolResult{Success: true, Output: output}, nil
@@ -75,115 +115,6 @@ func (t *wikiReadPageTool) Execute(ctx context.Context, args json.RawMessage) (*
return &types.ToolResult{Success: false, Error: fmt.Sprintf("Wiki page '%s' not found", params.Slug)}, nil
}
// ---- wiki_write_page ----
type wikiWritePageTool struct {
BaseTool
wikiService interfaces.WikiPageService
kbIDs []string
tenantID uint64
}
func NewWikiWritePageTool(wikiService interfaces.WikiPageService, kbIDs []string, tenantID uint64) types.Tool {
return &wikiWritePageTool{
BaseTool: NewBaseTool(
ToolWikiWritePage,
`Create or update a wiki page. Use this to save valuable analysis, synthesis, or new knowledge into the wiki.
The page content should be in Markdown format. Use [[slug]] syntax to create links between pages.`,
json.RawMessage(`{
"type": "object",
"properties": {
"slug": {
"type": "string",
"description": "Page slug (e.g. 'synthesis/quarterly-review', 'comparison/tool-a-vs-tool-b')"
},
"title": {
"type": "string",
"description": "Human-readable page title"
},
"content": {
"type": "string",
"description": "Full Markdown content of the page. Use [[slug]] for wiki links."
},
"page_type": {
"type": "string",
"enum": ["summary", "entity", "concept", "synthesis", "comparison"],
"description": "Type of wiki page"
},
"knowledge_base_id": {
"type": "string",
"description": "Target knowledge base ID. Required if multiple wiki KBs are available."
}
},
"required": ["slug", "title", "content", "page_type"]
}`),
),
wikiService: wikiService,
kbIDs: kbIDs,
tenantID: tenantID,
}
}
func (t *wikiWritePageTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
Slug string `json:"slug"`
Title string `json:"title"`
Content string `json:"content"`
PageType string `json:"page_type"`
KnowledgeBaseID string `json:"knowledge_base_id"`
}
if err := json.Unmarshal(args, &params); err != nil {
return &types.ToolResult{Success: false, Error: "Invalid parameters: " + err.Error()}, nil
}
kbID := params.KnowledgeBaseID
if kbID == "" && len(t.kbIDs) > 0 {
kbID = t.kbIDs[0]
}
if kbID == "" {
return &types.ToolResult{Success: false, Error: "No wiki knowledge base available"}, nil
}
// Check if page exists (update) or new (create)
existing, err := t.wikiService.GetPageBySlug(ctx, kbID, params.Slug)
if err == nil && existing != nil {
existing.Title = params.Title
existing.Content = params.Content
existing.PageType = params.PageType
existing.Summary = truncateForSummary(params.Content, 200)
if _, err := t.wikiService.UpdatePage(ctx, existing); err != nil {
return &types.ToolResult{Success: false, Error: "Failed to update page: " + err.Error()}, nil
}
return &types.ToolResult{
Success: true,
Output: fmt.Sprintf("Updated wiki page [[%s]] (v%d)", params.Slug, existing.Version),
}, nil
}
// Create new page
page := &types.WikiPage{
ID: uuid.New().String(),
TenantID: t.tenantID,
KnowledgeBaseID: kbID,
Slug: params.Slug,
Title: params.Title,
Content: params.Content,
PageType: params.PageType,
Status: types.WikiPageStatusPublished,
Summary: truncateForSummary(params.Content, 200),
}
if _, err := t.wikiService.CreatePage(ctx, page); err != nil {
return &types.ToolResult{Success: false, Error: "Failed to create page: " + err.Error()}, nil
}
return &types.ToolResult{
Success: true,
Output: fmt.Sprintf("Created wiki page [[%s]] — %s", params.Slug, params.Title),
}, nil
}
// ---- wiki_search ----
type wikiSearchTool struct {
@@ -241,191 +172,20 @@ func (t *wikiSearchTool) Execute(ctx context.Context, args json.RawMessage) (*ty
if len(allPages) == 0 {
return &types.ToolResult{
Success: true,
Output: fmt.Sprintf("No wiki pages found matching '%s'", params.Query),
Output: fmt.Sprintf("<search_results count=\"0\" query=\"%s\" />", params.Query),
}, nil
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Found %d wiki pages:\n\n", len(allPages)))
sb.WriteString(fmt.Sprintf("<search_results count=\"%d\" query=\"%s\">\n", len(allPages), params.Query))
for _, p := range allPages {
fmt.Fprintf(&sb, "- **[[%s]]** (%s) — %s\n", p.Slug, p.PageType, p.Summary)
fmt.Fprintf(&sb, "<page>\n<title>%s</title>\n<slug>%s</slug>\n<type>%s</type>\n<summary>%s</summary>\n</page>\n", p.Title, p.Slug, p.PageType, p.Summary)
}
sb.WriteString("</search_results>")
return &types.ToolResult{Success: true, Output: sb.String()}, nil
}
// ---- wiki_read_index ----
type wikiReadIndexTool struct {
BaseTool
wikiService interfaces.WikiPageService
kbIDs []string
}
func NewWikiReadIndexTool(wikiService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiReadIndexTool{
BaseTool: NewBaseTool(
ToolWikiReadIndex,
`Read the wiki index page. The index lists all wiki pages organized by category.
Use this first to understand what knowledge is available in the wiki before searching or reading specific pages.`,
json.RawMessage(`{
"type": "object",
"properties": {
"knowledge_base_id": {
"type": "string",
"description": "Optional: specific knowledge base ID"
}
}
}`),
),
wikiService: wikiService,
kbIDs: kbIDs,
}
}
func (t *wikiReadIndexTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
KnowledgeBaseID string `json:"knowledge_base_id"`
}
_ = json.Unmarshal(args, &params)
kbIDs := t.kbIDs
if params.KnowledgeBaseID != "" {
kbIDs = []string{params.KnowledgeBaseID}
}
var output strings.Builder
for _, kbID := range kbIDs {
indexPage, err := t.wikiService.GetIndex(ctx, kbID)
if err == nil && indexPage != nil {
if len(kbIDs) > 1 {
fmt.Fprintf(&output, "## Wiki Index (KB: %s)\n\n", kbID)
}
output.WriteString(indexPage.Content)
output.WriteString("\n\n")
}
}
if output.Len() == 0 {
return &types.ToolResult{Success: true, Output: "No wiki index found. The wiki may be empty."}, nil
}
return &types.ToolResult{Success: true, Output: output.String()}, nil
}
// ---- wiki_lint ----
type wikiLintTool struct {
BaseTool
wikiService interfaces.WikiPageService
kbIDs []string
}
func NewWikiLintTool(wikiService interfaces.WikiPageService, kbIDs []string) types.Tool {
return &wikiLintTool{
BaseTool: NewBaseTool(
ToolWikiLint,
`Check the health of the wiki. Reports issues like orphan pages, broken links, and provides statistics.
Use this to identify maintenance tasks and ensure wiki quality.`,
json.RawMessage(`{
"type": "object",
"properties": {
"knowledge_base_id": {
"type": "string",
"description": "Optional: specific knowledge base ID"
}
}
}`),
),
wikiService: wikiService,
kbIDs: kbIDs,
}
}
func (t *wikiLintTool) Execute(ctx context.Context, args json.RawMessage) (*types.ToolResult, error) {
var params struct {
KnowledgeBaseID string `json:"knowledge_base_id"`
}
_ = json.Unmarshal(args, &params)
kbIDs := t.kbIDs
if params.KnowledgeBaseID != "" {
kbIDs = []string{params.KnowledgeBaseID}
}
var output strings.Builder
for _, kbID := range kbIDs {
stats, err := t.wikiService.GetStats(ctx, kbID)
if err != nil {
fmt.Fprintf(&output, "## Wiki Health Check (KB: %s)\nError: %v\n\n", kbID, err)
continue
}
graph, _ := t.wikiService.GetGraph(ctx, kbID)
fmt.Fprintf(&output, "## Wiki Health Check (KB: %s)\n\n", kbID)
fmt.Fprintf(&output, "### Statistics\n")
fmt.Fprintf(&output, "- **Total pages**: %d\n", stats.TotalPages)
for pt, count := range stats.PagesByType {
fmt.Fprintf(&output, " - %s: %d\n", pt, count)
}
fmt.Fprintf(&output, "- **Total links**: %d\n", stats.TotalLinks)
fmt.Fprintf(&output, "- **Orphan pages** (no inbound links): %d\n", stats.OrphanCount)
// Health score (simple heuristic)
healthScore := 100
if stats.TotalPages > 0 {
orphanPct := float64(stats.OrphanCount) / float64(stats.TotalPages) * 100
if orphanPct > 50 {
healthScore -= 30
} else if orphanPct > 25 {
healthScore -= 15
}
}
if stats.TotalLinks == 0 && stats.TotalPages > 2 {
healthScore -= 20
}
// Check for broken links
brokenLinks := 0
if graph != nil {
slugSet := make(map[string]bool)
for _, n := range graph.Nodes {
slugSet[n.Slug] = true
}
for _, e := range graph.Edges {
if !slugSet[e.Target] {
brokenLinks++
}
}
}
if brokenLinks > 0 {
healthScore -= brokenLinks * 5
fmt.Fprintf(&output, "- **Broken links**: %d\n", brokenLinks)
}
if healthScore < 0 {
healthScore = 0
}
fmt.Fprintf(&output, "\n### Health Score: %d/100\n\n", healthScore)
// Suggestions
fmt.Fprintf(&output, "### Suggestions\n")
if stats.OrphanCount > 0 {
fmt.Fprintf(&output, "- Link orphan pages from related entity/concept pages\n")
}
if brokenLinks > 0 {
fmt.Fprintf(&output, "- Fix or remove %d broken [[wiki-link]] references\n", brokenLinks)
}
if stats.TotalPages < 3 {
fmt.Fprintf(&output, "- Wiki is sparse — consider ingesting more documents\n")
}
output.WriteString("\n")
}
return &types.ToolResult{Success: true, Output: output.String()}, nil
}
// --- Helper ---
func truncateForSummary(content string, maxLen int) string {
+2 -8
View File
@@ -56,10 +56,7 @@ func TestWikiToolConstants(t *testing.T) {
// Verify all wiki tool constants are defined and unique
names := []string{
ToolWikiReadPage,
ToolWikiWritePage,
ToolWikiSearch,
ToolWikiReadIndex,
ToolWikiLint,
}
seen := make(map[string]bool)
@@ -82,11 +79,8 @@ func TestWikiToolConstants(t *testing.T) {
func TestWikiToolsInAvailableDefinitions(t *testing.T) {
defs := AvailableToolDefinitions()
wikiTools := map[string]bool{
ToolWikiReadPage: false,
ToolWikiWritePage: false,
ToolWikiSearch: false,
ToolWikiReadIndex: false,
ToolWikiLint: false,
ToolWikiReadPage: false,
ToolWikiSearch: false,
}
for _, def := range defs {