From 0a2863988d5a0540bfc2864a75f66574f53439fa Mon Sep 17 00:00:00 2001 From: Mby159 Date: Thu, 25 Jun 2026 18:35:56 +0800 Subject: [PATCH] feat: inject placeholder-preservation prompt for online providers --- splitmind/core/engine.py | 6 ++ splitmind/providers/base.py | 40 ++++++++ tests/test_placeholder_preservation.py | 129 +++++++++++++++++++++++++ 3 files changed, 175 insertions(+) create mode 100644 tests/test_placeholder_preservation.py diff --git a/splitmind/core/engine.py b/splitmind/core/engine.py index 009ce03..a0d14ae 100644 --- a/splitmind/core/engine.py +++ b/splitmind/core/engine.py @@ -314,8 +314,14 @@ async def execute_single(subtask: SubTask, provider_name: str) -> SubTaskResult: for attempt in range(retries): try: start = datetime.now() + placeholders = list(subtask.sensitive_info.keys()) + system_prompt = provider.compose_system_prompt( + task_type=subtask.task_type.value, + placeholders=placeholders, + ) result = await provider.generate_async( prompt=subtask.input_data, + system_prompt=system_prompt, task_type=subtask.task_type.value, ) execution_time = (datetime.now() - start).total_seconds() diff --git a/splitmind/providers/base.py b/splitmind/providers/base.py index 9caea5a..b48747a 100644 --- a/splitmind/providers/base.py +++ b/splitmind/providers/base.py @@ -108,6 +108,46 @@ def _build_system_prompt(self, task_type: Optional[str]) -> str: return base_prompt + @staticmethod + def build_placeholder_preservation_instruction( + placeholders: Optional[List[str]], + ) -> str: + """Build a privacy instruction telling the model to preserve placeholders. + + Only placeholder IDs (e.g. ``[REDACTED_EMAIL_0]``) are passed here. + The original sensitive values are never included; they stay local. + Returns an empty string when there are no placeholders. + """ + if not placeholders: + return "" + ids = ", ".join(sorted(set(placeholders))) + return ( + "The user input contains privacy placeholders such as " + f"{ids}. These are opaque tokens that replace redacted private " + "information. Do not translate, alter, reformat, split, remove, or " + "invent these placeholders. If you need to refer to a redacted value, " + "copy the placeholder exactly as written. Do not ask for the original " + "value." + ) + + def compose_system_prompt( + self, + task_type: Optional[str] = None, + system_prompt: Optional[str] = None, + placeholders: Optional[List[str]] = None, + ) -> str: + """Compose the task system prompt with optional placeholder rules. + + Uses ``system_prompt`` if given, otherwise the provider's task prompt, + then appends the placeholder-preservation instruction when placeholders + are present. + """ + base = system_prompt or self._build_system_prompt(task_type) + instruction = self.build_placeholder_preservation_instruction(placeholders) + if instruction: + return f"{base}\n\n{instruction}" + return base + def _merge_config(self, **kwargs) -> Dict[str, Any]: config = { "temperature": kwargs.get("temperature", self.config.temperature), diff --git a/tests/test_placeholder_preservation.py b/tests/test_placeholder_preservation.py new file mode 100644 index 0000000..6f8c9be --- /dev/null +++ b/tests/test_placeholder_preservation.py @@ -0,0 +1,129 @@ +"""Tests for placeholder-preservation prompt injection. + +When a subtask carries privacy placeholders (e.g. [REDACTED_EMAIL_0]), the +online provider must receive a system prompt that instructs it to preserve the +placeholders exactly. The original sensitive values must never be sent. +""" + +import asyncio + +from splitmind.core.engine import SplitMindEngine, ExecutionConfig, ExecutionMode +from splitmind.providers.base import ( + BaseProvider, + ProviderInfo, + ProviderCapability, +) +from splitmind.providers import register_provider + + +class CapturingProvider(BaseProvider): + """Provider that records the prompts it receives.""" + + last_prompt = None + last_system_prompt = None + + def _default_model(self) -> str: + return "capturing-model" + + def get_info(self): + return ProviderInfo( + name="capturing", + description="Provider that captures prompts", + models=["capturing-model"], + capabilities=[ProviderCapability.CHAT], + max_tokens=4096, + supports_streaming=False, + ) + + def generate(self, prompt, system_prompt=None, task_type=None, **kwargs): + CapturingProvider.last_prompt = prompt + CapturingProvider.last_system_prompt = system_prompt + return f"echo: {prompt}" + + async def generate_async(self, prompt, system_prompt=None, task_type=None, **kwargs): + CapturingProvider.last_prompt = prompt + CapturingProvider.last_system_prompt = system_prompt + return f"echo: {prompt}" + + +register_provider(CapturingProvider) + + +class TestPlaceholderPreservationInstruction: + """Unit tests for the base provider helper.""" + + def test_empty_when_no_placeholders(self): + assert BaseProvider.build_placeholder_preservation_instruction(None) == "" + assert BaseProvider.build_placeholder_preservation_instruction([]) == "" + + def test_mentions_placeholders_and_rules(self): + instr = BaseProvider.build_placeholder_preservation_instruction( + ["[REDACTED_EMAIL_0]", "[REDACTED_PHONE_0]"] + ) + assert "[REDACTED_EMAIL_0]" in instr + assert "[REDACTED_PHONE_0]" in instr + # Must instruct preservation, not modification. + assert "Do not" in instr + assert "copy the placeholder exactly" in instr + + def test_compose_appends_instruction_when_placeholders(self): + provider = CapturingProvider() + composed = provider.compose_system_prompt( + task_type="analysis", + placeholders=["[REDACTED_EMAIL_0]"], + ) + assert "analytical AI assistant" in composed + assert "[REDACTED_EMAIL_0]" in composed + + def test_compose_no_instruction_when_empty(self): + provider = CapturingProvider() + composed = provider.compose_system_prompt( + task_type="analysis", + placeholders=[], + ) + assert "[REDACTED" not in composed + + +class TestEngineInjectsPreservationPrompt: + """Integration test: engine routes placeholders into the system prompt.""" + + def _run_online(self, task): + engine = SplitMindEngine( + providers=[CapturingProvider()], + config=ExecutionConfig(execution_mode=ExecutionMode.ONLINE), + ) + return engine.execute_sync( + task, split_strategy="single", providers=["capturing"] + ) + + def test_system_prompt_contains_placeholders_and_no_raw_values(self): + CapturingProvider.last_prompt = None + CapturingProvider.last_system_prompt = None + + task = "请分析这个客户需求,客户邮箱是 alice@example.com,手机号是 13800138000。" + result = self._run_online(task) + assert result.success + + system_prompt = CapturingProvider.last_system_prompt + assert system_prompt is not None + # Placeholder IDs must be present. + assert "[REDACTED_EMAIL_0]" in system_prompt + assert "[REDACTED_PHONE_0]" in system_prompt + # Raw sensitive values must NOT leak into the system prompt. + assert "alice@example.com" not in system_prompt + assert "13800138000" not in system_prompt + # The redacted prompt also must not contain raw values. + assert "alice@example.com" not in CapturingProvider.last_prompt + assert "13800138000" not in CapturingProvider.last_prompt + + def test_no_instruction_when_no_sensitive_info(self): + CapturingProvider.last_prompt = None + CapturingProvider.last_system_prompt = None + + task = "Please summarize the benefits of unit testing." + result = self._run_online(task) + assert result.success + + system_prompt = CapturingProvider.last_system_prompt + assert system_prompt is not None + assert "[REDACTED" not in system_prompt