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 3.9KB

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