create_n8n_cohere_credential.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. """
  2. 创建 n8n Cohere API Key 凭证的脚本
  3. 注意: n8n 的凭证管理 API 可能有限制,如果 API 不支持,请使用 Web UI 手动配置。
  4. 参考文档: docs/n8n_cohere_credential_setup.md
  5. """
  6. import os
  7. import sys
  8. import json
  9. from typing import Optional, Dict, Any
  10. import requests
  11. from loguru import logger
  12. # 添加项目根目录到路径
  13. sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
  14. from app.config.config import BaseConfig
  15. def create_cohere_credential(
  16. api_url: Optional[str] = None,
  17. api_key: Optional[str] = None,
  18. cohere_api_key: str = "4pLcF0CGE7LeDmAudBQHdvAxGaKwNOKfxUGkHb5C",
  19. credential_name: str = "Cohere API Key",
  20. ) -> Dict[str, Any]:
  21. """
  22. 尝试通过 n8n API 创建 Cohere 凭证
  23. Args:
  24. api_url: n8n API 地址
  25. api_key: n8n API Key
  26. cohere_api_key: Cohere API Key 值
  27. credential_name: 凭证名称
  28. Returns:
  29. 创建结果
  30. Note:
  31. n8n 的凭证管理 API 可能不支持直接创建凭证(出于安全考虑)。
  32. 如果 API 调用失败,请使用 Web UI 手动配置。
  33. """
  34. # 获取配置
  35. if api_url is None or api_key is None:
  36. config = BaseConfig()
  37. api_url = api_url or config.N8N_API_URL
  38. api_key = api_key or config.N8N_API_KEY
  39. base_url = api_url.rstrip("/")
  40. headers = {
  41. "X-N8N-API-KEY": api_key,
  42. "Content-Type": "application/json",
  43. "Accept": "application/json",
  44. }
  45. # n8n 凭证 API 端点(可能不存在或需要特殊权限)
  46. # 注意: n8n 的凭证管理通常需要通过 Web UI 完成
  47. credential_data = {
  48. "name": credential_name,
  49. "type": "cohereApi", # 凭证类型
  50. "data": {
  51. "apiKey": cohere_api_key,
  52. },
  53. }
  54. # 尝试多个可能的 API 端点
  55. endpoints = [
  56. "/api/v1/credentials", # 标准凭证 API
  57. "/rest/credentials", # REST API
  58. ]
  59. for endpoint in endpoints:
  60. url = f"{base_url}{endpoint}"
  61. logger.info(f"尝试创建凭证: {url}")
  62. try:
  63. response = requests.post(
  64. url,
  65. headers=headers,
  66. json=credential_data,
  67. timeout=30,
  68. )
  69. logger.debug(f"响应状态码: {response.status_code}")
  70. logger.debug(f"响应内容: {response.text}")
  71. if response.status_code == 200 or response.status_code == 201:
  72. result = response.json()
  73. logger.success(f"✅ 凭证创建成功: {result}")
  74. return {
  75. "success": True,
  76. "message": "凭证创建成功",
  77. "data": result,
  78. }
  79. elif response.status_code == 401:
  80. logger.error("❌ API 认证失败,请检查 n8n API Key")
  81. return {
  82. "success": False,
  83. "message": "API 认证失败,请检查 n8n API Key",
  84. "error": "Unauthorized",
  85. }
  86. elif response.status_code == 403:
  87. logger.warning("⚠️ API 权限不足,凭证管理可能需要 Owner 权限")
  88. return {
  89. "success": False,
  90. "message": "API 权限不足,请使用 Web UI 手动配置",
  91. "error": "Forbidden",
  92. }
  93. elif response.status_code == 404:
  94. logger.warning(f"⚠️ 端点不存在: {endpoint}")
  95. continue # 尝试下一个端点
  96. else:
  97. logger.warning(
  98. f"⚠️ 请求失败: {response.status_code} - {response.text}"
  99. )
  100. except requests.exceptions.RequestException as e:
  101. logger.error(f"❌ 请求异常: {str(e)}")
  102. continue
  103. # 所有端点都失败,建议使用 Web UI
  104. logger.warning(
  105. "⚠️ 无法通过 API 创建凭证。n8n 的凭证管理通常需要通过 Web UI 完成。"
  106. )
  107. logger.info("📝 请参考文档手动配置: docs/n8n_cohere_credential_setup.md")
  108. return {
  109. "success": False,
  110. "message": "无法通过 API 创建凭证,请使用 Web UI 手动配置",
  111. "manual_setup_url": f"{base_url}/home/credentials",
  112. "guide": "docs/n8n_cohere_credential_setup.md",
  113. }
  114. def main():
  115. """主函数"""
  116. logger.info("🚀 开始创建 n8n Cohere API Key 凭证...")
  117. logger.info("API Key: 4pLcF0CGE7LeDmAudBQHdvAxGaKwNOKfxUGkHb5C")
  118. result = create_cohere_credential()
  119. print("\n" + "=" * 60)
  120. print("执行结果:")
  121. print("=" * 60)
  122. print(json.dumps(result, indent=2, ensure_ascii=False))
  123. if not result.get("success"):
  124. print("\n" + "=" * 60)
  125. print("建议:")
  126. print("=" * 60)
  127. print("由于 n8n 的凭证管理 API 可能有限制,")
  128. print("请使用 Web UI 手动配置凭证。")
  129. print(f"\n详细步骤请参考: {result.get('guide', 'docs/n8n_cohere_credential_setup.md')}")
  130. print(f"凭证管理页面: {result.get('manual_setup_url', 'https://n8n.citupro.com/home/credentials')}")
  131. return 0 if result.get("success") else 1
  132. if __name__ == "__main__":
  133. sys.exit(main())