commands.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. import base64
  2. import json
  3. import logging
  4. import secrets
  5. from typing import Optional
  6. import click
  7. from flask import current_app
  8. from werkzeug.exceptions import NotFound
  9. from constants.languages import languages
  10. from core.rag.datasource.vdb.vector_factory import Vector
  11. from core.rag.datasource.vdb.vector_type import VectorType
  12. from core.rag.models.document import Document
  13. from extensions.ext_database import db
  14. from extensions.ext_redis import redis_client
  15. from libs.helper import email as email_validate
  16. from libs.password import hash_password, password_pattern, valid_password
  17. from libs.rsa import generate_key_pair
  18. from models.account import Tenant
  19. from models.dataset import Dataset, DatasetCollectionBinding, DocumentSegment
  20. from models.dataset import Document as DatasetDocument
  21. from models.model import Account, App, AppAnnotationSetting, AppMode, Conversation, MessageAnnotation
  22. from models.provider import Provider, ProviderModel
  23. from services.account_service import RegisterService, TenantService
  24. @click.command('reset-password', help='Reset the account password.')
  25. @click.option('--email', prompt=True, help='The email address of the account whose password you need to reset')
  26. @click.option('--new-password', prompt=True, help='the new password.')
  27. @click.option('--password-confirm', prompt=True, help='the new password confirm.')
  28. def reset_password(email, new_password, password_confirm):
  29. """
  30. Reset password of owner account
  31. Only available in SELF_HOSTED mode
  32. """
  33. if str(new_password).strip() != str(password_confirm).strip():
  34. click.echo(click.style('sorry. The two passwords do not match.', fg='red'))
  35. return
  36. account = db.session.query(Account). \
  37. filter(Account.email == email). \
  38. one_or_none()
  39. if not account:
  40. click.echo(click.style('sorry. the account: [{}] not exist .'.format(email), fg='red'))
  41. return
  42. try:
  43. valid_password(new_password)
  44. except:
  45. click.echo(
  46. click.style('sorry. The passwords must match {} '.format(password_pattern), fg='red'))
  47. return
  48. # generate password salt
  49. salt = secrets.token_bytes(16)
  50. base64_salt = base64.b64encode(salt).decode()
  51. # encrypt password with salt
  52. password_hashed = hash_password(new_password, salt)
  53. base64_password_hashed = base64.b64encode(password_hashed).decode()
  54. account.password = base64_password_hashed
  55. account.password_salt = base64_salt
  56. db.session.commit()
  57. click.echo(click.style('Congratulations! Password has been reset.', fg='green'))
  58. @click.command('reset-email', help='Reset the account email.')
  59. @click.option('--email', prompt=True, help='The old email address of the account whose email you need to reset')
  60. @click.option('--new-email', prompt=True, help='the new email.')
  61. @click.option('--email-confirm', prompt=True, help='the new email confirm.')
  62. def reset_email(email, new_email, email_confirm):
  63. """
  64. Replace account email
  65. :return:
  66. """
  67. if str(new_email).strip() != str(email_confirm).strip():
  68. click.echo(click.style('Sorry, new email and confirm email do not match.', fg='red'))
  69. return
  70. account = db.session.query(Account). \
  71. filter(Account.email == email). \
  72. one_or_none()
  73. if not account:
  74. click.echo(click.style('sorry. the account: [{}] not exist .'.format(email), fg='red'))
  75. return
  76. try:
  77. email_validate(new_email)
  78. except:
  79. click.echo(
  80. click.style('sorry. {} is not a valid email. '.format(email), fg='red'))
  81. return
  82. account.email = new_email
  83. db.session.commit()
  84. click.echo(click.style('Congratulations!, email has been reset.', fg='green'))
  85. @click.command('reset-encrypt-key-pair', help='Reset the asymmetric key pair of workspace for encrypt LLM credentials. '
  86. 'After the reset, all LLM credentials will become invalid, '
  87. 'requiring re-entry.'
  88. 'Only support SELF_HOSTED mode.')
  89. @click.confirmation_option(prompt=click.style('Are you sure you want to reset encrypt key pair?'
  90. ' this operation cannot be rolled back!', fg='red'))
  91. def reset_encrypt_key_pair():
  92. """
  93. Reset the encrypted key pair of workspace for encrypt LLM credentials.
  94. After the reset, all LLM credentials will become invalid, requiring re-entry.
  95. Only support SELF_HOSTED mode.
  96. """
  97. if current_app.config['EDITION'] != 'SELF_HOSTED':
  98. click.echo(click.style('Sorry, only support SELF_HOSTED mode.', fg='red'))
  99. return
  100. tenants = db.session.query(Tenant).all()
  101. for tenant in tenants:
  102. if not tenant:
  103. click.echo(click.style('Sorry, no workspace found. Please enter /install to initialize.', fg='red'))
  104. return
  105. tenant.encrypt_public_key = generate_key_pair(tenant.id)
  106. db.session.query(Provider).filter(Provider.provider_type == 'custom', Provider.tenant_id == tenant.id).delete()
  107. db.session.query(ProviderModel).filter(ProviderModel.tenant_id == tenant.id).delete()
  108. db.session.commit()
  109. click.echo(click.style('Congratulations! '
  110. 'the asymmetric key pair of workspace {} has been reset.'.format(tenant.id), fg='green'))
  111. @click.command('vdb-migrate', help='migrate vector db.')
  112. @click.option('--scope', default='all', prompt=False, help='The scope of vector database to migrate, Default is All.')
  113. def vdb_migrate(scope: str):
  114. if scope in ['knowledge', 'all']:
  115. migrate_knowledge_vector_database()
  116. if scope in ['annotation', 'all']:
  117. migrate_annotation_vector_database()
  118. def migrate_annotation_vector_database():
  119. """
  120. Migrate annotation datas to target vector database .
  121. """
  122. click.echo(click.style('Start migrate annotation data.', fg='green'))
  123. create_count = 0
  124. skipped_count = 0
  125. total_count = 0
  126. page = 1
  127. while True:
  128. try:
  129. # get apps info
  130. apps = db.session.query(App).filter(
  131. App.status == 'normal'
  132. ).order_by(App.created_at.desc()).paginate(page=page, per_page=50)
  133. except NotFound:
  134. break
  135. page += 1
  136. for app in apps:
  137. total_count = total_count + 1
  138. click.echo(f'Processing the {total_count} app {app.id}. '
  139. + f'{create_count} created, {skipped_count} skipped.')
  140. try:
  141. click.echo('Create app annotation index: {}'.format(app.id))
  142. app_annotation_setting = db.session.query(AppAnnotationSetting).filter(
  143. AppAnnotationSetting.app_id == app.id
  144. ).first()
  145. if not app_annotation_setting:
  146. skipped_count = skipped_count + 1
  147. click.echo('App annotation setting is disabled: {}'.format(app.id))
  148. continue
  149. # get dataset_collection_binding info
  150. dataset_collection_binding = db.session.query(DatasetCollectionBinding).filter(
  151. DatasetCollectionBinding.id == app_annotation_setting.collection_binding_id
  152. ).first()
  153. if not dataset_collection_binding:
  154. click.echo('App annotation collection binding is not exist: {}'.format(app.id))
  155. continue
  156. annotations = db.session.query(MessageAnnotation).filter(MessageAnnotation.app_id == app.id).all()
  157. dataset = Dataset(
  158. id=app.id,
  159. tenant_id=app.tenant_id,
  160. indexing_technique='high_quality',
  161. embedding_model_provider=dataset_collection_binding.provider_name,
  162. embedding_model=dataset_collection_binding.model_name,
  163. collection_binding_id=dataset_collection_binding.id
  164. )
  165. documents = []
  166. if annotations:
  167. for annotation in annotations:
  168. document = Document(
  169. page_content=annotation.question,
  170. metadata={
  171. "annotation_id": annotation.id,
  172. "app_id": app.id,
  173. "doc_id": annotation.id
  174. }
  175. )
  176. documents.append(document)
  177. vector = Vector(dataset, attributes=['doc_id', 'annotation_id', 'app_id'])
  178. click.echo(f"Start to migrate annotation, app_id: {app.id}.")
  179. try:
  180. vector.delete()
  181. click.echo(
  182. click.style(f'Successfully delete vector index for app: {app.id}.',
  183. fg='green'))
  184. except Exception as e:
  185. click.echo(
  186. click.style(f'Failed to delete vector index for app {app.id}.',
  187. fg='red'))
  188. raise e
  189. if documents:
  190. try:
  191. click.echo(click.style(
  192. f'Start to created vector index with {len(documents)} annotations for app {app.id}.',
  193. fg='green'))
  194. vector.create(documents)
  195. click.echo(
  196. click.style(f'Successfully created vector index for app {app.id}.', fg='green'))
  197. except Exception as e:
  198. click.echo(click.style(f'Failed to created vector index for app {app.id}.', fg='red'))
  199. raise e
  200. click.echo(f'Successfully migrated app annotation {app.id}.')
  201. create_count += 1
  202. except Exception as e:
  203. click.echo(
  204. click.style('Create app annotation index error: {} {}'.format(e.__class__.__name__, str(e)),
  205. fg='red'))
  206. continue
  207. click.echo(
  208. click.style(f'Congratulations! Create {create_count} app annotation indexes, and skipped {skipped_count} apps.',
  209. fg='green'))
  210. def migrate_knowledge_vector_database():
  211. """
  212. Migrate vector database datas to target vector database .
  213. """
  214. click.echo(click.style('Start migrate vector db.', fg='green'))
  215. create_count = 0
  216. skipped_count = 0
  217. total_count = 0
  218. config = current_app.config
  219. vector_type = config.get('VECTOR_STORE')
  220. page = 1
  221. while True:
  222. try:
  223. datasets = db.session.query(Dataset).filter(Dataset.indexing_technique == 'high_quality') \
  224. .order_by(Dataset.created_at.desc()).paginate(page=page, per_page=50)
  225. except NotFound:
  226. break
  227. page += 1
  228. for dataset in datasets:
  229. total_count = total_count + 1
  230. click.echo(f'Processing the {total_count} dataset {dataset.id}. '
  231. + f'{create_count} created, {skipped_count} skipped.')
  232. try:
  233. click.echo('Create dataset vdb index: {}'.format(dataset.id))
  234. if dataset.index_struct_dict:
  235. if dataset.index_struct_dict['type'] == vector_type:
  236. skipped_count = skipped_count + 1
  237. continue
  238. collection_name = ''
  239. if vector_type == VectorType.WEAVIATE:
  240. dataset_id = dataset.id
  241. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  242. index_struct_dict = {
  243. "type": VectorType.WEAVIATE,
  244. "vector_store": {"class_prefix": collection_name}
  245. }
  246. dataset.index_struct = json.dumps(index_struct_dict)
  247. elif vector_type == VectorType.QDRANT:
  248. if dataset.collection_binding_id:
  249. dataset_collection_binding = db.session.query(DatasetCollectionBinding). \
  250. filter(DatasetCollectionBinding.id == dataset.collection_binding_id). \
  251. one_or_none()
  252. if dataset_collection_binding:
  253. collection_name = dataset_collection_binding.collection_name
  254. else:
  255. raise ValueError('Dataset Collection Bindings is not exist!')
  256. else:
  257. dataset_id = dataset.id
  258. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  259. index_struct_dict = {
  260. "type": VectorType.QDRANT,
  261. "vector_store": {"class_prefix": collection_name}
  262. }
  263. dataset.index_struct = json.dumps(index_struct_dict)
  264. elif vector_type == VectorType.MILVUS:
  265. dataset_id = dataset.id
  266. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  267. index_struct_dict = {
  268. "type": VectorType.MILVUS,
  269. "vector_store": {"class_prefix": collection_name}
  270. }
  271. dataset.index_struct = json.dumps(index_struct_dict)
  272. elif vector_type == VectorType.RELYT:
  273. dataset_id = dataset.id
  274. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  275. index_struct_dict = {
  276. "type": 'relyt',
  277. "vector_store": {"class_prefix": collection_name}
  278. }
  279. dataset.index_struct = json.dumps(index_struct_dict)
  280. elif vector_type == VectorType.TENCENT:
  281. dataset_id = dataset.id
  282. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  283. index_struct_dict = {
  284. "type": VectorType.TENCENT,
  285. "vector_store": {"class_prefix": collection_name}
  286. }
  287. dataset.index_struct = json.dumps(index_struct_dict)
  288. elif vector_type == VectorType.PGVECTOR:
  289. dataset_id = dataset.id
  290. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  291. index_struct_dict = {
  292. "type": VectorType.PGVECTOR,
  293. "vector_store": {"class_prefix": collection_name}
  294. }
  295. dataset.index_struct = json.dumps(index_struct_dict)
  296. elif vector_type == VectorType.OPENSEARCH:
  297. dataset_id = dataset.id
  298. collection_name = Dataset.gen_collection_name_by_id(dataset_id)
  299. index_struct_dict = {
  300. "type": VectorType.OPENSEARCH,
  301. "vector_store": {"class_prefix": collection_name}
  302. }
  303. dataset.index_struct = json.dumps(index_struct_dict)
  304. else:
  305. raise ValueError(f"Vector store {vector_type} is not supported.")
  306. vector = Vector(dataset)
  307. click.echo(f"Start to migrate dataset {dataset.id}.")
  308. try:
  309. vector.delete()
  310. click.echo(
  311. click.style(f'Successfully delete vector index {collection_name} for dataset {dataset.id}.',
  312. fg='green'))
  313. except Exception as e:
  314. click.echo(
  315. click.style(f'Failed to delete vector index {collection_name} for dataset {dataset.id}.',
  316. fg='red'))
  317. raise e
  318. dataset_documents = db.session.query(DatasetDocument).filter(
  319. DatasetDocument.dataset_id == dataset.id,
  320. DatasetDocument.indexing_status == 'completed',
  321. DatasetDocument.enabled == True,
  322. DatasetDocument.archived == False,
  323. ).all()
  324. documents = []
  325. segments_count = 0
  326. for dataset_document in dataset_documents:
  327. segments = db.session.query(DocumentSegment).filter(
  328. DocumentSegment.document_id == dataset_document.id,
  329. DocumentSegment.status == 'completed',
  330. DocumentSegment.enabled == True
  331. ).all()
  332. for segment in segments:
  333. document = Document(
  334. page_content=segment.content,
  335. metadata={
  336. "doc_id": segment.index_node_id,
  337. "doc_hash": segment.index_node_hash,
  338. "document_id": segment.document_id,
  339. "dataset_id": segment.dataset_id,
  340. }
  341. )
  342. documents.append(document)
  343. segments_count = segments_count + 1
  344. if documents:
  345. try:
  346. click.echo(click.style(
  347. f'Start to created vector index with {len(documents)} documents of {segments_count} segments for dataset {dataset.id}.',
  348. fg='green'))
  349. vector.create(documents)
  350. click.echo(
  351. click.style(f'Successfully created vector index for dataset {dataset.id}.', fg='green'))
  352. except Exception as e:
  353. click.echo(click.style(f'Failed to created vector index for dataset {dataset.id}.', fg='red'))
  354. raise e
  355. db.session.add(dataset)
  356. db.session.commit()
  357. click.echo(f'Successfully migrated dataset {dataset.id}.')
  358. create_count += 1
  359. except Exception as e:
  360. db.session.rollback()
  361. click.echo(
  362. click.style('Create dataset index error: {} {}'.format(e.__class__.__name__, str(e)),
  363. fg='red'))
  364. continue
  365. click.echo(
  366. click.style(f'Congratulations! Create {create_count} dataset indexes, and skipped {skipped_count} datasets.',
  367. fg='green'))
  368. @click.command('convert-to-agent-apps', help='Convert Agent Assistant to Agent App.')
  369. def convert_to_agent_apps():
  370. """
  371. Convert Agent Assistant to Agent App.
  372. """
  373. click.echo(click.style('Start convert to agent apps.', fg='green'))
  374. proceeded_app_ids = []
  375. while True:
  376. # fetch first 1000 apps
  377. sql_query = """SELECT a.id AS id FROM apps a
  378. INNER JOIN app_model_configs am ON a.app_model_config_id=am.id
  379. WHERE a.mode = 'chat'
  380. AND am.agent_mode is not null
  381. AND (
  382. am.agent_mode like '%"strategy": "function_call"%'
  383. OR am.agent_mode like '%"strategy": "react"%'
  384. )
  385. AND (
  386. am.agent_mode like '{"enabled": true%'
  387. OR am.agent_mode like '{"max_iteration": %'
  388. ) ORDER BY a.created_at DESC LIMIT 1000
  389. """
  390. with db.engine.begin() as conn:
  391. rs = conn.execute(db.text(sql_query))
  392. apps = []
  393. for i in rs:
  394. app_id = str(i.id)
  395. if app_id not in proceeded_app_ids:
  396. proceeded_app_ids.append(app_id)
  397. app = db.session.query(App).filter(App.id == app_id).first()
  398. apps.append(app)
  399. if len(apps) == 0:
  400. break
  401. for app in apps:
  402. click.echo('Converting app: {}'.format(app.id))
  403. try:
  404. app.mode = AppMode.AGENT_CHAT.value
  405. db.session.commit()
  406. # update conversation mode to agent
  407. db.session.query(Conversation).filter(Conversation.app_id == app.id).update(
  408. {Conversation.mode: AppMode.AGENT_CHAT.value}
  409. )
  410. db.session.commit()
  411. click.echo(click.style('Converted app: {}'.format(app.id), fg='green'))
  412. except Exception as e:
  413. click.echo(
  414. click.style('Convert app error: {} {}'.format(e.__class__.__name__,
  415. str(e)), fg='red'))
  416. click.echo(click.style('Congratulations! Converted {} agent apps.'.format(len(proceeded_app_ids)), fg='green'))
  417. @click.command('add-qdrant-doc-id-index', help='add qdrant doc_id index.')
  418. @click.option('--field', default='metadata.doc_id', prompt=False, help='index field , default is metadata.doc_id.')
  419. def add_qdrant_doc_id_index(field: str):
  420. click.echo(click.style('Start add qdrant doc_id index.', fg='green'))
  421. config = current_app.config
  422. vector_type = config.get('VECTOR_STORE')
  423. if vector_type != "qdrant":
  424. click.echo(click.style('Sorry, only support qdrant vector store.', fg='red'))
  425. return
  426. create_count = 0
  427. try:
  428. bindings = db.session.query(DatasetCollectionBinding).all()
  429. if not bindings:
  430. click.echo(click.style('Sorry, no dataset collection bindings found.', fg='red'))
  431. return
  432. import qdrant_client
  433. from qdrant_client.http.exceptions import UnexpectedResponse
  434. from qdrant_client.http.models import PayloadSchemaType
  435. from core.rag.datasource.vdb.qdrant.qdrant_vector import QdrantConfig
  436. for binding in bindings:
  437. qdrant_config = QdrantConfig(
  438. endpoint=config.get('QDRANT_URL'),
  439. api_key=config.get('QDRANT_API_KEY'),
  440. root_path=current_app.root_path,
  441. timeout=config.get('QDRANT_CLIENT_TIMEOUT'),
  442. grpc_port=config.get('QDRANT_GRPC_PORT'),
  443. prefer_grpc=config.get('QDRANT_GRPC_ENABLED')
  444. )
  445. try:
  446. client = qdrant_client.QdrantClient(**qdrant_config.to_qdrant_params())
  447. # create payload index
  448. client.create_payload_index(binding.collection_name, field,
  449. field_schema=PayloadSchemaType.KEYWORD)
  450. create_count += 1
  451. except UnexpectedResponse as e:
  452. # Collection does not exist, so return
  453. if e.status_code == 404:
  454. click.echo(click.style(f'Collection not found, collection_name:{binding.collection_name}.', fg='red'))
  455. continue
  456. # Some other error occurred, so re-raise the exception
  457. else:
  458. click.echo(click.style(f'Failed to create qdrant index, collection_name:{binding.collection_name}.', fg='red'))
  459. except Exception as e:
  460. click.echo(click.style('Failed to create qdrant client.', fg='red'))
  461. click.echo(
  462. click.style(f'Congratulations! Create {create_count} collection indexes.',
  463. fg='green'))
  464. @click.command('create-tenant', help='Create account and tenant.')
  465. @click.option('--email', prompt=True, help='The email address of the tenant account.')
  466. @click.option('--language', prompt=True, help='Account language, default: en-US.')
  467. def create_tenant(email: str, language: Optional[str] = None):
  468. """
  469. Create tenant account
  470. """
  471. if not email:
  472. click.echo(click.style('Sorry, email is required.', fg='red'))
  473. return
  474. # Create account
  475. email = email.strip()
  476. if '@' not in email:
  477. click.echo(click.style('Sorry, invalid email address.', fg='red'))
  478. return
  479. account_name = email.split('@')[0]
  480. if language not in languages:
  481. language = 'en-US'
  482. # generate random password
  483. new_password = secrets.token_urlsafe(16)
  484. # register account
  485. account = RegisterService.register(
  486. email=email,
  487. name=account_name,
  488. password=new_password,
  489. language=language
  490. )
  491. TenantService.create_owner_tenant_if_not_exist(account)
  492. click.echo(click.style('Congratulations! Account and tenant created.\n'
  493. 'Account: {}\nPassword: {}'.format(email, new_password), fg='green'))
  494. @click.command('upgrade-db', help='upgrade the database')
  495. def upgrade_db():
  496. click.echo('Preparing database migration...')
  497. lock = redis_client.lock(name='db_upgrade_lock', timeout=60)
  498. if lock.acquire(blocking=False):
  499. try:
  500. click.echo(click.style('Start database migration.', fg='green'))
  501. # run db migration
  502. import flask_migrate
  503. flask_migrate.upgrade()
  504. click.echo(click.style('Database migration successful!', fg='green'))
  505. except Exception as e:
  506. logging.exception(f'Database migration failed, error: {e}')
  507. finally:
  508. lock.release()
  509. else:
  510. click.echo('Database migration skipped')
  511. def register_commands(app):
  512. app.cli.add_command(reset_password)
  513. app.cli.add_command(reset_email)
  514. app.cli.add_command(reset_encrypt_key_pair)
  515. app.cli.add_command(vdb_migrate)
  516. app.cli.add_command(convert_to_agent_apps)
  517. app.cli.add_command(add_qdrant_doc_id_index)
  518. app.cli.add_command(create_tenant)
  519. app.cli.add_command(upgrade_db)