base.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import logging
  2. import re
  3. from string import Template
  4. from typing import Any, Optional
  5. from embedchain.config.base_config import BaseConfig
  6. from embedchain.helpers.json_serializable import register_deserializable
  7. DEFAULT_PROMPT = """
  8. Use the following pieces of context to answer the query at the end.
  9. If you don't know the answer, just say that you don't know, don't try to make up an answer.
  10. $context
  11. Query: $query
  12. Helpful Answer:
  13. """ # noqa:E501
  14. DEFAULT_PROMPT_WITH_HISTORY = """
  15. Use the following pieces of context to answer the query at the end.
  16. If you don't know the answer, just say that you don't know, don't try to make up an answer.
  17. I will provide you with our conversation history.
  18. $context
  19. History: $history
  20. Query: $query
  21. Helpful Answer:
  22. """ # noqa:E501
  23. DOCS_SITE_DEFAULT_PROMPT = """
  24. Use the following pieces of context to answer the query at the end.
  25. If you don't know the answer, just say that you don't know, don't try to make up an answer. Wherever possible, give complete code snippet. Dont make up any code snippet on your own.
  26. $context
  27. Query: $query
  28. Helpful Answer:
  29. """ # noqa:E501
  30. DEFAULT_PROMPT_TEMPLATE = Template(DEFAULT_PROMPT)
  31. DEFAULT_PROMPT_WITH_HISTORY_TEMPLATE = Template(DEFAULT_PROMPT_WITH_HISTORY)
  32. DOCS_SITE_PROMPT_TEMPLATE = Template(DOCS_SITE_DEFAULT_PROMPT)
  33. query_re = re.compile(r"\$\{*query\}*")
  34. context_re = re.compile(r"\$\{*context\}*")
  35. history_re = re.compile(r"\$\{*history\}*")
  36. @register_deserializable
  37. class BaseLlmConfig(BaseConfig):
  38. """
  39. Config for the `query` method.
  40. """
  41. def __init__(
  42. self,
  43. number_documents: int = 3,
  44. template: Optional[Template] = None,
  45. prompt: Optional[Template] = None,
  46. model: Optional[str] = None,
  47. temperature: float = 0,
  48. max_tokens: int = 1000,
  49. top_p: float = 1,
  50. stream: bool = False,
  51. deployment_name: Optional[str] = None,
  52. system_prompt: Optional[str] = None,
  53. where: dict[str, Any] = None,
  54. query_type: Optional[str] = None,
  55. callbacks: Optional[list] = None,
  56. api_key: Optional[str] = None,
  57. endpoint: Optional[str] = None,
  58. model_kwargs: Optional[dict[str, Any]] = None,
  59. ):
  60. """
  61. Initializes a configuration class instance for the LLM.
  62. Takes the place of the former `QueryConfig` or `ChatConfig`.
  63. :param number_documents: Number of documents to pull from the database as
  64. context, defaults to 1
  65. :type number_documents: int, optional
  66. :param template: The `Template` instance to use as a template for
  67. prompt, defaults to None (deprecated)
  68. :type template: Optional[Template], optional
  69. :param prompt: The `Template` instance to use as a template for
  70. prompt, defaults to None
  71. :type prompt: Optional[Template], optional
  72. :param model: Controls the OpenAI model used, defaults to None
  73. :type model: Optional[str], optional
  74. :param temperature: Controls the randomness of the model's output.
  75. Higher values (closer to 1) make output more random, lower values make it more deterministic, defaults to 0
  76. :type temperature: float, optional
  77. :param max_tokens: Controls how many tokens are generated, defaults to 1000
  78. :type max_tokens: int, optional
  79. :param top_p: Controls the diversity of words. Higher values (closer to 1) make word selection more diverse,
  80. defaults to 1
  81. :type top_p: float, optional
  82. :param stream: Control if response is streamed back to user, defaults to False
  83. :type stream: bool, optional
  84. :param deployment_name: t.b.a., defaults to None
  85. :type deployment_name: Optional[str], optional
  86. :param system_prompt: System prompt string, defaults to None
  87. :type system_prompt: Optional[str], optional
  88. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  89. :type where: dict[str, Any], optional
  90. :param api_key: The api key of the custom endpoint, defaults to None
  91. :type api_key: Optional[str], optional
  92. :param endpoint: The api url of the custom endpoint, defaults to None
  93. :type endpoint: Optional[str], optional
  94. :param model_kwargs: A dictionary of key-value pairs to pass to the model, defaults to None
  95. :type model_kwargs: Optional[Dict[str, Any]], optional
  96. :param callbacks: Langchain callback functions to use, defaults to None
  97. :type callbacks: Optional[list], optional
  98. :param query_type: The type of query to use, defaults to None
  99. :type query_type: Optional[str], optional
  100. :raises ValueError: If the template is not valid as template should
  101. contain $context and $query (and optionally $history)
  102. :raises ValueError: Stream is not boolean
  103. """
  104. if template is not None:
  105. logging.warning(
  106. "The `template` argument is deprecated and will be removed in a future version. "
  107. + "Please use `prompt` instead."
  108. )
  109. if prompt is None:
  110. prompt = template
  111. if prompt is None:
  112. prompt = DEFAULT_PROMPT_TEMPLATE
  113. self.number_documents = number_documents
  114. self.temperature = temperature
  115. self.max_tokens = max_tokens
  116. self.model = model
  117. self.top_p = top_p
  118. self.deployment_name = deployment_name
  119. self.system_prompt = system_prompt
  120. self.query_type = query_type
  121. self.callbacks = callbacks
  122. self.api_key = api_key
  123. self.endpoint = endpoint
  124. self.model_kwargs = model_kwargs
  125. if isinstance(prompt, str):
  126. prompt = Template(prompt)
  127. if self.validate_prompt(prompt):
  128. self.prompt = prompt
  129. else:
  130. raise ValueError("The 'prompt' should have 'query' and 'context' keys and potentially 'history' (if used).")
  131. if not isinstance(stream, bool):
  132. raise ValueError("`stream` should be bool")
  133. self.stream = stream
  134. self.where = where
  135. @staticmethod
  136. def validate_prompt(prompt: Template) -> Optional[re.Match[str]]:
  137. """
  138. validate the prompt
  139. :param prompt: the prompt to validate
  140. :type prompt: Template
  141. :return: valid (true) or invalid (false)
  142. :rtype: Optional[re.Match[str]]
  143. """
  144. return re.search(query_re, prompt.template) and re.search(context_re, prompt.template)
  145. @staticmethod
  146. def _validate_prompt_history(prompt: Template) -> Optional[re.Match[str]]:
  147. """
  148. validate the prompt with history
  149. :param prompt: the prompt to validate
  150. :type prompt: Template
  151. :return: valid (true) or invalid (false)
  152. :rtype: Optional[re.Match[str]]
  153. """
  154. return re.search(history_re, prompt.template)