返回 JoyAI-Echo
prompt_templates.py
根目录 / echo_longvideo / Director_Agent / nanobot / utils / prompt_templates.py
1 """Load and render agent system prompt templates (Jinja2) under nanobot/templates/.
2
3 Agent prompts live in ``templates/agent/`` (pass names like ``agent/identity.md``).
4 Shared copy lives under ``agent/_snippets/`` and is included via
5 ``{% include 'agent/_snippets/....md' %}``.
6 """
7
8 from pathlib import Path
9 from typing import Any
10
11 from jinja2 import Environment, FileSystemLoader
12
13 _TEMPLATES_ROOT = Path(__file__).resolve().parent.parent / "templates"
14
15
16 # @lru_cache
17 def _environment() -> Environment:
18 # Plain-text prompts: do not HTML-escape variable values.
19 # Search the active PE set's templates first, then the packaged defaults,
20 # so an experimental PE set can override individual templates and fall back
21 # for the rest. Read the PE dirs dynamically so hot-switching takes effect.
22 search_paths: list[str] = []
23 try:
24 from nanobot.prompts import PEManager
25
26 search_paths.extend(str(p) for p in PEManager.instance().templates_dir())
27 except Exception:
28 pass
29 search_paths.append(str(_TEMPLATES_ROOT))
30 return Environment(
31 loader=FileSystemLoader(search_paths),
32 auto_reload=True,
33 autoescape=False,
34 trim_blocks=True,
35 lstrip_blocks=True,
36 )
37
38
39 def render_template(name: str, *, strip: bool = False, **kwargs: Any) -> str:
40 """Render ``name`` (e.g. ``agent/identity.md``, ``agent/platform_policy.md``) under ``templates/``.
41
42 Use ``strip=True`` for single-line user-facing strings when the file ends
43 with a trailing newline you do not want preserved.
44 """
45 text = _environment().get_template(name).render(**kwargs)
46 return text.rstrip() if strip else text
47
47 lines PYTHON