RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
Refactor: move rag prompts (#20873)
Wang Qia8216e5f38a7
diff --git a/Dockerfile b/Dockerfileindex 0177a399f2..88bb8400bb 100644--- a/Dockerfile+++ b/Dockerfile@@ -259,7 +259,6 @@ RUN rm -f /etc/nginx/sites-enabled/defaultCOPY conf confCOPY internal/agent/templates agent/templates-COPY rag/prompts rag/prompts# Wiki page-structure presets read at runtime by the Go backend# (CompilationTemplateService.LoadWikiPresets).diff --git a/internal/agent/component/prompts/citation.go b/internal/agent/component/prompts/citation.goindex b65e57c9dc..0eee819503 100644--- a/internal/agent/component/prompts/citation.go+++ b/internal/agent/component/prompts/citation.go@@ -14,9 +14,7 @@// limitations under the License.//-// Package prompts holds LLM prompt templates used by the agent-// components. The strings mirror the canonical Python templates under-// rag/prompts/ — keep them in sync when editing either side.+// Package prompts holds LLM prompt templates used by the agent components.package promptsimport (@@ -29,9 +27,8 @@ import (// CitationPrompt returns the citation-instruction text. The LLM// component appends it to the system prompt when LLMParam.Cite is true.//-// The text lives once, in internal/rag/prompts/citation_prompt.md (a copy of-// rag/prompts/citation_prompt.md), and is delegated to here so the two Go-// columns cannot drift apart again.+// The text lives in internal/rag/prompts/citation_prompt.md and is loaded+// through the shared embedded prompt package.//// Format: [ID:N] inline citation; max 4 per sentence; placed at// sentence end before punctuation; forbidden format "[ID:0, ID:5, ...]"@@ -40,8 +37,7 @@ func CitationPrompt() string {return ragprompts.CitationPrompt("")}-// citationPlusTemplate is the post-stream citation-grounding template,-// mirrored from rag/prompts/citation_plus.md.+// citationPlusTemplate is the post-stream citation-grounding template.//// Two placeholders are substituted at render time://diff --git a/internal/common/metadata_utils.go b/internal/common/metadata_utils.goindex 3cfd7c80d2..0a4d8f8db8 100644--- a/internal/common/metadata_utils.go+++ b/internal/common/metadata_utils.go@@ -386,7 +386,7 @@ type MetadataFieldDef struct {// Turn2JSONSchema converts a metadata field list into a JSON-Schema object,// mirroring Python common/metadata_utils.py::turn2jsonschema /// metadata_schema. The result is rendered into the auto-metadata extraction-// prompt (rag/prompts/meta_data.md equivalent) so the LLM knows the exact+// prompt so the LLM knows the exact// keys, descriptions and allowed enum values to extract.func Turn2JSONSchema(fields []MetadataFieldDef) map[string]any {properties := make(map[string]any, len(fields))diff --git a/internal/ingestion/component/extractor.go b/internal/ingestion/component/extractor.goindex ad4b84e13d..9635f5a6d3 100644--- a/internal/ingestion/component/extractor.go+++ b/internal/ingestion/component/extractor.go@@ -126,7 +126,7 @@ func SetExtractorConcurrency(n int) {}// extractorTopNPattern matches the {{ topn }} placeholder accepted in-// keyword/question system prompts (same convention as rag/prompts/*.md).+// keyword/question system prompts.// It is replaced with the configured top_n so the count slider stays// authoritative even when a prompt was pre-filled by the frontend.var extractorTopNPattern = regexp.MustCompile(`\{\{\s*topn\s*\}\}`)diff --git a/internal/ingestion/component/pdf_vision_dispatch.go b/internal/ingestion/component/pdf_vision_dispatch.goindex 9cd60c1fc8..bad7e288cd 100644--- a/internal/ingestion/component/pdf_vision_dispatch.go+++ b/internal/ingestion/component/pdf_vision_dispatch.go@@ -17,7 +17,6 @@ import ("regexp""strconv""strings"- "sync""time""ragflow/internal/common"@@ -25,6 +24,7 @@ import (modelModule "ragflow/internal/entity/models""ragflow/internal/ingestion/component/schema""ragflow/internal/parser/parser"+ "ragflow/internal/rag/prompts""ragflow/internal/utility""go.uber.org/zap"@@ -54,18 +54,12 @@ const (var monkeyOCRv2ImagePattern = regexp.MustCompile(`!\[([^]]*)\]\(([^)]+)\)`)var (- pdfVisionPromptLoader = loadPDFVisionPrompt+ pdfVisionPromptLoader = (prompts.EmbeddedPromptLoader{}).LoadpdfVisionPageRenderer = defaultRenderPDFVisionPagespdfVisionModelResolver = defaultPDFVisionModelResolverpdfVisionChatInvoker = defaultPDFVisionChatInvoker)-var (- pdfVisionPromptCache = make(map[string]string)- pdfVisionPromptCacheMu sync.RWMutex- pdfVisionPrompts promptDirState-)-func maybeDispatchPDFVision(ctx context.Context,db *gorm.DB,@@ -1194,34 +1188,6 @@ func defaultPDFVisionChatInvoker(return chatModel.ChatWithMessages(ctx, messages, &modelModule.ChatConfig{Vision: &vision}, nil)}-func loadPDFVisionPrompt(name string) (string, error) {- pdfVisionPromptCacheMu.RLock()- if cached, ok := pdfVisionPromptCache[name]; ok {- pdfVisionPromptCacheMu.RUnlock()- return cached, nil- }- pdfVisionPromptCacheMu.RUnlock()-- baseDir, err := pdfVisionPromptsBaseDir()- if err != nil {- return "", err- }- promptPath := filepath.Join(baseDir, "rag", "prompts", fmt.Sprintf("%s.md", name))- content, err := os.ReadFile(promptPath)- if err != nil {- return "", fmt.Errorf("prompt file %q not found: %w", name, err)- }- cached := strings.TrimSpace(string(content))- pdfVisionPromptCacheMu.Lock()- pdfVisionPromptCache[name] = cached- pdfVisionPromptCacheMu.Unlock()- return cached, nil-}--func pdfVisionPromptsBaseDir() (string, error) {- return pdfVisionPrompts.resolve(utility.GetProjectRoot())-}-// renderPDFVisionPrompt only renders page metadata. The full-page PDF vision// prompt is a transcription contract that preserves the document's original// language; dataset-language instructions apply to figure descriptions indiff --git a/internal/ingestion/component/vision_enhancement.go b/internal/ingestion/component/vision_enhancement.goindex dbd2c8d835..d635a115d9 100644--- a/internal/ingestion/component/vision_enhancement.go+++ b/internal/ingestion/component/vision_enhancement.go@@ -24,12 +24,9 @@ package componentimport ("context""encoding/base64"- "errors""fmt""image""io"- "os"- "path/filepath""strings""sync""sync/atomic"@@ -42,6 +39,7 @@ import ("ragflow/internal/entity"modelModule "ragflow/internal/entity/models""ragflow/internal/parser/parser"+ "ragflow/internal/rag/prompts""ragflow/internal/utility""gorm.io/gorm"@@ -54,7 +52,6 @@ var ()const (- figureVisionPromptFile = "vision_llm_figure_describe_prompt.md"visionEnhancementConcurrency int = 10// visionChatTimeout bounds a single VLM call so a hung endpoint cannot// occupy one of the concurrency slots indefinitely. Python wraps the@@ -63,38 +60,6 @@ const (visionMediaItemBudget = 10 * time.Second)-var (- figureVisionPrompts promptDirState- figureVisionPromptCache = make(map[string]string)- figureVisionPromptMu sync.RWMutex-)--// promptDirState caches the project root that contains rag/prompts. The once-// guard makes initialization sticky; unlike a function-local initErr, an-// initialization failure is preserved for every subsequent call.-type promptDirState struct {- once sync.Once- root string- initErr error-}--func (s *promptDirState) resolve(requestedRoot string) (string, error) {- s.once.Do(func() {- if info, statErr := os.Stat(filepath.Join(requestedRoot, "rag", "prompts")); statErr == nil && info.IsDir() {- s.root = requestedRoot- return- }- s.initErr = fmt.Errorf("rag/prompts not found under project root %q", requestedRoot)- })- if s.initErr != nil {- return "", s.initErr- }- if s.root == "" {- return "", errors.New("prompts base dir not initialized")- }- return s.root, nil-}-// isUsableVisionImage reports whether raw carries a valid image data URI or a// base64 payload that can be sent to a vision model.func isUsableVisionImage(raw string) bool {@@ -410,41 +375,13 @@ func appendItemText(item map[string]any, text string) {}func buildFigureVisionPrompt(language string) (string, error) {- template, err := loadFigureVisionPromptFile(figureVisionPromptFile)+ template, err := (prompts.EmbeddedPromptLoader{}).Load("vision_llm_figure_describe_prompt")if err != nil {return "", err}return renderFigureVisionLanguage(template, language), nil}-func loadFigureVisionPromptFile(filename string) (string, error) {- figureVisionPromptMu.RLock()- if cached, ok := figureVisionPromptCache[filename]; ok {- figureVisionPromptMu.RUnlock()- return cached, nil- }- figureVisionPromptMu.RUnlock()-- baseDir, err := figureVisionPromptsBaseDir()- if err != nil {- return "", err- }- promptPath := filepath.Join(baseDir, "rag", "prompts", filename)- content, err := os.ReadFile(promptPath)- if err != nil {- return "", fmt.Errorf("figure vision prompt %q: %w", filename, err)- }- cached := strings.TrimSpace(string(content))- figureVisionPromptMu.Lock()- figureVisionPromptCache[filename] = cached- figureVisionPromptMu.Unlock()- return cached, nil-}--func figureVisionPromptsBaseDir() (string, error) {- return figureVisionPrompts.resolve(utility.GetProjectRoot())-}-func buildVisionMessages(prompt, imageBase64 string) []modelModule.Message {dataURI := pdflayout.InlinePNGDataURL(imageBase64)if dataURI == "" {diff --git a/internal/ingestion/component/vision_enhancement_test.go b/internal/ingestion/component/vision_enhancement_test.goindex fd621e39cd..aa6e7b88c2 100644--- a/internal/ingestion/component/vision_enhancement_test.go+++ b/internal/ingestion/component/vision_enhancement_test.go@@ -24,8 +24,6 @@ import ("fmt""image""image/png"- "os"- "path/filepath""strings""sync""testing"@@ -1096,33 +1094,6 @@ func TestExtractVisionAnswer_EdgeCases(t *testing.T) {}}-func TestPromptDirState_FailureIsSticky(t *testing.T) {- dir := t.TempDir()- var state promptDirState- for i := 0; i < 2; i++ {- if _, err := state.resolve(dir); err == nil {- t.Fatalf("call %d: resolve() = nil error, want sticky init error", i+1)- }- }-}--func TestPromptDirState_SuccessIsCached(t *testing.T) {- dir := t.TempDir()- if err := os.MkdirAll(filepath.Join(dir, "rag", "prompts"), 0o755); err != nil {- t.Fatal(err)- }- var state promptDirState- for i := 0; i < 2; i++ {- got, err := state.resolve(dir)- if err != nil {- t.Fatalf("call %d: resolve() error: %v", i+1, err)- }- if got != dir {- t.Fatalf("call %d: resolve() = %q, want %q", i+1, got, dir)- }- }-}-func TestVisionEnhancement_GlobalModelPreferredOverPDFParser(t *testing.T) {origTenantResolver := resolveTenantModelByTypeorigModelResolver := resolveModelConfigdiff --git a/internal/ingestion/component/vision_language_test.go b/internal/ingestion/component/vision_language_test.goindex c91394743b..b39c987b3f 100644--- a/internal/ingestion/component/vision_language_test.go+++ b/internal/ingestion/component/vision_language_test.go@@ -66,6 +66,7 @@ func TestRenderFigureVisionLanguage(t *testing.T) {}func TestBuildFigureVisionPromptRendersLanguage(t *testing.T) {+ t.Chdir(t.TempDir())prompt, err := buildFigureVisionPrompt("Japanese")if err != nil {t.Fatalf("buildFigureVisionPrompt: %v", err)@@ -80,15 +81,15 @@ func TestBuildFigureVisionPromptRendersLanguage(t *testing.T) {}}- // Second call uses cache — verify language is re-rendered correctly per call.+ // Verify language is rendered separately for each request.secondPrompt, err := buildFigureVisionPrompt("Chinese")if err != nil {- t.Fatalf("buildFigureVisionPrompt with cached template: %v", err)+ t.Fatalf("buildFigureVisionPrompt for second language: %v", err)}if !strings.Contains(secondPrompt, "Write all descriptions and field values in Chinese.") {- t.Fatalf("cached prompt did not render the second request language")+ t.Fatalf("prompt did not render the second request language")}if strings.Contains(secondPrompt, "in Japanese.") {- t.Fatalf("cached prompt leaked the previous request language")+ t.Fatalf("prompt leaked the previous request language")}}diff --git a/rag/prompts/ask_summary.md b/internal/rag/prompts/ask_summary.mdsimilarity index 100%rename from rag/prompts/ask_summary.mdrename to internal/rag/prompts/ask_summary.mddiff --git a/rag/prompts/cross_languages_sys_prompt.md b/internal/rag/prompts/cross_languages_sys_prompt.mdsimilarity index 100%rename from rag/prompts/cross_languages_sys_prompt.mdrename to internal/rag/prompts/cross_languages_sys_prompt.mddiff --git a/rag/prompts/cross_languages_user_prompt.md b/internal/rag/prompts/cross_languages_user_prompt.mdsimilarity index 100%rename from rag/prompts/cross_languages_user_prompt.mdrename to internal/rag/prompts/cross_languages_user_prompt.mddiff --git a/internal/rag/prompts/generator.go b/internal/rag/prompts/generator.goindex 3ab677717e..d1a78ff5d6 100644--- a/internal/rag/prompts/generator.go+++ b/internal/rag/prompts/generator.go@@ -14,21 +14,9 @@// limitations under the License.//-// Package prompts is the Go mirror of Python rag/prompts/generator.py — the-// prompt helpers the agentic loop, the chat seam and the deep parsers share-// (chunk formatting, token-budget fitting, knowledge-block rendering, tool-// schema serialization, history formatting, and the named prompt templates-// that load from rag/prompts/*.md).-//-// Porting is staged function-by-function: pure helpers that do not touch an-// LLM are mirrored first and covered by tests; helpers that call the model-// (Python chat_mdl.async_chat) are left as declared entry points until the Go-// LLM-call seam is confirmed, so they are not part of the compile surface yet.-//-// Template loading mirrors Python rag/prompts/template.py::load_prompt, which-// reads {name}.md from rag/prompts/ at import time. The Go seam for that is a-// named-template loader passed in by callers so this package stays free of a-// hard dependency on the service layer (see the Render* helpers).+// Package prompts provides embedded templates and prompt helpers shared by+// retrieval, chat, and ingestion, including chunk formatting, token-budget+// fitting, knowledge-block rendering, and history formatting.package promptsimport (@@ -98,11 +86,8 @@ func ChunksFormat(reference map[string]any) []map[string]any {return out}-// DefaultCiteRules mirrors rag/prompts/generator.citation_prompt's-// CITATION_PROMPT_TEMPLATE output. Python loads citation_prompt.md via-// load_prompt("citation_prompt"); the Go build keeps the same .md embedded-// (citation_prompt.md) and reads it here so the template has a single source of-// truth. A user-defined override (RAGConfig.CiteRules / user_defined_prompts)+// DefaultCiteRules loads the embedded citation_prompt.md template.+// A user-defined override (RAGConfig.CiteRules / user_defined_prompts)// replaces it verbatim when present — see CitationPrompt.//// Loaded from the embedded md rather than a string literal so edits todiff --git a/rag/prompts/keyword_prompt.md b/internal/rag/prompts/keyword_prompt.mdsimilarity index 100%rename from rag/prompts/keyword_prompt.mdrename to internal/rag/prompts/keyword_prompt.mddiff --git a/rag/prompts/meta_filter.md b/internal/rag/prompts/meta_filter.mdsimilarity index 98%rename from rag/prompts/meta_filter.mdrename to internal/rag/prompts/meta_filter.mdindex 28aff93a21..21b86edaee 100644--- a/rag/prompts/meta_filter.md+++ b/internal/rag/prompts/meta_filter.md@@ -1,8 +1,8 @@You are a metadata filtering condition generator. Analyze the user's question and available document metadata to output a JSON array of filter objects. Follow these rules:-1. **Metadata Structure**:+1. **Metadata Structure**:- Metadata is provided as JSON where keys are attribute names (e.g., "color"), and values are objects mapping attribute values to document IDs.- - Example:+ - Example:{"color": {"red": ["doc1"], "blue": ["doc2"]},"listing_date": {"2025-07-11": ["doc1"], "2025-08-01": ["doc2"]}@@ -42,7 +42,7 @@ You are a metadata filtering condition generator. Analyze the user's question an6. **Example A**:- User query: "上市日期七月份的有哪些新品,不要蓝色的,只看鞋子和帽子"- Metadata: { "color": {...}, "listing_date": {...} }- - Output:+ - Output:{"logic": "and","conditions": [@@ -56,8 +56,8 @@ You are a metadata filtering condition generator. Analyze the user's question an7. **Example B**:- User query: "It must be from China or India. Otherwise, it must not be blue or red."- Metadata: { "color": {...}, "country": {...} }- -- - Output:+ -+ - Output:{"logic": "or","conditions": [diff --git a/rag/prompts/related_question.md b/internal/rag/prompts/related_question.mdsimilarity index 100%rename from rag/prompts/related_question.mdrename to internal/rag/prompts/related_question.mddiff --git a/internal/rag/prompts/templates.go b/internal/rag/prompts/templates.goindex d887a5f7dc..3a4bab4d51 100644--- a/internal/rag/prompts/templates.go+++ b/internal/rag/prompts/templates.go@@ -23,17 +23,8 @@ import ("strings")-// Prompt template loading, the Go mirror of Python rag/prompts/template.py-// ::load_prompt. Python reads {name}.md from rag/prompts/ at import time; the-// Go column keeps the authoritative copy of each template as a .md embedded-// here so the binary is self-contained and survives the Python source being-// deleted.-//-// The templates mirrored by this package (action_run, action_set,-// action_initialize_state, consumed by the harness action session; sca_select-// and sca_query_rewrite, consumed by the orchestrator) were previously-// duplicated as copies under harness/prompts/. They are now unified here, with-// the harness wiring its PromptLoader default to this package's embedded loader.+// Prompt templates for retrieval, chat, and ingestion are embedded here so+// callers can load them independently of the working directory.//// action_set is the ONE template that is not part of a system prompt: the harness// appends it to a session's seed message, and only for a direction that is a SET@@ -41,6 +32,7 @@ import (// every question, including the ones it cannot help.//go:embed action_run.md action_set.md action_initialize_state.md sca_select.md sca_query_rewrite.md citation_prompt.md+//go:embed ask_summary.md keyword_prompt.md cross_languages_sys_prompt.md cross_languages_user_prompt.md meta_filter.md related_question.md vision_llm_describe_prompt.md vision_llm_figure_describe_prompt.mdvar templatesFS embed.FS// EmbeddedPromptLoader serves the bundled .md templates by name. Load returns@@ -73,12 +65,10 @@ type Loader interface {// verbatim in the prompt.var leftoverVarRE = regexp.MustCompile(`\{\{\s*[A-Za-z_][A-Za-z0-9_.]*\s*\}\}`)-// Render loads `name` and substitutes the {{var}} placeholders the way-// PROMPT_JINJA_ENV.from_string(...).render(...) does on the Python side. A nil-// loader defaults to the embedded canonical .md templates (1:1 copies of the-// Python rag/prompts/*.md); a loader that cannot resolve `name` falls back to-// `fallback`. Unprovided variables render as the empty string (Jinja default-// Undefined), not as a literal placeholder.+// Render loads `name` and substitutes the {{var}} placeholders. A nil loader+// defaults to the embedded templates; a loader that cannot resolve `name`+// falls back to `fallback`. Unprovided variables render as the empty string+// (Jinja default Undefined), not as a literal placeholder.func Render(loader Loader, name, fallback string, vars map[string]string) string {if loader == nil {loader = EmbeddedPromptLoader{}diff --git a/internal/rag/prompts/templates_test.go b/internal/rag/prompts/templates_test.goindex 0535a66403..2bdde02820 100644--- a/internal/rag/prompts/templates_test.go+++ b/internal/rag/prompts/templates_test.go@@ -21,16 +21,25 @@ import ("testing")-// TestEmbeddedLoaderCanonicalTemplates makes sure every template the Go column-// relies on is actually embedded and stripped the way Python's load_prompt-// strips the canonical rag/prompts/*.md files.+// TestEmbeddedLoaderCanonicalTemplates checks that templates are available+// without source files in the working directory and have whitespace trimmed.func TestEmbeddedLoaderCanonicalTemplates(t *testing.T) {+ t.Chdir(t.TempDir())names := []string{"action_run","action_set","action_initialize_state","sca_select","sca_query_rewrite",+ "citation_prompt",+ "ask_summary",+ "keyword_prompt",+ "cross_languages_sys_prompt",+ "cross_languages_user_prompt",+ "meta_filter",+ "related_question",+ "vision_llm_describe_prompt",+ "vision_llm_figure_describe_prompt",}for _, name := range names {got, err := (EmbeddedPromptLoader{}).Load(name)@@ -41,7 +50,7 @@ func TestEmbeddedLoaderCanonicalTemplates(t *testing.T) {t.Errorf("Load(%q) returned an empty template", name)}if strings.TrimSpace(got) != got {- t.Errorf("Load(%q) returned surrounding whitespace (load_prompt strips both ends)", name)+ t.Errorf("Load(%q) returned surrounding whitespace", name)}}}@@ -55,7 +64,7 @@ func TestEmbeddedLoaderMissingName(t *testing.T) {}// TestRenderPromptNilLoaderUsesEmbeddedCanonical locks in that an unset loader-// now resolves the canonical embedded .md (1:1 with rag/prompts/sca_select.md)+// resolves the embedded sca_select.md// rather than the condensed constant — the whole point of the orchestration// parity fix.func TestRenderPromptNilLoaderUsesEmbeddedCanonical(t *testing.T) {@@ -159,7 +168,7 @@ type stubLoader struct{ text string }func (s stubLoader) Load(string) (string, error) { return s.text, nil }// TestRenderPromptNilLoaderUsesEmbeddedCanonical locks in that an unset loader-// now resolves the canonical embedded .md (1:1 with rag/prompts/sca_select.md)+// resolves the embedded sca_select.md// rather than the condensed constant — the whole point of the orchestration// parity fix.diff --git a/rag/prompts/vision_llm_describe_prompt.md b/internal/rag/prompts/vision_llm_describe_prompt.mdsimilarity index 100%rename from rag/prompts/vision_llm_describe_prompt.mdrename to internal/rag/prompts/vision_llm_describe_prompt.mddiff --git a/rag/prompts/vision_llm_figure_describe_prompt.md b/internal/rag/prompts/vision_llm_figure_describe_prompt.mdsimilarity index 100%rename from rag/prompts/vision_llm_figure_describe_prompt.mdrename to internal/rag/prompts/vision_llm_figure_describe_prompt.mddiff --git a/internal/service/ask_service.go b/internal/service/ask_service.goindex 0c5bbe387f..b0f66f4372 100644--- a/internal/service/ask_service.go+++ b/internal/service/ask_service.go@@ -22,6 +22,7 @@ import ("ragflow/internal/common"modelModule "ragflow/internal/entity/models"+ "ragflow/internal/rag/prompts""go.uber.org/zap")@@ -204,7 +205,7 @@ func (s *AskService) run(ctx context.Context, llm StreamingLLM, userID, question// Phase 2: Build system prompt.knowledge := KbPrompt(chunks, s.tokenBudget)- prompt, err := LoadPrompt("ask_summary")+ prompt, err := (prompts.EmbeddedPromptLoader{}).Load("ask_summary")if err != nil {common.Warn("AskService failed to load prompt", zap.Error(err))s.sendOrCancel(out, AskDelta{Kind: AskDeltaError, Value: "prompt configuration error"}, ctx)diff --git a/internal/service/generator.go b/internal/service/generator.goindex 4480d56d1c..9f7d570d99 100644--- a/internal/service/generator.go+++ b/internal/service/generator.go@@ -27,6 +27,7 @@ import ("ragflow/internal/common"modelModule "ragflow/internal/entity/models"+ "ragflow/internal/rag/prompts""go.uber.org/zap")@@ -65,7 +66,7 @@ func KeywordExtraction(ctx context.Context, chatModel *modelModule.ChatModel, co}// Load keyword prompt template from file- keywordPromptTemplate, err := LoadPrompt("keyword_prompt")+ keywordPromptTemplate, err := (prompts.EmbeddedPromptLoader{}).Load("keyword_prompt")if err != nil {return "", fmt.Errorf("failed to load keyword prompt: %w", err)}@@ -150,13 +151,13 @@ func CrossLanguages(ctx context.Context, tenantID string, llmID string, query st}// Load system prompt from embedded file- systemPrompt, err := LoadPrompt("cross_languages_sys_prompt")+ systemPrompt, err := (prompts.EmbeddedPromptLoader{}).Load("cross_languages_sys_prompt")if err != nil {return query, fmt.Errorf("failed to load system prompt: %w", err)}- // Load user prompt template from file- userPromptTemplate, err := LoadPrompt("cross_languages_user_prompt")+ // Load user prompt template+ userPromptTemplate, err := (prompts.EmbeddedPromptLoader{}).Load("cross_languages_user_prompt")if err != nil {return query, fmt.Errorf("failed to load user prompt: %w", err)}@@ -217,9 +218,8 @@ func CrossLanguages(ctx context.Context, tenantID string, llmID string, query streturn query, nil}-// fullQuestionTmpl mirrors the Python Jinja2 template-// rag/prompts/full_question_prompt.md. The rendered output is used as the-// system message; the user message is just "Output: ".+// fullQuestionTmpl is rendered as the system message; the user message is+// just "Output: ".var fullQuestionTmpl = template.Must(template.New("full_question").Parse(`## RoleA helpful assistant.@@ -293,8 +293,6 @@ var errorMarkerRE = regexp.MustCompile(`\*\*ERROR\*\*`)// The prompt structure mirrors Python's full_question():// - System: fullQuestionTmpl (instructions, examples, conversation)// - User: "Output: "-//-// This matches rag/prompts/full_question_prompt.md rendered via Jinja2.func FullQuestion(ctx context.Context,chatModel *modelModule.ChatModel,diff --git a/internal/service/load_prompt.go b/internal/service/load_prompt.goindex c06c3a397a..f69a1ba487 100644--- a/internal/service/load_prompt.go+++ b/internal/service/load_prompt.go@@ -18,19 +18,8 @@ package serviceimport ("fmt"- "os"- "path/filepath""regexp""strings"- "sync"-- "ragflow/internal/utility"-)--var (- promptCache = make(map[string]string)- promptMu sync.RWMutex- promptsBaseDir string)// jsonFenceRE matches Markdown code fences around JSON responses.@@ -40,44 +29,8 @@ var (// by trailing spaces (e.g. "``` \n") is left intact.var jsonFenceRE = regexp.MustCompile("```json\\n|```\\n*$")-func init() {- root := utility.GetProjectRoot()- if _, err := os.Stat(filepath.Join(root, "rag", "prompts")); err == nil {- promptsBaseDir = root- return- }- // Final fallback- promptsBaseDir = "/ragflow"-}--// LoadPrompt loads a prompt by name from the rag/prompts/ directory.-// It caches loaded prompts for subsequent calls.-// Corresponds to rag/prompts/template.py:load_prompt()-func LoadPrompt(name string) (string, error) {- promptMu.RLock()- if cached, ok := promptCache[name]; ok {- promptMu.RUnlock()- return cached, nil- }- promptMu.RUnlock()-- promptPath := filepath.Join(promptsBaseDir, "rag", "prompts", fmt.Sprintf("%s.md", name))- content, err := os.ReadFile(promptPath)- if err != nil {- return "", fmt.Errorf("prompt file '%s.md' not found in rag/prompts/: %w", name, err)- }-- cached := strings.TrimSpace(string(content))- promptMu.Lock()- promptCache[name] = cached- promptMu.Unlock()-- return cached, nil-}-// RenderPrompt renders a prompt template with the given variables.// Supports {{ variable }} and {{ variable | filter(args) }} syntax.-// Corresponds to rag/prompts/generator.py template rendering (Jinja2).func RenderPrompt(template string, data map[string]interface{}) string {// Handle {{ variable | filter(args) }} syntax - capture filter arguments toofilterPattern := regexp.MustCompile(`\{\{\s*(\w+)\s*\|\s*(\w+)\s*\(\s*([^)]*)\s*\)\s*\}\}`)diff --git a/internal/service/metadata_filter.go b/internal/service/metadata_filter.goindex 42dbd78226..db24bc538a 100644--- a/internal/service/metadata_filter.go+++ b/internal/service/metadata_filter.go@@ -20,11 +20,11 @@ import ("context""encoding/json""fmt"- "os""ragflow/internal/common""ragflow/internal/dao""ragflow/internal/engine""ragflow/internal/entity"+ "ragflow/internal/rag/prompts""regexp""strconv"@@ -91,44 +91,9 @@ type ManualValueResolver func(map[string]interface{}) map[string]interface{}// NoMatchDocIDSentinel forces retrieval to return no documents when filters match nothing.const NoMatchDocIDSentinel = "-999"-// metaFilterTemplateCache caches the template content-var metaFilterTemplateCache string--// getMetaFilterTemplate loads and caches the meta_filter.md template-func getMetaFilterTemplate() (string, error) {- if metaFilterTemplateCache != "" {- return metaFilterTemplateCache, nil- }-- // Try to find meta_filter.md relative to the rag module- // Look for it in rag/prompts/ directory- possiblePaths := []string{- "rag/prompts/meta_filter.md",- "../rag/prompts/meta_filter.md",- "../../rag/prompts/meta_filter.md",- }-- var templateContent string- for _, path := range possiblePaths {- content, err := os.ReadFile(path)- if err == nil {- templateContent = string(content)- break- }- }-- if templateContent == "" {- // Fallback: return error- return "", fmt.Errorf("could not find meta_filter.md template")- }-- metaFilterTemplateCache = templateContent- return templateContent, nil-}-// renderMetaFilterTemplate renders the Jinja2-like template from meta_filter.mdfunc renderMetaFilterTemplate(currentDate, metadataKeys, question, constraints string) (string, error) {- templateContent, err := getMetaFilterTemplate()+ templateContent, err := (prompts.EmbeddedPromptLoader{}).Load("meta_filter")if err != nil {return "", err}diff --git a/internal/service/metadata_filter_test.go b/internal/service/metadata_filter_test.goindex 86a40c32d2..732ba3026d 100644--- a/internal/service/metadata_filter_test.go+++ b/internal/service/metadata_filter_test.go@@ -18,11 +18,31 @@ package serviceimport ("sort"+ "strings""testing""ragflow/internal/common")+func TestRenderMetaFilterTemplate(t *testing.T) {+ t.Chdir(t.TempDir())+ prompt, err := renderMetaFilterTemplate("2026-10-13", `{"author":["Alice"]}`, "Find Alice's documents", "")+ if err != nil {+ t.Fatalf("renderMetaFilterTemplate: %v", err)+ }+ for _, want := range []string{"2026-10-13", `{"author":["Alice"]}`, "Find Alice's documents"} {+ if !strings.Contains(prompt, want) {+ t.Errorf("rendered prompt missing %q", want)+ }+ }+ if strings.Contains(prompt, "{{") || strings.Contains(prompt, "{%") {+ t.Error("rendered prompt contains unresolved template syntax")+ }+ if strings.Contains(prompt, "- Operator constraints:") {+ t.Error("rendered prompt contains operator constraints when none were provided")+ }+}+func TestApplyMetaFilter_Equals(t *testing.T) {metas := common.MetaData{"author": {"Zhang San": {"doc1", "doc2"}, "Li Si": {"doc3"}},diff --git a/internal/service/related_question.go b/internal/service/related_question.goindex 03bd32154d..e3417814ef 100644--- a/internal/service/related_question.go+++ b/internal/service/related_question.go@@ -25,6 +25,7 @@ import ("ragflow/internal/entity"modelModule "ragflow/internal/entity/models"+ "ragflow/internal/rag/prompts")// GenerateRelatedQuestions generates related search questions for chat/searchbot endpoints.@@ -37,7 +38,7 @@ func GenerateRelatedQuestions(ctx context.Context, tenantID, question, searchIDif modelID == "" {return nil, fmt.Errorf("no chat model configured")}- prompt, err := LoadPrompt("related_question")+ prompt, err := (prompts.EmbeddedPromptLoader{}).Load("related_question")if err != nil {return nil, err}diff --git a/rag/prompts/action_initialize_state.md b/rag/prompts/action_initialize_state.mddeleted file mode 100644index 34bec2298f..0000000000--- a/rag/prompts/action_initialize_state.md+++ /dev/null@@ -1,23 +0,0 @@-You are a research strategist. Decompose the user's question into a table of FACT SLOTS that must be filled to answer it.--The question may span MULTIPLE DATASETS and/or the open WEB. The available data sources are listed in the user message:--- "Dataset '<name>'" — slots whose facts live in that corpus. If more than one dataset is listed, create at least one slot PER DATASET (its facts may need corpus-specific phrasing); cross-referencing between datasets is encouraged when the question spans them.-- "Web" — when listed, the open web is a source: create a dedicated slot (type "web") for facts that are current-world knowledge, recent events, or simply not covered by the listed datasets.--Output ONLY a JSON object:-{- "slots": [- {"id": 0, "type": "<entity|person|date|duration|count|number|place|web|dataset>", "clues": ["<what identifies this slot from the question>", "..."], "source": "<dataset name or 'web'>"},- ...- ],- "first_queries": ["<concrete searchable query for the first retrieval round>", ...]-}--Rules:-- 2-6 slots; each slot ONE fact (a name, a date, a count...), never a clause.-- Order slots so the FIRST one holds the top-level requested fact; the later ones are its dependencies.-- Cover EVERY listed source: one or more slots per dataset, plus a "web" slot when Web is available and the question touches world knowledge or recent events.-- clues must be self-contained phrases usable as retrieval hints.-- 1-4 first_queries: direct keyword-style searches against the listed sources.-- No prose outside JSON.diff --git a/rag/prompts/action_run.md b/rag/prompts/action_run.mddeleted file mode 100644index 8af822faa5..0000000000--- a/rag/prompts/action_run.md+++ /dev/null@@ -1,92 +0,0 @@-You are a deep research assistant working INSIDE a bounded search tree.--Input: the user message contains ONE research `Direction`, plus the current-`State` (slot table with immutable ids and mutable candidate fields).--Execute this single direction. Reply with EXACTLY ONE of the three below.--The three differ in HOW they are delivered — read this carefully, because only-the first one is a real tool call. `state` and `answer` are NOT tools: never emit-`<state>` / `<answer>` as a tool call and never name a native call after them.--1) TOOL CALL MODE — a real tool call: call `retrieve` with 1-3 corpus queries.- Results arrive in the next turn.--2) STATE PATCH MODE — NOT a tool call. Write this XML as plain TEXT in your- reply body:-<state>-{"new_states": [{"state": [- {"id": 1, "candidate": "1571", "candidate_strength": 0.92,- "discovered_clues": ["chunk 42: 'the treaty was signed in 1571'"]},- {"id": 2, "candidate": null, "candidate_strength": 0.0,- "discovered_clues": ["candidate 'Palermo' contradicted by chunk 7"]}-]}]}-</state>-Rules: patch ONLY existing ids; include ONLY changed variables; every change-must trace to retrieved evidence; candidate_strength semantics: proven >0.9,-strong 0.7-0.9, tentative 0.4-0.7, weak <0.4. Eliminate an unverifiable-candidate by setting `candidate` to null with a clue documenting why. An EMPTY-branch list (`"new_states": []`) signals no progress — emit it rather than-calling tools forever.--3) FINAL ANSWER MODE — NOT a tool call either. Write this XML as plain TEXT in- your reply body. Use it only when ALL slots can be filled consistently:-<answer>-{"answer": "1571", "new_state": [{"id": 1, "candidate": "1571", "candidate_strength": 0.92}]}-</answer>--CRITICAL RULES-- Think before choosing a mode, but output exactly ONE mode per response.-- EXCEPTION to "always patch": when the answer slot reaches strength >0.7 you- MUST emit a final answer instead of another state patch.-- Otherwise ALWAYS end this action with a state patch: a patch with your- updates, or `<state>{"new_states": []}</state>` if you found nothing new.-- **Do NOT keep calling tools once the direction is reasonably exhausted.** If further searches return repetitive, irrelevant, or empty results, immediately return a state patch (with updates or empty). Extra redundant searches waste the session — stop after 1-2 useful tool calls per direction unless a NEW fact is actually emerging.-- ACTION COMPLETION IS MANDATORY: when you have what you need (or hit a dead end), output the state patch now. Do not ask to continue searching.-- Partial verification is OK: record a candidate at tentative strength (0.4-0.7) if you can't fully verify it yet, and move on.--WRONG — never do this:-- calling a tool named "state" or "answer" (they are plain-text XML blocks);-- wrapping either XML block in markdown fences.--# TOOL PLAYBOOK--Available tools: `retrieve`, `search_chunks`, `metadata_search`, `list_chunks`,-`navigate_tree`, `navigate_structure`, `calculate`, and `web_search` (only when a-web provider is configured); `graph_explore` joins them in ultra mode. Low mode-has NO tool loop — answer with plain retrieval. Per-tool WHEN TO CALL /-DO NOT CALL / ARGUMENTS / IF IT FAILS details live in each tool's own schema —-this playbook covers only how to COMBINE tools and when to STOP.--## 1. Combination chains (call in this order)--- **You already hold a `doc_id`** → `navigate_structure(doc_id, query)` to find the right passage, then `list_chunks(doc_id)` to read it. Do NOT call `navigate_tree` first.-- **No `doc_id` yet, and the corpus is large** → `navigate_tree(query)` to route to candidate documents, take a `doc_id`, then `navigate_structure(doc_id, query)` → `list_chunks(doc_id)`.-- **You can name the document / need to narrow the search** → `metadata_search(query[1-2], filters)` ONCE per direction to pre-filter by title, then `search_chunks` / `retrieve` INSIDE the returned documents.-- **Exact term / short answer** → `retrieve(query[1-3])` first; if snippets are insufficient, `search_chunks(query[1-2])` (semantic, may find passages with NO shared surface words); if you need the full document, `list_chunks(doc_id)`.-- **You must DERIVE a number** → first collect every needed number with any of the above, then `calculate(question, facts)` with the facts verbatim, and report the computed result as-is. If the answer is already one of the stated numbers, answer directly.-- **Relational multi-hop (ultra only)** → get a start entity from `search_chunks` / `navigate_structure`, then `graph_explore(query, doc_scope)`.--## 2. Convergence rules (hard, enforced by the runtime — follow them to avoid wasted turns)--- Make at most **1-2 useful tool calls per direction**, then emit a state patch. Do not keep searching once the direction is reasonably exhausted.-- Re-submitting the SAME intent with a paraphrase is intercepted as a near-duplicate and SKIPPED (you get a nudge, not new results). Change the angle or patch what you have.-- If a compile-only tool (`navigate_tree` / `navigate_structure` / `graph_explore`) returns "no compiled structure", switch to `search_chunks` / `retrieve` / `list_chunks` **immediately**. A second such result disables that tool for the REST of the session — do not retry it.--## 3. What a tool result means → your next action--Each tool returns a status. Act on it:--| Status | Meaning | Your next action |-| --- | --- | --- |-| `ok` | New evidence entered the shared pool | Fill slots / move to the next direction |-| `miss` | This query matched nothing, but the tool itself is valid | Rephrase or switch tools — do NOT conclude the dataset lacks it |-| `empty` (`no_structure`) | Dataset-level: no such compiled structure exists | Switch to `search_chunks` / `retrieve` / `list_chunks` now; retrying disables the tool |-| `poor` | Output returned but too weak to use | Add evidence with another tool |-| `redundant` | Every hit was already in your evidence | Stop re-searching; emit a `<state>` patch with what you have |-| `error` | Infrastructure / provider failure | Switch tools; do not retry the same call |--Special case — `metadata_search` (at most ONCE per direction):-- `ok` → continue with `search_chunks` / `retrieve` INSIDE the documents it returned; do NOT call it again this direction.-- `miss` / `empty` → no title matched; drop the filter and fall back to `search_chunks` / `navigate_tree`.-- `poor` → the filter was too narrow; widen it once, or abandon it for plain retrieval.diff --git a/rag/prompts/analyze_task_system.md b/rag/prompts/analyze_task_system.mddeleted file mode 100644index 8a610aa3f3..0000000000--- a/rag/prompts/analyze_task_system.md+++ /dev/null@@ -1,48 +0,0 @@-You are an intelligent task analyzer that adapts analysis depth to task complexity.--**Analysis Framework**--**Step 1: Task Transmission Assessment**-**Note**: This section is not subject to word count limitations when transmission is needed, as it serves critical handoff functions.--**Evaluate if task transmission information is needed:**-- **Is this an initial step?** If yes, skip this section-- **Are there upstream agents/steps?** If no, provide minimal transmission-- **Is there critical state/context to preserve?** If yes, include full transmission--### If Task Transmission is Needed:-- **Current State Summary**: [1-2 sentences on where we are]-- **Key Data/Results**: [Critical findings that must carry forward]-- **Context Dependencies**: [Essential context for next agent/step]-- **Unresolved Items**: [Issues requiring continuation]-- **Status for User**: [Clear status update in user terms]-- **Technical State**: [System state for technical handoffs]--**Step 2: Complexity Classification**-Classify as LOW / MEDIUM / HIGH:-- **LOW**: Single-step tasks, direct queries, small talk-- **MEDIUM**: Multi-step tasks within one domain-- **HIGH**: Multi-domain coordination or complex reasoning--**Step 3: Adaptive Analysis**-Scale depth to match complexity. Always stop once success criteria are met.--**For LOW (max 50 words for analysis only):**-- Detect small talk; if true, output exactly: `Small talk — no further analysis needed`-- One-sentence objective-- Direct execution approach (1–2 steps)--**For MEDIUM (80–150 words for analysis only):**-- Objective; Intent & Scope-- 3–5 step minimal Plan (may mark parallel steps)-- **Uncertainty & Probes** (at least one probe with a clear stop condition)-- Success Criteria + basic Failure detection & fallback-- **Source Plan** (how evidence will be obtained/verified)--**For HIGH (150–250 words for analysis only):**-- Comprehensive objective analysis; Intent & Scope-- 5–8 steps Plan with dependencies/parallelism-- **Uncertainty & Probes** (key unknowns → probe → stop condition)-- Measurable Success Criteria; Failure detectors & fallbacks-- **Source Plan** (evidence acquisition & validation)-- **Reflection Hooks** (escalation/de-escalation triggers)diff --git a/rag/prompts/analyze_task_user.md b/rag/prompts/analyze_task_user.mddeleted file mode 100644index 81dc9f2bd9..0000000000--- a/rag/prompts/analyze_task_user.md+++ /dev/null@@ -1,9 +0,0 @@-**Input Variables**-- **{{ task }}** — the task/request to analyze-- **{{ context }}** — background, history, situational context-- **{{ agent_prompt }}** — special instructions/role hints-- **{{ tools_desc }}** — available sub-agents and capabilities--**Final Output Rule**-Return the Task Transmission section (if needed) followed by the concrete analysis and planning steps according to LOW / MEDIUM / HIGH complexity.-Do not restate the framework, definitions, or rules. Output only the final structured result.diff --git a/rag/prompts/assign_toc_levels.md b/rag/prompts/assign_toc_levels.mddeleted file mode 100644index 5e6ab22911..0000000000--- a/rag/prompts/assign_toc_levels.md+++ /dev/null@@ -1,55 +0,0 @@-You are given a JSON array of TOC(table of contents) items. Each item has at least {"title": string} and may include an existing title hierarchical level.--Task-- For each item, assign a depth label using Arabic numerals only: top-level = 1, second-level = 2, third-level = 3, etc.-- Multiple items may share the same depth (e.g., many 1s, many 2s).-- Do not use dotted numbering (no 1.1/1.2). Use a single digit string per item indicating its depth only.-- Preserve the original item order exactly. Do not insert, delete, or reorder.-- Decide levels yourself to keep a coherent hierarchy. Keep peers at the same depth.--Output-- Return a valid JSON array only (no extra text, no markdown code blocks).-- Each element MUST be a JSON object with exactly this structure: {"level": "1", "title": "some title"}.-- title must be the original title string exactly.-- DO NOT return arrays of arrays like [["1", "title"]] or other formats.-- The output must be parseable by json.loads() directly.--Examples--Example A (chapters with sections)-Input:-["Chapter 1 Methods", "Section 1 Definition", "Section 2 Process", "Chapter 2 Experiment"]--Output:-[- {"level":"1","title":"Chapter 1 Methods"},- {"level":"2","title":"Section 1 Definition"},- {"level":"2","title":"Section 2 Process"},- {"level":"1","title":"Chapter 2 Experiment"}-]--Example B (parts with chapters)-Input:-["Part I Theory", "Chapter 1 Basics", "Chapter 2 Methods", "Part II Applications", "Chapter 3 Case Studies"]--Output:-[- {"level":"1","title":"Part I Theory"},- {"level":"2","title":"Chapter 1 Basics"},- {"level":"2","title":"Chapter 2 Methods"},- {"level":"1","title":"Part II Applications"},- {"level":"2","title":"Chapter 3 Case Studies"}-]--Example C (plain headings)-Input:-["Introduction", "Background and Motivation", "Related Work", "Methodology", "Evaluation"]--Output:-[- {"level":"1","title":"Introduction"},- {"level":"2","title":"Background and Motivation"},- {"level":"2","title":"Related Work"},- {"level":"1","title":"Methodology"},- {"level":"1","title":"Evaluation"}-]\ No newline at end of filediff --git a/rag/prompts/citation_plus.md b/rag/prompts/citation_plus.mddeleted file mode 100644index 77bba4e254..0000000000--- a/rag/prompts/citation_plus.md+++ /dev/null@@ -1,13 +0,0 @@-You are an agent for adding correct citations to the given text by user.-You are given a piece of text within [ID:<ID>] tags, which was generated based on the provided sources.-However, the sources are not cited in the [ID:<ID>].-Your task is to enhance user trust by generating correct, appropriate citations for this report.--{{ example }}--<context>--{{ sources }}--</context>-diff --git a/rag/prompts/citation_prompt.md b/rag/prompts/citation_prompt.mddeleted file mode 100644index 09b14c54de..0000000000--- a/rag/prompts/citation_prompt.md+++ /dev/null@@ -1,123 +0,0 @@-Based on the provided document or chat history, add citations to the input text using the format specified later.--# Citation Requirements:--## Technical Rules:-- Use format: [ID:i] or [ID:i] [ID:j] for multiple sources. NEVER merge consecutive citations into a range such as [ID:i-j] or [ID:i~j] — ranges cannot be resolved to a source.-- Place citations at the end of sentences, before punctuation-- Maximum 4 citations per sentence-- DO NOT cite content not from <context></context>-- DO NOT modify whitespace or original text-- STRICTLY prohibit non-standard formatting (~~, etc.)-- For RTL languages (Arabic, Hebrew, Persian): Place citations at the logical end of sentences (same position as LTR). The frontend handles bidirectional rendering automatically.--## What MUST Be Cited:-1. **Quantitative data**: Numbers, percentages, statistics, measurements-2. **Temporal claims**: Dates, timeframes, sequences of events-3. **Causal relationships**: Claims about cause and effect-4. **Comparative statements**: Rankings, comparisons, superlatives-5. **Technical definitions**: Specialized terms, concepts, methodologies-6. **Direct attributions**: What someone said, did, or believes-7. **Predictions/forecasts**: Future projections, trend analyses-8. **Controversial claims**: Disputed facts, minority opinions--## What Should NOT Be Cited:-- Common knowledge (e.g., "The sun rises in the east")-- Transitional phrases-- General introductions-- Your own analysis or synthesis (unless directly from source)--# Comprehensive Examples:--## Example 1: Data and Statistics-<context>-ID: 45-└── Content: The global smartphone market grew by 7.8% in Q3 2024, with Samsung holding 20.6% market share and Apple at 15.8%.--ID: 46-└── Content: 5G adoption reached 1.5 billion users worldwide by October 2024.-</context>--USER: How is the smartphone market performing?--ASSISTANT:-The smartphone industry is showing strong recovery. The global smartphone market grew by 7.8% in Q3 2024 [ID:45]. Samsung leads with 20.6% market share, followed by Apple at 15.8% [ID:45]. This growth is partly driven by 5G technology, which reached 1.5 billion users worldwide by October 2024 [ID:46].--## Example 2: Causal Relationships and Predictions-<context>-ID: 78-└── Content: Rising interest rates have led to a 15% decline in housing starts. Economists predict this trend will continue through 2025.--ID: 79-└── Content: The Federal Reserve's aggressive monetary policy is the primary driver behind the real estate slowdown.-</context>--USER: What's happening in the real estate market?--ASSISTANT:-The real estate market is experiencing significant challenges. Rising interest rates have led to a 15% decline in housing starts [ID:78]. The Federal Reserve's aggressive monetary policy is the primary driver behind this real estate slowdown [ID:79]. Economists predict this trend will continue through 2025 [ID:78]. These factors suggest a prolonged period of market adjustment ahead.--## Example 3: Technical Concepts and Comparisons-<context>-ID: 101-└── Content: Quantum computing uses quantum bits (qubits) that can exist in superposition, unlike classical bits which are either 0 or 1.--ID: 102-└── Content: Current quantum computers can solve certain problems 158 million times faster than classical supercomputers.-</context>--USER: Explain quantum computing advantages.--ASSISTANT:-Quantum computing represents a fundamental shift in computational capability. Unlike classical computers, quantum computing uses quantum bits (qubits) that can exist in superposition, rather than being limited to just 0 or 1 [ID:101]. This unique property enables extraordinary performance gains. Current quantum computers can solve certain problems 158 million times faster than classical supercomputers [ID:102]. This technology promises to revolutionize fields requiring complex calculations.--## Example 4: Mixed Citation Needs-<context>-ID: 201-└── Content: CEO Jane Smith announced: "We're pivoting to AI-first strategy, expecting 40% revenue growth by 2026."--ID: 202-└── Content: Industry analysts remain skeptical, with Morgan Stanley rating the stock as "underperform."--ID: 203-└── Content: The company's AI division currently represents only 5% of total revenue.-</context>--USER: What's the company's new strategy?--ASSISTANT:-The company is undergoing a major strategic transformation. CEO Jane Smith announced: "We're pivoting to AI-first strategy, expecting 40% revenue growth by 2026" [ID:201]. However, this ambitious goal faces skepticism, as industry analysts remain doubtful, with Morgan Stanley rating the stock as "underperform" [ID:202]. The challenge is significant given that the company's AI division currently represents only 5% of total revenue [ID:203]. Success will depend on execution of this bold vision.--## Example 5: When NOT to Cite-<context>-ID: 301-└── Content: Paris is the capital of France. The Eiffel Tower was completed in 1889.-</context>--USER: Tell me about Paris.--ASSISTANT:-Paris is the capital of France. It's known for its rich history, culture, and architecture. The Eiffel Tower was completed in 1889 [ID:301]. The city attracts millions of tourists annually. Paris remains one of the world's most visited destinations.-(Note: Only the specific date needs citation, not common knowledge about Paris)--## Example 6: RTL Language (Arabic)-<context>-ID: 401-└── Content: في أول أيام شهر رمضان، أثار وضع رأس خنزير على مدخل مسجد بمدينة سانت أومير شمالي فرنسا تفاعلات واسعة.-</context>--USER: ماذا حدث في رمضان؟--ASSISTANT:-في أول أيام شهر رمضان، أثار وضع رأس خنزير على مدخل مسجد بمدينة سانت أومير شمالي فرنسا تفاعلات واسعة [ID:401].-(Note: Citation is placed at the logical end of the sentence, same as LTR languages. The frontend handles RTL display automatically.)----- Examples END -----REMEMBER:-- Cite FACTS, not opinions or transitions-- Each citation supports the ENTIRE sentence-- When in doubt, ask: "Would a fact-checker need to verify this?"-- Place citations at sentence end, before punctuation-- Format likes this is FORBIDDEN: [ID:0, ID:5, ID:...]. It MUST be separated like, [ID:0][ID:5]...-- Range citations like [ID:1-3] are FORBIDDEN too. Multiple sources MUST be spelled out individually: [ID:1][ID:2][ID:3].diff --git a/rag/prompts/content_tagging_prompt.md b/rag/prompts/content_tagging_prompt.mddeleted file mode 100644index 75d6f1586e..0000000000--- a/rag/prompts/content_tagging_prompt.md+++ /dev/null@@ -1,32 +0,0 @@-## Role-You are a text analyzer.--## Task-Add tags (labels) to a given piece of text content based on the examples and the entire tag set.--## Steps-- Review the tag/label set.-- Review examples which all consist of both text content and assigned tags with relevance score in JSON format.-- Summarize the text content, and tag it with the top {{ topn }} most relevant tags from the set of tags/labels and the corresponding relevance score.--## Requirements-- The tags MUST be from the tag set.-- The output MUST be in JSON format only, the key is tag and the value is its relevance score.-- The relevance score must range from 1 to 10.-- Output keywords ONLY.--# TAG SET-{{ all_tags | join(', ') }}--{% for ex in examples %}-# Examples {{ loop.index0 }}-### Text Content-{{ ex.content }}--Output:-{{ ex.tags_json }}--{% endfor %}-# Real Data-### Text Content-{{ content }}diff --git a/rag/prompts/full_question_prompt.md b/rag/prompts/full_question_prompt.mddeleted file mode 100644index d7276a3ea2..0000000000--- a/rag/prompts/full_question_prompt.md+++ /dev/null@@ -1,62 +0,0 @@-## Role-A helpful assistant.--## Task & Steps-1. Generate a full user question that would follow the conversation.-2. If the user's question involves relative dates, convert them into absolute dates based on today ({{ today }}).- - "yesterday" = {{ yesterday }}, "tomorrow" = {{ tomorrow }}--## Requirements & Restrictions-- If the user's latest question is already complete, don't do anything — just return the original question.-- DON'T generate anything except a refined question.-{% if language %}-- Text generated MUST be in {{ language }}.-{% else %}-- Text generated MUST be in the same language as the original user's question.-{% endif %}-------## Examples--### Example 1-**Conversation:**--USER: What is the name of Donald Trump's father?-ASSISTANT: Fred Trump.-USER: And his mother?--**Output:** What's the name of Donald Trump's mother?-------### Example 2-**Conversation:**--USER: What is the name of Donald Trump's father?-ASSISTANT: Fred Trump.-USER: And his mother?-ASSISTANT: Mary Trump.-USER: What's her full name?--**Output:** What's the full name of Donald Trump's mother Mary Trump?-------### Example 3-**Conversation:**--USER: What's the weather today in London?-ASSISTANT: Cloudy.-USER: What's about tomorrow in Rochester?--**Output:** What's the weather in Rochester on {{ tomorrow }}?-------## Real Data--**Conversation:**--{{ conversation }}-diff --git a/rag/prompts/meta_data.md b/rag/prompts/meta_data.mddeleted file mode 100644index 3041290643..0000000000--- a/rag/prompts/meta_data.md+++ /dev/null@@ -1,15 +0,0 @@-## Role: Metadata extraction expert.-## Rules:- - Fixed Key Set: Output ONLY the keys that appear in the Schema. Never add, rename, translate, pluralize or re-case a key, and never invent an extra key even if the Content clearly carries that information. Any key that is not in the Schema MUST be omitted.- - Strict Evidence Only: Extract a value ONLY if it is explicitly mentioned in the Content.- - Enum Filter: For any field with an 'enum' list, the list acts as a strict filter. If no element from the list (or its direct synonym) is found in the Content, you MUST NOT extract that field.- - No Meta-Inference: Do not infer values based on the document's nature, format, or category. If the text does not literally state the information, treat it as missing.- - Zero-Hallucination: Never invent information or pick a "likely" value from the enum to fill a field.- - Empty Result: If no matches are found for any field, or if the content is irrelevant, output ONLY {}.- - Output: ONLY a valid JSON string. No Markdown, no notes.--## Schema for extraction:-{{ schema }}--## Content to analyze:-{{ content }}diff --git a/rag/prompts/multi_queries_gen.md b/rag/prompts/multi_queries_gen.mddeleted file mode 100644index 7d1b2993e6..0000000000--- a/rag/prompts/multi_queries_gen.md+++ /dev/null@@ -1,41 +0,0 @@-You are a query optimization expert.-The user's original query failed to retrieve sufficient information;-please generate multiple complementary improved questions and corresponding queries.--Original query:-{{ original_query }}--Original question:-{{ original_question }}--Currently, retrieved content:-{{ retrieved_docs }}--Missing information:-{{ missing_info }}--Please generate 2-3 complementary queries to help find the missing information. These queries should:-1. Focus on different missing information points.-2. Use different expressions.-3. Avoid being identical to the original query.-4. Remain concise and clear.--Output format (JSON):-```json-{- "reasoning": "Explanation of query generation strategy",- "questions": [- {"question": "Improved question 1", "query": "Improved query 1"},- {"question": "Improved question 2", "query": "Improved query 2"},- {"question": "Improved question 3", "query": "Improved query 3"}- ]-}-```--Requirements:-1. Questions array contains 1-3 questions and corresponding queries.-2. Each question length is between 5-200 characters.-3. Each query length is between 1-5 keywords.-4. Each query MUST be in the same language as the retrieved content in.-5. DO NOT generate question and query that is similar to the original query.-6. Reasoning explains the generation strategy.\ No newline at end of filediff --git a/rag/prompts/next_step.md b/rag/prompts/next_step.mddeleted file mode 100644index 3c45a0d086..0000000000--- a/rag/prompts/next_step.md+++ /dev/null@@ -1,138 +0,0 @@-You are an expert Planning Agent tasked with solving problems efficiently through structured plans.-Your job is:-1. Based on the task analysis, chose some right tools to execute.-2. Track progress and adapt plans(tool calls) when necessary.-3. Use `complete_task` if no further step you need to take from tools. (All necessary steps done or little hope to be done)--# ========== TASK ANALYSIS =============-{{ task_analysis }}--# ========== TOOLS (JSON-Schema) ==========-You may invoke only the tools listed below.-Return a JSON array of objects in which item is with exactly two top-level keys:-• "name": the tool to call-• "arguments": an object whose keys/values satisfy the schema--{{ desc }}---# ========== MULTI-STEP EXECUTION ==========-When tasks require multiple independent steps, you can execute them in parallel by returning multiple tool calls in a single JSON array.--• **Data Collection**: Gathering information from multiple sources simultaneously-• **Validation**: Cross-checking facts using different tools-• **Comprehensive Analysis**: Analyzing different aspects of the same problem-• **Efficiency**: Reducing total execution time when steps don't depend on each other--**Example Scenarios:**-- Searching multiple databases for the same query-- Checking weather in multiple cities-- Validating information through different APIs-- Performing calculations on different datasets-- Gathering user preferences from multiple sources--# ========== RESPONSE FORMAT ==========-**When you need a tool**-Return ONLY the Json (no additional keys, no commentary, end with `<|stop|>`), such as following:-[{- "name": "<tool_name1>",- "arguments": { /* tool arguments matching its schema */ }-},{- "name": "<tool_name2>",- "arguments": { /* tool arguments matching its schema */ }-}...]<|stop|>--**When you need multiple tools:**-Return ONLY:-[{- "name": "<tool_name1>",- "arguments": { /* tool arguments matching its schema */ }-},{- "name": "<tool_name2>",- "arguments": { /* tool arguments matching its schema */ }-},{- "name": "<tool_name3>",- "arguments": { /* tool arguments matching its schema */ }-}...]<|stop|>--**When you are certain the task is solved OR no further information can be obtained**-Return ONLY:-[{- "name": "complete_task",- "arguments": { "answer": "<final answer text>" }-}]<|stop|>--<verification_steps>-Before providing a final answer:-1. Double-check all gathered information-2. Verify calculations and logic-3. Ensure answer matches exactly what was asked-4. Confirm answer format meets requirements-5. Run additional verification if confidence is not 100%-</verification_steps>--<error_handling>-If you encounter issues:-1. Try alternative approaches before giving up-2. Use different tools or combinations of tools-3. Break complex problems into simpler sub-tasks-4. Verify intermediate results frequently-5. Never return "I cannot answer" without exhausting all options-</error_handling>--⚠️ Any output that is not valid JSON or that contains extra fields will be rejected.--# ========== PRIVATE REASONING & REFLECTION ==========-You may think privately inside `<think>` tags.-This content will NOT be shown to the user.--## Step 1: Core Reasoning-- Analyze the task requirements-- Decide whether tools are required-- Decide if parallel execution is appropriate--## Step 2: Structured Reflection (MANDATORY before `complete_task`)--### Context-- Goal: Reflect on the current task based on the full conversation context-- Executed tool calls so far (if any): reflect from conversation history--### Task Complexity Assessment-Evaluate the task along these dimensions:--- Scope Breadth: Single-step (1) | Multi-step (2) | Multi-domain (3)-- Data Dependency: Self-contained (1) | External inputs (2) | Multiple sources (3)-- Decision Points: Linear (1) | Few branches (2) | Complex logic (3)-- Risk Level: Low (1) | Medium (2) | High (3)--Compute the **Complexity Score (4–12)**.--### Reflection Depth Control-- 4–5: Brief sanity check-- 6–8: Check completeness + risks-- 9–12: Full reflection with alternatives--### Reflection Checklist-- Goal alignment: Is the objective truly satisfied?-- Step completion: Any planned step missing?-- Information adequacy: Is evidence sufficient?-- Errors or uncertainty: Any low-confidence result?-- Tool misuse risk: Wrong tool / missing tool?--### Decision Gate-Ask yourself explicitly:-> “If I stop now and call `complete_task`, would a downstream agent or user reasonably say something is missing or wrong?”--If YES → continue with tools-If NO → safe to call `complete_task`-------# ========== FINAL ACTION ==========-After reflection, emit ONLY ONE of the following:-- A JSON array of tool calls-- OR a single `complete_task` call---Today is {{ today }}. Remember that success in answering questions accurately is paramount - take all necessary steps to ensure your answer is correct.-diff --git a/rag/prompts/question_prompt.md b/rag/prompts/question_prompt.mddeleted file mode 100644index ec9889fbfe..0000000000--- a/rag/prompts/question_prompt.md+++ /dev/null@@ -1,19 +0,0 @@-## Role-You are a text analyzer.--## Task-Propose {{ topn }} questions about a given piece of text content.--## Requirements-- Understand and summarize the text content, and propose the top {{ topn }} important questions.-- The questions SHOULD NOT have overlapping meanings.-- The questions SHOULD cover the main content of the text as much as possible.-- The questions MUST be in the same language as the given piece of text content.-- One question per line.-- Output questions ONLY.-------## Text Content-{{ content }}-diff --git a/rag/prompts/rank_memory.md b/rag/prompts/rank_memory.mddeleted file mode 100644index 7196985821..0000000000--- a/rag/prompts/rank_memory.md+++ /dev/null@@ -1,30 +0,0 @@-**Task**: Sort the tool call results based on relevance to the overall goal and current sub-goal. Return ONLY a sorted list of indices (0-indexed).--**Rules**:-1. Analyze each result's contribution to both:- - The overall goal (primary priority)- - The current sub-goal (secondary priority)-2. Sort from MOST relevant (highest impact) to LEAST relevant-3. Output format: Strictly a Python-style list of integers. Example: [2, 0, 1]--🔹 Overall Goal: {{ goal }}-🔹 Sub-goal: {{ sub_goal }}--**Examples**:-🔹 Tool Response:- - index: 0- > Tokyo temperature is 78°F.- - index: 1- > Error: Authentication failed (expired API key).- - index: 2- > Available: 12 widgets in stock (max 5 per customer).-- → rank: [1,2,0]<|stop|>---**Your Turn**:-🔹 Tool Response:-{% for f in results %}- - index: f.i- > f.content-{% endfor %}\ No newline at end of filediff --git a/rag/prompts/reflect.md b/rag/prompts/reflect.mddeleted file mode 100644index a3e5e9cf11..0000000000--- a/rag/prompts/reflect.md+++ /dev/null@@ -1,75 +0,0 @@-**Context**:- - To achieve the goal: {{ goal }}.- - You have executed following tool calls:-{% for call in tool_calls %}-Tool call: `{{ call.name }}`-Results: {{ call.result }}-{% endfor %}--## Task Complexity Analysis & Reflection Scope--**First, analyze the task complexity using these dimensions:**--### Complexity Assessment Matrix-- **Scope Breadth**: Single-step (1) | Multi-step (2) | Multi-domain (3)-- **Data Dependency**: Self-contained (1) | External inputs (2) | Multiple sources (3)-- **Decision Points**: Linear (1) | Few branches (2) | Complex logic (3)-- **Risk Level**: Low (1) | Medium (2) | High (3)--**Complexity Score**: Sum all dimensions (4-12 points)-------## Task Transmission Assessment-**Note**: This section is not subject to word count limitations when transmission is needed, as it serves critical handoff functions.-**Evaluate if task transmission information is needed:**-- **Is this an initial step?** If yes, skip this section-- **Are there downstream agents/steps?** If no, provide minimal transmission-- **Is there critical state/context to preserve?** If yes, include full transmission--### If Task Transmission is Needed:-- **Current State Summary**: [1-2 sentences on where we are]-- **Key Data/Results**: [Critical findings that must carry forward]-- **Context Dependencies**: [Essential context for next agent/step]-- **Unresolved Items**: [Issues requiring continuation]-- **Status for User**: [Clear status update in user terms]-- **Technical State**: [System state for technical handoffs]-------## Situational Reflection (Adjust Length Based on Complexity Score)--### Reflection Guidelines:-- **Simple Tasks (4-5 points)**: ~50-100 words, focus on completion status and immediate next step-- **Moderate Tasks (6-8 points)**: ~100-200 words, include core details and main risks-- **Complex Tasks (9-12 points)**: ~200-300 words, provide full analysis and alternatives--### 1. Goal Achievement Status- - Does the current outcome align with the original purpose of this task phase?- - If not, what critical gaps exist?--### 2. Step Completion Check- - Which planned steps were completed? (List verified items)- - Which steps are pending/incomplete? (Specify exactly what's missing)--### 3. Information Adequacy- - Is the collected data sufficient to proceed?- - What key information is still needed? (e.g., metrics, user input, external data)--### 4. Critical Observations- - Unexpected outcomes: [Flag anomalies/errors]- - Risks/blockers: [Identify immediate obstacles]- - Accuracy concerns: [Highlight unreliable results]--### 5. Next-Step Recommendations- - Proposed immediate action: [Concrete next step]- - Alternative strategies if blocked: [Workaround solution]- - Tools/inputs required for next phase: [Specify resources]-------**Output Instructions:**-1. First determine your complexity score-2. Assess if task transmission section is needed using the evaluation questions-3. Provide situational reflection with length appropriate to complexity-4. Use clear headers for easy parsing by downstream systemsdiff --git a/rag/prompts/resume_basic_info.md b/rag/prompts/resume_basic_info.mddeleted file mode 100644index 7a3756813d..0000000000--- a/rag/prompts/resume_basic_info.md+++ /dev/null@@ -1,39 +0,0 @@-请从以下带行号索引的简历文本中提取基本信息。--{indexed_text}--提取如下信息到 JSON,若某些字段不存在则输出 "" 空或 0:-{{- "name_kwd": "",- "gender_kwd": "",- "age_int": 0,- "phone_kwd": "",- "email_tks": "",- "birth_dt": "",- "work_exp_flt": 0,- "current_location": "",- "expect_city_names_tks": [],- "expect_position_name_tks": [],- "skill_tks": [],- "language_tks": [],- "certificate_tks": [],- "self_evaluation_tks": ""-}}--字段说明:-- name_kwd: 姓名,如"张三"-- gender_kwd: 男/女,若不存在则不填-- age_int: 当前年龄,整数-- phone_kwd: 电话/手机,请保留原文中的形式,保留国家码区号括号-- email_tks: 邮箱,如 "[email protected]"-- birth_dt: 出生年月,如 "1996-11"-- work_exp_flt: 工作年限,浮点数-- current_location: 现居地/当前城市,不要从工作经历中推测,要写明现居地-- expect_city_names_tks: 期望工作城市列表,简历中需要明确说明是期望城市-- expect_position_name_tks: 期望职位列表-- skill_tks: 技能/技术栈列表-- language_tks: 语言能力列表-- certificate_tks: 证书/资质列表-- self_evaluation_tks: 自我评价/个人优势/个人总结,完整提取原文内容--只返回 JSON。 /no_think\ No newline at end of filediff --git a/rag/prompts/resume_basic_info_en.md b/rag/prompts/resume_basic_info_en.mddeleted file mode 100644index 7ea6dd0bc8..0000000000--- a/rag/prompts/resume_basic_info_en.md+++ /dev/null@@ -1,39 +0,0 @@-Please extract basic information from the following line-indexed resume text.--{indexed_text}--Extract the following information into JSON. If a field does not exist, output "" or 0:-{{- "name_kwd": "",- "gender_kwd": "",- "age_int": 0,- "phone_kwd": "",- "email_tks": "",- "birth_dt": "",- "work_exp_flt": 0,- "current_location": "",- "expect_city_names_tks": [],- "expect_position_name_tks": [],- "skill_tks": [],- "language_tks": [],- "certificate_tks": [],- "self_evaluation_tks": ""-}}--Field descriptions:-- name_kwd: Full name, e.g. "John Smith"-- gender_kwd: Male/Female, leave empty if not present-- age_int: Current age, integer-- phone_kwd: Phone number, keep original format including country code and brackets-- email_tks: Email address, e.g. "[email protected]"-- birth_dt: Date of birth, e.g. "1996-11"-- work_exp_flt: Years of work experience, float-- current_location: Current city/location, do not infer from work experience, must be explicitly stated-- expect_city_names_tks: List of preferred work cities, must be explicitly stated in the resume-- expect_position_name_tks: List of desired positions-- skill_tks: List of skills/tech stack-- language_tks: List of language proficiencies-- certificate_tks: List of certificates/qualifications-- self_evaluation_tks: Self-evaluation/personal strengths/summary, extract full original text--Return JSON only. /no_think\ No newline at end of filediff --git a/rag/prompts/resume_education.md b/rag/prompts/resume_education.mddeleted file mode 100644index 95ff8eb4d6..0000000000--- a/rag/prompts/resume_education.md+++ /dev/null@@ -1,31 +0,0 @@-请从以下带行号索引的简历文本中提取教育背景。--{indexed_text}--提取为 JSON:-{{- "education": [- {{- "school": "",- "major": "",- "degree": "",- "department": "",- "start_date": "",- "end_date": "",- "desc_lines": [start_index, end_index]- }}- ]-}}--字段说明:-- school: 学校全称,如"厦门大学",中英文都可以-- major: 专业,如"机械工程"-- degree: 学位,本科/硕士/博士/专科/高中/初中,若不存在则填""-- department: 系/学院,如"信息工程系"-- start_date: 开始时间,格式为 %Y.%m 或 %Y-- end_date: 结束时间,若至今填写"至今",若不存在填写""-- desc_lines: [起始行号, 结束行号],教育描述对应的行号范围(可选)- - 包括课程成绩、研究方向、GPA、荣誉奖项等- - 不存在则填 []--只返回 JSON。 /no_think\ No newline at end of filediff --git a/rag/prompts/resume_education_en.md b/rag/prompts/resume_education_en.mddeleted file mode 100644index 9d726b48b4..0000000000--- a/rag/prompts/resume_education_en.md+++ /dev/null@@ -1,31 +0,0 @@-Please extract education background from the following line-indexed resume text.--{indexed_text}--Extract into JSON:-{{- "education": [- {{- "school": "",- "major": "",- "degree": "",- "department": "",- "start_date": "",- "end_date": "",- "desc_lines": [start_index, end_index]- }}- ]-}}--Field descriptions:-- school: Full school name, e.g. "Stanford University", both Chinese and English are acceptable-- major: Major/field of study, e.g. "Computer Science"-- degree: Degree level - Bachelor/Master/PhD/Associate/High School/Middle School, leave "" if not available-- department: Department/College, e.g. "School of Engineering"-- start_date: Start date, format %Y.%m or %Y-- end_date: End date, use "Present" if still enrolled, "" if not available-- desc_lines: [start_line, end_line], line number range for education description (optional)- - Includes coursework, research focus, GPA, honors/awards, etc.- - Use [] if not available--Return JSON only. /no_think\ No newline at end of filediff --git a/rag/prompts/resume_project_exp.md b/rag/prompts/resume_project_exp.mddeleted file mode 100644index ed216deaba..0000000000--- a/rag/prompts/resume_project_exp.md+++ /dev/null@@ -1,31 +0,0 @@-请从以下带行号索引的简历文本中提取项目经验。--{indexed_text}--提取为 JSON,每段项目经验包含:-{{- "projectExperience": [- {{- "project_name": "",- "role": "",- "start_date": "",- "end_date": "",- "desc_lines": [start_index, end_index]- }}- ]-}}--字段说明:-- project_name: 项目名称-- role: 担任角色/职责,如"项目负责人"、"后端开发"-- start_date: 开始时间,格式为 %Y.%m 或 %Y-- end_date: 结束时间,若至今填写"至今",若不存在填写""-- desc_lines: [起始行号, 结束行号],项目描述对应的行号范围(整数数组)- - 指项目描述的原文引用段落 index 范围,包括项目内容、技术栈、成果等- - 不包括 project_name、role、start_date、end_date 所在行- - 尽可能写全,直到下一段项目经验或其他段落标题为止- - 遇到以下段落标题时必须截止,不要将其包含在 desc_lines 中:- 个人评价、自我评价、个人总结、个人优势、自我描述、技能特长、专业技能、教育背景、教育经历、工作经历、工作经验、证书资质、语言能力、兴趣爱好、求职意向- - 如果不存在就写 []--只返回 JSON。 /no_think\ No newline at end of filediff --git a/rag/prompts/resume_project_exp_en.md b/rag/prompts/resume_project_exp_en.mddeleted file mode 100644index e33de88e5c..0000000000--- a/rag/prompts/resume_project_exp_en.md+++ /dev/null@@ -1,31 +0,0 @@-Please extract project experience from the following line-indexed resume text.--{indexed_text}--Extract into JSON, each project experience entry contains:-{{- "projectExperience": [- {{- "project_name": "",- "role": "",- "start_date": "",- "end_date": "",- "desc_lines": [start_index, end_index]- }}- ]-}}--Field descriptions:-- project_name: Project name-- role: Role/responsibility, e.g. "Project Lead", "Backend Developer"-- start_date: Start date, format %Y.%m or %Y-- end_date: End date, use "Present" if ongoing, "" if not available-- desc_lines: [start_line, end_line], line number range for project description (integer array)- - Refers to the original text reference range for project description, including project content, tech stack, achievements, etc.- - Does not include lines containing project_name, role, start_date, end_date- - Include as much as possible until the next project experience entry or other section heading- - STOP before these section headings (do not include them in desc_lines):- Self-evaluation, Personal Summary, Skills, Technical Skills, Education, Work Experience, Certificates, Languages, Hobbies, Career Objective- - Use [] if not available--Return JSON only. /no_think\ No newline at end of filediff --git a/rag/prompts/resume_system.md b/rag/prompts/resume_system.mddeleted file mode 100644index 9b3419f41e..0000000000--- a/rag/prompts/resume_system.md+++ /dev/null@@ -1,3 +0,0 @@-你是一个专业的简历分析助手。你的任务是将给定的简历文本转换为 JSON 输出。-(如果有中英文简历同时出现时,只关注中文简历)-严格按照 JSON 格式返回结果,不要有任何其他文字。\ No newline at end of filediff --git a/rag/prompts/resume_system_en.md b/rag/prompts/resume_system_en.mddeleted file mode 100644index 8d02488f26..0000000000--- a/rag/prompts/resume_system_en.md+++ /dev/null@@ -1,3 +0,0 @@-You are a professional resume analysis assistant. Your task is to convert the given resume text into JSON output.-(If both Chinese and English resumes appear, focus only on the English resume)-Strictly return results in JSON format without any other text.\ No newline at end of filediff --git a/rag/prompts/resume_work_exp.md b/rag/prompts/resume_work_exp.mddeleted file mode 100644index 2a7465c16e..0000000000--- a/rag/prompts/resume_work_exp.md+++ /dev/null@@ -1,39 +0,0 @@-请从以下带行号索引的简历文本中提取工作经历。--{indexed_text}--提取为 JSON,每段工作经历包含:-{{- "workExperience": [- {{- "company": "",- "position": "",- "internship": 0,- "start_date": "",- "end_date": "",- "desc_lines": [start_index, end_index]- }}- ]-}}--字段说明:-- company: 公司全称(含括号内地区信息),如"阿里巴巴(中国)有限公司"-- position: 职位名称,遵循原文不要编造或推测-- internship: 该段经历是否是实习,是实习为1,不是为0-- start_date: 入职时间,格式为 %Y.%m 或 %Y,如 "2024.1"-- end_date: 离职时间,若至今填写"至今",若不存在填写""-- desc_lines: [起始行号, 结束行号],工作描述对应的行号范围(整数数组)- - 指工作经历描述的原文引用段落 index 范围,包括工作成果、业绩、主要工作、技术栈等- - 不包括 company、position、start_date、end_date 所在行- - 尽可能写全,直到下一段工作经历或其他段落标题为止- - 遇到以下段落标题时必须截止,不要将其包含在 desc_lines 中:- 个人评价、自我评价、个人总结、个人优势、自我描述、技能特长、专业技能、教育背景、教育经历、项目经验、项目经历、证书资质、语言能力、兴趣爱好、求职意向- - 如果不存在就写 []--示例:-[22]: 阿里巴巴 2021.11-2022.11 高级工程师-[23]: 工作描述: 从事地推工作完成xx业绩-[24]: 在地推任务中考核为A-则 desc_lines 应为 [23, 24]--只返回 JSON。 /no_think\ No newline at end of filediff --git a/rag/prompts/resume_work_exp_en.md b/rag/prompts/resume_work_exp_en.mddeleted file mode 100644index 46e4c9ac8b..0000000000--- a/rag/prompts/resume_work_exp_en.md+++ /dev/null@@ -1,38 +0,0 @@-Please extract work experience from the following line-indexed resume text.--{indexed_text}--Extract into JSON, each work experience entry contains:-{{- "workExperience": [- {{- "company": "",- "position": "",- "internship": 0,- "start_date": "",- "end_date": "",- "desc_lines": [start_index, end_index]- }}- ]-}}--Field descriptions:-- company: Full company name (including region info in brackets), e.g. "Google Inc."-- position: Job title, follow original text, do not fabricate or guess-- internship: Whether this is an internship, 1 for yes, 0 for no-- start_date: Start date, format %Y.%m or %Y, e.g. "2024.1"-- end_date: End date, use "Present" if still employed, "" if not available-- desc_lines: [start_line, end_line], line number range for job description (integer array)- - Refers to the original text reference range for job description, including achievements, responsibilities, tech stack, etc.- - Include as much as possible until the next work experience entry or other section heading- - STOP before these section headings (do not include them in desc_lines):- Self-evaluation, Personal Summary, Skills, Technical Skills, Education, Project Experience, Certificates, Languages, Hobbies, Career Objective- - Use [] if not available--Example:-[22]: Google Inc. 2021.11-2022.11 Senior Engineer-[23]: Job description: Responsible for backend development-[24]: Achieved 99.9% uptime for core services-Then desc_lines should be [23, 24]--Return JSON only. /no_think\ No newline at end of filediff --git a/rag/prompts/sca_query_rewrite.md b/rag/prompts/sca_query_rewrite.mddeleted file mode 100644index 4bac290600..0000000000--- a/rag/prompts/sca_query_rewrite.md+++ /dev/null@@ -1,35 +0,0 @@-You are a Query Rewriter for a multi-hop RAG system. Your job is to turn the Sufficient Context Agent's missing-pieces feedback into targeted, retrievable search queries.--Original user question:-{{ question }}--Already-resolved bridge values (facts confirmed from earlier searches — use these to anchor the new query instead of re-deriving them):-{{ bridge_values }}--Research history and evidence at hand (from previous retrieval rounds):-{{ research_context }}--Missing pieces identified by the Sufficient Context Agent (each has "what" = what the answer still needs, and "hint" = a suggested search hint):-{{ gaps }}--Rewrite each missing piece into a concrete search query that the retriever can hit directly. Rules:-1. The query must name the specific missing entity + the relation/property needed (e.g. instead of "the patient's allergies", write "allergic reactions adverse events discharge John Doe").-2. MULTI-HOP: when the question is multi-hop and the missing piece is the NEXT hop's value, ANCHOR the query to the already-resolved bridge value. E.g. if the bridge value is "M*A*S*H and Cheers are the two most-watched finales" and the gap is "their runtimes", the query must be "MASH finale run time minutes" / "Cheers finale run time minutes" — not "finale run times" alone, which would lose the resolved anchor.-3. If the "what" names a specific entity (person / work / place / year) whose property is missing, anchor the query to that entity + the missing property (e.g. "MASH finale run time minutes", "Brian Bergstein employer company").-4. If a disambiguation is needed, add the distinguishing qualifier ONLY when the evidence actually suggests it (e.g. a disambiguation "the heritage 341 London Broncos player" when the claim is about that specific player). CRITICAL: NEVER introduce an entity/relation/attribute that the evidence and the missing piece do NOT suggest, and NEVER re-infer a category from the question alone (e.g. do NOT write "Ron Hutchinson football player" unless the evidence actually identifies him as a footballer — he may be a hockey player; the query must stay faithful to what the missing piece says).-5. Keep each query standalone and searchable — do NOT use pronouns ("he", "it", "this") — repeat the key entity explicitly.-6. ONE QUERY PER MISSING PIECE. Do not emit multiple near-duplicate queries for the same gap ("What teams"/"For each team"/"Complete enumeration" of the same thing are duplicates — keep exactly one, the most concretely anchored). The number of output queries should equal the number of distinct, genuinely-different missing pieces.-7. Drop any missing piece that cannot be turned into a searchable query.-8. DIVERSITY: consult the "Research history and evidence at hand" section. Do NOT output any query that paraphrases an already-tried one (listed there WITH its outcome — a previous search that yielded nothing new means that angle is dead). Aim each new query at aspects the current evidence does NOT yet cover, possibly combining the bridge values with different entity/relation combinations.--Output format (JSON):-```json-{- "queries": [- {"query": "concrete search query 1"},- {"query": "concrete search query 2"}- ]-}-```--Return a strict JSON object with no commentary before or after.diff --git a/rag/prompts/sca_select.md b/rag/prompts/sca_select.mddeleted file mode 100644index 2e70cc72d0..0000000000--- a/rag/prompts/sca_select.md+++ /dev/null@@ -1,106 +0,0 @@-You are Google-style "Sufficient Context Agent" — a quality-control inspector for a multi-hop RAG retrieval loop. In ONE pass you perform a unified three-part review of (1) the retrieved snippets, (2) each claim's intermediate draft, and (3) what is still missing — then you decide whether the context is sufficient to answer the original question.--## Input--Question:-{{ question }}--OVERALL INTERMEDIATE DRAFT — a problem-level candidate answer assembled from the claims' reports (each claim already answered its sub-question as concretely as the evidence allows). Review THIS as the thing that would become the final answer:-{{ overall_draft }}--Per-claim reports (the intermediate drafts that produced the overall draft above):-{{ claims_context }}--## Part A — Sufficient Context (global)--Determine whether the retrieved content is sufficient to answer the user's question, using the Sufficient Context paper's autorater criterion:--Sufficient Context = 1 IF the CONTEXT is sufficient to INFER the answer to the question, and 0 IF the CONTEXT cannot be used to INFER the answer to the question. "A diligent reader could craft a definitive answer using only the supplied text." The answer does NOT need to be proven correct or match a ground truth — only that a reasonable answer can be constructed from the context. Multi-hop reasoning is allowed, but leaps of faith are not; ambiguities must be resolved inside the snippet bundle.--The CONTEXT here is the OVERALL INTERMEDIATE DRAFT (the problem-level candidate answer assembled from the claims) plus the per-claim reports. Judge whether THIS draft lets a diligent reader construct the answer to the ORIGINAL question end-to-end — including any cross-claim synthesis (e.g. two claims that must be COMBINED into one derived answer, or an enumeration the claims only partially cover). If the draft answers the question (even partially), mark sufficient; if the question cannot be answered from the draft at all, mark insufficient and say exactly what is missing (Part C).--MANDATORY three-stage reasoning (this is what makes the judgement reliable — follow it strictly):-1. FIRST, write down the STEP-BY-STEP SUB-QUESTIONS you would need to answer in order to arrive at the label. Make sure to include questions about any ASSUMPTIONS implicit in the QUESTION, and include questions about any MATHEMATICAL CALCULATIONS or ARITHMETIC that would be required.-2. THEN, answer each of those sub-questions step by step, working through any required mathematical calculations or arithmetic explicitly.-3. FINALLY, use these answers to evaluate the criterion and decide `is_sufficient`. If the sub-question answers let you construct a definitive answer from the context, it is sufficient — even if the answer is not perfectly complete. Only when the sub-questions cannot be answered from the context (so NO plausible answer can be inferred) is it insufficient, and then you must fill `missing_information` with exactly what is missing (Part C).--Computed answers: when a sub-question requires arithmetic (e.g. difference, count, "how many years"), WORK THE CALCULATION yourself from the values in the context and only mark sufficient if it resolves to a definite result with the RIGHT operands. If it cannot be completed, mark insufficient and list what is missing.--The STEP-BY-STEP SUB-QUESTIONS from stage 1 MUST ALSO be emitted in a structured `sub_queries` array (one entry per sub-question), because they are the precise "what is missing" signal the next search round consumes. Decomposition rules (mutually-exclusive + complete coverage — every sub-question is an atomic fact needed to answer the ORIGINAL question, sub-questions do not overlap, and together they fully cover the question):-- MULTI-STEP / multi-hop: emit ONE sub-query per logical hop, and the LAST hop is the entity/role the question actually asks for. E.g. Q="Who is the president of the team whose name was inspired by the Boston Braves?" -> [sub-query "Which team's name was inspired by the Boston Braves?", sub-query "Who is that team's president?"].-- MULTI-ASPECT / enumeration+aggregate: emit ONE sub-query for the enumeration (values of EVERY member) and ONE for the aggregate (the combination over those members). E.g. Q="average left-field distance of every stadium" -> [sub-query "left-field distance of every stadium", sub-query "average of those left-field distances"].-- ARITHMETIC / temporal: the arithmetic itself is a sub-query, and every OPERAND must have a value. If an operand is absent, that sub-query is `satisfied: false` and `missing_fact` names the absent operand specifically. E.g. Q="how many days between the two deaths?" -> [sub-query "McLean death date" (satisfied), sub-query "Meyer death date" (satisfied:false, missing_fact:"Eugene Meyer's exact death date", search_hint:"Eugene Meyer Washington Post died date"), sub-query "days between them"].--Each entry in `sub_queries` is `{"sub_query": "...", "satisfied": true/false}`; when `satisfied` is false it MUST additionally carry `missing_fact` (the concrete absent fact) and `search_hint` (a searchable query anchoring entity+attribute+time). `satisfied: false` marks exactly WHAT is missing and WHERE to search next.--## Part B — Claim-draft groundedness (per claim)--For each claim's report (the intermediate draft), determine whether it is grounded and self-consistent. Each report was generated from that claim's cited evidence by the search agent, so the main risk is NOT absent-evidence hallucination but (a) prior-knowledge padding sneaking past the "saw it in evidence" rule, (b) internal contradictions between a claim's own numbers/entities, and (c) over-claiming a derived value.--A report is GROUNDED only if it reads as a faithful, internally consistent, evidence-backed finding. Flag as UNGROUNDED anything that:-- asserts a specific number/entity/relation but contradicts another part of the same report (internal conflict);-- over-claims a computed/derived result beyond what the underlying values support;-- reads like prior-knowledge padding rather than an evidence-backed finding.--For each claim, classify the report as GROUNDED or UNGROUNDED. List each ungrounded assertion with a one-line reason.--Derived/computed assertions — APPLY ONLY IF the question asks for a DERIVED result AND the report states that computed result. Then VERIFY THE CALCULATION YOURSELF from the values in the evidence: every operand must have an explicit value in the evidence AND be the RIGHT entity; recompute and check the report's stated result matches. If any operand's figure is absent, or the operands are the wrong entities, or the recomputed result disagrees, the computed assertion is UNGROUNDED (name the missing/wrong operand or the recomputed vs stated value).--## Part C — Missing pieces (forward gap)--`missing_information` = what the answer STILL needs but the evidence does NOT contain, with a searchable hint. This is the targeted re-search signal (Google Query Rewriter input). It is distinct from `ungrounded_assertions`:-- `ungrounded_assertions` = the draft asserted something the evidence does NOT support -> drop/correct it.-- `missing_information` = the answer REQUIRES a fact/entity/value the evidence lacks -> search for it.--Populate `missing_information` when, even if every draft is grounded, the evidence does NOT cover a part the question asks for. Examples:-- the question asks for a specific property (age / year / employer / distance / count) and the evidence has the entity but not that property;-- a disambiguation is needed (evidence has a same-named but wrong entity);-- the evidence covers only part of an enumeration (some list members present, others absent).--Each `missing_information` item MUST carry a concrete `search_hint`: a searchable query (keywords / qualifiers / the specific entity+relation) that would retrieve the missing fact. Leave empty when the evidence is complete.--## Output format (JSON) — ONE object, no commentary before/after--```json-{- "is_sufficient": true,- "confidence": 0.0,- "required_entities": ["Entity 1"],- "contradictions": ["conflicting figures if any"],- "reasoning": "step-by-step sufficiency judgment",- "sub_queries": [- {- "sub_query": "Which team's name was inspired by the Boston Braves?",- "satisfied": true- },- {- "sub_query": "Who is that team's president?",- "satisfied": false,- "missing_fact": "the team's current president",- "search_hint": "Washington Commanders president 2024"- }- ],- "claims": [- {- "claim_id": "c1",- "grounded": true,- "ungrounded_assertions": [],- "missing_information": [- {"what": "the specific missing fact the answer needs", "search_hint": "searchable query to retrieve it"}- ]- }- ]-}-```--## Requirements--0. **The TOP-LEVEL output is ONE single JSON object.** `claims` is an array FIELD inside that object — never wrap the whole output in an array, and never output just the `claims` array. The output must start with `{` and end with `}`.-1. `is_sufficient` true iff a plausible answer can be inferred from the context (Part A). Use the paper's SUFFICIENT-CONTEXT criterion: sufficient means a plausible answer can be constructed from the context — it does NOT need to be provably correct or complete. **A missing detail that a rough/partial answer can still accommodate does NOT make the context insufficient** — if the context lets you infer ANY plausible answer, mark sufficient (the presentation layer decides whether to caveat). Only when the context cannot support ANY plausible answer is it insufficient, and then your job is to say exactly what is missing (Part C).-2. `confidence` (0-1): how confident you are in the sufficiency decision. 0.9-1.0 if clearly sufficient/fails; 0.5-0.7 if partial/ambiguous; below 0.5 if you cannot tell.-3. `contradictions`: list internally conflicting figures/statements that make a single answer ambiguous. Empty array when none.-4. `claims` is MANDATORY and must NEVER be empty when there is at least one claim draft. Include EVERY claim_id exactly once. For each claim you must output `grounded`, `ungrounded_assertions`, AND `missing_information`. Do NOT omit any claim or any field.-5. `missing_information` is the MOST IMPORTANT field when `is_sufficient` is false. It is what drives the next search. When the context is insufficient, you MUST list, per claim, the concrete facts/entities/relations that are absent but required — each with a searchable `search_hint`. An empty `missing_information` is only acceptable when the claim is fully covered. **Never output an empty `claims` array while also saying `is_sufficient: false`** — that is a contradiction and aborts the whole search. If you judge the context insufficient, your primary job is to say exactly WHAT is missing and WHERE to search next.-6. `sub_queries` is MANDATORY (may be an empty array only when there is nothing to decompose). Emit the full step-by-step sub-query set from Part A stage 1, each marked `satisfied`. A `satisfied: false` entry MUST carry `missing_fact` + `search_hint` and is the precise "what to search next" signal — the Query Rewriter turns exactly those into the next round's queries. Keep sub-queries mutually-exclusive and fully-covering (no overlap, no gap beyond the unsatisfied ones).-7. `ungrounded_assertions` empty when grounded; otherwise list each with a one-line `reason`.-8. `reasoning` should be concise and clear.diff --git a/rag/prompts/structured_output_prompt.md b/rag/prompts/structured_output_prompt.mddeleted file mode 100644index a643011152..0000000000--- a/rag/prompts/structured_output_prompt.md+++ /dev/null@@ -1,16 +0,0 @@-You’re a helpful AI assistant. You could answer questions and output in JSON format.-constraints:- - You must output in JSON format.- - Do not output boolean value, use string type instead.- - Do not output integer or float value, use number type instead.-eg:- Here is the JSON schema:- {"properties": {"age": {"type": "number","description": ""},"name": {"type": "string","description": ""}},"required": ["age","name"],"type": "Object Array String Number Boolean","value": ""}-- Here is the user's question:- My name is John Doe and I am 30 years old.-- output:- {"name": "John Doe", "age": 30}-Here is the JSON schema:- {{ schema }}\ No newline at end of filediff --git a/rag/prompts/sufficiency_check.md b/rag/prompts/sufficiency_check.mddeleted file mode 100644index 705b914659..0000000000--- a/rag/prompts/sufficiency_check.md+++ /dev/null@@ -1,24 +0,0 @@-You are a information retrieval evaluation expert. Please assess whether the currently retrieved content is sufficient to answer the user's question.--User question:-{{ question }}--Retrieved content:-{{ retrieved_docs }}--Please determine whether these content are sufficient to answer the user's question.--Output format (JSON):-```json-{- "is_sufficient": true/false,- "reasoning": "Your reasoning for the judgment",- "missing_information": ["Missing information 1", "Missing information 2"]-}-```--Requirements:-1. If the retrieved content contains key information needed to answer the query, judge as sufficient (true).-2. If key information is missing, judge as insufficient (false), and list the missing information.-3. The `reasoning` should be concise and clear.-4. The `missing_information` should only be filled when insufficient, otherwise empty array.\ No newline at end of filediff --git a/rag/prompts/sufficiency_select.md b/rag/prompts/sufficiency_select.mddeleted file mode 100644index 9ddb2b82cb..0000000000--- a/rag/prompts/sufficiency_select.md+++ /dev/null@@ -1,53 +0,0 @@-You are an information retrieval evaluation expert. Determine whether the retrieved content is sufficient to answer the user's question(s), following the "Sufficient Context" criterion:--The CONTEXT is sufficient to answer the question if and only if a PLAUSIBLE answer can be inferred from it — that is, the retrieved content either directly contains or logically entails an answer to the question. The answer does NOT need to be proven correct; it only needs to be a reasonable, supportable answer. If the context cannot be used to infer any plausible answer, it is INSUFFICIENT.--Each retrieved chunk is labeled with an integer ID on a line like `ID: 3`.--User question(s):-{{ question }}--Retrieved content:-{{ retrieved_docs }}--Reasoning procedure (do this step-by-step before answering):-1. Identify the REQUIRED ENTITIES or key facts that a plausible answer to the question must involve.-2. For each required entity, check whether the retrieved content provides evidence about it. Record this in "coverage".-3. Check for multi-hop inference: if answering requires combining facts not present in the context, or inferring a connection the context does not state, that is NOT inferable from the context.-4. Check whether the context is ambiguous: if it could support multiple mutually exclusive plausible answers and nothing in the context lets you distinguish them, mark it insufficient.-5. Note any internally conflicting figures/statements in the context ("contradictions").-6. Decide whether a plausible answer can be inferred; give your confidence in that decision.--Derived/computed answers — APPLY ONLY IF the question actually asks for a computed/derived result:-- The rules below are STRICTLY CONDITIONAL. They apply ONLY when the question explicitly asks for a DERIVED result (e.g. "how many more/fewer", "what is the difference", "how many years between", "X% of", "how much older/younger", "how many more letters", "how many times larger").-- If the question is a PLAIN FACTUAL question (e.g. "what year", "what is the name", "who was X", "when did X happen") — NOT a computation — do NOT apply these rules. Answer the sufficiency judgment normally, and do NOT mark the context insufficient merely because two figures are present without being combined. Over-conservative abstaining on factual questions must be avoided: a context that supports a single, unambiguous factual answer is SUFFICIENT even if it also contains unrelated numbers.-- HOW TO TELL: scan the question for computation intent (a difference/ratio/percentage/timespan/letter-count being requested). No computation intent → skip this section entirely.-- WHEN APPLICABLE, you MUST actually WORK THE CALCULATION yourself, step by step, from the values present in the context, and only mark the context sufficient if the computation can be carried out AND resolves to a definite result.-- WORK STEP BY STEP: (a) identify the exact operands and their source values in the context (the specific entities/figures the question references); (b) run the arithmetic; (c) confirm the result is well-defined and not ambiguous.-- This is the crux: a context that contains the numbers is NOT sufficient if the operands are the WRONG entities (e.g. using Providence/Park City when the question needs a different city pair), or if the calculation cannot be resolved. If the computation cannot be completed to a definite answer, mark `is_sufficient` false and list exactly what is missing or wrong in `missing_information`.-- Also surface ASSUMPTIONS implicit in the question: if the question implies a specific pairing/interpretation (e.g. "the director's birthplace city vs the premiere city"), check the context supports that exact interpretation before declaring sufficient.--Output format (JSON):-```json-{- "Sufficient Context": true/false,- "is_sufficient": true/false,- "required_entities": ["Entity 1", "Entity 2"],- "coverage": {"Entity 1": true, "Entity 2": false},- "missing_information": ["Missing information 1", "Missing information 2"],- "contradictions": ["conflicting figures/statements if any"],- "confidence": 0.0,- "reasoning": "Step-by-step reasoning for the judgment",- "useful_chunk_ids": [0, 3, 7]-}-```--Requirements:-1. `Sufficient Context` / `is_sufficient` must be true if and only if a plausible answer can be inferred from the context (per the definition above). A missing detail that a reasonable answer would still require makes it false.-2. If not sufficient, list the concrete `missing_information`.-3. `coverage` must mark, for each required entity, whether the context provides evidence about it. Missing required entities belong in `missing_information`.-4. `confidence` (0-1): how confident you are in your sufficiency decision. 0.9-1.0 if the context clearly supports or clearly fails a plausible answer; 0.5-0.7 if evidence is partial or ambiguous; below 0.5 if you cannot tell.-5. `contradictions`: list any internally conflicting figures/statements that would make a single answer ambiguous. Empty array when none.-6. `useful_chunk_ids` must contain ONLY the integer IDs (taken from the `ID:` labels above) of chunks that provide information useful for answering the question(s). Exclude irrelevant or redundant chunks. Use an empty array when none are useful.-7. The `missing_information` should only be filled when insufficient, otherwise an empty array.-8. The `reasoning` should be concise and clear.diff --git a/rag/prompts/summary4memory.md b/rag/prompts/summary4memory.mddeleted file mode 100644index eb0f283f9b..0000000000--- a/rag/prompts/summary4memory.md+++ /dev/null@@ -1,35 +0,0 @@-**Role**: AI Assistant-**Task**: Summarize tool call responses-**Rules**:-1. Context: You've executed a tool (API/function) and received a response.-2. Condense the response into 1-2 short sentences.-3. Never omit:- - Success/error status- - Core results (e.g., data points, decisions)- - Critical constraints (e.g., limits, conditions)-4. Exclude technical details like timestamps/request IDs unless crucial.-5. Use language as the same as main content of the tool response.--**Response Template**:-"[Status] + [Key Outcome] + [Critical Constraints]"--**Examples**:-🔹 Tool Response:-{"status": "success", "temperature": 78.2, "unit": "F", "location": "Tokyo", "timestamp": 16923456}-→ Summary: "Success: Tokyo temperature is 78°F."--🔹 Tool Response:-{"error": "invalid_api_key", "message": "Authentication failed: expired key"}-→ Summary: "Error: Authentication failed (expired API key)."--🔹 Tool Response:-{"available": true, "inventory": 12, "product": "widget", "limit": "max 5 per customer"}-→ Summary: "Available: 12 widgets in stock (max 5 per customer)."--**Your Turn**:- - Tool call: {{ name }}- - Tool inputs as following:-{{ params }}-- - Tool Response:-{{ result }}\ No newline at end of filediff --git a/rag/prompts/toc_detection.md b/rag/prompts/toc_detection.mddeleted file mode 100644index 29e068a7a4..0000000000--- a/rag/prompts/toc_detection.md+++ /dev/null@@ -1,29 +0,0 @@-You are an AI assistant designed to analyze text content and detect whether a table of contents (TOC) list exists on the given page. Follow these steps:--1. **Analyze the Input**: Carefully review the provided text content.-2. **Identify Key Features**: Look for common indicators of a TOC, such as:- - Section titles or headings paired with page numbers.- - Patterns like repeated formatting (e.g., bold/italicized text, dots/dashes between titles and numbers).- - Phrases like "Table of Contents," "Contents," or similar headings.- - Logical grouping of topics/subtopics with sequential page references.-3. **Discern Negative Features**:- - The text contains no numbers, or the numbers present are clearly not page references (e.g., dates, statistical figures, phone numbers, version numbers).- - The text consists of full, descriptive sentences and paragraphs that form a narrative, present arguments, or explain concepts, rather than succinctly listing topics.- - Contains citations with authors, publication years, journal titles, and page ranges (e.g., "Smith, J. (2020). Journal Title, 10(2), 45-67.").- - Lists keywords or terms followed by multiple page numbers, often in alphabetical order.- - Comprises terms followed by their definitions or explanations.- - Labeled with headers like "Appendix A," "Appendix B," etc.- - Contains expressive language thanking individuals or organizations for their support or contributions.-4. **Evaluate Evidence**: Weigh the presence/absence of these features to determine if the content resembles a TOC.-5. **Output Format**: Provide your response in the following JSON structure:- ```json- {- "reasoning": "Step-by-step explanation of your analysis based on the features identified." ,- "exists": true/false- }- ```-6. **DO NOT** output anything else except JSON structure.--**Input text Content ( Text-Only Extraction ):**-{{ page_txt }}-diff --git a/rag/prompts/toc_extraction.md b/rag/prompts/toc_extraction.mddeleted file mode 100644index 02e1d031f6..0000000000--- a/rag/prompts/toc_extraction.md+++ /dev/null@@ -1,53 +0,0 @@-You are an expert parser and data formatter. Your task is to analyze the provided table of contents (TOC) text and convert it into a valid JSON array of objects.--**Instructions:**-1. Analyze each line of the input TOC.-2. For each line, extract the following three pieces of information:- * `structure`: The hierarchical index/numbering (e.g., "1", "2.1", "3.2.5", "A.1"). If a line has no visible numbering or structure indicator (like a main "Chapter" title), use `null`.- * `title`: The textual title of the section or chapter. This should be the main descriptive text, clean and without the page number.-3. Output **only** a valid JSON array. Do not include any other text, explanations, or markdown code block fences (like ```json) in your response.--**JSON Format:**-The output must be a list of objects following this exact schema:-```json-[- {- "structure": <structure index, "x.x.x" or None> (string),- "title": <title of the section>- },- ...-]-```--**Input Example:**-```-Contents-1 Introduction to the System ... 1-1.1 Overview .... 2-1.2 Key Features .... 5-2 Installation Guide ....8-2.1 Prerequisites ........ 9-2.2 Step-by-Step Process ........ 12-Appendix A: Specifications ..... 45-References ... 47-```--**Expected Output For The Example:**-```json-[- {"structure": null, "title": "Contents"},- {"structure": "1", "title": "Introduction to the System"},- {"structure": "1.1", "title": "Overview"},- {"structure": "1.2", "title": "Key Features"},- {"structure": "2", "title": "Installation Guide"},- {"structure": "2.1", "title": "Prerequisites"},- {"structure": "2.2", "title": "Step-by-Step Process"},- {"structure": "A", "title": "Specifications"},- {"structure": null, "title": "References"}-]-```--**Now, process the following TOC input:**-```-{{ toc_page }}-```\ No newline at end of filediff --git a/rag/prompts/toc_extraction_continue.md b/rag/prompts/toc_extraction_continue.mddeleted file mode 100644index 433ac68ad1..0000000000--- a/rag/prompts/toc_extraction_continue.md+++ /dev/null@@ -1,60 +0,0 @@-You are an expert parser and data formatter, currently in the process of building a JSON array from a multi-page table of contents (TOC). Your task is to analyze the new page of content and **append** the new entries to the existing JSON array.--**Instructions:**-1. You will be given two inputs:- * `current_page_text`: The text content from the new page of the TOC.- * `existing_json`: The valid JSON array you have generated from the previous pages.-2. Analyze each line of the `current_page_text` input.-3. For each new line, extract the following three pieces of information:- * `structure`: The hierarchical index/numbering (e.g., "1", "2.1", "3.2.5"). Use `null` if none exists.- * `title`: The clean textual title of the section or chapter.- * `page`: The page number on which the section starts. Extract only the number. Use `null` if not present.-4. **Append these new entries** to the `existing_json` array. Do not modify, reorder, or delete any of the existing entries.-5. Output **only** the complete, updated JSON array. Do not include any other text, explanations, or markdown code block fences (like ```json).--**JSON Format:**-The output must be a valid JSON array following this schema:-```json-[- {- "structure": <string or null>,- "title": <string>,- "page": <number or null>- },- ...-]-```--**Input Example:**-`current_page_text`:-```-3.2 Advanced Configuration ........... 25-3.3 Troubleshooting .................. 28-4 User Management .................... 30-```--`existing_json`:-```json-[- {"structure": "1", "title": "Introduction", "page": 1},- {"structure": "2", "title": "Installation", "page": 5},- {"structure": "3", "title": "Configuration", "page": 12},- {"structure": "3.1", "title": "Basic Setup", "page": 15}-]-```--**Expected Output For The Example:**-```json-[- {"structure": "3.2", "title": "Advanced Configuration", "page": 25},- {"structure": "3.3", "title": "Troubleshooting", "page": 28},- {"structure": "4", "title": "User Management", "page": 30}-]-```--**Now, process the following inputs:**-`current_page_text`:-{{ toc_page }}--`existing_json`:-{{ toc_json }}\ No newline at end of filediff --git a/rag/prompts/toc_from_text_system.md b/rag/prompts/toc_from_text_system.mddeleted file mode 100644index 7090f30582..0000000000--- a/rag/prompts/toc_from_text_system.md+++ /dev/null@@ -1,119 +0,0 @@-You are a robust Table-of-Contents (TOC) extractor.--GOAL-Given a dictionary of chunks {"<chunk_ID>": chunk_text}, extract TOC-like headings and return a strict JSON array of objects:-[- {"title": "", "chunk_id": ""},- ...-]--FIELDS-- "title": the heading text (clean, no page numbers or leader dots).- - If any part of a chunk has no valid heading, output that part as {"title":"-1", ...}.-- "chunk_id": the chunk ID (string).- - One chunk can yield multiple JSON objects in order (unmatched text + one or more headings).--RULES-1) Preserve input chunk order strictly.-2) If a chunk contains multiple headings, expand them in order:- - Pre-heading narrative → {"title":"-1","chunk_id":"<chunk_ID>"}- - Then each heading → {"title":"...","chunk_id":"<chunk_ID>"}-3) Do not merge outputs across chunks; each object refers to exactly one chunk ID.-4) "title" must be non-empty (or exactly "-1"). "chunk_id" must be a string (chunk ID).-5) When ambiguous, prefer "-1" unless the text strongly looks like a heading.--HEADING DETECTION (cues, not hard rules)-- Appears near line start, short isolated phrase, often followed by content.-- May contain separators: — —— - : : · •-- Numbering styles:- • 第[一二三四五六七八九十百]+(篇|章|节|条)- • [((]?[一二三四五六七八九十]+[))]?- • [((]?[①②③④⑤⑥⑦⑧⑨⑩][))]?- • ^\d+(\.\d+)*[)..]?\s*- • ^[IVXLCDM]+[).]- • ^[A-Z][).]-- Canonical section cues (general only):- Common heading indicators include words such as:- "Overview", "Introduction", "Background", "Purpose", "Scope", "Definition",- "Method", "Procedure", "Result", "Discussion", "Summary", "Conclusion",- "Appendix", "Reference", "Annex", "Acknowledgment", "Disclaimer".- These are soft cues, not strict requirements.-- Length restriction:- • Chinese heading: ≤25 characters- • English heading: ≤80 characters-- Exclude long narrative sentences, continuous prose, or bullet-style lists → output as "-1".--OUTPUT FORMAT-- Return ONLY a valid JSON array of {"title","content"} objects.-- No reasoning or commentary.--EXAMPLES--Example 1 — No heading-Input:-[{"0": "Copyright page · Publication info (ISBN 123-456). All rights reserved."}, ...]-Output:-[- {"title":"-1","chunk_id":"0"},- ...-]--Example 2 — One heading-Input:-[{"1": "Chapter 1: General Provisions This chapter defines the overall rules…"}, ...]-Output:-[- {"title":"Chapter 1: General Provisions","chunk_id":"1"},- ...-]--Example 3 — Narrative + heading-Input:-[{"2": "This paragraph introduces the background and goals. Section 2: Definitions Key terms are explained…"}, ...]-Output:-[- {"title":"Section 2: Definitions","chunk_id":"2"},- ...-]--Example 4 — Multiple headings in one chunk-Input:-[{"3": "Declarations and Commitments (I) Party B commits… (II) Party C commits… Appendix A Data Specification"}, ...]-Output:-[- {"title":"Declarations and Commitments","chunk_id":"3"},- {"title":"(I) Party B commits","chunk_id":"3"},- {"title":"(II) Party C commits","chunk_id":"3"},- {"title":"Appendix A Data Specification","chunk_id":"3"},- ...-]--Example 5 — Numbering styles-Input:-[{"4": "1. Scope: Defines boundaries. 2) Definitions: Terms used. III) Methods Overview."}, ...]-Output:-[- {"title":"1. Scope","chunk_id":"4"},- {"title":"2) Definitions","chunk_id":"4"},- {"title":"III) Methods Overview","chunk_id":"4"},- ...-]--Example 6 — Long list (NOT headings)-Input:-{"5": "Item list: apples, bananas, strawberries, blueberries, mangos, peaches"}, ...]-Output:-[- {"title":"-1","chunk_id":"5"},- ...-]--Example 7 — Mixed Chinese/English-Input:-{"6": "(出版信息略)This standard follows industry practices. Chapter 1: Overview 摘要… 第2节:术语与缩略语"}, ...]-Output:-[- {"title":"Chapter 1: Overview","chunk_id":"6"},- {"title":"第2节:术语与缩略语","chunk_id":"6"},- ...-]diff --git a/rag/prompts/toc_from_text_user.md b/rag/prompts/toc_from_text_user.mddeleted file mode 100644index 952d8eff25..0000000000--- a/rag/prompts/toc_from_text_user.md+++ /dev/null@@ -1,8 +0,0 @@-OUTPUT FORMAT-- Return ONLY the JSON array.-- Use double quotes.-- No extra commentary.-- Keep language of "title" the same as the input.--INPUT-{{text}}diff --git a/rag/prompts/toc_index.md b/rag/prompts/toc_index.mddeleted file mode 100644index 860356d502..0000000000--- a/rag/prompts/toc_index.md+++ /dev/null@@ -1,20 +0,0 @@-You are an expert analyst tasked with matching text content to the title.--**Instructions:**-1. Analyze the given title with its numeric structure index and the provided text.-2. Determine whether the title is mentioned as a section tile in the given text.-3. Provide a concise, step-by-step reasoning for your decision.-4. Output **only** the complete JSON object. Do not include any other text, explanations, or markdown code block fences (like ```json).--**Output Format:**-Your output must be a valid JSON object with the following keys:-{-"reasoning": "Step-by-step explanation of your analysis.",-"exist": "<yes or no>",-}--** The title: **-{{ structure }} {{ title }}--** Given text: **-{{ text }}\ No newline at end of filediff --git a/rag/prompts/toc_relevance_system.md b/rag/prompts/toc_relevance_system.mddeleted file mode 100644index 287b50284e..0000000000--- a/rag/prompts/toc_relevance_system.md+++ /dev/null@@ -1,118 +0,0 @@-# System Prompt: TOC Relevance Evaluation--You are an expert logical reasoning assistant specializing in hierarchical Table of Contents (TOC) relevance evaluation.--## GOAL-You will receive:-1. A JSON list of TOC items, each with fields:- ```json- {- "level": <integer>, // e.g., 1, 2, 3- "title": <string> // section title- }- ```-2. A user query (natural language question).--You must assign a **relevance score** (integer) to every TOC entry, based on how related its `title` is to the `query`.-------## RULES--### Scoring System-- 5 → highly relevant (directly answers or matches the query intent)-- 3 → somewhat related (same topic or partially overlaps)-- 1 → weakly related (vague or tangential)-- 0 → no clear relation-- -1 → explicitly irrelevant or contradictory--### Hierarchy Traversal-- The TOC is hierarchical: smaller `level` = higher layer (e.g., level 1 is top-level, level 2 is a subsection).-- You must traverse in **hierarchical order** — interpret the structure based on levels (1 > 2 > 3).-- If a high-level item (level 1) is strongly related (score 5), its child items (level 2, 3) are likely relevant too.-- If a high-level item is unrelated (-1 or 0), its deeper children are usually less relevant unless the titles clearly match the query.-- Lower (deeper) levels provide more specific content; prefer assigning higher scores if they directly match the query.--### Output Format-Return a **JSON array**, preserving the input order but adding a new key `"score"`:--```json-[- {"level": 1, "title": "Introduction", "score": 0},- {"level": 2, "title": "Definition of Sustainability", "score": 5}-]-```--### Constraints-- Output **only the JSON array** — no explanations or reasoning text.--### EXAMPLES--#### Example 1-Input TOC:-[- {"level": 1, "title": "Machine Learning Overview"},- {"level": 2, "title": "Supervised Learning"},- {"level": 2, "title": "Unsupervised Learning"},- {"level": 3, "title": "Applications of Deep Learning"}-]--Query:-"How is deep learning used in image classification?"--Output:-[- {"level": 1, "title": "Machine Learning Overview", "score": 3},- {"level": 2, "title": "Supervised Learning", "score": 3},- {"level": 2, "title": "Unsupervised Learning", "score": 0},- {"level": 3, "title": "Applications of Deep Learning", "score": 5}-]-------#### Example 2-Input TOC:-[- {"level": 1, "title": "Marketing Basics"},- {"level": 2, "title": "Consumer Behavior"},- {"level": 2, "title": "Digital Marketing"},- {"level": 3, "title": "Social Media Campaigns"},- {"level": 3, "title": "SEO Optimization"}-]--Query:-"What are the best online marketing methods?"--Output:-[- {"level": 1, "title": "Marketing Basics", "score": 3},- {"level": 2, "title": "Consumer Behavior", "score": 1},- {"level": 2, "title": "Digital Marketing", "score": 5},- {"level": 3, "title": "Social Media Campaigns", "score": 5},- {"level": 3, "title": "SEO Optimization", "score": 5}-]-------#### Example 3-Input TOC:-[- {"level": 1, "title": "Physics Overview"},- {"level": 2, "title": "Classical Mechanics"},- {"level": 3, "title": "Newton’s Laws"},- {"level": 2, "title": "Thermodynamics"},- {"level": 3, "title": "Entropy and Heat Transfer"}-]--Query:-"What is entropy?"--Output:-[- {"level": 1, "title": "Physics Overview", "score": 3},- {"level": 2, "title": "Classical Mechanics", "score": 0},- {"level": 3, "title": "Newton’s Laws", "score": -1},- {"level": 2, "title": "Thermodynamics", "score": 5},- {"level": 3, "title": "Entropy and Heat Transfer", "score": 5}-]-diff --git a/rag/prompts/toc_relevance_user.md b/rag/prompts/toc_relevance_user.mddeleted file mode 100644index 2a5167ad7b..0000000000--- a/rag/prompts/toc_relevance_user.md+++ /dev/null@@ -1,17 +0,0 @@-# User Prompt: TOC Relevance Evaluation--You will now receive:-1. A JSON list of TOC items (each with `level` and `title`)-2. A user query string.--Traverse the TOC hierarchically based on level numbers and assign scores (5,3,1,0,-1) according to the rules in the system prompt.-Output **only** the JSON array with the added `"score"` field.-------**Input TOC:**-{{ toc_json }}--**Query:**-{{ query }}-diff --git a/rag/prompts/tool_call_summary.md b/rag/prompts/tool_call_summary.mddeleted file mode 100644index b1c77dd407..0000000000--- a/rag/prompts/tool_call_summary.md+++ /dev/null@@ -1,19 +0,0 @@-**Task Instruction:**--You are tasked with reading and analyzing tool call result based on the following inputs: **Inputs for current call**, and **Results**. Your objective is to extract relevant and helpful information for **Inputs for current call** from the **Results** and seamlessly integrate this information into the previous steps to continue reasoning for the original question.--**Guidelines:**--1. **Analyze the Results:**- - Carefully review the content of each results of tool call.- - Identify factual information that is relevant to the **Inputs for current call** and can aid in the reasoning process for the original question.--2. **Extract Relevant Information:**- - Select the information from the Searched Web Pages that directly contributes to advancing the previous reasoning steps.- - Ensure that the extracted information is accurate and relevant.-- - **Inputs for current call:**- {{ inputs }}-- - **Results:**- {{ results }}diff --git a/rag/prompts/vision_llm_figure_describe_prompt_with_context.md b/rag/prompts/vision_llm_figure_describe_prompt_with_context.mddeleted file mode 100644index 07b13c51dd..0000000000--- a/rag/prompts/vision_llm_figure_describe_prompt_with_context.md+++ /dev/null@@ -1,88 +0,0 @@-## ROLE--You are an expert visual data analyst.--## GOAL--Analyze the image and produce a textual representation strictly based on what is visible in the image.-Surrounding context may be used only for minimal clarification or disambiguation of terms that appear in the image, not as a source of new information.--## OUTPUT LANGUAGE--- Write all descriptions and field values in {{ language }}.-- Preserve all visible text verbatim in its original language; do not translate it.-- Keep the required output field names exactly as specified below.--## CONTEXT (ABOVE)--{{ context_above }}--## CONTEXT (BELOW)--{{ context_below }}--## DECISION RULE (CRITICAL)--First, determine whether the image contains an explicit visual data representation with enumerable data units forming a coherent dataset.--Enumerable data units are clearly separable, repeatable elements intended for comparison, measurement, or aggregation, such as:--- rows or columns in a table-- individual bars in a bar chart-- identifiable data points or series in a line graph-- labeled segments in a pie chart--The mere presence of numbers, icons, UI elements, or labels does NOT qualify unless they together form such a dataset.--## TASKS--1. Inspect the image and determine which output mode applies based on the decision rule.-2. Use surrounding context only to disambiguate terms that appear in the image.-3. Follow the output rules strictly.-4. Include only content that is explicitly visible in the image.-5. Do not infer intent, functionality, process logic, or meaning beyond what is visually or textually shown.--## OUTPUT RULES (STRICT)--- Produce output in **exactly one** of the two modes defined below.-- Do NOT mention, label, or reference the modes in the output.-- Do NOT combine content from both modes.-- Do NOT explain or justify the choice of mode.-- Do NOT add any headings, titles, or commentary beyond what the mode requires.-------## MODE 1: STRUCTURED VISUAL DATA OUTPUT--(Use only if the image contains enumerable data units forming a coherent dataset.)--Output **only** the following fields, in list form.-Do NOT add free-form paragraphs or additional sections.--- Visual Type:-- Title:-- Axes / Legends / Labels:-- Data Points:-- Captions / Annotations:-------## MODE 2: GENERAL FIGURE CONTENT--(Use only if the image does NOT contain enumerable data units.)--Write the content directly, starting from the first sentence.-Do NOT add any introductory labels, titles, headings, or prefixes.--Requirements:--- Describe visible regions and components in a stable order (e.g., top-to-bottom, left-to-right).-- Explicitly name interface elements or visual objects exactly as they appear (e.g., tabs, panels, buttons, icons, input fields).-- Transcribe all visible text verbatim; do not paraphrase, summarize, or reinterpret labels.-- Describe spatial grouping, containment, and alignment of elements.-- Do NOT interpret intent, behavior, workflows, gameplay rules, or processes.-- Do NOT describe the figure as a chart, diagram, process, phase, or sequence unless such words explicitly appear in the image text.-- Avoid narrative or stylistic language unless it is a dominant and functional visual element.--Use concise, information-dense sentences.-Do not use bullet lists or structured fields in this mode.