client.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import json
  2. import logging
  3. import os
  4. import uuid
  5. import requests
  6. from embedchain.constants import CONFIG_DIR, CONFIG_FILE, DB_URI
  7. from embedchain.core.db.database import init_db, setup_engine
  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. logging.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. setup_engine(database_uri=DB_URI)
  38. init_db()
  39. if os.path.exists(CONFIG_FILE):
  40. with open(CONFIG_FILE, "r") as f:
  41. data = json.load(f)
  42. if "user_id" in data:
  43. return data["user_id"]
  44. u_id = str(uuid.uuid4())
  45. with open(CONFIG_FILE, "w") as f:
  46. json.dump({"user_id": u_id}, f)
  47. @classmethod
  48. def load_config(cls):
  49. if not os.path.exists(CONFIG_FILE):
  50. cls.setup()
  51. with open(CONFIG_FILE, "r") as config_file:
  52. return json.load(config_file)
  53. def save(self):
  54. self.config_data["api_key"] = self.api_key
  55. with open(CONFIG_FILE, "w") as config_file:
  56. json.dump(self.config_data, config_file, indent=4)
  57. logging.info("API key saved successfully!")
  58. def clear(self):
  59. if "api_key" in self.config_data:
  60. del self.config_data["api_key"]
  61. with open(CONFIG_FILE, "w") as config_file:
  62. json.dump(self.config_data, config_file, indent=4)
  63. self.api_key = None
  64. logging.info("API key deleted successfully!")
  65. else:
  66. logging.warning("API key not found in the configuration file.")
  67. def update(self, api_key):
  68. if self.check(api_key):
  69. self.api_key = api_key
  70. self.save()
  71. logging.info("API key updated successfully!")
  72. else:
  73. logging.warning("Invalid API key provided. API key not updated.")
  74. def check(self, api_key):
  75. validation_url = f"{self.host}/api/v1/accounts/api_keys/validate/"
  76. response = requests.post(validation_url, headers={"Authorization": f"Token {api_key}"})
  77. if response.status_code == 200:
  78. return True
  79. else:
  80. logging.warning(f"Response from API: {response.text}")
  81. logging.warning("Invalid API key. Unable to validate.")
  82. return False
  83. def get(self):
  84. return self.api_key
  85. def __str__(self):
  86. return self.api_key