QueryConfig.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from embedchain.config.BaseConfig import BaseConfig
  2. from string import Template
  3. import re
  4. DEFAULT_PROMPT = """
  5. Use the following pieces of context to answer the query at the end.
  6. If you don't know the answer, just say that you don't know, don't try to make up an answer.
  7. $context
  8. Query: $query
  9. Helpful Answer:
  10. """
  11. DEFAULT_PROMPT_TEMPLATE = Template(DEFAULT_PROMPT)
  12. query_re = re.compile(r"\$\{*query\}*")
  13. context_re = re.compile(r"\$\{*context\}*")
  14. class QueryConfig(BaseConfig):
  15. """
  16. Config for the `query` method.
  17. """
  18. def __init__(self, template: Template = None, stream: bool = False):
  19. """
  20. Initializes the QueryConfig instance.
  21. :param template: Optional. The `Template` instance to use as a template for prompt.
  22. :param stream: Optional. Control if response is streamed back to the user
  23. :raises ValueError: If the template is not valid as template should contain $context and $query
  24. """
  25. if template is None:
  26. template = DEFAULT_PROMPT_TEMPLATE
  27. if not (re.search(query_re, template.template) \
  28. and re.search(context_re, template.template)):
  29. raise ValueError("`template` should have `query` and `context` keys")
  30. self.template = template
  31. if not isinstance(stream, bool):
  32. raise ValueError("`stream` should be bool")
  33. self.stream = stream