commands.py 25 KB

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