import_to_dify.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. """
  2. 导入知识文件到 Dify 知识库
  3. 用法: python import_to_dify.py <知识库ID> <文件路径1> [文件路径2 ...]
  4. """
  5. import os
  6. import sys
  7. import json
  8. import requests
  9. # Fix Windows console encoding for Unicode
  10. import io
  11. if sys.platform == "win32":
  12. sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
  13. DIFY_BASE_URL = "http://dify.bianwoyou.cn"
  14. API_KEY = os.environ.get("DIFY_API_KEY", "")
  15. def import_document(dataset_id, file_path):
  16. """通过文件上传方式导入文档到知识库"""
  17. headers = {
  18. "Authorization": f"Bearer {API_KEY}"
  19. }
  20. file_name = os.path.splitext(os.path.basename(file_path))[0]
  21. data = {
  22. "name": file_name,
  23. "indexing_technique": "high_quality",
  24. "process_rule": {"mode": "automatic"}
  25. }
  26. url = f"{DIFY_BASE_URL}/v1/datasets/{dataset_id}/document/create_by_file"
  27. with open(file_path, "r", encoding="utf-8") as f:
  28. text_content = f.read()
  29. # Use create_by_text instead to avoid multipart encoding issues
  30. text_data = {
  31. "name": file_name,
  32. "text": text_content,
  33. "indexing_technique": "high_quality",
  34. "process_rule": {"mode": "automatic"}
  35. }
  36. text_url = f"{DIFY_BASE_URL}/v1/datasets/{dataset_id}/document/create_by_text"
  37. print(f"正在导入: {file_name}...")
  38. resp = requests.post(
  39. text_url,
  40. headers={**headers, "Content-Type": "application/json"},
  41. json=text_data,
  42. timeout=120
  43. )
  44. if resp.status_code in (200, 201):
  45. result = resp.json()
  46. doc_id = result.get("document", {}).get("id", "unknown")
  47. print(f" [OK] 导入成功! 文档ID: {doc_id}")
  48. return True
  49. else:
  50. print(f" [FAIL] 导入失败: {resp.status_code} - {resp.text}")
  51. return False
  52. if __name__ == "__main__":
  53. if len(sys.argv) < 3:
  54. print("用法: python import_to_dify.py <dataset_id> <file_path1> [file_path2 ...]")
  55. sys.exit(1)
  56. if not API_KEY:
  57. print("错误: 请设置环境变量 DIFY_API_KEY")
  58. sys.exit(1)
  59. dataset_id = sys.argv[1]
  60. file_paths = sys.argv[2:]
  61. success = 0
  62. for fp in file_paths:
  63. if import_document(dataset_id, fp):
  64. success += 1
  65. print(f"\n导入完成: {success}/{len(file_paths)} 个文档导入成功")