|
| 1 | +from dataclasses import dataclass |
| 2 | +from dataclasses_json import dataclass_json, Undefined # type: ignore |
| 3 | +import requests |
| 4 | +from requests.structures import CaseInsensitiveDict |
| 5 | +from typing import Optional, Dict, Any, Union |
| 6 | +from urllib.parse import urlparse |
| 7 | + |
| 8 | + |
| 9 | +class InferenceClientError(Exception): |
| 10 | + """Base exception for InferenceClient errors.""" |
| 11 | + pass |
| 12 | + |
| 13 | + |
| 14 | +@dataclass_json(undefined=Undefined.EXCLUDE) |
| 15 | +@dataclass |
| 16 | +class InferenceResponse: |
| 17 | + body: Any |
| 18 | + headers: CaseInsensitiveDict[str] |
| 19 | + status_code: int |
| 20 | + status_text: str |
| 21 | + |
| 22 | + |
| 23 | +class InferenceClient: |
| 24 | + def __init__(self, inference_key: str, endpoint_base_url: str, timeout_seconds: int = 300) -> None: |
| 25 | + """ |
| 26 | + Initialize the InferenceClient. |
| 27 | +
|
| 28 | + Args: |
| 29 | + inference_key: The authentication key for the API |
| 30 | + endpoint_base_url: The base URL for the API |
| 31 | + timeout_seconds: Request timeout in seconds |
| 32 | +
|
| 33 | + Raises: |
| 34 | + InferenceClientError: If the parameters are invalid |
| 35 | + """ |
| 36 | + if not inference_key: |
| 37 | + raise InferenceClientError("inference_key cannot be empty") |
| 38 | + |
| 39 | + parsed_url = urlparse(endpoint_base_url) |
| 40 | + if not parsed_url.scheme or not parsed_url.netloc: |
| 41 | + raise InferenceClientError("endpoint_base_url must be a valid URL") |
| 42 | + |
| 43 | + self.inference_key = inference_key |
| 44 | + self.endpoint_base_url = endpoint_base_url.rstrip('/') |
| 45 | + self.timeout_seconds = timeout_seconds |
| 46 | + self._session = requests.Session() |
| 47 | + self._global_headers = { |
| 48 | + 'Authorization': f'Bearer {inference_key}', |
| 49 | + 'Content-Type': 'application/json' |
| 50 | + } |
| 51 | + |
| 52 | + def __enter__(self): |
| 53 | + return self |
| 54 | + |
| 55 | + def __exit__(self, exc_type, exc_val, exc_tb): |
| 56 | + self._session.close() |
| 57 | + |
| 58 | + @property |
| 59 | + def global_headers(self) -> Dict[str, str]: |
| 60 | + """ |
| 61 | + Get the current global headers that will be used for all requests. |
| 62 | +
|
| 63 | + Returns: |
| 64 | + Dictionary of current global headers |
| 65 | + """ |
| 66 | + return self._global_headers.copy() |
| 67 | + |
| 68 | + def set_global_header(self, key: str, value: str) -> None: |
| 69 | + """ |
| 70 | + Set or update a global header that will be used for all requests. |
| 71 | +
|
| 72 | + Args: |
| 73 | + key: Header name |
| 74 | + value: Header value |
| 75 | + """ |
| 76 | + self._global_headers[key] = value |
| 77 | + |
| 78 | + def set_global_headers(self, headers: Dict[str, str]) -> None: |
| 79 | + """ |
| 80 | + Set multiple global headers at once that will be used for all requests. |
| 81 | +
|
| 82 | + Args: |
| 83 | + headers: Dictionary of headers to set globally |
| 84 | + """ |
| 85 | + self._global_headers.update(headers) |
| 86 | + |
| 87 | + def remove_global_header(self, key: str) -> None: |
| 88 | + """ |
| 89 | + Remove a global header. |
| 90 | +
|
| 91 | + Args: |
| 92 | + key: Header name to remove from global headers |
| 93 | + """ |
| 94 | + if key in self._global_headers: |
| 95 | + del self._global_headers[key] |
| 96 | + |
| 97 | + def _build_url(self, path: str) -> str: |
| 98 | + """Construct the full URL by joining the base URL with the path.""" |
| 99 | + return f"{self.endpoint_base_url}/{path.lstrip('/')}" |
| 100 | + |
| 101 | + def _build_request_headers(self, request_headers: Optional[Dict[str, str]] = None) -> Dict[str, str]: |
| 102 | + """ |
| 103 | + Build the final headers by merging global headers with request-specific headers. |
| 104 | +
|
| 105 | + Args: |
| 106 | + request_headers: Optional headers specific to this request |
| 107 | +
|
| 108 | + Returns: |
| 109 | + Merged headers dictionary |
| 110 | + """ |
| 111 | + headers = self._global_headers.copy() |
| 112 | + if request_headers: |
| 113 | + headers.update(request_headers) |
| 114 | + return headers |
| 115 | + |
| 116 | + def _make_request(self, method: str, path: str, **kwargs) -> requests.Response: |
| 117 | + """ |
| 118 | + Make an HTTP request with error handling. |
| 119 | +
|
| 120 | + Args: |
| 121 | + method: HTTP method to use |
| 122 | + path: API endpoint path |
| 123 | + **kwargs: Additional arguments to pass to the request |
| 124 | +
|
| 125 | + Returns: |
| 126 | + Response object from the request |
| 127 | +
|
| 128 | + Raises: |
| 129 | + InferenceClientError: If the request fails |
| 130 | + """ |
| 131 | + timeout = kwargs.pop('timeout_seconds', self.timeout_seconds) |
| 132 | + try: |
| 133 | + response = self._session.request( |
| 134 | + method=method, |
| 135 | + url=self._build_url(path), |
| 136 | + headers=self._build_request_headers( |
| 137 | + kwargs.pop('headers', None)), |
| 138 | + timeout=timeout, |
| 139 | + **kwargs |
| 140 | + ) |
| 141 | + response.raise_for_status() |
| 142 | + return response |
| 143 | + except requests.exceptions.Timeout: |
| 144 | + raise InferenceClientError( |
| 145 | + f"Request to {path} timed out after {timeout} seconds") |
| 146 | + except requests.exceptions.RequestException as e: |
| 147 | + raise InferenceClientError(f"Request to {path} failed: {str(e)}") |
| 148 | + |
| 149 | + def run_sync(self, data: Dict[str, Any], path: str = "", timeout_seconds: int = 60 * 5, headers: Optional[Dict[str, str]] = None): |
| 150 | + response = self.post( |
| 151 | + path, json=data, timeout_seconds=timeout_seconds, headers=headers) |
| 152 | + |
| 153 | + return InferenceResponse( |
| 154 | + body=response.json(), |
| 155 | + headers=response.headers, |
| 156 | + status_code=response.status_code, |
| 157 | + status_text=response.reason |
| 158 | + ) |
| 159 | + |
| 160 | + def get(self, path: str, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, timeout_seconds: Optional[int] = None) -> requests.Response: |
| 161 | + return self._make_request('GET', path, params=params, headers=headers, timeout_seconds=timeout_seconds) |
| 162 | + |
| 163 | + def post(self, path: str, json: Optional[Dict[str, Any]] = None, data: Optional[Union[str, Dict[str, Any]]] = None, |
| 164 | + params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, timeout_seconds: Optional[int] = None) -> requests.Response: |
| 165 | + return self._make_request('POST', path, json=json, data=data, params=params, headers=headers, timeout_seconds=timeout_seconds) |
| 166 | + |
| 167 | + def put(self, path: str, json: Optional[Dict[str, Any]] = None, data: Optional[Union[str, Dict[str, Any]]] = None, |
| 168 | + params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, timeout_seconds: Optional[int] = None) -> requests.Response: |
| 169 | + return self._make_request('PUT', path, json=json, data=data, params=params, headers=headers, timeout_seconds=timeout_seconds) |
| 170 | + |
| 171 | + def delete(self, path: str, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, timeout_seconds: Optional[int] = None) -> requests.Response: |
| 172 | + return self._make_request('DELETE', path, params=params, headers=headers, timeout_seconds=timeout_seconds) |
| 173 | + |
| 174 | + def patch(self, path: str, json: Optional[Dict[str, Any]] = None, data: Optional[Union[str, Dict[str, Any]]] = None, |
| 175 | + params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, timeout_seconds: Optional[int] = None) -> requests.Response: |
| 176 | + return self._make_request('PATCH', path, json=json, data=data, params=params, headers=headers, timeout_seconds=timeout_seconds) |
| 177 | + |
| 178 | + def head(self, path: str, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, timeout_seconds: Optional[int] = None) -> requests.Response: |
| 179 | + return self._make_request('HEAD', path, params=params, headers=headers, timeout_seconds=timeout_seconds) |
| 180 | + |
| 181 | + def options(self, path: str, params: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, timeout_seconds: Optional[int] = None) -> requests.Response: |
| 182 | + return self._make_request('OPTIONS', path, params=params, headers=headers, timeout_seconds=timeout_seconds) |
| 183 | + |
| 184 | + def health(self) -> dict: |
| 185 | + """ |
| 186 | + Check the health status of the API. |
| 187 | +
|
| 188 | + Returns: |
| 189 | + dict: Health status information |
| 190 | +
|
| 191 | + Raises: |
| 192 | + InferenceClientError: If the health check fails |
| 193 | + """ |
| 194 | + try: |
| 195 | + response = self.get('/health') |
| 196 | + return response.json() |
| 197 | + except InferenceClientError as e: |
| 198 | + raise InferenceClientError(f"Health check failed: {str(e)}") |
0 commit comments