base.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. logger = logging.getLogger(__name__)
  8. DEFAULT_PROMPT = """
  9. You are a Q&A expert system. Your responses must always be rooted in the context provided for each query. Here are some guidelines to follow:
  10. 1. Refrain from explicitly mentioning the context provided in your response.
  11. 2. The context should silently guide your answers without being directly acknowledged.
  12. 3. Do not use phrases such as 'According to the context provided', 'Based on the context, ...' etc.
  13. Context information:
  14. ----------------------
  15. $context
  16. ----------------------
  17. Query: $query
  18. Answer:
  19. """ # noqa:E501
  20. DEFAULT_PROMPT_WITH_HISTORY = """
  21. You are a Q&A expert system. Your responses must always be rooted in the context provided for each query. You are also provided with the conversation history with the user. Make sure to use relevant context from conversation history as needed.
  22. Here are some guidelines to follow:
  23. 1. Refrain from explicitly mentioning the context provided in your response.
  24. 2. The context should silently guide your answers without being directly acknowledged.
  25. 3. Do not use phrases such as 'According to the context provided', 'Based on the context, ...' etc.
  26. Context information:
  27. ----------------------
  28. $context
  29. ----------------------
  30. Conversation history:
  31. ----------------------
  32. $history
  33. ----------------------
  34. Query: $query
  35. Answer:
  36. """ # noqa:E501
  37. DOCS_SITE_DEFAULT_PROMPT = """
  38. You are an expert AI assistant for developer support product. Your responses must always be rooted in the context provided for each query. Wherever possible, give complete code snippet. Dont make up any code snippet on your own.
  39. Here are some guidelines to follow:
  40. 1. Refrain from explicitly mentioning the context provided in your response.
  41. 2. The context should silently guide your answers without being directly acknowledged.
  42. 3. Do not use phrases such as 'According to the context provided', 'Based on the context, ...' etc.
  43. Context information:
  44. ----------------------
  45. $context
  46. ----------------------
  47. Query: $query
  48. Answer:
  49. """ # noqa:E501
  50. DEFAULT_PROMPT_TEMPLATE = Template(DEFAULT_PROMPT)
  51. DEFAULT_PROMPT_WITH_HISTORY_TEMPLATE = Template(DEFAULT_PROMPT_WITH_HISTORY)
  52. DOCS_SITE_PROMPT_TEMPLATE = Template(DOCS_SITE_DEFAULT_PROMPT)
  53. query_re = re.compile(r"\$\{*query\}*")
  54. context_re = re.compile(r"\$\{*context\}*")
  55. history_re = re.compile(r"\$\{*history\}*")
  56. @register_deserializable
  57. class BaseLlmConfig(BaseConfig):
  58. """
  59. Config for the `query` method.
  60. """
  61. def __init__(
  62. self,
  63. number_documents: int = 3,
  64. template: Optional[Template] = None,
  65. prompt: Optional[Template] = None,
  66. model: Optional[str] = None,
  67. temperature: float = 0,
  68. max_tokens: int = 1000,
  69. top_p: float = 1,
  70. stream: bool = False,
  71. deployment_name: Optional[str] = None,
  72. system_prompt: Optional[str] = None,
  73. where: dict[str, Any] = None,
  74. query_type: Optional[str] = None,
  75. callbacks: Optional[list] = None,
  76. api_key: Optional[str] = None,
  77. base_url: Optional[str] = None,
  78. endpoint: Optional[str] = None,
  79. model_kwargs: Optional[dict[str, Any]] = None,
  80. local: Optional[bool] = False,
  81. ):
  82. """
  83. Initializes a configuration class instance for the LLM.
  84. Takes the place of the former `QueryConfig` or `ChatConfig`.
  85. :param number_documents: Number of documents to pull from the database as
  86. context, defaults to 1
  87. :type number_documents: int, optional
  88. :param template: The `Template` instance to use as a template for
  89. prompt, defaults to None (deprecated)
  90. :type template: Optional[Template], optional
  91. :param prompt: The `Template` instance to use as a template for
  92. prompt, defaults to None
  93. :type prompt: Optional[Template], optional
  94. :param model: Controls the OpenAI model used, defaults to None
  95. :type model: Optional[str], optional
  96. :param temperature: Controls the randomness of the model's output.
  97. Higher values (closer to 1) make output more random, lower values make it more deterministic, defaults to 0
  98. :type temperature: float, optional
  99. :param max_tokens: Controls how many tokens are generated, defaults to 1000
  100. :type max_tokens: int, optional
  101. :param top_p: Controls the diversity of words. Higher values (closer to 1) make word selection more diverse,
  102. defaults to 1
  103. :type top_p: float, optional
  104. :param stream: Control if response is streamed back to user, defaults to False
  105. :type stream: bool, optional
  106. :param deployment_name: t.b.a., defaults to None
  107. :type deployment_name: Optional[str], optional
  108. :param system_prompt: System prompt string, defaults to None
  109. :type system_prompt: Optional[str], optional
  110. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  111. :type where: dict[str, Any], optional
  112. :param api_key: The api key of the custom endpoint, defaults to None
  113. :type api_key: Optional[str], optional
  114. :param endpoint: The api url of the custom endpoint, defaults to None
  115. :type endpoint: Optional[str], optional
  116. :param model_kwargs: A dictionary of key-value pairs to pass to the model, defaults to None
  117. :type model_kwargs: Optional[Dict[str, Any]], optional
  118. :param callbacks: Langchain callback functions to use, defaults to None
  119. :type callbacks: Optional[list], optional
  120. :param query_type: The type of query to use, defaults to None
  121. :type query_type: Optional[str], optional
  122. :param local: If True, the model will be run locally, defaults to False (for huggingface provider)
  123. :type local: Optional[bool], optional
  124. :raises ValueError: If the template is not valid as template should
  125. contain $context and $query (and optionally $history)
  126. :raises ValueError: Stream is not boolean
  127. """
  128. if template is not None:
  129. logger.warning(
  130. "The `template` argument is deprecated and will be removed in a future version. "
  131. + "Please use `prompt` instead."
  132. )
  133. if prompt is None:
  134. prompt = template
  135. if prompt is None:
  136. prompt = DEFAULT_PROMPT_TEMPLATE
  137. self.number_documents = number_documents
  138. self.temperature = temperature
  139. self.max_tokens = max_tokens
  140. self.model = model
  141. self.top_p = top_p
  142. self.deployment_name = deployment_name
  143. self.system_prompt = system_prompt
  144. self.query_type = query_type
  145. self.callbacks = callbacks
  146. self.api_key = api_key
  147. self.base_url = base_url
  148. self.endpoint = endpoint
  149. self.model_kwargs = model_kwargs
  150. self.local = local
  151. if isinstance(prompt, str):
  152. prompt = Template(prompt)
  153. if self.validate_prompt(prompt):
  154. self.prompt = prompt
  155. else:
  156. raise ValueError("The 'prompt' should have 'query' and 'context' keys and potentially 'history' (if used).")
  157. if not isinstance(stream, bool):
  158. raise ValueError("`stream` should be bool")
  159. self.stream = stream
  160. self.where = where
  161. @staticmethod
  162. def validate_prompt(prompt: Template) -> Optional[re.Match[str]]:
  163. """
  164. validate the prompt
  165. :param prompt: the prompt to validate
  166. :type prompt: Template
  167. :return: valid (true) or invalid (false)
  168. :rtype: Optional[re.Match[str]]
  169. """
  170. return re.search(query_re, prompt.template) and re.search(context_re, prompt.template)
  171. @staticmethod
  172. def _validate_prompt_history(prompt: Template) -> Optional[re.Match[str]]:
  173. """
  174. validate the prompt with history
  175. :param prompt: the prompt to validate
  176. :type prompt: Template
  177. :return: valid (true) or invalid (false)
  178. :rtype: Optional[re.Match[str]]
  179. """
  180. return re.search(history_re, prompt.template)