conversation_message_task.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. import decimal
  2. import json
  3. from typing import Optional, Union, List
  4. from core.callback_handler.entity.agent_loop import AgentLoop
  5. from core.callback_handler.entity.dataset_query import DatasetQueryObj
  6. from core.callback_handler.entity.llm_message import LLMMessage
  7. from core.callback_handler.entity.chain_result import ChainResult
  8. from core.model_providers.model_factory import ModelFactory
  9. from core.model_providers.models.entity.message import to_prompt_messages, MessageType
  10. from core.model_providers.models.llm.base import BaseLLM
  11. from core.prompt.prompt_builder import PromptBuilder
  12. from core.prompt.prompt_template import JinjaPromptTemplate
  13. from events.message_event import message_was_created
  14. from extensions.ext_database import db
  15. from extensions.ext_redis import redis_client
  16. from models.dataset import DatasetQuery
  17. from models.model import AppModelConfig, Conversation, Account, Message, EndUser, App, MessageAgentThought, \
  18. MessageChain, DatasetRetrieverResource
  19. class ConversationMessageTask:
  20. def __init__(self, task_id: str, app: App, app_model_config: AppModelConfig, user: Account,
  21. inputs: dict, query: str, streaming: bool, model_instance: BaseLLM,
  22. conversation: Optional[Conversation] = None, is_override: bool = False):
  23. self.task_id = task_id
  24. self.app = app
  25. self.tenant_id = app.tenant_id
  26. self.app_model_config = app_model_config
  27. self.is_override = is_override
  28. self.user = user
  29. self.inputs = inputs
  30. self.query = query
  31. self.streaming = streaming
  32. self.conversation = conversation
  33. self.is_new_conversation = False
  34. self.model_instance = model_instance
  35. self.message = None
  36. self.retriever_resource = None
  37. self.model_dict = self.app_model_config.model_dict
  38. self.provider_name = self.model_dict.get('provider')
  39. self.model_name = self.model_dict.get('name')
  40. self.mode = app.mode
  41. self.init()
  42. self._pub_handler = PubHandler(
  43. user=self.user,
  44. task_id=self.task_id,
  45. message=self.message,
  46. conversation=self.conversation,
  47. chain_pub=False, # disabled currently
  48. agent_thought_pub=True
  49. )
  50. def init(self):
  51. override_model_configs = None
  52. if self.is_override:
  53. override_model_configs = self.app_model_config.to_dict()
  54. introduction = ''
  55. system_instruction = ''
  56. system_instruction_tokens = 0
  57. if self.mode == 'chat':
  58. introduction = self.app_model_config.opening_statement
  59. if introduction:
  60. prompt_template = JinjaPromptTemplate.from_template(template=introduction)
  61. prompt_inputs = {k: self.inputs[k] for k in prompt_template.input_variables if k in self.inputs}
  62. try:
  63. introduction = prompt_template.format(**prompt_inputs)
  64. except KeyError:
  65. pass
  66. if self.app_model_config.pre_prompt:
  67. system_message = PromptBuilder.to_system_message(self.app_model_config.pre_prompt, self.inputs)
  68. system_instruction = system_message.content
  69. model_instance = ModelFactory.get_text_generation_model(
  70. tenant_id=self.tenant_id,
  71. model_provider_name=self.provider_name,
  72. model_name=self.model_name
  73. )
  74. system_instruction_tokens = model_instance.get_num_tokens(to_prompt_messages([system_message]))
  75. if not self.conversation:
  76. self.is_new_conversation = True
  77. self.conversation = Conversation(
  78. app_id=self.app_model_config.app_id,
  79. app_model_config_id=self.app_model_config.id,
  80. model_provider=self.provider_name,
  81. model_id=self.model_name,
  82. override_model_configs=json.dumps(override_model_configs) if override_model_configs else None,
  83. mode=self.mode,
  84. name='',
  85. inputs=self.inputs,
  86. introduction=introduction,
  87. system_instruction=system_instruction,
  88. system_instruction_tokens=system_instruction_tokens,
  89. status='normal',
  90. from_source=('console' if isinstance(self.user, Account) else 'api'),
  91. from_end_user_id=(self.user.id if isinstance(self.user, EndUser) else None),
  92. from_account_id=(self.user.id if isinstance(self.user, Account) else None),
  93. )
  94. db.session.add(self.conversation)
  95. db.session.flush()
  96. self.message = Message(
  97. app_id=self.app_model_config.app_id,
  98. model_provider=self.provider_name,
  99. model_id=self.model_name,
  100. override_model_configs=json.dumps(override_model_configs) if override_model_configs else None,
  101. conversation_id=self.conversation.id,
  102. inputs=self.inputs,
  103. query=self.query,
  104. message="",
  105. message_tokens=0,
  106. message_unit_price=0,
  107. message_price_unit=0,
  108. answer="",
  109. answer_tokens=0,
  110. answer_unit_price=0,
  111. answer_price_unit=0,
  112. provider_response_latency=0,
  113. total_price=0,
  114. currency=self.model_instance.get_currency(),
  115. from_source=('console' if isinstance(self.user, Account) else 'api'),
  116. from_end_user_id=(self.user.id if isinstance(self.user, EndUser) else None),
  117. from_account_id=(self.user.id if isinstance(self.user, Account) else None),
  118. agent_based=self.app_model_config.agent_mode_dict.get('enabled'),
  119. )
  120. db.session.add(self.message)
  121. db.session.flush()
  122. def append_message_text(self, text: str):
  123. if text is not None:
  124. self._pub_handler.pub_text(text)
  125. def save_message(self, llm_message: LLMMessage, by_stopped: bool = False):
  126. message_tokens = llm_message.prompt_tokens
  127. answer_tokens = llm_message.completion_tokens
  128. message_unit_price = self.model_instance.get_tokens_unit_price(MessageType.HUMAN)
  129. message_price_unit = self.model_instance.get_price_unit(MessageType.HUMAN)
  130. answer_unit_price = self.model_instance.get_tokens_unit_price(MessageType.ASSISTANT)
  131. answer_price_unit = self.model_instance.get_price_unit(MessageType.ASSISTANT)
  132. message_total_price = self.model_instance.calc_tokens_price(message_tokens, MessageType.HUMAN)
  133. answer_total_price = self.model_instance.calc_tokens_price(answer_tokens, MessageType.ASSISTANT)
  134. total_price = message_total_price + answer_total_price
  135. self.message.message = llm_message.prompt
  136. self.message.message_tokens = message_tokens
  137. self.message.message_unit_price = message_unit_price
  138. self.message.message_price_unit = message_price_unit
  139. self.message.answer = PromptBuilder.process_template(
  140. llm_message.completion.strip()) if llm_message.completion else ''
  141. self.message.answer_tokens = answer_tokens
  142. self.message.answer_unit_price = answer_unit_price
  143. self.message.answer_price_unit = answer_price_unit
  144. self.message.provider_response_latency = llm_message.latency
  145. self.message.total_price = total_price
  146. db.session.commit()
  147. message_was_created.send(
  148. self.message,
  149. conversation=self.conversation,
  150. is_first_message=self.is_new_conversation
  151. )
  152. if not by_stopped:
  153. self.end()
  154. def init_chain(self, chain_result: ChainResult):
  155. message_chain = MessageChain(
  156. message_id=self.message.id,
  157. type=chain_result.type,
  158. input=json.dumps(chain_result.prompt),
  159. output=''
  160. )
  161. db.session.add(message_chain)
  162. db.session.flush()
  163. return message_chain
  164. def on_chain_end(self, message_chain: MessageChain, chain_result: ChainResult):
  165. message_chain.output = json.dumps(chain_result.completion)
  166. self._pub_handler.pub_chain(message_chain)
  167. def on_agent_start(self, message_chain: MessageChain, agent_loop: AgentLoop) -> MessageAgentThought:
  168. message_agent_thought = MessageAgentThought(
  169. message_id=self.message.id,
  170. message_chain_id=message_chain.id,
  171. position=agent_loop.position,
  172. thought=agent_loop.thought,
  173. tool=agent_loop.tool_name,
  174. tool_input=agent_loop.tool_input,
  175. message=agent_loop.prompt,
  176. message_price_unit=0,
  177. answer=agent_loop.completion,
  178. answer_price_unit=0,
  179. created_by_role=('account' if isinstance(self.user, Account) else 'end_user'),
  180. created_by=self.user.id
  181. )
  182. db.session.add(message_agent_thought)
  183. db.session.flush()
  184. self._pub_handler.pub_agent_thought(message_agent_thought)
  185. return message_agent_thought
  186. def on_agent_end(self, message_agent_thought: MessageAgentThought, agent_model_instant: BaseLLM,
  187. agent_loop: AgentLoop):
  188. agent_message_unit_price = agent_model_instant.get_tokens_unit_price(MessageType.HUMAN)
  189. agent_message_price_unit = agent_model_instant.get_price_unit(MessageType.HUMAN)
  190. agent_answer_unit_price = agent_model_instant.get_tokens_unit_price(MessageType.ASSISTANT)
  191. agent_answer_price_unit = agent_model_instant.get_price_unit(MessageType.ASSISTANT)
  192. loop_message_tokens = agent_loop.prompt_tokens
  193. loop_answer_tokens = agent_loop.completion_tokens
  194. loop_message_total_price = agent_model_instant.calc_tokens_price(loop_message_tokens, MessageType.HUMAN)
  195. loop_answer_total_price = agent_model_instant.calc_tokens_price(loop_answer_tokens, MessageType.ASSISTANT)
  196. loop_total_price = loop_message_total_price + loop_answer_total_price
  197. message_agent_thought.observation = agent_loop.tool_output
  198. message_agent_thought.tool_process_data = '' # currently not support
  199. message_agent_thought.message_token = loop_message_tokens
  200. message_agent_thought.message_unit_price = agent_message_unit_price
  201. message_agent_thought.message_price_unit = agent_message_price_unit
  202. message_agent_thought.answer_token = loop_answer_tokens
  203. message_agent_thought.answer_unit_price = agent_answer_unit_price
  204. message_agent_thought.answer_price_unit = agent_answer_price_unit
  205. message_agent_thought.latency = agent_loop.latency
  206. message_agent_thought.tokens = agent_loop.prompt_tokens + agent_loop.completion_tokens
  207. message_agent_thought.total_price = loop_total_price
  208. message_agent_thought.currency = agent_model_instant.get_currency()
  209. db.session.flush()
  210. def on_dataset_query_end(self, dataset_query_obj: DatasetQueryObj):
  211. dataset_query = DatasetQuery(
  212. dataset_id=dataset_query_obj.dataset_id,
  213. content=dataset_query_obj.query,
  214. source='app',
  215. source_app_id=self.app.id,
  216. created_by_role=('account' if isinstance(self.user, Account) else 'end_user'),
  217. created_by=self.user.id
  218. )
  219. db.session.add(dataset_query)
  220. def on_dataset_query_finish(self, resource: List):
  221. if resource and len(resource) > 0:
  222. for item in resource:
  223. dataset_retriever_resource = DatasetRetrieverResource(
  224. message_id=self.message.id,
  225. position=item.get('position'),
  226. dataset_id=item.get('dataset_id'),
  227. dataset_name=item.get('dataset_name'),
  228. document_id=item.get('document_id'),
  229. document_name=item.get('document_name'),
  230. data_source_type=item.get('data_source_type'),
  231. segment_id=item.get('segment_id'),
  232. score=item.get('score') if 'score' in item else None,
  233. hit_count=item.get('hit_count') if 'hit_count' else None,
  234. word_count=item.get('word_count') if 'word_count' in item else None,
  235. segment_position=item.get('segment_position') if 'segment_position' in item else None,
  236. index_node_hash=item.get('index_node_hash') if 'index_node_hash' in item else None,
  237. content=item.get('content'),
  238. retriever_from=item.get('retriever_from'),
  239. created_by=self.user.id
  240. )
  241. db.session.add(dataset_retriever_resource)
  242. db.session.flush()
  243. self.retriever_resource = resource
  244. def message_end(self):
  245. self._pub_handler.pub_message_end(self.retriever_resource)
  246. def end(self):
  247. self._pub_handler.pub_message_end(self.retriever_resource)
  248. self._pub_handler.pub_end()
  249. class PubHandler:
  250. def __init__(self, user: Union[Account | EndUser], task_id: str,
  251. message: Message, conversation: Conversation,
  252. chain_pub: bool = False, agent_thought_pub: bool = False):
  253. self._channel = PubHandler.generate_channel_name(user, task_id)
  254. self._stopped_cache_key = PubHandler.generate_stopped_cache_key(user, task_id)
  255. self._task_id = task_id
  256. self._message = message
  257. self._conversation = conversation
  258. self._chain_pub = chain_pub
  259. self._agent_thought_pub = agent_thought_pub
  260. @classmethod
  261. def generate_channel_name(cls, user: Union[Account | EndUser], task_id: str):
  262. if not user:
  263. raise ValueError("user is required")
  264. user_str = 'account-' + str(user.id) if isinstance(user, Account) else 'end-user-' + str(user.id)
  265. return "generate_result:{}-{}".format(user_str, task_id)
  266. @classmethod
  267. def generate_stopped_cache_key(cls, user: Union[Account | EndUser], task_id: str):
  268. user_str = 'account-' + str(user.id) if isinstance(user, Account) else 'end-user-' + str(user.id)
  269. return "generate_result_stopped:{}-{}".format(user_str, task_id)
  270. def pub_text(self, text: str):
  271. content = {
  272. 'event': 'message',
  273. 'data': {
  274. 'task_id': self._task_id,
  275. 'message_id': str(self._message.id),
  276. 'text': text,
  277. 'mode': self._conversation.mode,
  278. 'conversation_id': str(self._conversation.id)
  279. }
  280. }
  281. redis_client.publish(self._channel, json.dumps(content))
  282. if self._is_stopped():
  283. self.pub_end()
  284. raise ConversationTaskStoppedException()
  285. def pub_chain(self, message_chain: MessageChain):
  286. if self._chain_pub:
  287. content = {
  288. 'event': 'chain',
  289. 'data': {
  290. 'task_id': self._task_id,
  291. 'message_id': self._message.id,
  292. 'chain_id': message_chain.id,
  293. 'type': message_chain.type,
  294. 'input': json.loads(message_chain.input),
  295. 'output': json.loads(message_chain.output),
  296. 'mode': self._conversation.mode,
  297. 'conversation_id': self._conversation.id
  298. }
  299. }
  300. redis_client.publish(self._channel, json.dumps(content))
  301. if self._is_stopped():
  302. self.pub_end()
  303. raise ConversationTaskStoppedException()
  304. def pub_agent_thought(self, message_agent_thought: MessageAgentThought):
  305. if self._agent_thought_pub:
  306. content = {
  307. 'event': 'agent_thought',
  308. 'data': {
  309. 'id': message_agent_thought.id,
  310. 'task_id': self._task_id,
  311. 'message_id': self._message.id,
  312. 'chain_id': message_agent_thought.message_chain_id,
  313. 'position': message_agent_thought.position,
  314. 'thought': message_agent_thought.thought,
  315. 'tool': message_agent_thought.tool,
  316. 'tool_input': message_agent_thought.tool_input,
  317. 'mode': self._conversation.mode,
  318. 'conversation_id': self._conversation.id
  319. }
  320. }
  321. redis_client.publish(self._channel, json.dumps(content))
  322. if self._is_stopped():
  323. self.pub_end()
  324. raise ConversationTaskStoppedException()
  325. def pub_message_end(self, retriever_resource: List):
  326. content = {
  327. 'event': 'message_end',
  328. 'data': {
  329. 'task_id': self._task_id,
  330. 'message_id': self._message.id,
  331. 'mode': self._conversation.mode,
  332. 'conversation_id': self._conversation.id
  333. }
  334. }
  335. if retriever_resource:
  336. content['data']['retriever_resources'] = retriever_resource
  337. redis_client.publish(self._channel, json.dumps(content))
  338. if self._is_stopped():
  339. self.pub_end()
  340. raise ConversationTaskStoppedException()
  341. def pub_end(self):
  342. content = {
  343. 'event': 'end',
  344. }
  345. redis_client.publish(self._channel, json.dumps(content))
  346. @classmethod
  347. def pub_error(cls, user: Union[Account | EndUser], task_id: str, e):
  348. content = {
  349. 'error': type(e).__name__,
  350. 'description': e.description if getattr(e, 'description', None) is not None else str(e)
  351. }
  352. channel = cls.generate_channel_name(user, task_id)
  353. redis_client.publish(channel, json.dumps(content))
  354. def _is_stopped(self):
  355. return redis_client.get(self._stopped_cache_key) is not None
  356. @classmethod
  357. def ping(cls, user: Union[Account | EndUser], task_id: str):
  358. content = {
  359. 'event': 'ping'
  360. }
  361. channel = cls.generate_channel_name(user, task_id)
  362. redis_client.publish(channel, json.dumps(content))
  363. @classmethod
  364. def stop(cls, user: Union[Account | EndUser], task_id: str):
  365. stopped_cache_key = cls.generate_stopped_cache_key(user, task_id)
  366. redis_client.setex(stopped_cache_key, 600, 1)
  367. class ConversationTaskStoppedException(Exception):
  368. pass