completion_service.py 21 KB

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