jina.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import json
  2. import requests
  3. from services.auth.api_key_auth_base import ApiKeyAuthBase
  4. class JinaAuth(ApiKeyAuthBase):
  5. def __init__(self, credentials: dict):
  6. super().__init__(credentials)
  7. auth_type = credentials.get("auth_type")
  8. if auth_type != "bearer":
  9. raise ValueError("Invalid auth type, Jina Reader auth type must be Bearer")
  10. self.api_key = credentials.get("config").get("api_key", None)
  11. if not self.api_key:
  12. raise ValueError("No API key provided")
  13. def validate_credentials(self):
  14. headers = self._prepare_headers()
  15. options = {
  16. "url": "https://example.com",
  17. }
  18. response = self._post_request("https://r.jina.ai", options, headers)
  19. if response.status_code == 200:
  20. return True
  21. else:
  22. self._handle_error(response)
  23. def _prepare_headers(self):
  24. return {"Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}"}
  25. def _post_request(self, url, data, headers):
  26. return requests.post(url, headers=headers, json=data)
  27. def _handle_error(self, response):
  28. if response.status_code in {402, 409, 500}:
  29. error_message = response.json().get("error", "Unknown error occurred")
  30. raise Exception(f"Failed to authorize. Status code: {response.status_code}. Error: {error_message}")
  31. else:
  32. if response.text:
  33. error_message = json.loads(response.text).get("error", "Unknown error occurred")
  34. raise Exception(f"Failed to authorize. Status code: {response.status_code}. Error: {error_message}")
  35. raise Exception(f"Unexpected error occurred while trying to authorize. Status code: {response.status_code}")