Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

create_api_key.py 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. #!/usr/bin/env python3
  2. import sys
  3. from pathlib import Path
  4. sys.path.append(str(Path(__file__).parent.parent))
  5. import httpx
  6. import json
  7. from common import config_helper
  8. from common import Logger
  9. def create_api_key() -> None:
  10. """Create API key for the imported app."""
  11. log = Logger("CreateAPIKey")
  12. log.header("Creating API Key")
  13. # Read token from config
  14. access_token = config_helper.get_token()
  15. if not access_token:
  16. log.error("No access token found in config")
  17. return
  18. # Read app_id from config
  19. app_id = config_helper.get_app_id()
  20. if not app_id:
  21. log.error("No app_id found in config")
  22. log.info("Please run import_workflow_app.py first to import the app")
  23. return
  24. log.step(f"Creating API key for app: {app_id}")
  25. # API endpoint for creating API key
  26. base_url = "http://localhost:5001"
  27. api_key_endpoint = f"{base_url}/console/api/apps/{app_id}/api-keys"
  28. headers = {
  29. "Accept": "*/*",
  30. "Accept-Language": "en-US,en;q=0.9",
  31. "Cache-Control": "no-cache",
  32. "Connection": "keep-alive",
  33. "Content-Length": "0",
  34. "DNT": "1",
  35. "Origin": "http://localhost:3000",
  36. "Pragma": "no-cache",
  37. "Referer": "http://localhost:3000/",
  38. "Sec-Fetch-Dest": "empty",
  39. "Sec-Fetch-Mode": "cors",
  40. "Sec-Fetch-Site": "same-site",
  41. "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36",
  42. "authorization": f"Bearer {access_token}",
  43. "content-type": "application/json",
  44. "sec-ch-ua": '"Not;A=Brand";v="99", "Google Chrome";v="139", "Chromium";v="139"',
  45. "sec-ch-ua-mobile": "?0",
  46. "sec-ch-ua-platform": '"macOS"',
  47. }
  48. cookies = {"locale": "en-US"}
  49. try:
  50. # Make the API key creation request
  51. with httpx.Client() as client:
  52. response = client.post(
  53. api_key_endpoint,
  54. headers=headers,
  55. cookies=cookies,
  56. )
  57. if response.status_code == 200 or response.status_code == 201:
  58. response_data = response.json()
  59. api_key_id = response_data.get("id")
  60. api_key_token = response_data.get("token")
  61. if api_key_token:
  62. log.success("API key created successfully!")
  63. log.key_value("Key ID", api_key_id)
  64. log.key_value("Token", api_key_token)
  65. log.key_value("Type", response_data.get("type"))
  66. # Save API key to config
  67. api_key_config = {
  68. "id": api_key_id,
  69. "token": api_key_token,
  70. "type": response_data.get("type"),
  71. "app_id": app_id,
  72. "created_at": response_data.get("created_at"),
  73. }
  74. if config_helper.write_config("api_key_config", api_key_config):
  75. log.info(
  76. f"API key saved to: {config_helper.get_config_path('benchmark_state')}"
  77. )
  78. else:
  79. log.error("No API token received")
  80. log.debug(f"Response: {json.dumps(response_data, indent=2)}")
  81. elif response.status_code == 401:
  82. log.error("API key creation failed: Unauthorized")
  83. log.info("Token may have expired. Please run login_admin.py again")
  84. else:
  85. log.error(
  86. f"API key creation failed with status code: {response.status_code}"
  87. )
  88. log.debug(f"Response: {response.text}")
  89. except httpx.ConnectError:
  90. log.error("Could not connect to Dify API at http://localhost:5001")
  91. log.info("Make sure the API server is running with: ./dev/start-api")
  92. except Exception as e:
  93. log.error(f"An error occurred: {e}")
  94. if __name__ == "__main__":
  95. create_api_key()