Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

install_openai_plugin.py 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #!/usr/bin/env python3
  2. import sys
  3. from pathlib import Path
  4. sys.path.append(str(Path(__file__).parent.parent))
  5. import time
  6. import httpx
  7. from common import Logger, config_helper
  8. def install_openai_plugin() -> None:
  9. """Install OpenAI plugin using saved access token."""
  10. log = Logger("InstallPlugin")
  11. log.header("Installing OpenAI Plugin")
  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. log.info("Please run login_admin.py first to get access token")
  17. return
  18. log.step("Installing OpenAI plugin...")
  19. # API endpoint for plugin installation
  20. base_url = "http://localhost:5001"
  21. install_endpoint = f"{base_url}/console/api/workspaces/current/plugin/install/marketplace"
  22. # Plugin identifier
  23. plugin_payload = {
  24. "plugin_unique_identifiers": [
  25. "langgenius/openai:0.2.5@373362a028986aae53a7baf73a7f11991ba3c22c69eaf97d6cde048cfd4a9f98"
  26. ]
  27. }
  28. headers = {
  29. "Accept": "*/*",
  30. "Accept-Language": "en-US,en;q=0.9",
  31. "Cache-Control": "no-cache",
  32. "Connection": "keep-alive",
  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 installation request
  50. with httpx.Client() as client:
  51. response = client.post(
  52. install_endpoint,
  53. json=plugin_payload,
  54. headers=headers,
  55. cookies=cookies,
  56. )
  57. if response.status_code == 200:
  58. response_data = response.json()
  59. task_id = response_data.get("task_id")
  60. if not task_id:
  61. log.error("No task ID received from installation request")
  62. return
  63. log.progress(f"Installation task created: {task_id}")
  64. log.info("Polling for task completion...")
  65. # Poll for task completion
  66. task_endpoint = f"{base_url}/console/api/workspaces/current/plugin/tasks/{task_id}"
  67. max_attempts = 30 # 30 attempts with 2 second delay = 60 seconds max
  68. attempt = 0
  69. log.spinner_start("Installing plugin")
  70. while attempt < max_attempts:
  71. attempt += 1
  72. time.sleep(2) # Wait 2 seconds between polls
  73. task_response = client.get(
  74. task_endpoint,
  75. headers=headers,
  76. cookies=cookies,
  77. )
  78. if task_response.status_code != 200:
  79. log.spinner_stop(
  80. success=False,
  81. message=f"Failed to get task status: {task_response.status_code}",
  82. )
  83. return
  84. task_data = task_response.json()
  85. task_info = task_data.get("task", {})
  86. status = task_info.get("status")
  87. if status == "success":
  88. log.spinner_stop(success=True, message="Plugin installed!")
  89. log.success("OpenAI plugin installed successfully!")
  90. # Display plugin info
  91. plugins = task_info.get("plugins", [])
  92. if plugins:
  93. plugin_info = plugins[0]
  94. log.key_value("Plugin ID", plugin_info.get("plugin_id"))
  95. log.key_value("Message", plugin_info.get("message"))
  96. break
  97. elif status == "failed":
  98. log.spinner_stop(success=False, message="Installation failed")
  99. log.error("Plugin installation failed")
  100. plugins = task_info.get("plugins", [])
  101. if plugins:
  102. for plugin in plugins:
  103. log.list_item(f"{plugin.get('plugin_id')}: {plugin.get('message')}")
  104. break
  105. # Continue polling if status is "pending" or other
  106. else:
  107. log.spinner_stop(success=False, message="Installation timed out")
  108. log.error("Installation timed out after 60 seconds")
  109. elif response.status_code == 401:
  110. log.error("Installation failed: Unauthorized")
  111. log.info("Token may have expired. Please run login_admin.py again")
  112. elif response.status_code == 409:
  113. log.warning("Plugin may already be installed")
  114. log.debug(f"Response: {response.text}")
  115. else:
  116. log.error(f"Installation failed with status code: {response.status_code}")
  117. log.debug(f"Response: {response.text}")
  118. except httpx.ConnectError:
  119. log.error("Could not connect to Dify API at http://localhost:5001")
  120. log.info("Make sure the API server is running with: ./dev/start-api")
  121. except Exception as e:
  122. log.error(f"An error occurred: {e}")
  123. if __name__ == "__main__":
  124. install_openai_plugin()