completion.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. from typing import Optional, List, Union
  2. from langchain.callbacks import CallbackManager
  3. from langchain.chat_models.base import BaseChatModel
  4. from langchain.llms import BaseLLM
  5. from langchain.schema import BaseMessage, BaseLanguageModel, HumanMessage
  6. from core.constant import llm_constant
  7. from core.callback_handler.llm_callback_handler import LLMCallbackHandler
  8. from core.callback_handler.std_out_callback_handler import DifyStreamingStdOutCallbackHandler, \
  9. DifyStdOutCallbackHandler
  10. from core.conversation_message_task import ConversationMessageTask, ConversationTaskStoppedException
  11. from core.llm.error import LLMBadRequestError
  12. from core.llm.llm_builder import LLMBuilder
  13. from core.chain.main_chain_builder import MainChainBuilder
  14. from core.llm.streamable_chat_open_ai import StreamableChatOpenAI
  15. from core.llm.streamable_open_ai import StreamableOpenAI
  16. from core.memory.read_only_conversation_token_db_buffer_shared_memory import \
  17. ReadOnlyConversationTokenDBBufferSharedMemory
  18. from core.memory.read_only_conversation_token_db_string_buffer_shared_memory import \
  19. ReadOnlyConversationTokenDBStringBufferSharedMemory
  20. from core.prompt.prompt_builder import PromptBuilder
  21. from core.prompt.prompt_template import OutLinePromptTemplate
  22. from core.prompt.prompts import MORE_LIKE_THIS_GENERATE_PROMPT
  23. from models.model import App, AppModelConfig, Account, Conversation, Message
  24. class Completion:
  25. @classmethod
  26. def generate(cls, task_id: str, app: App, app_model_config: AppModelConfig, query: str, inputs: dict,
  27. user: Account, conversation: Optional[Conversation], streaming: bool, is_override: bool = False):
  28. """
  29. errors: ProviderTokenNotInitError
  30. """
  31. cls.validate_query_tokens(app.tenant_id, app_model_config, query)
  32. memory = None
  33. if conversation:
  34. # get memory of conversation (read-only)
  35. memory = cls.get_memory_from_conversation(
  36. tenant_id=app.tenant_id,
  37. app_model_config=app_model_config,
  38. conversation=conversation
  39. )
  40. inputs = conversation.inputs
  41. conversation_message_task = ConversationMessageTask(
  42. task_id=task_id,
  43. app=app,
  44. app_model_config=app_model_config,
  45. user=user,
  46. conversation=conversation,
  47. is_override=is_override,
  48. inputs=inputs,
  49. query=query,
  50. streaming=streaming
  51. )
  52. # build main chain include agent
  53. main_chain = MainChainBuilder.to_langchain_components(
  54. tenant_id=app.tenant_id,
  55. agent_mode=app_model_config.agent_mode_dict,
  56. memory=ReadOnlyConversationTokenDBStringBufferSharedMemory(memory=memory) if memory else None,
  57. conversation_message_task=conversation_message_task
  58. )
  59. chain_output = ''
  60. if main_chain:
  61. chain_output = main_chain.run(query)
  62. # run the final llm
  63. try:
  64. cls.run_final_llm(
  65. tenant_id=app.tenant_id,
  66. mode=app.mode,
  67. app_model_config=app_model_config,
  68. query=query,
  69. inputs=inputs,
  70. chain_output=chain_output,
  71. conversation_message_task=conversation_message_task,
  72. memory=memory,
  73. streaming=streaming
  74. )
  75. except ConversationTaskStoppedException:
  76. return
  77. @classmethod
  78. def run_final_llm(cls, tenant_id: str, mode: str, app_model_config: AppModelConfig, query: str, inputs: dict,
  79. chain_output: str,
  80. conversation_message_task: ConversationMessageTask,
  81. memory: Optional[ReadOnlyConversationTokenDBBufferSharedMemory], streaming: bool):
  82. final_llm = LLMBuilder.to_llm_from_model(
  83. tenant_id=tenant_id,
  84. model=app_model_config.model_dict,
  85. streaming=streaming
  86. )
  87. # get llm prompt
  88. prompt = cls.get_main_llm_prompt(
  89. mode=mode,
  90. llm=final_llm,
  91. pre_prompt=app_model_config.pre_prompt,
  92. query=query,
  93. inputs=inputs,
  94. chain_output=chain_output,
  95. memory=memory
  96. )
  97. final_llm.callback_manager = cls.get_llm_callback_manager(final_llm, streaming, conversation_message_task)
  98. cls.recale_llm_max_tokens(
  99. final_llm=final_llm,
  100. prompt=prompt,
  101. mode=mode
  102. )
  103. response = final_llm.generate([prompt])
  104. return response
  105. @classmethod
  106. def get_main_llm_prompt(cls, mode: str, llm: BaseLanguageModel, pre_prompt: str, query: str, inputs: dict, chain_output: Optional[str],
  107. memory: Optional[ReadOnlyConversationTokenDBBufferSharedMemory]) -> \
  108. Union[str | List[BaseMessage]]:
  109. pre_prompt = PromptBuilder.process_template(pre_prompt) if pre_prompt else pre_prompt
  110. if mode == 'completion':
  111. prompt_template = OutLinePromptTemplate.from_template(
  112. template=("""Use the following CONTEXT as your learned knowledge:
  113. [CONTEXT]
  114. {context}
  115. [END CONTEXT]
  116. When answer to user:
  117. - If you don't know, just say that you don't know.
  118. - If you don't know when you are not sure, ask for clarification.
  119. Avoid mentioning that you obtained the information from the context.
  120. And answer according to the language of the user's question.
  121. """ if chain_output else "")
  122. + (pre_prompt + "\n" if pre_prompt else "")
  123. + "{query}\n"
  124. )
  125. if chain_output:
  126. inputs['context'] = chain_output
  127. prompt_inputs = {k: inputs[k] for k in prompt_template.input_variables if k in inputs}
  128. prompt_content = prompt_template.format(
  129. query=query,
  130. **prompt_inputs
  131. )
  132. if isinstance(llm, BaseChatModel):
  133. # use chat llm as completion model
  134. return [HumanMessage(content=prompt_content)]
  135. else:
  136. return prompt_content
  137. else:
  138. messages: List[BaseMessage] = []
  139. human_inputs = {
  140. "query": query
  141. }
  142. human_message_prompt = "{query}"
  143. if chain_output:
  144. human_inputs['context'] = chain_output
  145. human_message_instruction = """Use the following CONTEXT as your learned knowledge.
  146. [CONTEXT]
  147. {context}
  148. [END CONTEXT]
  149. When answer to user:
  150. - If you don't know, just say that you don't know.
  151. - If you don't know when you are not sure, ask for clarification.
  152. Avoid mentioning that you obtained the information from the context.
  153. And answer according to the language of the user's question.
  154. """
  155. if pre_prompt:
  156. human_inputs.update(inputs)
  157. human_message_instruction += pre_prompt + "\n"
  158. human_message_prompt = human_message_instruction + "Q:{query}\nA:"
  159. else:
  160. if pre_prompt:
  161. human_inputs.update(inputs)
  162. human_message_prompt = pre_prompt + "\n" + human_message_prompt
  163. # construct main prompt
  164. human_message = PromptBuilder.to_human_message(
  165. prompt_content=human_message_prompt,
  166. inputs=human_inputs
  167. )
  168. if memory:
  169. # append chat histories
  170. tmp_messages = messages.copy() + [human_message]
  171. curr_message_tokens = memory.llm.get_messages_tokens(tmp_messages)
  172. rest_tokens = llm_constant.max_context_token_length[
  173. memory.llm.model_name] - memory.llm.max_tokens - curr_message_tokens
  174. rest_tokens = max(rest_tokens, 0)
  175. history_messages = cls.get_history_messages_from_memory(memory, rest_tokens)
  176. messages += history_messages
  177. messages.append(human_message)
  178. return messages
  179. @classmethod
  180. def get_llm_callback_manager(cls, llm: Union[StreamableOpenAI, StreamableChatOpenAI],
  181. streaming: bool, conversation_message_task: ConversationMessageTask) -> CallbackManager:
  182. llm_callback_handler = LLMCallbackHandler(llm, conversation_message_task)
  183. if streaming:
  184. callback_handlers = [llm_callback_handler, DifyStreamingStdOutCallbackHandler()]
  185. else:
  186. callback_handlers = [llm_callback_handler, DifyStdOutCallbackHandler()]
  187. return CallbackManager(callback_handlers)
  188. @classmethod
  189. def get_history_messages_from_memory(cls, memory: ReadOnlyConversationTokenDBBufferSharedMemory,
  190. max_token_limit: int) -> \
  191. List[BaseMessage]:
  192. """Get memory messages."""
  193. memory.max_token_limit = max_token_limit
  194. memory_key = memory.memory_variables[0]
  195. external_context = memory.load_memory_variables({})
  196. return external_context[memory_key]
  197. @classmethod
  198. def get_memory_from_conversation(cls, tenant_id: str, app_model_config: AppModelConfig,
  199. conversation: Conversation,
  200. **kwargs) -> ReadOnlyConversationTokenDBBufferSharedMemory:
  201. # only for calc token in memory
  202. memory_llm = LLMBuilder.to_llm_from_model(
  203. tenant_id=tenant_id,
  204. model=app_model_config.model_dict
  205. )
  206. # use llm config from conversation
  207. memory = ReadOnlyConversationTokenDBBufferSharedMemory(
  208. conversation=conversation,
  209. llm=memory_llm,
  210. max_token_limit=kwargs.get("max_token_limit", 2048),
  211. memory_key=kwargs.get("memory_key", "chat_history"),
  212. return_messages=kwargs.get("return_messages", True),
  213. input_key=kwargs.get("input_key", "input"),
  214. output_key=kwargs.get("output_key", "output"),
  215. message_limit=kwargs.get("message_limit", 10),
  216. )
  217. return memory
  218. @classmethod
  219. def validate_query_tokens(cls, tenant_id: str, app_model_config: AppModelConfig, query: str):
  220. llm = LLMBuilder.to_llm_from_model(
  221. tenant_id=tenant_id,
  222. model=app_model_config.model_dict
  223. )
  224. model_limited_tokens = llm_constant.max_context_token_length[llm.model_name]
  225. max_tokens = llm.max_tokens
  226. if model_limited_tokens - max_tokens - llm.get_num_tokens(query) < 0:
  227. raise LLMBadRequestError("Query is too long")
  228. @classmethod
  229. def recale_llm_max_tokens(cls, final_llm: Union[StreamableOpenAI, StreamableChatOpenAI],
  230. prompt: Union[str, List[BaseMessage]], mode: str):
  231. # recalc max_tokens if sum(prompt_token + max_tokens) over model token limit
  232. model_limited_tokens = llm_constant.max_context_token_length[final_llm.model_name]
  233. max_tokens = final_llm.max_tokens
  234. if mode == 'completion' and isinstance(final_llm, BaseLLM):
  235. prompt_tokens = final_llm.get_num_tokens(prompt)
  236. else:
  237. prompt_tokens = final_llm.get_messages_tokens(prompt)
  238. if prompt_tokens + max_tokens > model_limited_tokens:
  239. max_tokens = max(model_limited_tokens - prompt_tokens, 16)
  240. final_llm.max_tokens = max_tokens
  241. @classmethod
  242. def generate_more_like_this(cls, task_id: str, app: App, message: Message, pre_prompt: str,
  243. app_model_config: AppModelConfig, user: Account, streaming: bool):
  244. llm: StreamableOpenAI = LLMBuilder.to_llm(
  245. tenant_id=app.tenant_id,
  246. model_name='gpt-3.5-turbo',
  247. streaming=streaming
  248. )
  249. # get llm prompt
  250. original_prompt = cls.get_main_llm_prompt(
  251. mode="completion",
  252. llm=llm,
  253. pre_prompt=pre_prompt,
  254. query=message.query,
  255. inputs=message.inputs,
  256. chain_output=None,
  257. memory=None
  258. )
  259. original_completion = message.answer.strip()
  260. prompt = MORE_LIKE_THIS_GENERATE_PROMPT
  261. prompt = prompt.format(prompt=original_prompt, original_completion=original_completion)
  262. if isinstance(llm, BaseChatModel):
  263. prompt = [HumanMessage(content=prompt)]
  264. conversation_message_task = ConversationMessageTask(
  265. task_id=task_id,
  266. app=app,
  267. app_model_config=app_model_config,
  268. user=user,
  269. inputs=message.inputs,
  270. query=message.query,
  271. is_override=True if message.override_model_configs else False,
  272. streaming=streaming
  273. )
  274. llm.callback_manager = cls.get_llm_callback_manager(llm, streaming, conversation_message_task)
  275. cls.recale_llm_max_tokens(
  276. final_llm=llm,
  277. prompt=prompt,
  278. mode='completion'
  279. )
  280. llm.generate([prompt])