Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
fix: strip reasoning/thinking blocks from knowledge base summary output (#38623)
citizen2046b98dc0655d6
diff --git a/api/core/rag/index_processor/processor/paragraph_index_processor.py b/api/core/rag/index_processor/processor/paragraph_index_processor.pyindex 1a64038dbd2..55bfbbc2d8e 100644--- a/api/core/rag/index_processor/processor/paragraph_index_processor.py+++ b/api/core/rag/index_processor/processor/paragraph_index_processor.py@@ -43,6 +43,7 @@ from graphon.model_runtime.entities.message_entities import (UserPromptMessage,)from graphon.model_runtime.entities.model_entities import ModelFeature, ModelType+from graphon.nodes.llm.reasoning import split_reasoningfrom libs import helperfrom models import UploadFilefrom models.account import Account@@ -437,7 +438,14 @@ class ParagraphIndexProcessor(BaseIndexProcessor):document_language: str | None,image_loader: Callable[[], list[File]],) -> tuple[str, LLMUsage]:- """Generate a summary after an explicit loader materializes any required images."""+ """Generate summary text with model reasoning removed.++ Requires enabled settings naming a provider and model. The image loader+ materializes images only for vision-capable models. Returns cleaned text+ and the original LLMUsage object; output containing only reasoning returns+ empty text for the caller to handle. Invalid settings or a response other+ than LLMResult raise ValueError.+ """if not summary_index_setting or not summary_index_setting.get("enable"):raise ValueError("summary_index_setting is required and must be enabled to generate summary.")@@ -520,7 +528,7 @@ class ParagraphIndexProcessor(BaseIndexProcessor):if not isinstance(result, LLMResult):raise ValueError("Expected LLMResult when stream=False")- summary_content = result.message.get_text_content()+ summary_content, _ = split_reasoning(result.message.get_text_content(), "separated")usage = result.usagereturn summary_content, usagediff --git a/api/tests/unit_tests/core/rag/index_processor/processor/test_paragraph_index_processor.py b/api/tests/unit_tests/core/rag/index_processor/processor/test_paragraph_index_processor.pyindex 4cf1893869f..eb0fab3d511 100644--- a/api/tests/unit_tests/core/rag/index_processor/processor/test_paragraph_index_processor.py+++ b/api/tests/unit_tests/core/rag/index_processor/processor/test_paragraph_index_processor.py@@ -1,6 +1,7 @@import loggingfrom contextlib import nullcontextfrom datetime import datetime+from decimal import Decimalfrom types import SimpleNamespacefrom typing import Anyfrom unittest.mock import Mock, patch@@ -10,18 +11,23 @@ from sqlalchemy import eventfrom sqlalchemy.orm import Session, sessionmakerfrom core.entities.knowledge_entities import PreviewDetail+from core.entities.provider_configuration import ProviderModelBundle+from core.entities.provider_entities import CustomProviderConfiguration+from core.model_manager import ModelManager+from core.plugin.impl.model_runtime_factory import create_plugin_model_assemblyfrom core.rag.index_processor.constant.index_type import IndexTechniqueTypefrom core.rag.index_processor.processor.paragraph_index_processor import ParagraphIndexProcessorfrom core.rag.models.document import AttachmentDocument, Documentfrom extensions.storage.storage_type import StorageTypefrom graphon.model_runtime.entities.llm_entities import LLMResult, LLMUsagefrom graphon.model_runtime.entities.message_entities import AssistantPromptMessage, ImagePromptMessageContent-from graphon.model_runtime.entities.model_entities import ModelFeature, ModelType+from graphon.model_runtime.entities.model_entities import AIModelEntity, ModelFeature, ModelTypefrom models.account import Accountfrom models.dataset import Dataset, DocumentCreatedFrom, DocumentSegment, SegmentAttachmentBindingfrom models.dataset import Document as DatasetDocumentfrom models.enums import CreatorUserRole, DataSourceTypefrom models.model import UploadFile+from tests.helpers.unit.core.model_fixtures import make_model_configclass TestParagraphIndexProcessor:@@ -580,6 +586,104 @@ class TestParagraphIndexProcessor:session=self.session,)+ @pytest.mark.parametrize(+ ("model_output", "expected_summary"),+ [+ pytest.param(+ "<think>\nstep one\nstep two\n</think>\nFinal summary.",+ "Final summary.",+ id="closed-multiline",+ ),+ pytest.param("<THINK>hidden</THINK>Visible", "Visible", id="case-insensitive"),+ pytest.param(+ '<think type="reasoning">hidden</think>Visible',+ "Visible",+ id="tag-attributes",+ ),+ pytest.param(+ "Start<think>one</think> middle <think>two</think>end",+ "Start middle end",+ id="multiple-blocks",+ ),+ pytest.param(+ "Visible summary\n<think>unfinished",+ "Visible summary",+ id="trailing-unclosed",+ ),+ pytest.param("<think>unfinished", "", id="reasoning-only-unclosed"),+ pytest.param("Plain summary", "Plain summary", id="no-reasoning"),+ ],+ )+ def test_generate_summary_from_inputs_strips_reasoning_and_preserves_usage(+ self,+ monkeypatch: pytest.MonkeyPatch,+ model_output: str,+ expected_summary: str,+ ) -> None:+ model_config = make_model_config(provider="provider-a", model="model-a", mode="chat")+ bundle = model_config.provider_model_bundle+ credentials = {"api_key": "test-key"}+ bundle.configuration.tenant_id = "tenant-1"+ bundle.configuration.custom_configuration.provider = CustomProviderConfiguration(credentials=credentials)++ assembly = create_plugin_model_assembly(tenant_id="tenant-1")++ def get_provider_model_bundle(*, tenant_id: str, provider: str, model_type: ModelType) -> ProviderModelBundle:+ assert (tenant_id, provider, model_type) == ("tenant-1", "provider-a", ModelType.LLM)+ return bundle++ def for_tenant(*, tenant_id: str) -> ModelManager:+ assert tenant_id == "tenant-1"+ return assembly.model_manager++ def get_model_schema(model: str, resolved_credentials: dict[str, Any]) -> AIModelEntity:+ assert model == "model-a"+ assert resolved_credentials == credentials+ return model_config.model_schema++ usage = LLMUsage(+ prompt_tokens=11,+ prompt_unit_price=Decimal("0.001"),+ prompt_price_unit=Decimal("0.001"),+ prompt_price=Decimal("0.011"),+ completion_tokens=7,+ completion_unit_price=Decimal("0.002"),+ completion_price_unit=Decimal("0.001"),+ completion_price=Decimal("0.014"),+ total_tokens=18,+ total_price=Decimal("0.025"),+ currency="USD",+ latency=0.25,+ )+ llm_result = LLMResult(+ model="model-a",+ message=AssistantPromptMessage(content=model_output),+ usage=usage,+ )+ invocations: list[dict[str, object]] = []++ def invoke(**kwargs: object) -> LLMResult:+ invocations.append(kwargs)+ return llm_result++ monkeypatch.setattr(assembly.provider_manager, "get_provider_model_bundle", get_provider_model_bundle)+ monkeypatch.setattr(ModelManager, "for_tenant", staticmethod(for_tenant))+ monkeypatch.setattr(bundle.model_type_instance, "get_model_schema", get_model_schema)+ monkeypatch.setattr(bundle.model_type_instance, "invoke", invoke)++ summary, returned_usage = ParagraphIndexProcessor.generate_summary_from_inputs(+ "tenant-1",+ "text content",+ {"enable": True, "model_name": "model-a", "model_provider_name": "provider-a"},+ document_language="English",+ image_loader=lambda: [],+ )++ assert summary == expected_summary+ assert returned_usage is usage+ assert len(invocations) == 1+ assert invocations[0]["stream"] is False+def test_generate_summary_handles_vision_and_image_conversion(self) -> None:model_instance = Mock()model_instance.credentials = {"k": "v"}