completion_service.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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.remove()
  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. try:
  202. user = db.session.merge(detached_user)
  203. sleep_iterations = 0
  204. while sleep_iterations < timeout and worker_thread.is_alive():
  205. if sleep_iterations > 0 and sleep_iterations % 10 == 0:
  206. PubHandler.ping(user, generate_task_id)
  207. time.sleep(1)
  208. sleep_iterations += 1
  209. if worker_thread.is_alive():
  210. PubHandler.stop(user, generate_task_id)
  211. try:
  212. pubsub.close()
  213. except Exception:
  214. pass
  215. finally:
  216. db.session.remove()
  217. countdown_thread = threading.Thread(target=close_pubsub)
  218. countdown_thread.start()
  219. return countdown_thread
  220. @classmethod
  221. def generate_more_like_this(cls, app_model: App, user: Union[Account, EndUser],
  222. message_id: str, streaming: bool = True,
  223. retriever_from: str = 'dev') -> Union[dict, Generator]:
  224. if not user:
  225. raise ValueError('user cannot be None')
  226. message = db.session.query(Message).filter(
  227. Message.id == message_id,
  228. Message.app_id == app_model.id,
  229. Message.from_source == ('api' if isinstance(user, EndUser) else 'console'),
  230. Message.from_end_user_id == (user.id if isinstance(user, EndUser) else None),
  231. Message.from_account_id == (user.id if isinstance(user, Account) else None),
  232. ).first()
  233. if not message:
  234. raise MessageNotExistsError()
  235. current_app_model_config = app_model.app_model_config
  236. more_like_this = current_app_model_config.more_like_this_dict
  237. if not current_app_model_config.more_like_this or more_like_this.get("enabled", False) is False:
  238. raise MoreLikeThisDisabledError()
  239. app_model_config = message.app_model_config
  240. model_dict = app_model_config.model_dict
  241. completion_params = model_dict.get('completion_params')
  242. completion_params['temperature'] = 0.9
  243. model_dict['completion_params'] = completion_params
  244. app_model_config.model = json.dumps(model_dict)
  245. # parse files
  246. message_file_parser = MessageFileParser(tenant_id=app_model.tenant_id, app_id=app_model.id)
  247. file_objs = message_file_parser.transform_message_files(
  248. message.files, app_model_config
  249. )
  250. generate_task_id = str(uuid.uuid4())
  251. pubsub = redis_client.pubsub()
  252. pubsub.subscribe(PubHandler.generate_channel_name(user, generate_task_id))
  253. user = cls.get_real_user_instead_of_proxy_obj(user)
  254. generate_worker_thread = threading.Thread(target=cls.generate_worker, kwargs={
  255. 'flask_app': current_app._get_current_object(),
  256. 'generate_task_id': generate_task_id,
  257. 'detached_app_model': app_model,
  258. 'app_model_config': app_model_config.copy(),
  259. 'query': message.query,
  260. 'inputs': message.inputs,
  261. 'files': file_objs,
  262. 'detached_user': user,
  263. 'detached_conversation': None,
  264. 'streaming': streaming,
  265. 'is_model_config_override': True,
  266. 'retriever_from': retriever_from,
  267. 'auto_generate_name': False
  268. })
  269. generate_worker_thread.start()
  270. # wait for 10 minutes to close the thread
  271. cls.countdown_and_close(current_app._get_current_object(), generate_worker_thread, pubsub, user,
  272. generate_task_id)
  273. return cls.compact_response(pubsub, streaming)
  274. @classmethod
  275. def get_cleaned_inputs(cls, user_inputs: dict, app_model_config: AppModelConfig):
  276. if user_inputs is None:
  277. user_inputs = {}
  278. filtered_inputs = {}
  279. # Filter input variables from form configuration, handle required fields, default values, and option values
  280. input_form_config = app_model_config.user_input_form_list
  281. for config in input_form_config:
  282. input_config = list(config.values())[0]
  283. variable = input_config["variable"]
  284. input_type = list(config.keys())[0]
  285. if variable not in user_inputs or not user_inputs[variable]:
  286. if "required" in input_config and input_config["required"]:
  287. raise ValueError(f"{variable} is required in input form")
  288. else:
  289. filtered_inputs[variable] = input_config["default"] if "default" in input_config else ""
  290. continue
  291. value = user_inputs[variable]
  292. if input_type == "select":
  293. options = input_config["options"] if "options" in input_config else []
  294. if value not in options:
  295. raise ValueError(f"{variable} in input form must be one of the following: {options}")
  296. else:
  297. if 'max_length' in input_config:
  298. max_length = input_config['max_length']
  299. if len(value) > max_length:
  300. raise ValueError(f'{variable} in input form must be less than {max_length} characters')
  301. filtered_inputs[variable] = value.replace('\x00', '') if value else None
  302. return filtered_inputs
  303. @classmethod
  304. def compact_response(cls, pubsub: PubSub, streaming: bool = False) -> Union[dict, Generator]:
  305. generate_channel = list(pubsub.channels.keys())[0].decode('utf-8')
  306. if not streaming:
  307. try:
  308. message_result = {}
  309. for message in pubsub.listen():
  310. if message["type"] == "message":
  311. result = message["data"].decode('utf-8')
  312. result = json.loads(result)
  313. if result.get('error'):
  314. cls.handle_error(result)
  315. if result['event'] == 'message' and 'data' in result:
  316. message_result['message'] = result.get('data')
  317. if result['event'] == 'message_end' and 'data' in result:
  318. message_result['message_end'] = result.get('data')
  319. return cls.get_blocking_message_response_data(message_result)
  320. except ValueError as e:
  321. if e.args[0] != "I/O operation on closed file.": # ignore this error
  322. raise CompletionStoppedError()
  323. else:
  324. logging.exception(e)
  325. raise
  326. finally:
  327. db.session.remove()
  328. try:
  329. pubsub.unsubscribe(generate_channel)
  330. except ConnectionError:
  331. pass
  332. else:
  333. def generate() -> Generator:
  334. try:
  335. for message in pubsub.listen():
  336. if message["type"] == "message":
  337. result = message["data"].decode('utf-8')
  338. result = json.loads(result)
  339. if result.get('error'):
  340. cls.handle_error(result)
  341. event = result.get('event')
  342. if event == "end":
  343. logging.debug("{} finished".format(generate_channel))
  344. break
  345. if event == 'message':
  346. yield "data: " + json.dumps(cls.get_message_response_data(result.get('data'))) + "\n\n"
  347. elif event == 'message_replace':
  348. yield "data: " + json.dumps(
  349. cls.get_message_replace_response_data(result.get('data'))) + "\n\n"
  350. elif event == 'chain':
  351. yield "data: " + json.dumps(cls.get_chain_response_data(result.get('data'))) + "\n\n"
  352. elif event == 'agent_thought':
  353. yield "data: " + json.dumps(
  354. cls.get_agent_thought_response_data(result.get('data'))) + "\n\n"
  355. elif event == 'message_end':
  356. yield "data: " + json.dumps(
  357. cls.get_message_end_data(result.get('data'))) + "\n\n"
  358. elif event == 'ping':
  359. yield "event: ping\n\n"
  360. else:
  361. yield "data: " + json.dumps(result) + "\n\n"
  362. except ValueError as e:
  363. if e.args[0] != "I/O operation on closed file.": # ignore this error
  364. logging.exception(e)
  365. raise
  366. finally:
  367. db.session.remove()
  368. try:
  369. pubsub.unsubscribe(generate_channel)
  370. except ConnectionError:
  371. pass
  372. return generate()
  373. @classmethod
  374. def get_message_response_data(cls, data: dict):
  375. response_data = {
  376. 'event': 'message',
  377. 'task_id': data.get('task_id'),
  378. 'id': data.get('message_id'),
  379. 'answer': data.get('text'),
  380. 'created_at': int(time.time())
  381. }
  382. if data.get('mode') == 'chat':
  383. response_data['conversation_id'] = data.get('conversation_id')
  384. return response_data
  385. @classmethod
  386. def get_message_replace_response_data(cls, data: dict):
  387. response_data = {
  388. 'event': 'message_replace',
  389. 'task_id': data.get('task_id'),
  390. 'id': data.get('message_id'),
  391. 'answer': data.get('text'),
  392. 'created_at': int(time.time())
  393. }
  394. if data.get('mode') == 'chat':
  395. response_data['conversation_id'] = data.get('conversation_id')
  396. return response_data
  397. @classmethod
  398. def get_blocking_message_response_data(cls, data: dict):
  399. message = data.get('message')
  400. response_data = {
  401. 'event': 'message',
  402. 'task_id': message.get('task_id'),
  403. 'id': message.get('message_id'),
  404. 'answer': message.get('text'),
  405. 'metadata': {},
  406. 'created_at': int(time.time())
  407. }
  408. if message.get('mode') == 'chat':
  409. response_data['conversation_id'] = message.get('conversation_id')
  410. if 'message_end' in data:
  411. message_end = data.get('message_end')
  412. if 'retriever_resources' in message_end:
  413. response_data['metadata']['retriever_resources'] = message_end.get('retriever_resources')
  414. return response_data
  415. @classmethod
  416. def get_message_end_data(cls, data: dict):
  417. response_data = {
  418. 'event': 'message_end',
  419. 'task_id': data.get('task_id'),
  420. 'id': data.get('message_id')
  421. }
  422. if 'retriever_resources' in data:
  423. response_data['retriever_resources'] = data.get('retriever_resources')
  424. if data.get('mode') == 'chat':
  425. response_data['conversation_id'] = data.get('conversation_id')
  426. return response_data
  427. @classmethod
  428. def get_chain_response_data(cls, data: dict):
  429. response_data = {
  430. 'event': 'chain',
  431. 'id': data.get('chain_id'),
  432. 'task_id': data.get('task_id'),
  433. 'message_id': data.get('message_id'),
  434. 'type': data.get('type'),
  435. 'input': data.get('input'),
  436. 'output': data.get('output'),
  437. 'created_at': int(time.time())
  438. }
  439. if data.get('mode') == 'chat':
  440. response_data['conversation_id'] = data.get('conversation_id')
  441. return response_data
  442. @classmethod
  443. def get_agent_thought_response_data(cls, data: dict):
  444. response_data = {
  445. 'event': 'agent_thought',
  446. 'id': data.get('id'),
  447. 'chain_id': data.get('chain_id'),
  448. 'task_id': data.get('task_id'),
  449. 'message_id': data.get('message_id'),
  450. 'position': data.get('position'),
  451. 'thought': data.get('thought'),
  452. 'tool': data.get('tool'),
  453. 'tool_input': data.get('tool_input'),
  454. 'created_at': int(time.time())
  455. }
  456. if data.get('mode') == 'chat':
  457. response_data['conversation_id'] = data.get('conversation_id')
  458. return response_data
  459. @classmethod
  460. def handle_error(cls, result: dict):
  461. logging.debug("error: %s", result)
  462. error = result.get('error')
  463. description = result.get('description')
  464. # handle errors
  465. llm_errors = {
  466. 'ValueError': LLMBadRequestError,
  467. 'LLMBadRequestError': LLMBadRequestError,
  468. 'LLMAPIConnectionError': LLMAPIConnectionError,
  469. 'LLMAPIUnavailableError': LLMAPIUnavailableError,
  470. 'LLMRateLimitError': LLMRateLimitError,
  471. 'ProviderTokenNotInitError': ProviderTokenNotInitError,
  472. 'QuotaExceededError': QuotaExceededError,
  473. 'ModelCurrentlyNotSupportError': ModelCurrentlyNotSupportError
  474. }
  475. if error in llm_errors:
  476. raise llm_errors[error](description)
  477. elif error == 'LLMAuthorizationError':
  478. raise LLMAuthorizationError('Incorrect API key provided')
  479. else:
  480. raise Exception(description)