prompt_template.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import re
  2. REGEX = re.compile(r"\{\{([a-zA-Z_][a-zA-Z0-9_]{1,29}|#histories#|#query#|#context#)\}\}")
  3. class PromptTemplateParser:
  4. """
  5. Rules:
  6. 1. Template variables must be enclosed in `{{}}`.
  7. 2. The template variable Key can only be: letters + numbers + underscore, with a maximum length of 16 characters,
  8. and can only start with letters and underscores.
  9. 3. The template variable Key cannot contain new lines or spaces, and must comply with rule 2.
  10. 4. In addition to the above, 3 types of special template variable Keys are accepted:
  11. `{{#histories#}}` `{{#query#}}` `{{#context#}}`. No other `{{##}}` template variables are allowed.
  12. """
  13. def __init__(self, template: str):
  14. self.template = template
  15. self.variable_keys = self.extract()
  16. def extract(self) -> list:
  17. # Regular expression to match the template rules
  18. return re.findall(REGEX, self.template)
  19. def format(self, inputs: dict, remove_template_variables: bool = True) -> str:
  20. def replacer(match):
  21. key = match.group(1)
  22. value = inputs.get(key, match.group(0)) # return original matched string if key not found
  23. if remove_template_variables:
  24. return PromptTemplateParser.remove_template_variables(value)
  25. return value
  26. return re.sub(REGEX, replacer, self.template)
  27. @classmethod
  28. def remove_template_variables(cls, text: str):
  29. return re.sub(REGEX, r'{\1}', text)