2025-11-05 15:18:44 +00:00
package agent
import (
"fmt"
"strings"
2025-11-12 13:27:56 +00:00
"time"
2025-11-05 15:18:44 +00:00
)
// formatFileSize formats file size in human-readable format
func formatFileSize ( size int64 ) string {
const (
KB = 1024
MB = 1024 * KB
GB = 1024 * MB
)
if size < KB {
return fmt . Sprintf ( "%d B" , size )
} else if size < MB {
return fmt . Sprintf ( "%.2f KB" , float64 ( size ) / KB )
} else if size < GB {
return fmt . Sprintf ( "%.2f MB" , float64 ( size ) / MB )
}
return fmt . Sprintf ( "%.2f GB" , float64 ( size ) / GB )
}
2025-11-12 13:27:56 +00:00
// formatDocSummary cleans and truncates document summaries for table display
func formatDocSummary ( summary string , maxLen int ) string {
cleaned := strings . TrimSpace ( summary )
if cleaned == "" {
return "-"
}
cleaned = strings . ReplaceAll ( cleaned , "\n" , " " )
cleaned = strings . ReplaceAll ( cleaned , "\r" , " " )
cleaned = strings . Join ( strings . Fields ( cleaned ) , " " )
runes := [ ] rune ( cleaned )
if len ( runes ) <= maxLen {
return cleaned
}
return strings . TrimSpace ( string ( runes [ : maxLen ] ) ) + "..."
}
2025-11-05 15:18:44 +00:00
// RecentDocInfo contains brief information about a recently added document
type RecentDocInfo struct {
2025-11-25 05:28:21 +00:00
ChunkID string
KnowledgeBaseID string
2025-11-17 07:33:43 +00:00
KnowledgeID string
Title string
Description string
FileName string
FileSize int64
Type string
CreatedAt string // Formatted time string
FAQStandardQuestion string
FAQSimilarQuestions [ ] string
FAQAnswers [ ] string
2025-11-05 15:18:44 +00:00
}
// KnowledgeBaseInfo contains essential information about a knowledge base for agent prompt
type KnowledgeBaseInfo struct {
ID string
Name string
2025-11-17 07:33:43 +00:00
Type string // Knowledge base type: "document" or "faq"
2025-11-05 15:18:44 +00:00
Description string
DocCount int
RecentDocs [ ] RecentDocInfo // Recently added documents (up to 10)
}
2025-11-10 12:11:45 +00:00
// PlaceholderDefinition defines a placeholder exposed to UI/configuration
type PlaceholderDefinition struct {
Name string ` json:"name" `
Label string ` json:"label" `
Description string ` json:"description" `
}
// AvailablePlaceholders lists all supported prompt placeholders for UI hints
func AvailablePlaceholders ( ) [ ] PlaceholderDefinition {
return [ ] PlaceholderDefinition {
{
Name : "knowledge_bases" ,
Label : "知识库列表" ,
Description : "自动格式化为表格形式的知识库列表,包含知识库名称、描述、文档数量、最近添加的文档等信息" ,
} ,
2025-11-11 14:26:59 +00:00
{
Name : "web_search_status" ,
Label : "网络检索模式开关状态" ,
Description : "网络检索( web_search) 工具是否启用的状态说明, 值为 Enabled 或 Disabled" ,
} ,
2025-11-12 13:27:56 +00:00
{
Name : "current_time" ,
Label : "当前系统时间" ,
Description : "格式为 RFC3339 的当前系统时间,用于帮助模型感知实时性" ,
} ,
2025-11-10 12:11:45 +00:00
}
}
2025-11-05 15:18:44 +00:00
// formatKnowledgeBaseList formats knowledge base information for the prompt
func formatKnowledgeBaseList ( kbInfos [ ] * KnowledgeBaseInfo ) string {
if len ( kbInfos ) == 0 {
return "None"
}
var builder strings . Builder
builder . WriteString ( "\n" )
for i , kb := range kbInfos {
2025-11-17 07:33:43 +00:00
// Display knowledge base name and ID
2025-11-05 15:18:44 +00:00
builder . WriteString ( fmt . Sprintf ( "%d. **%s** (knowledge_base_id: `%s`)\n" , i + 1 , kb . Name , kb . ID ) )
2025-11-17 07:33:43 +00:00
// Display knowledge base type
kbType := kb . Type
if kbType == "" {
kbType = "document" // Default type
}
builder . WriteString ( fmt . Sprintf ( " - Type: %s\n" , kbType ) )
2025-11-05 15:18:44 +00:00
if kb . Description != "" {
builder . WriteString ( fmt . Sprintf ( " - Description: %s\n" , kb . Description ) )
}
builder . WriteString ( fmt . Sprintf ( " - Document count: %d\n" , kb . DocCount ) )
2025-11-25 05:28:21 +00:00
// Display recent documents if available
// For FAQ type knowledge bases, adjust the display format
if len ( kb . RecentDocs ) > 0 {
if kbType == "faq" {
// FAQ knowledge base: show Q&A pairs in a more compact format
builder . WriteString ( " - Recent FAQ entries:\n\n" )
builder . WriteString ( " | # | Question | Answers | Chunk ID | Knowledge ID | Created At |\n" )
builder . WriteString ( " |---|-------------------|---------|----------|--------------|------------|\n" )
for j , doc := range kb . RecentDocs {
if j >= 10 { // Limit to 10 documents
break
}
question := doc . FAQStandardQuestion
if question == "" {
question = doc . FileName
}
answers := "-"
if len ( doc . FAQAnswers ) > 0 {
answers = strings . Join ( doc . FAQAnswers , " | " )
}
builder . WriteString ( fmt . Sprintf ( " | %d | %s | %s | `%s` | `%s` | %s |\n" ,
j + 1 , question , answers , doc . ChunkID , doc . KnowledgeID , doc . CreatedAt ) )
}
} else {
// Document knowledge base: show documents in standard format
builder . WriteString ( " - Recently added documents:\n\n" )
builder . WriteString ( " | # | Document Name | Type | Created At | Knowledge ID | File Size | Summary |\n" )
builder . WriteString ( " |---|---------------|------|------------|--------------|----------|---------|\n" )
for j , doc := range kb . RecentDocs {
if j >= 10 { // Limit to 10 documents
break
}
docName := doc . Title
if docName == "" {
docName = doc . FileName
}
// Format file size
fileSize := formatFileSize ( doc . FileSize )
summary := formatDocSummary ( doc . Description , 120 )
builder . WriteString ( fmt . Sprintf ( " | %d | %s | %s | %s | `%s` | %s | %s |\n" ,
j + 1 , docName , doc . Type , doc . CreatedAt , doc . KnowledgeID , fileSize , summary ) )
}
}
builder . WriteString ( "\n" )
}
builder . WriteString ( "\n" )
2025-11-05 15:18:44 +00:00
}
return builder . String ( )
}
2025-11-09 15:17:39 +00:00
// renderPromptPlaceholders renders placeholders in the prompt template
// Supported placeholders:
// - {{knowledge_bases}} - Replaced with formatted knowledge base list
func renderPromptPlaceholders ( template string , knowledgeBases [ ] * KnowledgeBaseInfo ) string {
result := template
// Replace {{knowledge_bases}} placeholder
if strings . Contains ( result , "{{knowledge_bases}}" ) {
kbList := formatKnowledgeBaseList ( knowledgeBases )
result = strings . ReplaceAll ( result , "{{knowledge_bases}}" , kbList )
}
return result
}
2025-11-11 14:26:59 +00:00
// renderPromptPlaceholdersWithStatus renders placeholders including web search status
// Supported placeholders:
// - {{knowledge_bases}}
// - {{web_search_status}} -> "Enabled" or "Disabled"
2025-11-12 13:27:56 +00:00
// - {{current_time}} -> current time string
2025-11-28 08:17:52 +00:00
func renderPromptPlaceholdersWithStatus (
template string ,
knowledgeBases [ ] * KnowledgeBaseInfo ,
webSearchEnabled bool ,
currentTime string ,
) string {
2025-11-11 14:26:59 +00:00
result := renderPromptPlaceholders ( template , knowledgeBases )
status := "Disabled"
if webSearchEnabled {
status = "Enabled"
}
if strings . Contains ( result , "{{web_search_status}}" ) {
result = strings . ReplaceAll ( result , "{{web_search_status}}" , status )
}
2025-11-12 13:27:56 +00:00
if strings . Contains ( result , "{{current_time}}" ) {
result = strings . ReplaceAll ( result , "{{current_time}}" , currentTime )
}
2025-11-11 14:26:59 +00:00
return result
}
2025-12-01 09:24:57 +00:00
// BuildSystemPromptWithWeb builds the progressive RAG system prompt with web search enabled
func BuildSystemPromptWithWeb (
2025-11-28 08:17:52 +00:00
knowledgeBases [ ] * KnowledgeBaseInfo ,
systemPromptTemplate ... string ,
) string {
2025-11-19 11:27:25 +00:00
var template string
if len ( systemPromptTemplate ) > 0 && systemPromptTemplate [ 0 ] != "" {
template = systemPromptTemplate [ 0 ]
} else {
template = ProgressiveRAGSystemPromptWithWeb
}
currentTime := time . Now ( ) . Format ( time . RFC3339 )
return renderPromptPlaceholdersWithStatus ( template , knowledgeBases , true , currentTime )
}
2025-12-01 09:24:57 +00:00
// BuildSystemPromptWithoutWeb builds the progressive RAG system prompt without web search
func BuildSystemPromptWithoutWeb (
2025-11-28 08:17:52 +00:00
knowledgeBases [ ] * KnowledgeBaseInfo ,
systemPromptTemplate ... string ,
) string {
2025-11-19 11:27:25 +00:00
var template string
if len ( systemPromptTemplate ) > 0 && systemPromptTemplate [ 0 ] != "" {
template = systemPromptTemplate [ 0 ]
} else {
template = ProgressiveRAGSystemPromptWithoutWeb
}
currentTime := time . Now ( ) . Format ( time . RFC3339 )
return renderPromptPlaceholdersWithStatus ( template , knowledgeBases , false , currentTime )
}
// BuildProgressiveRAGSystemPrompt builds the progressive RAG system prompt based on web search status
// This is the main function to use - it automatically selects the appropriate version
2025-12-01 09:24:57 +00:00
func BuildSystemPrompt (
2025-11-28 08:17:52 +00:00
knowledgeBases [ ] * KnowledgeBaseInfo ,
webSearchEnabled bool ,
systemPromptTemplate ... string ,
) string {
2025-11-19 11:27:25 +00:00
if webSearchEnabled {
2025-12-01 09:24:57 +00:00
return BuildSystemPromptWithWeb ( knowledgeBases , systemPromptTemplate ... )
2025-11-19 11:27:25 +00:00
}
2025-12-01 09:24:57 +00:00
return BuildSystemPromptWithoutWeb ( knowledgeBases , systemPromptTemplate ... )
2025-11-19 11:27:25 +00:00
}
// ProgressiveRAGSystemPromptWithWeb is the progressive RAG system prompt template with web search enabled
// This version emphasizes hybrid retrieval strategy: KB-first with web supplementation
2025-11-27 06:19:57 +00:00
var ProgressiveRAGSystemPromptWithWeb = ` # # # Role
2025-11-27 09:56:53 +00:00
You are WeKnora , an intelligent retrieval assistant powered by Progressive Agentic RAG . You operate in a multi - tenant environment with strictly isolated knowledge bases . Your core philosophy is "Evidence-First" : you never rely on internal parametric knowledge but construct answers solely from verified data retrieved from the Knowledge Base ( KB ) or Web .
2025-11-27 06:19:57 +00:00
# # # Mission
2025-11-27 09:56:53 +00:00
To deliver accurate , traceable , and verifiable answers by orchestrating a dynamic retrieval process . You must first gauge the information landscape through preliminary retrieval , then rigorously execute and reflect upon specific research tasks . * * You prioritize "Deep Reading" over superficial scanning . * *
2025-11-27 06:19:57 +00:00
# # # Critical Constraints ( ABSOLUTE RULES )
2025-11-27 09:56:53 +00:00
1. * * NO Internal Knowledge : * * You must behave as if your training data does not exist regarding facts .
2. * * Mandatory Deep Read : * * Whenever grep_chunks or knowledge_search returns matched knowledge_ids or chunk_ids , you * * MUST * * immediately call list_knowledge_chunks to read the full content of those specific chunks . Do not rely on search snippets alone .
3. * * KB First , Web Second : * * Always exhaust KB strategies ( including the Deep Read ) before attempting Web Search .
4. * * Strict Plan Adherence : * * If a todo_write plan exists , execute it sequentially . No skipping .
5. * * Tool Privacy : * * Never expose tool names to the user .
2025-11-27 06:19:57 +00:00
# # # Workflow : The "Reconnaissance-Plan-Execute" Cycle
# # # # Phase 1 : Preliminary Reconnaissance ( Mandatory Initial Step )
2025-11-27 09:56:53 +00:00
Before answering or creating a plan , you MUST perform a "Deep Read" test of the KB to gain preliminary cognition .
1. * * Search : * * Execute grep_chunks ( keyword ) and knowledge_search ( semantic ) based on core entities .
2. * * DEEP READ ( Crucial ) : * * If the search returns IDs , you * * MUST * * call list_knowledge_chunks on the top relevant IDs to fetch their actual text .
3. * * Analyze : * * In your think block , evaluate the * full text * you just retrieved .
* * Does this text fully answer the user ? *
* * Is the information complete or partial ? *
2025-11-27 06:19:57 +00:00
# # # # Phase 2 : Strategic Decision & Planning
2025-11-27 09:56:53 +00:00
Based on the * * Deep Read * * results from Phase 1 :
* * * Path A ( Direct Answer ) : * * If the full text provides sufficient , unambiguous evidence → Proceed to * * Answer Generation * * .
* * * Path B ( Complex Research ) : * * If the query involves comparison , missing data , or the content requires synthesis → Use todo_write to formulate a Work Plan .
* * Structure : * Break the problem into distinct retrieval tasks ( e . g . , "Deep read specs for Product A" , "Deep read safety protocols" ) .
2025-11-27 06:19:57 +00:00
# # # # Phase 3 : Disciplined Execution & Deep Reflection ( The Loop )
2025-11-27 09:56:53 +00:00
If in * * Path B * * , execute tasks in todo_write sequentially . For * * EACH * * task :
1. * * Search : * * Perform grep_chunks / knowledge_search for the sub - task .
2. * * DEEP READ ( Mandatory ) : * * Call list_knowledge_chunks for any relevant IDs found . * * Never skip this step . * *
3. * * MANDATORY Deep Reflection ( in think ) : * * Pause and evaluate the full text :
* * Validity : * "Does this full text specifically address the sub-task?"
2025-11-27 10:29:04 +00:00
* * Gap Analysis : * "Is anything missing? Is the information outdated? Is the information irrelevant?"
2025-11-27 09:56:53 +00:00
* * Correction : * If insufficient , formulate a remedial action ( e . g . , "Search for synonym X" , "Web Search" ) immediately .
* * Completion : * Mark task as "completed" ONLY when evidence is secured .
2025-11-27 06:19:57 +00:00
# # # # Phase 4 : Final Synthesis
2025-11-27 10:29:04 +00:00
Only when ALL todo_write tasks are "completed" :
2025-11-27 09:56:53 +00:00
* Synthesize findings from the full text of all retrieved chunks .
* Check for consistency .
2025-11-27 06:19:57 +00:00
* Generate the final response .
2025-11-27 09:56:53 +00:00
# # # Core Retrieval Strategy ( Strict Sequence )
For every retrieval attempt ( Phase 1 or Phase 3 ) , follow this exact chain :
1. * * Entity Anchoring ( grep_chunks ) : * * Use short keywords ( 1 - 3 words ) to find candidate documents .
2. * * Semantic Expansion ( knowledge_search ) : * * Use vector search for context ( filter by IDs from step 1 if applicable ) .
2025-11-27 10:29:04 +00:00
3. * * Deep Contextualization ( list_knowledge_chunks ) : MANDATORY . * *
* Rule : After Step 1 or 2 returns knowledge_ids , you MUST call this tool .
* Frequency : Call it frequently for multiple IDs to ensure you have the full results . * * Do not be lazy ; fetch the content . * *
4. * * Graph Exploration ( query_knowledge_graph ) : * * Optional for relationships .
5. * * Fallback ( web_search ) : * * Use ONLY if the Deep Read in Step 3 confirms the data is missing or irrelevant .
2025-11-27 06:19:57 +00:00
# # # Tool Selection Guidelines
2025-11-27 09:56:53 +00:00
* * * grep_chunks / knowledge_search : * * Your "Index" . Use these to find * where * the information might be .
2025-11-27 10:29:04 +00:00
* * * list_knowledge_chunks : * * Your "Eyes" . MUST be used after every search . Use to read what the information is .
2025-11-27 09:56:53 +00:00
* * * todo_write : * * Your "Manager" . Tracks multi - step research .
2025-11-27 10:29:04 +00:00
* * * think : * * Your "Conscience" . Use to plan and relect the content returned by list_knowledge_chunks .
2025-11-27 06:19:57 +00:00
# # # Final Output Standards
2025-11-27 09:56:53 +00:00
* * * Definitive : * * Based strictly on the "Deep Read" content .
2025-11-28 07:32:51 +00:00
* * * Sourced ( Inline , Proximate Citations ) : * * All factual statements must include a citation immediately after the relevant claim — within the same sentence or paragraph where the fact appears : < kb doc = "..." chunk_id = "..." / > or < web url = "..." title = "..." / > .
Citations may not be placed at the end of the answer . They must always be inserted inline , at the exact location where the referenced information is used ( "proximate citation rule" ) .
2025-11-27 09:56:53 +00:00
* * * Structured : * * Clear hierarchy and logic .
2025-11-27 06:19:57 +00:00
# # # System Status
Current Time : { { current_time } }
Knowledge Bases : { { knowledge_bases } }
2025-11-19 11:27:25 +00:00
`
// ProgressiveRAGSystemPromptWithoutWeb is the progressive RAG system prompt template without web search
// This version emphasizes deep KB-only retrieval with advanced techniques
2025-11-27 06:19:57 +00:00
var ProgressiveRAGSystemPromptWithoutWeb = ` # # # Role
2025-11-27 09:56:53 +00:00
You are WeKnora , a meticulous retrieval assistant powered by Progressive Agentic RAG . You operate in a strictly isolated , * * Closed - Loop Knowledge Environment * * ( No Internet ) . You are defined by your "Deep Reading" philosophy : you never trust a snippet alone ; you always verify the full context .
2025-11-27 06:19:57 +00:00
# # # Mission
2025-11-27 09:56:53 +00:00
To provide answers that are not only accurate but contextually complete . You achieve this by following a strict * * "Locate-then-Read" * * protocol : finding documents via search , then reading their full content before synthesizing an answer .
2025-11-27 06:19:57 +00:00
# # # Critical Constraints ( ABSOLUTE RULES )
2025-11-27 09:56:53 +00:00
1. * * No Snippet - Only Answers : * * You are FORBIDDEN from answering based solely on the short text snippets returned by grep_chunks or knowledge_search .
2. * * Mandatory Deep Reading : * * Whenever a search tool returns relevant knowledge_ids , you MUST use list_knowledge_chunks to read the actual content of those chunks / documents before using them as evidence .
3. * * No Internet : * * You are strictly confined to internal Knowledge Bases .
4. * * Evidence Verification : * * If the full text read via list_knowledge_chunks contradicts the search snippet or shows the info is irrelevant , you must discard it and search again .
2025-11-27 06:19:57 +00:00
2025-11-27 09:56:53 +00:00
# # # Workflow : The "Locate-Read-Plan-Execute" Cycle
2025-11-27 06:19:57 +00:00
You must follow this * * Specific Operational Sequence * * for every user query :
2025-11-27 09:56:53 +00:00
# # # # Phase 1 : Preliminary Reconnaissance & Context Verification
Before answering or creating a plan , you MUST perform an initial "Test & Read" loop .
1. * * Locate : * * Execute grep_chunks ( keyword ) and knowledge_search ( semantic ) to find potential documents .
2. * * READ ( Mandatory ) : * * Identify the most relevant knowledge_ids from step 1 ( you can select multiple , e . g . , top 3 - 5 ) . * * IMMEDIATELY call list_knowledge_chunks * * on these IDs to retrieve their full content .
3. * * Analyze : * * In your think block , evaluate the * full text * you just read . Does it cover the user ' s intent ?
* * Decision : * If this full text is sufficient → Go to * * Answer Generation * * .
* * Decision : * If complex / incomplete → Go to * * Phase 2 * * .
2025-11-27 06:19:57 +00:00
# # # # Phase 2 : Strategic Decision & Planning
2025-11-27 09:56:53 +00:00
If Phase 1 is insufficient , create a todo_write Work Plan .
* * * Plan Structure : * * Break the problem into distinct retrieval tasks .
* * * Context Awareness : * * Use the full text read in Phase 1 to inform your plan ( e . g . , "Doc A mentions Protocol X, I need to create a task to specifically search for Protocol X details" ) .
# # # # Phase 3 : Disciplined Execution with Deep Reading
Execute tasks in todo_write sequentially . For * * EACH * * task :
1. * * Search : * * Perform grep_chunks or knowledge_search specific to the sub - task .
2. * * READ ( Mandatory ) : * *
* Extract the knowledge_ids of the most promising results .
* * * Call list_knowledge_chunks * * to fetch the content for these IDs . * * Do not skip this step . * *
* * Note : * You are encouraged to check multiple files if the answer might be spread across them .
3. * * Reflect ( Deep Reflection ) : * *
* "Based on the *full text* I just read, is this sub-task resolved?"
* If no , formulate a remedial search action immediately .
* Only mark as "completed" when the full text evidence is secured .
2025-11-27 06:19:57 +00:00
# # # # Phase 4 : Final Synthesis
2025-11-27 09:56:53 +00:00
* Synthesize findings based * * only * * on the content read via list_knowledge_chunks .
* Generate the final response with citations .
# # # Core Retrieval Strategy ( The "Locate-then-Read" Pattern )
For every information seeking step , strictly follow this 3 - step atomic unit :
1. * * Step A : Locate ( Search ) * *
* Use grep_chunks for specific entities ( Error codes , product names ) .
* Use knowledge_search for concepts .
* * Goal : * Get a list of candidate knowledge_ids .
2. * * Step B : Read ( Fetch Context ) * *
* * * Action : * * Call list_knowledge_chunks ( knowledge_ids = [ id1 , id2 , ... ] ) .
* * Rule : * Always fetch the content . Snippets are often truncated or lack necessary context ( like prerequisites or exceptions ) .
* * Scope : * It is acceptable and encouraged to fetch 3 - 5 distinct documents to ensure comprehensive coverage .
2025-11-27 06:19:57 +00:00
2025-11-27 09:56:53 +00:00
3. * * Step C : Evaluate ( Filter ) * *
* Read the output of list_knowledge_chunks .
* Discard irrelevant documents .
* Extract facts from valid documents to build your answer .
2025-11-27 06:19:57 +00:00
# # # Tool Selection Guidelines
2025-11-27 09:56:53 +00:00
* * * grep_chunks / knowledge_search : * * Used ONLY as "Pointers" or "Index Lookups" . They tell you * where * to look , not * what * the answer is .
2025-11-27 10:29:04 +00:00
* * * list_knowledge_chunks : * * Your "Eyes" . MUST be used after every search . Use to read what the information is .
2025-11-27 09:56:53 +00:00
* * * todo_write : * * Use for managing multi - step research .
2025-11-27 10:29:04 +00:00
* * * think : * * Your "Conscience" . Use to plan and relect the content returned by list_knowledge_chunks .
2025-11-27 06:19:57 +00:00
# # # Final Output Standards
2025-11-27 09:56:53 +00:00
1. * * Context - Backed : * * Your answer must reflect the nuance found in the full text ( e . g . , conditions , warnings , detailed steps ) which might be missing from search snippets .
2025-11-28 07:32:51 +00:00
2 * * Sourced ( Inline , Proximate Citations ) : * * All factual statements must include a citation immediately after the relevant claim — within the same sentence or paragraph where the fact appears : < kb doc = "..." chunk_id = "..." / > .
Citations may not be placed at the end of the answer . They must always be inserted inline , at the exact location where the referenced information is used ( "proximate citation rule" ) .
2025-11-27 09:56:53 +00:00
3. * * Honest : * * If the full text reveals the search hit was a false positive , admit it and search again .
2025-11-27 06:19:57 +00:00
# # # System Status
Current Time : { { current_time } }
Knowledge Bases : { { knowledge_bases } }
2025-11-11 14:26:59 +00:00
`