diff --git a/src/chat/utils/prompt.py b/src/chat/utils/prompt.py index 130865cb4..8c756b5e3 100644 --- a/src/chat/utils/prompt.py +++ b/src/chat/utils/prompt.py @@ -196,17 +196,17 @@ class PromptManager: # 确保我们有有效的parameters实例用于注入逻辑 params_for_injection = parameters or original_prompt.parameters - # 从组件管理器获取需要注入的内容 - components_prefix = await prompt_component_manager.execute_components_for( - injection_point=original_prompt.name, params=params_for_injection + # 应用所有匹配的注入规则,获取修改后的模板 + modified_template = await prompt_component_manager.apply_injections( + target_prompt_name=original_prompt.name, + original_template=original_prompt.template, + params=params_for_injection, ) - # 如果有内容需要注入 - if components_prefix: - logger.info(f"为'{name}'注入插件内容: \n{components_prefix}") - # 将注入内容与原始模板拼接 - new_template = f"{components_prefix}\n\n{original_prompt.template}" - # 创建一个新的、临时的Prompt实例。`should_register=False`是关键, - # 它防止了这个临时版本污染全局或上下文注册表。 + + # 如果模板被修改了,就创建一个新的临时Prompt实例 + if modified_template != original_prompt.template: + logger.info(f"为'{name}'应用了Prompt注入规则") + # 创建一个新的临时Prompt实例,不进行注册 temp_prompt = Prompt( template=modified_template, name=original_prompt.name, @@ -1245,10 +1245,9 @@ async def create_prompt_async( modified_template = await prompt_component_manager.apply_injections( target_prompt_name=name, original_template=template, params=final_params ) - if components_prefix: - logger.debug(f"为'{name}'注入插件内容: \n{components_prefix}") - # 将注入内容拼接到原始模板的前面 - template = f"{components_prefix}\n\n{template}" + if modified_template != template: + logger.debug(f"为'{name}'应用了Prompt注入规则") + template = modified_template # 使用可能已被修改的模板来创建最终的Prompt实例 prompt = create_prompt(template, name, final_params) diff --git a/src/chat/utils/prompt_component_manager.py b/src/chat/utils/prompt_component_manager.py index 32c943d9b..c1fb92e13 100644 --- a/src/chat/utils/prompt_component_manager.py +++ b/src/chat/utils/prompt_component_manager.py @@ -1,4 +1,6 @@ import asyncio +import re +from typing import Type from src.chat.utils.prompt_params import PromptParameters from src.common.logger import get_logger @@ -19,7 +21,7 @@ class PromptComponentManager: 3. 提供一个接口,以便在构建核心Prompt时,能够获取并执行所有相关的组件。 """ - def get_components_for(self, injection_point: str) -> list[type[BasePrompt]]: + def _get_rules_for(self, target_prompt_name: str) -> list[tuple[InjectionRule, Type[BasePrompt]]]: """ 获取指定目标Prompt的所有注入规则及其关联的组件类。 @@ -34,8 +36,7 @@ class PromptComponentManager: enabled_prompts = component_registry.get_enabled_components_by_type(ComponentType.PROMPT) matching_rules = [] - matching_components: list[type[BasePrompt]] = [] - + # 遍历所有启用的 Prompt 组件,查找与目标 Prompt 相关的注入规则 for prompt_name, prompt_info in enabled_prompts.items(): if not isinstance(prompt_info, PromptInfo): continue