client.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import json
  2. import logging
  3. import os
  4. import uuid
  5. import requests
  6. from embedchain.constants import CONFIG_DIR, CONFIG_FILE
  7. logger = logging.getLogger(__name__)
  8. class Client:
  9. def __init__(self, api_key=None, host="https://apiv2.embedchain.ai"):
  10. self.config_data = self.load_config()
  11. self.host = host
  12. if api_key:
  13. if self.check(api_key):
  14. self.api_key = api_key
  15. self.save()
  16. else:
  17. raise ValueError(
  18. "Invalid API key provided. You can find your API key on https://app.embedchain.ai/settings/keys."
  19. )
  20. else:
  21. if "api_key" in self.config_data:
  22. self.api_key = self.config_data["api_key"]
  23. logger.info("API key loaded successfully!")
  24. else:
  25. raise ValueError(
  26. "You are not logged in. Please obtain an API key from https://app.embedchain.ai/settings/keys/"
  27. )
  28. @classmethod
  29. def setup(cls):
  30. """
  31. Loads the user id from the config file if it exists, otherwise generates a new
  32. one and saves it to the config file.
  33. :return: user id
  34. :rtype: str
  35. """
  36. os.makedirs(CONFIG_DIR, exist_ok=True)
  37. if os.path.exists(CONFIG_FILE):
  38. with open(CONFIG_FILE, "r") as f:
  39. data = json.load(f)
  40. if "user_id" in data:
  41. return data["user_id"]
  42. u_id = str(uuid.uuid4())
  43. with open(CONFIG_FILE, "w") as f:
  44. json.dump({"user_id": u_id}, f)
  45. @classmethod
  46. def load_config(cls):
  47. if not os.path.exists(CONFIG_FILE):
  48. cls.setup()
  49. with open(CONFIG_FILE, "r") as config_file:
  50. return json.load(config_file)
  51. def save(self):
  52. self.config_data["api_key"] = self.api_key
  53. with open(CONFIG_FILE, "w") as config_file:
  54. json.dump(self.config_data, config_file, indent=4)
  55. logger.info("API key saved successfully!")
  56. def clear(self):
  57. if "api_key" in self.config_data:
  58. del self.config_data["api_key"]
  59. with open(CONFIG_FILE, "w") as config_file:
  60. json.dump(self.config_data, config_file, indent=4)
  61. self.api_key = None
  62. logger.info("API key deleted successfully!")
  63. else:
  64. logger.warning("API key not found in the configuration file.")
  65. def update(self, api_key):
  66. if self.check(api_key):
  67. self.api_key = api_key
  68. self.save()
  69. logger.info("API key updated successfully!")
  70. else:
  71. logger.warning("Invalid API key provided. API key not updated.")
  72. def check(self, api_key):
  73. validation_url = f"{self.host}/api/v1/accounts/api_keys/validate/"
  74. response = requests.post(validation_url, headers={"Authorization": f"Token {api_key}"})
  75. if response.status_code == 200:
  76. return True
  77. else:
  78. logger.warning(f"Response from API: {response.text}")
  79. logger.warning("Invalid API key. Unable to validate.")
  80. return False
  81. def get(self):
  82. return self.api_key
  83. def __str__(self):
  84. return self.api_key