client.py 3.2 KB

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