completion_service.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. import json
  2. import logging
  3. import threading
  4. import time
  5. import uuid
  6. from typing import Generator, Union, Any, Optional, List
  7. from flask import current_app, Flask
  8. from redis.client import PubSub
  9. from sqlalchemy import and_
  10. from core.completion import Completion
  11. from core.conversation_message_task import PubHandler, ConversationTaskStoppedException, \
  12. ConversationTaskInterruptException
  13. from core.file.message_file_parser import MessageFileParser
  14. from core.model_providers.error import LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError, \
  15. LLMRateLimitError, \
  16. LLMAuthorizationError, ProviderTokenNotInitError, QuotaExceededError, ModelCurrentlyNotSupportError
  17. from core.model_providers.models.entity.message import PromptMessageFile
  18. from extensions.ext_database import db
  19. from extensions.ext_redis import redis_client
  20. from models.model import Conversation, AppModelConfig, App, Account, EndUser, Message
  21. from services.app_model_config_service import AppModelConfigService
  22. from services.errors.app import MoreLikeThisDisabledError
  23. from services.errors.app_model_config import AppModelConfigBrokenError
  24. from services.errors.completion import CompletionStoppedError
  25. from services.errors.conversation import ConversationNotExistsError, ConversationCompletedError
  26. from services.errors.message import MessageNotExistsError
  27. class CompletionService:
  28. @classmethod
  29. def completion(cls, app_model: App, user: Union[Account, EndUser], args: Any,
  30. from_source: str, streaming: bool = True,
  31. is_model_config_override: bool = False) -> Union[dict, Generator]:
  32. # is streaming mode
  33. inputs = args['inputs']
  34. query = args['query']
  35. files = args['files'] if 'files' in args and args['files'] else []
  36. auto_generate_name = args['auto_generate_name'] \
  37. if 'auto_generate_name' in args else True
  38. if app_model.mode != 'completion' and not query:
  39. raise ValueError('query is required')
  40. query = query.replace('\x00', '')
  41. conversation_id = args['conversation_id'] if 'conversation_id' in args else None
  42. conversation = None
  43. if conversation_id:
  44. conversation_filter = [
  45. Conversation.id == args['conversation_id'],
  46. Conversation.app_id == app_model.id,
  47. Conversation.status == 'normal'
  48. ]
  49. if from_source == 'console':
  50. conversation_filter.append(Conversation.from_account_id == user.id)
  51. else:
  52. conversation_filter.append(Conversation.from_end_user_id == user.id if user else None)
  53. conversation = db.session.query(Conversation).filter(and_(*conversation_filter)).first()
  54. if not conversation:
  55. raise ConversationNotExistsError()
  56. if conversation.status != 'normal':
  57. raise ConversationCompletedError()
  58. if not conversation.override_model_configs:
  59. app_model_config = db.session.query(AppModelConfig).filter(
  60. AppModelConfig.id == conversation.app_model_config_id,
  61. AppModelConfig.app_id == app_model.id
  62. ).first()
  63. if not app_model_config:
  64. raise AppModelConfigBrokenError()
  65. else:
  66. conversation_override_model_configs = json.loads(conversation.override_model_configs)
  67. app_model_config = AppModelConfig(
  68. id=conversation.app_model_config_id,
  69. app_id=app_model.id,
  70. )
  71. app_model_config = app_model_config.from_model_config_dict(conversation_override_model_configs)
  72. if is_model_config_override:
  73. # build new app model config
  74. if 'model' not in args['model_config']:
  75. raise ValueError('model_config.model is required')
  76. if 'completion_params' not in args['model_config']['model']:
  77. raise ValueError('model_config.model.completion_params is required')
  78. completion_params = AppModelConfigService.validate_model_completion_params(
  79. cp=args['model_config']['model']['completion_params'],
  80. model_name=app_model_config.model_dict["name"]
  81. )
  82. app_model_config_model = app_model_config.model_dict
  83. app_model_config_model['completion_params'] = completion_params
  84. app_model_config.retriever_resource = json.dumps({'enabled': True})
  85. app_model_config = app_model_config.copy()
  86. app_model_config.model = json.dumps(app_model_config_model)
  87. else:
  88. if app_model.app_model_config_id is None:
  89. raise AppModelConfigBrokenError()
  90. app_model_config = app_model.app_model_config
  91. if not app_model_config:
  92. raise AppModelConfigBrokenError()
  93. if is_model_config_override:
  94. if not isinstance(user, Account):
  95. raise Exception("Only account can override model config")
  96. # validate config
  97. model_config = AppModelConfigService.validate_configuration(
  98. tenant_id=app_model.tenant_id,
  99. account=user,
  100. config=args['model_config'],
  101. mode=app_model.mode
  102. )
  103. app_model_config = AppModelConfig(
  104. id=app_model_config.id,
  105. app_id=app_model.id,
  106. )
  107. app_model_config = app_model_config.from_model_config_dict(model_config)
  108. # clean input by app_model_config form rules
  109. inputs = cls.get_cleaned_inputs(inputs, app_model_config)
  110. # parse files
  111. message_file_parser = MessageFileParser(tenant_id=app_model.tenant_id, app_id=app_model.id)
  112. file_objs = message_file_parser.validate_and_transform_files_arg(
  113. files,
  114. app_model_config,
  115. user
  116. )
  117. generate_task_id = str(uuid.uuid4())
  118. pubsub = redis_client.pubsub()
  119. pubsub.subscribe(PubHandler.generate_channel_name(user, generate_task_id))
  120. user = cls.get_real_user_instead_of_proxy_obj(user)
  121. generate_worker_thread = threading.Thread(target=cls.generate_worker, kwargs={
  122. 'flask_app': current_app._get_current_object(),
  123. 'generate_task_id': generate_task_id,
  124. 'detached_app_model': app_model,
  125. 'app_model_config': app_model_config.copy(),
  126. 'query': query,
  127. 'inputs': inputs,
  128. 'files': file_objs,
  129. 'detached_user': user,
  130. 'detached_conversation': conversation,
  131. 'streaming': streaming,
  132. 'is_model_config_override': is_model_config_override,
  133. 'retriever_from': args['retriever_from'] if 'retriever_from' in args else 'dev',
  134. 'auto_generate_name': auto_generate_name
  135. })
  136. generate_worker_thread.start()
  137. # wait for 10 minutes to close the thread
  138. cls.countdown_and_close(current_app._get_current_object(), generate_worker_thread, pubsub, user,
  139. generate_task_id)
  140. return cls.compact_response(pubsub, streaming)
  141. @classmethod
  142. def get_real_user_instead_of_proxy_obj(cls, user: Union[Account, EndUser]):
  143. if isinstance(user, Account):
  144. user = db.session.query(Account).filter(Account.id == user.id).first()
  145. elif isinstance(user, EndUser):
  146. user = db.session.query(EndUser).filter(EndUser.id == user.id).first()
  147. else:
  148. raise Exception("Unknown user type")
  149. return user
  150. @classmethod
  151. def generate_worker(cls, flask_app: Flask, generate_task_id: str, detached_app_model: App,
  152. app_model_config: AppModelConfig,
  153. query: str, inputs: dict, files: List[PromptMessageFile],
  154. detached_user: Union[Account, EndUser],
  155. detached_conversation: Optional[Conversation], streaming: bool, is_model_config_override: bool,
  156. retriever_from: str = 'dev', auto_generate_name: bool = True):
  157. with flask_app.app_context():
  158. # fixed the state of the model object when it detached from the original session
  159. user = db.session.merge(detached_user)
  160. app_model = db.session.merge(detached_app_model)
  161. if detached_conversation:
  162. conversation = db.session.merge(detached_conversation)
  163. else:
  164. conversation = None
  165. try:
  166. # run
  167. Completion.generate(
  168. task_id=generate_task_id,
  169. app=app_model,
  170. app_model_config=app_model_config,
  171. query=query,
  172. inputs=inputs,
  173. user=user,
  174. files=files,
  175. conversation=conversation,
  176. streaming=streaming,
  177. is_override=is_model_config_override,
  178. retriever_from=retriever_from,
  179. auto_generate_name=auto_generate_name
  180. )
  181. except (ConversationTaskInterruptException, ConversationTaskStoppedException):
  182. pass
  183. except (ValueError, LLMBadRequestError, LLMAPIConnectionError, LLMAPIUnavailableError,
  184. LLMRateLimitError, ProviderTokenNotInitError, QuotaExceededError,
  185. ModelCurrentlyNotSupportError) as e:
  186. PubHandler.pub_error(user, generate_task_id, e)
  187. except LLMAuthorizationError:
  188. PubHandler.pub_error(user, generate_task_id, LLMAuthorizationError('Incorrect API key provided'))
  189. except Exception as e:
  190. logging.exception("Unknown Error in completion")
  191. PubHandler.pub_error(user, generate_task_id, e)
  192. finally:
  193. db.session.commit()
  194. @classmethod
  195. def countdown_and_close(cls, flask_app: Flask, worker_thread, pubsub, detached_user,
  196. generate_task_id) -> threading.Thread:
  197. # wait for 10 minutes to close the thread
  198. timeout = 600
  199. def close_pubsub():
  200. with flask_app.app_context():
  201. user = db.session.merge(detached_user)
  202. sleep_iterations = 0
  203. while sleep_iterations < timeout and worker_thread.is_alive():
  204. if sleep_iterations > 0 and sleep_iterations % 10 == 0:
  205. PubHandler.ping(user, generate_task_id)
  206. time.sleep(1)
  207. sleep_iterations += 1
  208. if worker_thread.is_alive():
  209. PubHandler.stop(user, generate_task_id)
  210. try:
  211. pubsub.close()
  212. except Exception:
  213. pass
  214. countdown_thread = threading.Thread(target=close_pubsub)
  215. countdown_thread.start()
  216. return countdown_thread
  217. @classmethod
  218. def generate_more_like_this(cls, app_model: App, user: Union[Account, EndUser],
  219. message_id: str, streaming: bool = True,
  220. retriever_from: str = 'dev') -> Union[dict, Generator]:
  221. if not user:
  222. raise ValueError('user cannot be None')
  223. message = db.session.query(Message).filter(
  224. Message.id == message_id,
  225. Message.app_id == app_model.id,
  226. Message.from_source == ('api' if isinstance(user, EndUser) else 'console'),
  227. Message.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  228. Message.from_account_id == (user.id if isinstance(user, Account) else None),
  229. ).first()
  230. if not message:
  231. raise MessageNotExistsError()
  232. current_app_model_config = app_model.app_model_config
  233. more_like_this = current_app_model_config.more_like_this_dict
  234. if not current_app_model_config.more_like_this or more_like_this.get("enabled", False) is False:
  235. raise MoreLikeThisDisabledError()
  236. app_model_config = message.app_model_config
  237. model_dict = app_model_config.model_dict
  238. completion_params = model_dict.get('completion_params')
  239. completion_params['temperature'] = 0.9
  240. model_dict['completion_params'] = completion_params
  241. app_model_config.model = json.dumps(model_dict)
  242. # parse files
  243. message_file_parser = MessageFileParser(tenant_id=app_model.tenant_id, app_id=app_model.id)
  244. file_objs = message_file_parser.transform_message_files(
  245. message.files, app_model_config
  246. )
  247. generate_task_id = str(uuid.uuid4())
  248. pubsub = redis_client.pubsub()
  249. pubsub.subscribe(PubHandler.generate_channel_name(user, generate_task_id))
  250. user = cls.get_real_user_instead_of_proxy_obj(user)
  251. generate_worker_thread = threading.Thread(target=cls.generate_worker, kwargs={
  252. 'flask_app': current_app._get_current_object(),
  253. 'generate_task_id': generate_task_id,
  254. 'detached_app_model': app_model,
  255. 'app_model_config': app_model_config.copy(),
  256. 'query': message.query,
  257. 'inputs': message.inputs,
  258. 'files': file_objs,
  259. 'detached_user': user,
  260. 'detached_conversation': None,
  261. 'streaming': streaming,
  262. 'is_model_config_override': True,
  263. 'retriever_from': retriever_from,
  264. 'auto_generate_name': False
  265. })
  266. generate_worker_thread.start()
  267. # wait for 10 minutes to close the thread
  268. cls.countdown_and_close(current_app._get_current_object(), generate_worker_thread, pubsub, user,
  269. generate_task_id)
  270. return cls.compact_response(pubsub, streaming)
  271. @classmethod
  272. def get_cleaned_inputs(cls, user_inputs: dict, app_model_config: AppModelConfig):
  273. if user_inputs is None:
  274. user_inputs = {}
  275. filtered_inputs = {}
  276. # Filter input variables from form configuration, handle required fields, default values, and option values
  277. input_form_config = app_model_config.user_input_form_list
  278. for config in input_form_config:
  279. input_config = list(config.values())[0]
  280. variable = input_config["variable"]
  281. input_type = list(config.keys())[0]
  282. if variable not in user_inputs or not user_inputs[variable]:
  283. if "required" in input_config and input_config["required"]:
  284. raise ValueError(f"{variable} is required in input form")
  285. else:
  286. filtered_inputs[variable] = input_config["default"] if "default" in input_config else ""
  287. continue
  288. value = user_inputs[variable]
  289. if input_type == "select":
  290. options = input_config["options"] if "options" in input_config else []
  291. if value not in options:
  292. raise ValueError(f"{variable} in input form must be one of the following: {options}")
  293. else:
  294. if 'max_length' in input_config:
  295. max_length = input_config['max_length']
  296. if len(value) > max_length:
  297. raise ValueError(f'{variable} in input form must be less than {max_length} characters')
  298. filtered_inputs[variable] = value.replace('\x00', '') if value else None
  299. return filtered_inputs
  300. @classmethod
  301. def compact_response(cls, pubsub: PubSub, streaming: bool = False) -> Union[dict, Generator]:
  302. generate_channel = list(pubsub.channels.keys())[0].decode('utf-8')
  303. if not streaming:
  304. try:
  305. message_result = {}
  306. for message in pubsub.listen():
  307. if message["type"] == "message":
  308. result = message["data"].decode('utf-8')
  309. result = json.loads(result)
  310. if result.get('error'):
  311. cls.handle_error(result)
  312. if result['event'] == 'message' and 'data' in result:
  313. message_result['message'] = result.get('data')
  314. if result['event'] == 'message_end' and 'data' in result:
  315. message_result['message_end'] = result.get('data')
  316. return cls.get_blocking_message_response_data(message_result)
  317. except ValueError as e:
  318. if e.args[0] != "I/O operation on closed file.": # ignore this error
  319. raise CompletionStoppedError()
  320. else:
  321. logging.exception(e)
  322. raise
  323. finally:
  324. db.session.commit()
  325. try:
  326. pubsub.unsubscribe(generate_channel)
  327. except ConnectionError:
  328. pass
  329. else:
  330. def generate() -> Generator:
  331. try:
  332. for message in pubsub.listen():
  333. if message["type"] == "message":
  334. result = message["data"].decode('utf-8')
  335. result = json.loads(result)
  336. if result.get('error'):
  337. cls.handle_error(result)
  338. event = result.get('event')
  339. if event == "end":
  340. logging.debug("{} finished".format(generate_channel))
  341. break
  342. if event == 'message':
  343. yield "data: " + json.dumps(cls.get_message_response_data(result.get('data'))) + "\n\n"
  344. elif event == 'message_replace':
  345. yield "data: " + json.dumps(
  346. cls.get_message_replace_response_data(result.get('data'))) + "\n\n"
  347. elif event == 'chain':
  348. yield "data: " + json.dumps(cls.get_chain_response_data(result.get('data'))) + "\n\n"
  349. elif event == 'agent_thought':
  350. yield "data: " + json.dumps(
  351. cls.get_agent_thought_response_data(result.get('data'))) + "\n\n"
  352. elif event == 'message_end':
  353. yield "data: " + json.dumps(
  354. cls.get_message_end_data(result.get('data'))) + "\n\n"
  355. elif event == 'ping':
  356. yield "event: ping\n\n"
  357. else:
  358. yield "data: " + json.dumps(result) + "\n\n"
  359. except ValueError as e:
  360. if e.args[0] != "I/O operation on closed file.": # ignore this error
  361. logging.exception(e)
  362. raise
  363. finally:
  364. db.session.commit()
  365. try:
  366. pubsub.unsubscribe(generate_channel)
  367. except ConnectionError:
  368. pass
  369. return generate()
  370. @classmethod
  371. def get_message_response_data(cls, data: dict):
  372. response_data = {
  373. 'event': 'message',
  374. 'task_id': data.get('task_id'),
  375. 'id': data.get('message_id'),
  376. 'answer': data.get('text'),
  377. 'created_at': int(time.time())
  378. }
  379. if data.get('mode') == 'chat':
  380. response_data['conversation_id'] = data.get('conversation_id')
  381. return response_data
  382. @classmethod
  383. def get_message_replace_response_data(cls, data: dict):
  384. response_data = {
  385. 'event': 'message_replace',
  386. 'task_id': data.get('task_id'),
  387. 'id': data.get('message_id'),
  388. 'answer': data.get('text'),
  389. 'created_at': int(time.time())
  390. }
  391. if data.get('mode') == 'chat':
  392. response_data['conversation_id'] = data.get('conversation_id')
  393. return response_data
  394. @classmethod
  395. def get_blocking_message_response_data(cls, data: dict):
  396. message = data.get('message')
  397. response_data = {
  398. 'event': 'message',
  399. 'task_id': message.get('task_id'),
  400. 'id': message.get('message_id'),
  401. 'answer': message.get('text'),
  402. 'metadata': {},
  403. 'created_at': int(time.time())
  404. }
  405. if message.get('mode') == 'chat':
  406. response_data['conversation_id'] = message.get('conversation_id')
  407. if 'message_end' in data:
  408. message_end = data.get('message_end')
  409. if 'retriever_resources' in message_end:
  410. response_data['metadata']['retriever_resources'] = message_end.get('retriever_resources')
  411. return response_data
  412. @classmethod
  413. def get_message_end_data(cls, data: dict):
  414. response_data = {
  415. 'event': 'message_end',
  416. 'task_id': data.get('task_id'),
  417. 'id': data.get('message_id')
  418. }
  419. if 'retriever_resources' in data:
  420. response_data['retriever_resources'] = data.get('retriever_resources')
  421. if data.get('mode') == 'chat':
  422. response_data['conversation_id'] = data.get('conversation_id')
  423. return response_data
  424. @classmethod
  425. def get_chain_response_data(cls, data: dict):
  426. response_data = {
  427. 'event': 'chain',
  428. 'id': data.get('chain_id'),
  429. 'task_id': data.get('task_id'),
  430. 'message_id': data.get('message_id'),
  431. 'type': data.get('type'),
  432. 'input': data.get('input'),
  433. 'output': data.get('output'),
  434. 'created_at': int(time.time())
  435. }
  436. if data.get('mode') == 'chat':
  437. response_data['conversation_id'] = data.get('conversation_id')
  438. return response_data
  439. @classmethod
  440. def get_agent_thought_response_data(cls, data: dict):
  441. response_data = {
  442. 'event': 'agent_thought',
  443. 'id': data.get('id'),
  444. 'chain_id': data.get('chain_id'),
  445. 'task_id': data.get('task_id'),
  446. 'message_id': data.get('message_id'),
  447. 'position': data.get('position'),
  448. 'thought': data.get('thought'),
  449. 'tool': data.get('tool'),
  450. 'tool_input': data.get('tool_input'),
  451. 'created_at': int(time.time())
  452. }
  453. if data.get('mode') == 'chat':
  454. response_data['conversation_id'] = data.get('conversation_id')
  455. return response_data
  456. @classmethod
  457. def handle_error(cls, result: dict):
  458. logging.debug("error: %s", result)
  459. error = result.get('error')
  460. description = result.get('description')
  461. # handle errors
  462. llm_errors = {
  463. 'ValueError': LLMBadRequestError,
  464. 'LLMBadRequestError': LLMBadRequestError,
  465. 'LLMAPIConnectionError': LLMAPIConnectionError,
  466. 'LLMAPIUnavailableError': LLMAPIUnavailableError,
  467. 'LLMRateLimitError': LLMRateLimitError,
  468. 'ProviderTokenNotInitError': ProviderTokenNotInitError,
  469. 'QuotaExceededError': QuotaExceededError,
  470. 'ModelCurrentlyNotSupportError': ModelCurrentlyNotSupportError
  471. }
  472. if error in llm_errors:
  473. raise llm_errors[error](description)
  474. elif error == 'LLMAuthorizationError':
  475. raise LLMAuthorizationError('Incorrect API key provided')
  476. else:
  477. raise Exception(description)