commands.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. import base64
  2. import json
  3. import secrets
  4. import click
  5. from flask import current_app
  6. from werkzeug.exceptions import NotFound
  7. from core.rag.datasource.vdb.vector_factory import Vector
  8. from core.rag.models.document import Document
  9. from extensions.ext_database import db
  10. from libs.helper import email as email_validate
  11. from libs.password import hash_password, password_pattern, valid_password
  12. from libs.rsa import generate_key_pair
  13. from models.account import Tenant
  14. from models.dataset import Dataset, DatasetCollectionBinding, DocumentSegment
  15. from models.dataset import Document as DatasetDocument
  16. from models.model import Account, App, AppAnnotationSetting, MessageAnnotation
  17. from models.provider import Provider, ProviderModel
  18. @click.command('reset-password', help='Reset the account password.')
  19. @click.option('--email', prompt=True, help='The email address of the account whose password you need to reset')
  20. @click.option('--new-password', prompt=True, help='the new password.')
  21. @click.option('--password-confirm', prompt=True, help='the new password confirm.')
  22. def reset_password(email, new_password, password_confirm):
  23. """
  24. Reset password of owner account
  25. Only available in SELF_HOSTED mode
  26. """
  27. if str(new_password).strip() != str(password_confirm).strip():
  28. click.echo(click.style('sorry. The two passwords do not match.', fg='red'))
  29. return
  30. account = db.session.query(Account). \
  31. filter(Account.email == email). \
  32. one_or_none()
  33. if not account:
  34. click.echo(click.style('sorry. the account: [{}] not exist .'.format(email), fg='red'))
  35. return
  36. try:
  37. valid_password(new_password)
  38. except:
  39. click.echo(
  40. click.style('sorry. The passwords must match {} '.format(password_pattern), fg='red'))
  41. return
  42. # generate password salt
  43. salt = secrets.token_bytes(16)
  44. base64_salt = base64.b64encode(salt).decode()
  45. # encrypt password with salt
  46. password_hashed = hash_password(new_password, salt)
  47. base64_password_hashed = base64.b64encode(password_hashed).decode()
  48. account.password = base64_password_hashed
  49. account.password_salt = base64_salt
  50. db.session.commit()
  51. click.echo(click.style('Congratulations!, password has been reset.', fg='green'))
  52. @click.command('reset-email', help='Reset the account email.')
  53. @click.option('--email', prompt=True, help='The old email address of the account whose email you need to reset')
  54. @click.option('--new-email', prompt=True, help='the new email.')
  55. @click.option('--email-confirm', prompt=True, help='the new email confirm.')
  56. def reset_email(email, new_email, email_confirm):
  57. """
  58. Replace account email
  59. :return:
  60. """
  61. if str(new_email).strip() != str(email_confirm).strip():
  62. click.echo(click.style('Sorry, new email and confirm email do not match.', fg='red'))
  63. return
  64. account = db.session.query(Account). \
  65. filter(Account.email == email). \
  66. one_or_none()
  67. if not account:
  68. click.echo(click.style('sorry. the account: [{}] not exist .'.format(email), fg='red'))
  69. return
  70. try:
  71. email_validate(new_email)
  72. except:
  73. click.echo(
  74. click.style('sorry. {} is not a valid email. '.format(email), fg='red'))
  75. return
  76. account.email = new_email
  77. db.session.commit()
  78. click.echo(click.style('Congratulations!, email has been reset.', fg='green'))
  79. @click.command('reset-encrypt-key-pair', help='Reset the asymmetric key pair of workspace for encrypt LLM credentials. '
  80. 'After the reset, all LLM credentials will become invalid, '
  81. 'requiring re-entry.'
  82. 'Only support SELF_HOSTED mode.')
  83. @click.confirmation_option(prompt=click.style('Are you sure you want to reset encrypt key pair?'
  84. ' this operation cannot be rolled back!', fg='red'))
  85. def reset_encrypt_key_pair():
  86. """
  87. Reset the encrypted key pair of workspace for encrypt LLM credentials.
  88. After the reset, all LLM credentials will become invalid, requiring re-entry.
  89. Only support SELF_HOSTED mode.
  90. """
  91. if current_app.config['EDITION'] != 'SELF_HOSTED':
  92. click.echo(click.style('Sorry, only support SELF_HOSTED mode.', fg='red'))
  93. return
  94. tenants = db.session.query(Tenant).all()
  95. for tenant in tenants:
  96. if not tenant:
  97. click.echo(click.style('Sorry, no workspace found. Please enter /install to initialize.', fg='red'))
  98. return
  99. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  100. db.session.query(Provider).filter(Provider.provider_type == 'custom', Provider.tenant_id == tenant.id).delete()
  101. db.session.query(ProviderModel).filter(ProviderModel.tenant_id == tenant.id).delete()
  102. db.session.commit()
  103. click.echo(click.style('Congratulations! '
  104. 'the asymmetric key pair of workspace {} has been reset.'.format(tenant.id), fg='green'))
  105. @click.command('vdb-migrate', help='migrate vector db.')
  106. @click.option('--scope', default='all', prompt=False, help='The scope of vector database to migrate, Default is All.')
  107. def vdb_migrate(scope: str):
  108. if scope in ['knowledge', 'all']:
  109. migrate_knowledge_vector_database()
  110. if scope in ['annotation', 'all']:
  111. migrate_annotation_vector_database()
  112. def migrate_annotation_vector_database():
  113. """
  114. Migrate annotation datas to target vector database .
  115. """
  116. click.echo(click.style('Start migrate annotation data.', fg='green'))
  117. create_count = 0
  118. skipped_count = 0
  119. total_count = 0
  120. page = 1
  121. while True:
  122. try:
  123. # get apps info
  124. apps = db.session.query(App).filter(
  125. App.status == 'normal'
  126. ).order_by(App.created_at.desc()).paginate(page=page, per_page=50)
  127. except NotFound:
  128. break
  129. page += 1
  130. for app in apps:
  131. total_count = total_count + 1
  132. click.echo(f'Processing the {total_count} app {app.id}. '
  133. + f'{create_count} created, {skipped_count} skipped.')
  134. try:
  135. click.echo('Create app annotation index: {}'.format(app.id))
  136. app_annotation_setting = db.session.query(AppAnnotationSetting).filter(
  137. AppAnnotationSetting.app_id == app.id
  138. ).first()
  139. if not app_annotation_setting:
  140. skipped_count = skipped_count + 1
  141. click.echo('App annotation setting is disabled: {}'.format(app.id))
  142. continue
  143. # get dataset_collection_binding info
  144. dataset_collection_binding = db.session.query(DatasetCollectionBinding).filter(
  145. DatasetCollectionBinding.id == app_annotation_setting.collection_binding_id
  146. ).first()
  147. if not dataset_collection_binding:
  148. click.echo('App annotation collection binding is not exist: {}'.format(app.id))
  149. continue
  150. annotations = db.session.query(MessageAnnotation).filter(MessageAnnotation.app_id == app.id).all()
  151. dataset = Dataset(
  152. id=app.id,
  153. tenant_id=app.tenant_id,
  154. indexing_technique='high_quality',
  155. embedding_model_provider=dataset_collection_binding.provider_name,
  156. embedding_model=dataset_collection_binding.model_name,
  157. collection_binding_id=dataset_collection_binding.id
  158. )
  159. documents = []
  160. if annotations:
  161. for annotation in annotations:
  162. document = Document(
  163. page_content=annotation.question,
  164. metadata={
  165. "annotation_id": annotation.id,
  166. "app_id": app.id,
  167. "doc_id": annotation.id
  168. }
  169. )
  170. documents.append(document)
  171. vector = Vector(dataset, attributes=['doc_id', 'annotation_id', 'app_id'])
  172. click.echo(f"Start to migrate annotation, app_id: {app.id}.")
  173. try:
  174. vector.delete()
  175. click.echo(
  176. click.style(f'Successfully delete vector index for app: {app.id}.',
  177. fg='green'))
  178. except Exception as e:
  179. click.echo(
  180. click.style(f'Failed to delete vector index for app {app.id}.',
  181. fg='red'))
  182. raise e
  183. if documents:
  184. try:
  185. click.echo(click.style(
  186. f'Start to created vector index with {len(documents)} annotations for app {app.id}.',
  187. fg='green'))
  188. vector.create(documents)
  189. click.echo(
  190. click.style(f'Successfully created vector index for app {app.id}.', fg='green'))
  191. except Exception as e:
  192. click.echo(click.style(f'Failed to created vector index for app {app.id}.', fg='red'))
  193. raise e
  194. click.echo(f'Successfully migrated app annotation {app.id}.')
  195. create_count += 1
  196. except Exception as e:
  197. click.echo(
  198. click.style('Create app annotation index error: {} {}'.format(e.__class__.__name__, str(e)),
  199. fg='red'))
  200. continue
  201. click.echo(
  202. click.style(f'Congratulations! Create {create_count} app annotation indexes, and skipped {skipped_count} apps.',
  203. fg='green'))
  204. def migrate_knowledge_vector_database():
  205. """
  206. Migrate vector database datas to target vector database .
  207. """
  208. click.echo(click.style('Start migrate vector db.', fg='green'))
  209. create_count = 0
  210. skipped_count = 0
  211. total_count = 0
  212. config = current_app.config
  213. vector_type = config.get('VECTOR_STORE')
  214. page = 1
  215. while True:
  216. try:
  217. datasets = db.session.query(Dataset).filter(Dataset.indexing_technique == 'high_quality') \
  218. .order_by(Dataset.created_at.desc()).paginate(page=page, per_page=50)
  219. except NotFound:
  220. break
  221. page += 1
  222. for dataset in datasets:
  223. total_count = total_count + 1
  224. click.echo(f'Processing the {total_count} dataset {dataset.id}. '
  225. + f'{create_count} created, {skipped_count} skipped.')
  226. try:
  227. click.echo('Create dataset vdb index: {}'.format(dataset.id))
  228. if dataset.index_struct_dict:
  229. if dataset.index_struct_dict['type'] == vector_type:
  230. skipped_count = skipped_count + 1
  231. continue
  232. collection_name = ''
  233. if vector_type == "weaviate":
  234. dataset_id = dataset.id
  235. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  236. index_struct_dict = {
  237. "type": 'weaviate',
  238. "vector_store": {"class_prefix": collection_name}
  239. }
  240. dataset.index_struct = json.dumps(index_struct_dict)
  241. elif vector_type == "qdrant":
  242. if dataset.collection_binding_id:
  243. dataset_collection_binding = db.session.query(DatasetCollectionBinding). \
  244. filter(DatasetCollectionBinding.id == dataset.collection_binding_id). \
  245. one_or_none()
  246. if dataset_collection_binding:
  247. collection_name = dataset_collection_binding.collection_name
  248. else:
  249. raise ValueError('Dataset Collection Bindings is not exist!')
  250. else:
  251. dataset_id = dataset.id
  252. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  253. index_struct_dict = {
  254. "type": 'qdrant',
  255. "vector_store": {"class_prefix": collection_name}
  256. }
  257. dataset.index_struct = json.dumps(index_struct_dict)
  258. elif vector_type == "milvus":
  259. dataset_id = dataset.id
  260. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  261. index_struct_dict = {
  262. "type": 'milvus',
  263. "vector_store": {"class_prefix": collection_name}
  264. }
  265. dataset.index_struct = json.dumps(index_struct_dict)
  266. else:
  267. raise ValueError(f"Vector store {config.get('VECTOR_STORE')} is not supported.")
  268. vector = Vector(dataset)
  269. click.echo(f"Start to migrate dataset {dataset.id}.")
  270. try:
  271. vector.delete()
  272. click.echo(
  273. click.style(f'Successfully delete vector index {collection_name} for dataset {dataset.id}.',
  274. fg='green'))
  275. except Exception as e:
  276. click.echo(
  277. click.style(f'Failed to delete vector index {collection_name} for dataset {dataset.id}.',
  278. fg='red'))
  279. raise e
  280. dataset_documents = db.session.query(DatasetDocument).filter(
  281. DatasetDocument.dataset_id == dataset.id,
  282. DatasetDocument.indexing_status == 'completed',
  283. DatasetDocument.enabled == True,
  284. DatasetDocument.archived == False,
  285. ).all()
  286. documents = []
  287. segments_count = 0
  288. for dataset_document in dataset_documents:
  289. segments = db.session.query(DocumentSegment).filter(
  290. DocumentSegment.document_id == dataset_document.id,
  291. DocumentSegment.status == 'completed',
  292. DocumentSegment.enabled == True
  293. ).all()
  294. for segment in segments:
  295. document = Document(
  296. page_content=segment.content,
  297. metadata={
  298. "doc_id": segment.index_node_id,
  299. "doc_hash": segment.index_node_hash,
  300. "document_id": segment.document_id,
  301. "dataset_id": segment.dataset_id,
  302. }
  303. )
  304. documents.append(document)
  305. segments_count = segments_count + 1
  306. if documents:
  307. try:
  308. click.echo(click.style(
  309. f'Start to created vector index with {len(documents)} documents of {segments_count} segments for dataset {dataset.id}.',
  310. fg='green'))
  311. vector.create(documents)
  312. click.echo(
  313. click.style(f'Successfully created vector index for dataset {dataset.id}.', fg='green'))
  314. except Exception as e:
  315. click.echo(click.style(f'Failed to created vector index for dataset {dataset.id}.', fg='red'))
  316. raise e
  317. db.session.add(dataset)
  318. db.session.commit()
  319. click.echo(f'Successfully migrated dataset {dataset.id}.')
  320. create_count += 1
  321. except Exception as e:
  322. db.session.rollback()
  323. click.echo(
  324. click.style('Create dataset index error: {} {}'.format(e.__class__.__name__, str(e)),
  325. fg='red'))
  326. continue
  327. click.echo(
  328. click.style(f'Congratulations! Create {create_count} dataset indexes, and skipped {skipped_count} datasets.',
  329. fg='green'))
  330. def register_commands(app):
  331. app.cli.add_command(reset_password)
  332. app.cli.add_command(reset_email)
  333. app.cli.add_command(reset_encrypt_key_pair)
  334. app.cli.add_command(vdb_migrate)