forked from Darwin-lfl/langmanus
-
Notifications
You must be signed in to change notification settings - Fork 88
/
Copy pathtemplate.py
54 lines (44 loc) · 1.67 KB
/
template.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import os
from datetime import datetime
from jinja2 import Environment, FileSystemLoader, select_autoescape
from langgraph.prebuilt.chat_agent_executor import AgentState
# Initialize Jinja2 environment
env = Environment(
loader=FileSystemLoader(os.path.dirname(__file__)),
autoescape=select_autoescape(),
trim_blocks=True,
lstrip_blocks=True,
)
def get_prompt_template(prompt_name: str) -> str:
"""
Load and return a prompt template using Jinja2.
Args:
prompt_name: Name of the prompt template file (without .md extension)
Returns:
The template string with proper variable substitution syntax
"""
try:
template = env.get_template(f"{prompt_name}.md")
return template.render()
except Exception as e:
raise ValueError(f"Error loading template {prompt_name}: {e}")
def apply_prompt_template(prompt_name: str, state: AgentState) -> list:
"""
Apply template variables to a prompt template and return formatted messages.
Args:
prompt_name: Name of the prompt template to use
state: Current agent state containing variables to substitute
Returns:
List of messages with the system prompt as the first message
"""
# Convert state to dict for template rendering
state_vars = {
"CURRENT_TIME": datetime.now().strftime("%a %b %d %Y %H:%M:%S %z"),
**state,
}
try:
template = env.get_template(f"{prompt_name}.md")
system_prompt = template.render(**state_vars)
return [{"role": "system", "content": system_prompt}] + state["messages"]
except Exception as e:
raise ValueError(f"Error applying template {prompt_name}: {e}")