commands.py 23 KB

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