base.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import logging
  2. import re
  3. from string import Template
  4. from typing import Any, Mapping, 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. online: bool = False,
  72. deployment_name: Optional[str] = None,
  73. system_prompt: Optional[str] = None,
  74. where: dict[str, Any] = None,
  75. query_type: Optional[str] = None,
  76. callbacks: Optional[list] = None,
  77. api_key: Optional[str] = None,
  78. base_url: Optional[str] = None,
  79. endpoint: Optional[str] = None,
  80. model_kwargs: Optional[dict[str, Any]] = None,
  81. http_client: Optional[Any] = None,
  82. http_async_client: Optional[Any] = None,
  83. local: Optional[bool] = False,
  84. default_headers: Optional[Mapping[str, str]] = None,
  85. ):
  86. """
  87. Initializes a configuration class instance for the LLM.
  88. Takes the place of the former `QueryConfig` or `ChatConfig`.
  89. :param number_documents: Number of documents to pull from the database as
  90. context, defaults to 1
  91. :type number_documents: int, optional
  92. :param template: The `Template` instance to use as a template for
  93. prompt, defaults to None (deprecated)
  94. :type template: Optional[Template], optional
  95. :param prompt: The `Template` instance to use as a template for
  96. prompt, defaults to None
  97. :type prompt: Optional[Template], optional
  98. :param model: Controls the OpenAI model used, defaults to None
  99. :type model: Optional[str], optional
  100. :param temperature: Controls the randomness of the model's output.
  101. Higher values (closer to 1) make output more random, lower values make it more deterministic, defaults to 0
  102. :type temperature: float, optional
  103. :param max_tokens: Controls how many tokens are generated, defaults to 1000
  104. :type max_tokens: int, optional
  105. :param top_p: Controls the diversity of words. Higher values (closer to 1) make word selection more diverse,
  106. defaults to 1
  107. :type top_p: float, optional
  108. :param stream: Control if response is streamed back to user, defaults to False
  109. :type stream: bool, optional
  110. :param online: Controls whether to use internet for answering query, defaults to False
  111. :type online: bool, optional
  112. :param deployment_name: t.b.a., defaults to None
  113. :type deployment_name: Optional[str], optional
  114. :param system_prompt: System prompt string, defaults to None
  115. :type system_prompt: Optional[str], optional
  116. :param where: A dictionary of key-value pairs to filter the database results., defaults to None
  117. :type where: dict[str, Any], optional
  118. :param api_key: The api key of the custom endpoint, defaults to None
  119. :type api_key: Optional[str], optional
  120. :param endpoint: The api url of the custom endpoint, defaults to None
  121. :type endpoint: Optional[str], optional
  122. :param model_kwargs: A dictionary of key-value pairs to pass to the model, defaults to None
  123. :type model_kwargs: Optional[Dict[str, Any]], optional
  124. :param callbacks: Langchain callback functions to use, defaults to None
  125. :type callbacks: Optional[list], optional
  126. :param query_type: The type of query to use, defaults to None
  127. :type query_type: Optional[str], optional
  128. :param local: If True, the model will be run locally, defaults to False (for huggingface provider)
  129. :type local: Optional[bool], optional
  130. :param default_headers: Set additional HTTP headers to be sent with requests to OpenAI
  131. :type default_headers: Optional[Mapping[str, str]], optional
  132. :raises ValueError: If the template is not valid as template should
  133. contain $context and $query (and optionally $history)
  134. :raises ValueError: Stream is not boolean
  135. """
  136. if template is not None:
  137. logger.warning(
  138. "The `template` argument is deprecated and will be removed in a future version. "
  139. + "Please use `prompt` instead."
  140. )
  141. if prompt is None:
  142. prompt = template
  143. if prompt is None:
  144. prompt = DEFAULT_PROMPT_TEMPLATE
  145. self.number_documents = number_documents
  146. self.temperature = temperature
  147. self.max_tokens = max_tokens
  148. self.model = model
  149. self.top_p = top_p
  150. self.deployment_name = deployment_name
  151. self.system_prompt = system_prompt
  152. self.query_type = query_type
  153. self.callbacks = callbacks
  154. self.api_key = api_key
  155. self.base_url = base_url
  156. self.endpoint = endpoint
  157. self.model_kwargs = model_kwargs
  158. self.http_client = http_client
  159. self.http_async_client = http_async_client
  160. self.local = local
  161. self.default_headers = default_headers
  162. self.online = online
  163. if isinstance(prompt, str):
  164. prompt = Template(prompt)
  165. if self.validate_prompt(prompt):
  166. self.prompt = prompt
  167. else:
  168. raise ValueError("The 'prompt' should have 'query' and 'context' keys and potentially 'history' (if used).")
  169. if not isinstance(stream, bool):
  170. raise ValueError("`stream` should be bool")
  171. self.stream = stream
  172. self.where = where
  173. @staticmethod
  174. def validate_prompt(prompt: Template) -> Optional[re.Match[str]]:
  175. """
  176. validate the prompt
  177. :param prompt: the prompt to validate
  178. :type prompt: Template
  179. :return: valid (true) or invalid (false)
  180. :rtype: Optional[re.Match[str]]
  181. """
  182. return re.search(query_re, prompt.template) and re.search(context_re, prompt.template)
  183. @staticmethod
  184. def _validate_prompt_history(prompt: Template) -> Optional[re.Match[str]]:
  185. """
  186. validate the prompt with history
  187. :param prompt: the prompt to validate
  188. :type prompt: Template
  189. :return: valid (true) or invalid (false)
  190. :rtype: Optional[re.Match[str]]
  191. """
  192. return re.search(history_re, prompt.template)