configure_dify_kb.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. """
  2. Dify Knowledge Base Configuration Script
  3. =========================================
  4. Apply recommended settings to Dify KB.
  5. Usage:
  6. python configure_dify_kb.py
  7. Environment:
  8. DIFY_API_KEY: Dify dataset API Key
  9. DIFY_BASE_URL: Dify server URL (default http://dify.bianwoyou.cn)
  10. """
  11. import os
  12. import sys
  13. import json
  14. import requests
  15. DIFY_BASE_URL = os.environ.get("DIFY_BASE_URL", "http://dify.bianwoyou.cn")
  16. API_KEY = os.environ.get("DIFY_API_KEY", "")
  17. DATASET_ID = "3ff939b3-8686-44f6-8ef5-65b1e53b55d3"
  18. RECOMMENDED_CONFIG = {
  19. "retrieval_model": {
  20. "search_method": "hybrid_search",
  21. "reranking_enable": True,
  22. "reranking_mode": "weighted_score",
  23. "weights": {
  24. "vector_weight": 0.6,
  25. "keyword_weight": 0.4
  26. },
  27. "top_k": 6,
  28. "score_threshold_enabled": True,
  29. "score_threshold": 0.5
  30. }
  31. }
  32. def get_dataset_info():
  33. headers = {"Authorization": f"Bearer {API_KEY}"}
  34. url = f"{DIFY_BASE_URL}/v1/datasets/{DATASET_ID}"
  35. resp = requests.get(url, headers=headers, timeout=30)
  36. if resp.status_code == 200:
  37. return resp.json()
  38. print(f" [FAIL] Get dataset info failed: {resp.status_code}")
  39. return None
  40. def get_retrieval_config():
  41. headers = {"Authorization": f"Bearer {API_KEY}"}
  42. url = f"{DIFY_BASE_URL}/v1/datasets/{DATASET_ID}/retrieval-model"
  43. resp = requests.get(url, headers=headers, timeout=30)
  44. if resp.status_code == 200:
  45. return resp.json()
  46. print(f" [FAIL] Get retrieval config failed: {resp.status_code}")
  47. return None
  48. def update_retrieval_config():
  49. headers = {
  50. "Authorization": f"Bearer {API_KEY}",
  51. "Content-Type": "application/json"
  52. }
  53. url = f"{DIFY_BASE_URL}/v1/datasets/{DATASET_ID}/retrieval-model"
  54. resp = requests.post(url, headers=headers, json=RECOMMENDED_CONFIG, timeout=30)
  55. if resp.status_code in (200, 201):
  56. print(" [OK] Retrieval config updated successfully!")
  57. return True
  58. else:
  59. print(f" [FAIL] Update failed: {resp.status_code} - {resp.text[:200]}")
  60. return False
  61. def list_documents():
  62. headers = {"Authorization": f"Bearer {API_KEY}"}
  63. url = f"{DIFY_BASE_URL}/v1/datasets/{DATASET_ID}/documents?page=1&page_size=50"
  64. resp = requests.get(url, headers=headers, timeout=30)
  65. if resp.status_code == 200:
  66. docs = resp.json().get("data", [])
  67. print(f"\nDocuments ({len(docs)} total):")
  68. print(f"{'Name':<40} {'Status':<15} {'Words':<8}")
  69. print("-" * 65)
  70. for doc in docs:
  71. name = doc.get("name", "?")
  72. status = doc.get("indexing_status", "?")
  73. words = doc.get("word_count", 0)
  74. print(f"{name:<40} {status:<15} {words:<8}")
  75. return docs
  76. else:
  77. print(f" [FAIL] List documents failed: {resp.status_code}")
  78. return []
  79. def main():
  80. if not API_KEY:
  81. print("Error: Set DIFY_API_KEY environment variable")
  82. sys.exit(1)
  83. print("=" * 60)
  84. print("Dify Knowledge Base Configurator")
  85. print("=" * 60)
  86. print(f"Dataset ID: {DATASET_ID}")
  87. print(f"API URL: {DIFY_BASE_URL}")
  88. print()
  89. # Step 1: Connectivity
  90. print("[1/4] Checking connectivity...")
  91. info = get_dataset_info()
  92. if info:
  93. name = info.get("name", "?")
  94. doc_count = info.get("document_count", "?")
  95. method = info.get("retrieval_model_dict", {}).get("search_method", "?")
  96. top_k = info.get("retrieval_model_dict", {}).get("top_k", "?")
  97. print(f" [OK] KB: {name}")
  98. print(f" Documents: {doc_count}")
  99. print(f" Current: method={method}, top_k={top_k}")
  100. else:
  101. print(" [FAIL] Cannot reach Dify API")
  102. return
  103. # Step 2: Update config
  104. print()
  105. print("[2/4] Updating retrieval config...")
  106. print(f" Target: method=hybrid_search, top_k=6, rerank=True")
  107. update_retrieval_config()
  108. # Step 3: Verify
  109. print()
  110. print("[3/4] Verifying config...")
  111. updated = get_retrieval_config()
  112. if updated:
  113. print(f" [OK] Config applied")
  114. print(f" {json.dumps(updated, ensure_ascii=False)[:200]}")
  115. else:
  116. print(" [WARN] Could not verify config (API may not support direct read)")
  117. # Step 4: List documents
  118. print()
  119. print("[4/4] Document list...")
  120. list_documents()
  121. print()
  122. print("=" * 60)
  123. print("Recommended settings (from design doc):")
  124. print(" Search: hybrid (vector 60% + keyword 40%)")
  125. print(" Top-K: 6")
  126. print(" Threshold: 0.5")
  127. print(" Rerank: enabled (weighted score)")
  128. print("=" * 60)
  129. if __name__ == "__main__":
  130. main()