base.py 9.5 KB

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