client.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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(self):
  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. if not os.path.exists(CONFIG_DIR):
  36. os.makedirs(CONFIG_DIR)
  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_dir()
  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. logging.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. logging.info("API key deleted successfully!")
  63. else:
  64. logging.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. logging.info("API key updated successfully!")
  70. else:
  71. logging.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. logging.warning(f"Response from API: {response.text}")
  79. logging.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