commands.py 23 KB

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