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
fix(ingestion): strip mid-text think blocks in extractor metadata path (#18175)
jay77721207e2eaf3bdc
diff --git a/internal/ingestion/component/extractor.go b/internal/ingestion/component/extractor.goindex 9d72d50e24..3c8d38b5e3 100644--- a/internal/ingestion/component/extractor.go+++ b/internal/ingestion/component/extractor.go@@ -1043,12 +1043,21 @@ func cleanLLMText(s string) string {return strings.TrimSpace(s)}-// cleanExtractionResult strips `</think>` tags and rejects `**ERROR**` responses,-// matching Python's keyword_extraction and question_proposal post-processing.-func cleanExtractionResult(s string) string {+// stripTrailingThink mirrors Python's re.sub(r"^.*</think>", "", s, re.DOTALL)+// in generator.py's post-processing (e.g. gen_metadata:960): cut everything+// through the LAST `</think>` so a mid-text reasoning block preceded by a+// preamble is stripped on top of cleanLLMText's leading-only cleanup.+func stripTrailingThink(s string) string {if i := strings.LastIndex(s, "</think>"); i >= 0 {s = s[i+len("</think>"):]}+ return s+}++// cleanExtractionResult strips `</think>` tags and rejects `**ERROR**` responses,+// matching Python's keyword_extraction and question_proposal post-processing.+func cleanExtractionResult(s string) string {+ s = stripTrailingThink(s)s = strings.TrimSpace(s)if strings.Contains(s, "**ERROR**") {return ""@@ -1199,6 +1208,13 @@ func (c *ExtractorComponent) callStructured(ctx context.Context, db *gorm.DB, inif s == "" {return nil, nil}+ // Second cleanup layer, mirroring Python gen_metadata's+ // re.sub(r"^.*</think>", "", ans, re.DOTALL): cleanLLMText only strips a+ // leading <think>, so a mid-text reasoning block preceded by a preamble+ // would otherwise survive into JSON parsing and silently drop the whole+ // metadata extraction that Python would have kept. No **ERROR** check here+ // — Python's gen_metadata has none either.+ s = stripTrailingThink(s)parsed, ok := tryParseJSONObject(s)if !ok {return nil, nildiff --git a/internal/ingestion/component/extractor_test.go b/internal/ingestion/component/extractor_test.goindex 80450e703d..678079f307 100644--- a/internal/ingestion/component/extractor_test.go+++ b/internal/ingestion/component/extractor_test.go@@ -901,6 +901,27 @@ func TestExtractorComponent_runEnableMetadata_StripsJSONFence(t *testing.T) {}}+// TestExtractorComponent_runEnableMetadata_MidTextThink verifies the full+// metadata path — LLM call, second-layer <think> strip, JSON parse, merge —+// tolerates a mid-text reasoning block preceded by a preamble, matching+// Python gen_metadata. This is the end-to-end guard for callStructured's+// stripTrailingThink: without it the metadata extraction silently drops.+func TestExtractorComponent_runEnableMetadata_MidTextThink(t *testing.T) {+ withStubChatInvoker(t, stubResponse{Content: `preamble<think>reasoning</think>{"category":"finance"}`})+ c := newMetadataExtractor(common.MetadataFieldDef{Key: "category", Type: "string"})+ ck := map[string]any{}+ if err := c.runEnableMetadata(t.Context(), nil, extractorInputs{llmID: "m"}, ck, "chunk text"); err != nil {+ t.Fatalf("runEnableMetadata: %v", err)+ }+ meta, ok := ck["metadata"].(map[string]any)+ if !ok {+ t.Fatalf("ck[metadata] missing: %T", ck["metadata"])+ }+ if meta["category"] != "finance" {+ t.Errorf("metadata = %v, want category=finance", meta)+ }+}+// TestExtractorComponent_runEnableMetadata_DegradesGracefully verifies that an// empty / **ERROR** / unparseable / think-only LLM response does NOT block// ingestion: the chunk metadata is left untouched and no error is returned@@ -1353,6 +1374,48 @@ func TestExtractorComponent_callStructured(t *testing.T) {}}+// TestExtractorComponent_callStructured_MidTextThink verifies the metadata+// path's second cleanup layer (stripTrailingThink) strips a mid-text+// reasoning block preceded by a preamble, matching Python's gen_metadata+// double cleanup (async_chat + re.sub r"^.*</think>"). Without it the JSON+// would survive the leading-only cleanLLMText, fail to parse, and silently+// drop the metadata extraction.+func TestExtractorComponent_callStructured_MidTextThink(t *testing.T) {+ withStubChatInvoker(t, stubResponse{Content: `preamble<think>reasoning</think>{"a": 1}`})+ c := &ExtractorComponent{}+ got, err := c.callStructured(t.Context(), nil, extractorInputs{llmID: "m"}, "")+ if err != nil {+ t.Fatalf("callStructured: %v", err)+ }+ if got == nil || got["a"].(float64) != 1 {+ t.Errorf("parsed = %v, want map with a=1", got)+ }+}++// TestStripTrailingThink verifies the helper mirrors Python's+// re.sub(r"^.*</think>", "", s, re.DOTALL): it cuts through the LAST+// </think> and never inspects for **ERROR**.+func TestStripTrailingThink(t *testing.T) {+ tests := []struct {+ name string+ in string+ want string+ }{+ {name: "mid-text think", in: `prefix<think>r</think>{"a":1}`, want: `{"a":1}`},+ {name: "no think", in: "plain", want: "plain"},+ {name: "multiple closes", in: "<think>a</think>mid<think>b</think>tail", want: "tail"},+ {name: "close without open", in: "abc</think>def", want: "def"},+ {name: "open without close", in: "<think>unclosed", want: "<think>unclosed"},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ if got := stripTrailingThink(tt.in); got != tt.want {+ t.Errorf("stripTrailingThink(%q) = %q, want %q", tt.in, got, tt.want)+ }+ })+ }+}+// TestExtractorComponent_Invoke_ConcurrentKeywordsAndQuestions verifies// that when both auto_keywords and auto_questions are enabled, both// LLM calls are dispatched per chunk and results land on the chunk