Skip to content

Commit 85e52cd

Browse files
committed
♻️ standardize prompt vars with Jinja2 templating
# Conflicts: # backend/services/elasticsearch_service.py # backend/utils/attachment_utils.py
1 parent 4f5693a commit 85e52cd

File tree

10 files changed

+38
-33
lines changed

10 files changed

+38
-33
lines changed

backend/agents/create_agent_info.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@
1313
from services.tenant_config_service import get_selected_knowledge_list
1414
from utils.prompt_template_utils import get_agent_prompt_template
1515
from utils.config_utils import config_manager, tenant_config_manager, get_model_name_from_config
16-
from smolagents.agents import populate_template
1716
from smolagents.utils import BASE_BUILTIN_MODULES
1817
from services.memory_config_service import build_memory_context
18+
from jinja2 import Template, StrictUndefined
1919

2020
from nexent.memory.memory_service import search_memory_in_levels
2121

@@ -98,9 +98,8 @@ async def create_agent_config(agent_id, tenant_id, user_id, language: str = 'zh'
9898
# TODO: 前端展示"已抽取 xx 条回忆"
9999

100100
# Assemble system_prompt
101-
system_prompt = populate_template(
102-
prompt_template["system_prompt"],
103-
variables={
101+
if (duty_prompt or constraint_prompt or few_shots_prompt):
102+
system_prompt = Template(prompt_template["system_prompt"], undefined=StrictUndefined).render({
104103
"duty": duty_prompt,
105104
"constraint": constraint_prompt,
106105
"few_shots": few_shots_prompt,
@@ -110,8 +109,9 @@ async def create_agent_config(agent_id, tenant_id, user_id, language: str = 'zh'
110109
"APP_NAME": app_name,
111110
"APP_DESCRIPTION": app_description,
112111
"memory_list": memory_list
113-
},
114-
) if (duty_prompt or constraint_prompt or few_shots_prompt) else agent_info.get("prompt", "")
112+
})
113+
else:
114+
system_prompt = agent_info.get("prompt", "")
115115

116116
# special logic
117117
try:

backend/prompts/analyze_file.yaml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
image_analysis:
55
system_prompt: |-
6-
用户提出了一个问题:{query},请从回答这个问题的角度精简、仔细描述一下这个图片,200字以内。
6+
用户提出了一个问题:{{ query }},请从回答这个问题的角度精简、仔细描述一下这个图片,200字以内。
77
88
**图片分析要求:**
99
1. 重点关注与用户问题相关的图片内容
@@ -16,7 +16,7 @@ image_analysis:
1616
1717
long_text_analysis:
1818
system_prompt: |-
19-
用户提出了一个问题:{query},请从回答这个问题的角度精简、仔细描述一下这段文本,200字以内。
19+
用户提出了一个问题:{{ query }},请从回答这个问题的角度精简、仔细描述一下这段文本,200字以内。
2020
2121
**文本分析要求:**
2222
1. 重点提取与用户问题相关的文本内容
@@ -25,4 +25,4 @@ long_text_analysis:
2525
4. 避免冗余信息,专注于问题相关内容
2626
2727
user_prompt: |
28-
请仔细阅读并分析这段文本:{file_context}
28+
请仔细阅读并分析这段文本:{{ file_context }}

backend/prompts/analyze_file_en.yaml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
image_analysis:
55
system_prompt: |-
6-
The user has asked a question: {query}. Please provide a concise and careful description of this image from the perspective of answering this question, within 200 words.
6+
The user has asked a question: {{ query }}. Please provide a concise and careful description of this image from the perspective of answering this question, within 200 words.
77
88
**Image Analysis Requirements:**
99
1. Focus on image content relevant to the user's question
@@ -16,7 +16,7 @@ image_analysis:
1616
1717
long_text_analysis:
1818
system_prompt: |-
19-
The user has asked a question: {query}. Please provide a concise and careful description of this text from the perspective of answering this question, within 200 words.
19+
The user has asked a question: {{ query }}. Please provide a concise and careful description of this text from the perspective of answering this question, within 200 words.
2020
2121
**Text Analysis Requirements:**
2222
1. Focus on extracting text content relevant to the user's question
@@ -25,4 +25,4 @@ long_text_analysis:
2525
4. Avoid redundant information, focus on question-relevant content
2626
2727
user_prompt: |
28-
Please carefully read and analyze this text: {file_context}
28+
Please carefully read and analyze this text: {{ file_context }}

backend/prompts/knowledge_summary_agent.yaml

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,4 @@ system_prompt: |-
1313
1414
user_prompt: |
1515
请根据以下关键词内容生成一个简洁的知识库总结,不超过150个字:
16-
关键词内容:{content}
17-
18-
16+
关键词内容:{{ content }}

backend/prompts/knowledge_summary_agent_en.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,4 @@ system_prompt: |-
1313
1414
user_prompt: |
1515
Please generate a concise knowledge base summary based on the following keyword content, no more than 150 words:
16-
Keyword content: {content}
16+
Keyword content: {{ content }}

backend/services/conversation_management_service.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -250,8 +250,7 @@ def call_llm_for_title(content: str, tenant_id: str, language: str = 'zh') -> st
250250
api_key=model_config.get("api_key", ""), temperature=0.7, top_p=0.95)
251251

252252
# Build messages
253-
compiled_template = Template(prompt_template["USER_PROMPT"], undefined=StrictUndefined)
254-
user_prompt = compiled_template.render({
253+
user_prompt = Template(prompt_template["USER_PROMPT"], undefined=StrictUndefined).render({
255254
"content": content
256255
})
257256
messages = [{"role": "system",

backend/services/elasticsearch_service.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
from utils.config_utils import tenant_config_manager, get_model_name_from_config
2828
from utils.file_management_utils import get_all_files_status, get_file_size
2929
from utils.prompt_template_utils import get_knowledge_summary_prompt_template
30+
from jinja2 import Template, StrictUndefined
3031
from database.knowledge_db import create_knowledge_record, get_knowledge_record, update_knowledge_record, delete_knowledge_record
3132
from database.attachment_db import delete_file
3233

@@ -51,10 +52,15 @@ def generate_knowledge_summary_stream(keywords: str, language: str, tenant_id: s
5152

5253
# Load prompt words based on language
5354
prompts = get_knowledge_summary_prompt_template(language)
55+
56+
# Render templates using Jinja2
57+
system_prompt = Template(prompts['system_prompt'], undefined=StrictUndefined).render({})
58+
user_prompt = Template(prompts['user_prompt'], undefined=StrictUndefined).render({'content': keywords})
59+
5460
# Build messages
5561
messages: List[ChatCompletionMessageParam] = [
56-
{"role": "system", "content": prompts['system_prompt']},
57-
{"role": "user", "content": prompts['user_prompt'].format(content=keywords)}
62+
{"role": "system", "content": system_prompt},
63+
{"role": "user", "content": user_prompt}
5864
]
5965

6066
# Get model configuration from tenant config manager

backend/services/prompt_service.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -196,8 +196,7 @@ def join_info_for_generate_system_prompt(prompt_for_generate, sub_agent_info_lis
196196
agent_description = "\n".join(
197197
[f"- {sub_agent_info['name']}: {sub_agent_info['description']}" for sub_agent_info in sub_agent_info_list])
198198
# Generate content using template
199-
compiled_template = Template(prompt_for_generate["USER_PROMPT"], undefined=StrictUndefined)
200-
content = compiled_template.render({
199+
content = Template(prompt_for_generate["USER_PROMPT"], undefined=StrictUndefined).render({
201200
"tool_description": tool_description,
202201
"agent_description": agent_description,
203202
"task_description": task_description,
@@ -237,8 +236,7 @@ def fine_tune_prompt(system_prompt: str, command: str, tenant_id: str, language:
237236
with open(fine_tune_config_path, "r", encoding="utf-8") as f:
238237
prompt_for_fine_tune = yaml.safe_load(f)
239238

240-
compiled_template = Template(prompt_for_fine_tune["FINE_TUNE_USER_PROMPT"], undefined=StrictUndefined)
241-
content = compiled_template.render({
239+
content = Template(prompt_for_fine_tune["FINE_TUNE_USER_PROMPT"], undefined=StrictUndefined).render({
242240
"prompt": system_prompt,
243241
"command": command
244242
})

backend/utils/attachment_utils.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from utils.config_utils import tenant_config_manager, get_model_name_from_config
55
from utils.prompt_template_utils import get_analyze_file_prompt_template
6+
from jinja2 import Template, StrictUndefined
67

78
from nexent.core.models.openai_vlm import OpenAIVLModel
89
from nexent.core.models.openai_long_context_model import OpenAILongContextModel
@@ -37,8 +38,8 @@ def convert_image_to_text(query: str, image_input: Union[str, BinaryIO], tenant_
3738

3839
# Load prompts from yaml file
3940
prompts = get_analyze_file_prompt_template(language)
40-
system_prompt = prompts['image_analysis']['system_prompt'].format(query=query)
41-
41+
system_prompt = Template(prompts['image_analysis']['system_prompt'], undefined=StrictUndefined).render({'query': query})
42+
4243
return image_to_text_model.analyze_image(image_input=image_input, system_prompt=system_prompt).content
4344

4445

@@ -65,7 +66,7 @@ def convert_long_text_to_text(query: str, file_context: str, tenant_id: str, lan
6566

6667
# Load prompts from yaml file
6768
prompts = get_analyze_file_prompt_template(language)
68-
system_prompt = prompts['long_text_analysis']['system_prompt'].format(query=query)
69-
user_prompt = prompts['long_text_analysis']['user_prompt'].format(file_context=file_context)
69+
system_prompt = Template(prompts['long_text_analysis']['system_prompt'], undefined=StrictUndefined).render({'query': query})
70+
user_prompt = Template(prompts['long_text_analysis']['user_prompt'], undefined=StrictUndefined).render({'file_context': file_context})
7071

7172
return long_text_to_text_model.analyze_long_text(file_context, system_prompt, user_prompt)

sdk/nexent/core/agents/core_agent.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from rich.console import Group
88
from rich.text import Text
99

10-
from smolagents.agents import CodeAgent, populate_template, handle_agent_output_types, AgentError, AgentType
10+
from smolagents.agents import CodeAgent, handle_agent_output_types, AgentError, AgentType
1111
from smolagents.local_python_executor import fix_final_answer_code
1212
from smolagents.memory import ActionStep, ToolCall, TaskStep, SystemPromptStep
1313
from smolagents.models import ChatMessage
@@ -16,6 +16,7 @@
1616
truncate_content
1717

1818
from ..utils.observer import MessageObserver, ProcessType
19+
from jinja2 import Template, StrictUndefined
1920

2021

2122
def convert_code_format(text):
@@ -169,8 +170,9 @@ def __call__(self, task: str, **kwargs):
169170
"""Adds additional prompting for the managed agent, runs it, and wraps the output.
170171
This method is called only by a managed agent.
171172
"""
172-
full_task = populate_template(self.prompt_templates["managed_agent"]["task"],
173-
variables=dict(name=self.name, task=task), )
173+
full_task = Template(self.prompt_templates["managed_agent"]["task"], undefined=StrictUndefined).render({
174+
"name": self.name, "task": task, **self.state
175+
})
174176
report = self.run(full_task, **kwargs)
175177

176178
# When a sub-agent finishes running, return a marker
@@ -179,8 +181,9 @@ def __call__(self, task: str, **kwargs):
179181
except:
180182
self.observer.add_message(self.name, ProcessType.AGENT_FINISH, "")
181183

182-
answer = populate_template(self.prompt_templates["managed_agent"]["report"],
183-
variables=dict(name=self.name, final_answer=report))
184+
answer = Template(self.prompt_templates["managed_agent"]["report"], undefined=StrictUndefined).render({
185+
"name": self.name, "final_answer": report
186+
})
184187
if self.provide_run_summary:
185188
answer += "\n\nFor more detail, find below a summary of this agent's work:\n<summary_of_work>\n"
186189
for message in self.write_memory_to_messages(summary_mode=True):

0 commit comments

Comments
 (0)