prompt.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import os
  2. from jinja2 import Template
  3. class PromptManager:
  4. """
  5. Manages prompt templates and micro-agents for AI interactions.
  6. This class handles loading and rendering of system and user prompt templates,
  7. as well as loading micro-agent specifications. It provides methods to access
  8. rendered system and initial user messages for AI interactions.
  9. Attributes:
  10. prompt_dir (str): Directory containing prompt templates.
  11. agent_skills_docs (str): Documentation of agent skills.
  12. micro_agent (str | None): Content of the micro-agent definition file, if specified.
  13. """
  14. def __init__(
  15. self,
  16. prompt_dir: str,
  17. agent_skills_docs: str,
  18. micro_agent_name: str | None = None,
  19. ):
  20. self.prompt_dir: str = prompt_dir
  21. self.agent_skills_docs: str = agent_skills_docs
  22. self.system_template: Template = self._load_template('system_prompt')
  23. self.user_template: Template = self._load_template('user_prompt')
  24. self.micro_agent: str | None = (
  25. self._load_micro_agent(micro_agent_name) if micro_agent_name else None
  26. )
  27. def _load_template(self, template_name: str) -> Template:
  28. template_path = os.path.join(self.prompt_dir, f'{template_name}.j2')
  29. if not os.path.exists(template_path):
  30. raise FileNotFoundError(f'Prompt file {template_path} not found')
  31. with open(template_path, 'r') as file:
  32. return Template(file.read())
  33. def _load_micro_agent(self, micro_agent_name: str) -> str:
  34. micro_agent_path = os.path.join(self.prompt_dir, f'micro/{micro_agent_name}.md')
  35. if not os.path.exists(micro_agent_path):
  36. raise FileNotFoundError(
  37. f'Micro agent file {micro_agent_path} for {micro_agent_name} is not found'
  38. )
  39. with open(micro_agent_path, 'r') as file:
  40. return file.read()
  41. @property
  42. def system_message(self) -> str:
  43. rendered = self.system_template.render(
  44. agent_skills_docs=self.agent_skills_docs,
  45. ).strip()
  46. return rendered
  47. @property
  48. def initial_user_message(self) -> str:
  49. """This is the initial user message provided to the agent
  50. before *actual* user instructions are provided.
  51. It is used to provide a demonstration of how the agent
  52. should behave in order to solve the user's task. And it may
  53. optionally contain some additional context about the user's task.
  54. These additional context will convert the current generic agent
  55. into a more specialized agent that is tailored to the user's task.
  56. """
  57. rendered = self.user_template.render(micro_agent=self.micro_agent)
  58. return rendered.strip()