efficientai-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ """EfficientAI Python SDK."""
2
+
3
+ from efficientai_sdk._client import AsyncEfficientAI, EfficientAI
4
+ from efficientai_sdk._config import DEFAULT_BASE_URL
5
+ from efficientai_sdk._exceptions import (
6
+ APIConnectionError,
7
+ APIStatusError,
8
+ APITimeoutError,
9
+ AuthenticationError,
10
+ BadRequestError,
11
+ ConfigurationError,
12
+ ConflictError,
13
+ EfficientAIError,
14
+ InternalServerError,
15
+ NotFoundError,
16
+ PermissionDeniedError,
17
+ RateLimitError,
18
+ UnprocessableEntityError,
19
+ )
20
+ from efficientai_sdk._version import __version__
21
+
22
+ __all__ = [
23
+ "DEFAULT_BASE_URL",
24
+ "APIConnectionError",
25
+ "APIStatusError",
26
+ "APITimeoutError",
27
+ "AsyncEfficientAI",
28
+ "AuthenticationError",
29
+ "BadRequestError",
30
+ "ConfigurationError",
31
+ "ConflictError",
32
+ "EfficientAI",
33
+ "EfficientAIError",
34
+ "InternalServerError",
35
+ "NotFoundError",
36
+ "PermissionDeniedError",
37
+ "RateLimitError",
38
+ "UnprocessableEntityError",
39
+ "__version__",
40
+ ]
@@ -0,0 +1,313 @@
1
+ """HTTP transport shared by the sync and async clients: auth headers, retries, error mapping."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ import platform
8
+ import random
9
+ import time
10
+ from collections.abc import Mapping
11
+ from typing import Any, Optional, Union
12
+ from urllib.parse import urlparse
13
+
14
+ import httpx
15
+
16
+ from efficientai_sdk._config import DEFAULT_API_PREFIX, ClientConfig
17
+ from efficientai_sdk._exceptions import (
18
+ APIConnectionError,
19
+ APITimeoutError,
20
+ ConfigurationError,
21
+ make_status_error,
22
+ parse_retry_after,
23
+ )
24
+ from efficientai_sdk._version import __version__
25
+
26
+ logger = logging.getLogger("efficientai_sdk")
27
+
28
+ HEADER_API_KEY = "X-API-Key"
29
+ HEADER_WORKSPACE_ID = "X-Workspace-Id"
30
+
31
+ USER_AGENT = f"efficientai-sdk-python/{__version__} (python {platform.python_version()})"
32
+
33
+ RETRYABLE_STATUS = frozenset({408, 429, 500, 502, 503, 504})
34
+ # Statuses where the server did not process the request, so even POST/PATCH is safe to retry.
35
+ RETRYABLE_STATUS_NON_IDEMPOTENT = frozenset({429, 503})
36
+ IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "PUT", "DELETE"})
37
+
38
+ INITIAL_RETRY_DELAY = 0.5
39
+ MAX_RETRY_DELAY = 8.0
40
+ MAX_RETRY_AFTER = 60.0
41
+
42
+ QueryParams = Mapping[str, Any]
43
+ Timeout = Union[float, httpx.Timeout, None]
44
+
45
+
46
+ def _host_key(url: str) -> tuple[str, str, int]:
47
+ parsed = urlparse(url.strip())
48
+ host = (parsed.hostname or "").lower()
49
+ scheme = (parsed.scheme or "http").lower()
50
+ port = parsed.port
51
+ if port is None:
52
+ port = 443 if scheme == "https" else 80
53
+ return scheme, host, port
54
+
55
+
56
+ def _assert_url_allowed(absolute_url: str, *, base_url: str) -> None:
57
+ if _host_key(absolute_url) != _host_key(base_url):
58
+ raise ConfigurationError(
59
+ "Absolute request URLs must use the same host as base_url so the API key "
60
+ f"is not sent elsewhere (got {absolute_url!r}, base_url={base_url!r})"
61
+ )
62
+
63
+
64
+ class _BaseClient:
65
+ def __init__(self, config: ClientConfig) -> None:
66
+ self._config = config
67
+
68
+ @property
69
+ def base_url(self) -> str:
70
+ return self._config.base_url
71
+
72
+ @property
73
+ def workspace_id(self) -> Optional[str]:
74
+ return self._config.workspace_id
75
+
76
+ @property
77
+ def max_retries(self) -> int:
78
+ return self._config.max_retries
79
+
80
+ def _default_headers(self) -> dict[str, str]:
81
+ headers = {
82
+ HEADER_API_KEY: self._config.api_key,
83
+ "User-Agent": USER_AGENT,
84
+ "Accept": "application/json",
85
+ }
86
+ if self._config.workspace_id:
87
+ headers[HEADER_WORKSPACE_ID] = self._config.workspace_id
88
+ return headers
89
+
90
+ def api_path(self, suffix: str) -> str:
91
+ return self._config.api_path(suffix)
92
+
93
+ def _url(self, path: str) -> str:
94
+ if path.startswith(("http://", "https://")):
95
+ _assert_url_allowed(path, base_url=self._config.base_url)
96
+ return path
97
+ if path.startswith("/"):
98
+ legacy = DEFAULT_API_PREFIX
99
+ if path.startswith(legacy):
100
+ suffix = path[len(legacy) :].lstrip("/")
101
+ path = self._config.api_path(suffix)
102
+ elif path.startswith(self._config.api_prefix):
103
+ pass
104
+ else:
105
+ path = self._config.api_path(path.lstrip("/"))
106
+ return f"{self._config.base_url}{path}"
107
+ return f"{self._config.base_url}/{self._config.api_path(path).lstrip('/')}"
108
+
109
+ def _merge_headers(self, extra: Optional[Mapping[str, str]]) -> dict[str, str]:
110
+ headers = self._default_headers()
111
+ if extra:
112
+ headers.update(extra)
113
+ return headers
114
+
115
+ # ---- retry policy -------------------------------------------------
116
+
117
+ @staticmethod
118
+ def _should_retry_status(method: str, status: int, retry: Optional[bool]) -> bool:
119
+ if retry is False:
120
+ return False
121
+ if retry is True or method in IDEMPOTENT_METHODS:
122
+ return status in RETRYABLE_STATUS
123
+ return status in RETRYABLE_STATUS_NON_IDEMPOTENT
124
+
125
+ @staticmethod
126
+ def _should_retry_exception(method: str, exc: Exception, retry: Optional[bool]) -> bool:
127
+ if retry is False:
128
+ return False
129
+ if isinstance(exc, (httpx.ConnectError, httpx.ConnectTimeout)):
130
+ return True # the request was never sent
131
+ if not isinstance(exc, httpx.TransportError):
132
+ return False
133
+ return retry is True or method in IDEMPOTENT_METHODS
134
+
135
+ @staticmethod
136
+ def _retry_delay(attempt: int, response: Optional[httpx.Response]) -> float:
137
+ if response is not None:
138
+ hinted = parse_retry_after(response.headers.get("retry-after"))
139
+ if hinted is not None:
140
+ return min(hinted, MAX_RETRY_AFTER)
141
+ backoff = min(INITIAL_RETRY_DELAY * (2.0**attempt), MAX_RETRY_DELAY)
142
+ return backoff * (0.5 + random.random() / 2) # jitter: 50-100%
143
+
144
+ # ---- responses ----------------------------------------------------
145
+
146
+ @staticmethod
147
+ def _parse_body(response: httpx.Response) -> Any:
148
+ if response.status_code == 204 or not response.content:
149
+ return None
150
+ if "json" in response.headers.get("content-type", ""):
151
+ try:
152
+ return response.json()
153
+ except ValueError:
154
+ return response.text
155
+ return response.text
156
+
157
+ def _process_response(self, response: httpx.Response) -> Any:
158
+ body = self._parse_body(response)
159
+ if response.is_success:
160
+ return body
161
+ raise make_status_error(response, body)
162
+
163
+
164
+ class SyncAPIClient(_BaseClient):
165
+ def __init__(self, config: ClientConfig, *, http_client: Optional[httpx.Client] = None) -> None:
166
+ super().__init__(config)
167
+ self._owns_http_client = http_client is None
168
+ self._http = http_client or httpx.Client(timeout=config.timeout, follow_redirects=False)
169
+
170
+ def request(
171
+ self,
172
+ method: str,
173
+ path: str,
174
+ *,
175
+ params: Optional[QueryParams] = None,
176
+ json: Any = None,
177
+ content: Optional[bytes] = None,
178
+ headers: Optional[Mapping[str, str]] = None,
179
+ timeout: Timeout = None,
180
+ retry: Optional[bool] = None,
181
+ ) -> Any:
182
+ """Send a request and return the parsed body.
183
+
184
+ ``retry=None`` applies the default policy (idempotent methods retry on 5xx/timeouts,
185
+ POST/PATCH only on 429/503 and connection failures). ``True``/``False`` force it.
186
+ """
187
+ method = method.upper()
188
+ url = self._url(path)
189
+ merged = self._merge_headers(headers)
190
+ attempt = 0
191
+ while True:
192
+ try:
193
+ response = self._http.request(
194
+ method,
195
+ url,
196
+ params=params,
197
+ json=json,
198
+ content=content,
199
+ headers=merged,
200
+ timeout=timeout if timeout is not None else self._config.timeout,
201
+ )
202
+ except httpx.TransportError as exc:
203
+ if attempt < self.max_retries and self._should_retry_exception(method, exc, retry):
204
+ delay = self._retry_delay(attempt, None)
205
+ logger.debug("Retrying %s %s after %r in %.2fs", method, url, exc, delay)
206
+ time.sleep(delay)
207
+ attempt += 1
208
+ continue
209
+ if isinstance(exc, httpx.TimeoutException):
210
+ raise APITimeoutError(request=exc.request) from exc
211
+ raise APIConnectionError(
212
+ str(exc) or "Connection error.", request=exc.request
213
+ ) from exc
214
+
215
+ if (
216
+ not response.is_success
217
+ and attempt < self.max_retries
218
+ and self._should_retry_status(method, response.status_code, retry)
219
+ ):
220
+ delay = self._retry_delay(attempt, response)
221
+ logger.debug(
222
+ "Retrying %s %s after HTTP %s in %.2fs",
223
+ method,
224
+ url,
225
+ response.status_code,
226
+ delay,
227
+ )
228
+ response.close()
229
+ time.sleep(delay)
230
+ attempt += 1
231
+ continue
232
+
233
+ return self._process_response(response)
234
+
235
+ def close(self) -> None:
236
+ if self._owns_http_client:
237
+ self._http.close()
238
+
239
+
240
+ class AsyncAPIClient(_BaseClient):
241
+ def __init__(
242
+ self, config: ClientConfig, *, http_client: Optional[httpx.AsyncClient] = None
243
+ ) -> None:
244
+ super().__init__(config)
245
+ self._owns_http_client = http_client is None
246
+ self._http = http_client or httpx.AsyncClient(
247
+ timeout=config.timeout, follow_redirects=False
248
+ )
249
+
250
+ async def request(
251
+ self,
252
+ method: str,
253
+ path: str,
254
+ *,
255
+ params: Optional[QueryParams] = None,
256
+ json: Any = None,
257
+ content: Optional[bytes] = None,
258
+ headers: Optional[Mapping[str, str]] = None,
259
+ timeout: Timeout = None,
260
+ retry: Optional[bool] = None,
261
+ ) -> Any:
262
+ """Async version of :meth:`SyncAPIClient.request`."""
263
+ method = method.upper()
264
+ url = self._url(path)
265
+ merged = self._merge_headers(headers)
266
+ attempt = 0
267
+ while True:
268
+ try:
269
+ response = await self._http.request(
270
+ method,
271
+ url,
272
+ params=params,
273
+ json=json,
274
+ content=content,
275
+ headers=merged,
276
+ timeout=timeout if timeout is not None else self._config.timeout,
277
+ )
278
+ except httpx.TransportError as exc:
279
+ if attempt < self.max_retries and self._should_retry_exception(method, exc, retry):
280
+ delay = self._retry_delay(attempt, None)
281
+ logger.debug("Retrying %s %s after %r in %.2fs", method, url, exc, delay)
282
+ await asyncio.sleep(delay)
283
+ attempt += 1
284
+ continue
285
+ if isinstance(exc, httpx.TimeoutException):
286
+ raise APITimeoutError(request=exc.request) from exc
287
+ raise APIConnectionError(
288
+ str(exc) or "Connection error.", request=exc.request
289
+ ) from exc
290
+
291
+ if (
292
+ not response.is_success
293
+ and attempt < self.max_retries
294
+ and self._should_retry_status(method, response.status_code, retry)
295
+ ):
296
+ delay = self._retry_delay(attempt, response)
297
+ logger.debug(
298
+ "Retrying %s %s after HTTP %s in %.2fs",
299
+ method,
300
+ url,
301
+ response.status_code,
302
+ delay,
303
+ )
304
+ await response.aclose()
305
+ await asyncio.sleep(delay)
306
+ attempt += 1
307
+ continue
308
+
309
+ return self._process_response(response)
310
+
311
+ async def close(self) -> None:
312
+ if self._owns_http_client:
313
+ await self._http.aclose()
@@ -0,0 +1,196 @@
1
+ """Public client entry points."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from functools import cached_property
6
+ from types import TracebackType
7
+ from typing import TYPE_CHECKING, Optional
8
+
9
+ import httpx
10
+
11
+ from efficientai_sdk._base_client import AsyncAPIClient, SyncAPIClient
12
+ from efficientai_sdk._config import resolve_config
13
+
14
+ if TYPE_CHECKING:
15
+ from efficientai_sdk.simulations.api import (
16
+ AsyncEvaluatorsResource,
17
+ AsyncResultsResource,
18
+ AsyncSimulationsResource,
19
+ AsyncSuitesResource,
20
+ EvaluatorsResource,
21
+ ResultsResource,
22
+ SimulationsResource,
23
+ SuitesResource,
24
+ )
25
+ from efficientai_sdk.tracing.api import AsyncTraceResource, TraceResource
26
+
27
+
28
+ class EfficientAI(SyncAPIClient):
29
+ """Synchronous EfficientAI client.
30
+
31
+ Every argument falls back to an environment variable:
32
+ ``EFFICIENTAI_API_KEY``, ``EFFICIENTAI_WORKSPACE_ID``, ``EFFICIENTAI_BASE_URL``,
33
+ and ``EFFICIENTAI_API_PREFIX`` (defaults to ``/api/v1``).
34
+
35
+ >>> client = EfficientAI()
36
+ >>> client.verify()
37
+ True
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ *,
43
+ api_key: Optional[str] = None,
44
+ workspace_id: Optional[str] = None,
45
+ base_url: Optional[str] = None,
46
+ api_prefix: Optional[str] = None,
47
+ timeout: Optional[float] = None,
48
+ max_retries: Optional[int] = None,
49
+ http_client: Optional[httpx.Client] = None,
50
+ ) -> None:
51
+ config = resolve_config(
52
+ api_key=api_key,
53
+ workspace_id=workspace_id,
54
+ base_url=base_url,
55
+ api_prefix=api_prefix,
56
+ timeout=timeout,
57
+ max_retries=max_retries,
58
+ )
59
+ super().__init__(config, http_client=http_client)
60
+
61
+ def verify(self) -> bool:
62
+ """Check the API key against the server.
63
+
64
+ Returns ``True``, or raises ``AuthenticationError`` for a bad key and
65
+ ``APIConnectionError`` when the server can't be reached.
66
+ """
67
+ self.request("POST", self.api_path("auth/validate"), retry=True)
68
+ return True
69
+
70
+ @cached_property
71
+ def trace(self) -> TraceResource:
72
+ """Live call tracing. See :mod:`efficientai_sdk.tracing.api`."""
73
+ from efficientai_sdk.tracing.api import TraceResource
74
+
75
+ return TraceResource(self)
76
+
77
+ @cached_property
78
+ def simulations(self) -> SimulationsResource:
79
+ """Start and inspect simulation runs. See :mod:`efficientai_sdk.simulations`."""
80
+ from efficientai_sdk.simulations.api import SimulationsResource
81
+
82
+ return SimulationsResource(self)
83
+
84
+ @cached_property
85
+ def suites(self) -> SuitesResource:
86
+ """Run an evaluator suite."""
87
+ from efficientai_sdk.simulations.api import SuitesResource
88
+
89
+ return SuitesResource(self)
90
+
91
+ @cached_property
92
+ def evaluators(self) -> EvaluatorsResource:
93
+ """Run specific evaluators."""
94
+ from efficientai_sdk.simulations.api import EvaluatorsResource
95
+
96
+ return EvaluatorsResource(self)
97
+
98
+ @cached_property
99
+ def results(self) -> ResultsResource:
100
+ """Read evaluator results."""
101
+ from efficientai_sdk.simulations.api import ResultsResource
102
+
103
+ return ResultsResource(self)
104
+
105
+ def __enter__(self) -> EfficientAI:
106
+ return self
107
+
108
+ def __exit__(
109
+ self,
110
+ exc_type: Optional[type[BaseException]],
111
+ exc: Optional[BaseException],
112
+ tb: Optional[TracebackType],
113
+ ) -> None:
114
+ self.close()
115
+
116
+ def __repr__(self) -> str:
117
+ return f"EfficientAI(base_url={self.base_url!r}, workspace_id={self.workspace_id!r})"
118
+
119
+
120
+ class AsyncEfficientAI(AsyncAPIClient):
121
+ """Asynchronous EfficientAI client. Same arguments as :class:`EfficientAI`."""
122
+
123
+ def __init__(
124
+ self,
125
+ *,
126
+ api_key: Optional[str] = None,
127
+ workspace_id: Optional[str] = None,
128
+ base_url: Optional[str] = None,
129
+ api_prefix: Optional[str] = None,
130
+ timeout: Optional[float] = None,
131
+ max_retries: Optional[int] = None,
132
+ http_client: Optional[httpx.AsyncClient] = None,
133
+ ) -> None:
134
+ config = resolve_config(
135
+ api_key=api_key,
136
+ workspace_id=workspace_id,
137
+ base_url=base_url,
138
+ api_prefix=api_prefix,
139
+ timeout=timeout,
140
+ max_retries=max_retries,
141
+ )
142
+ super().__init__(config, http_client=http_client)
143
+
144
+ async def verify(self) -> bool:
145
+ """Async version of :meth:`EfficientAI.verify`."""
146
+ await self.request("POST", self.api_path("auth/validate"), retry=True)
147
+ return True
148
+
149
+ @cached_property
150
+ def trace(self) -> AsyncTraceResource:
151
+ """Live call tracing. See :mod:`efficientai_sdk.tracing.api`."""
152
+ from efficientai_sdk.tracing.api import AsyncTraceResource
153
+
154
+ return AsyncTraceResource(self)
155
+
156
+ @cached_property
157
+ def simulations(self) -> AsyncSimulationsResource:
158
+ """Async form of :attr:`EfficientAI.simulations`."""
159
+ from efficientai_sdk.simulations.api import AsyncSimulationsResource
160
+
161
+ return AsyncSimulationsResource(self)
162
+
163
+ @cached_property
164
+ def suites(self) -> AsyncSuitesResource:
165
+ """Async form of :attr:`EfficientAI.suites`."""
166
+ from efficientai_sdk.simulations.api import AsyncSuitesResource
167
+
168
+ return AsyncSuitesResource(self)
169
+
170
+ @cached_property
171
+ def evaluators(self) -> AsyncEvaluatorsResource:
172
+ """Async form of :attr:`EfficientAI.evaluators`."""
173
+ from efficientai_sdk.simulations.api import AsyncEvaluatorsResource
174
+
175
+ return AsyncEvaluatorsResource(self)
176
+
177
+ @cached_property
178
+ def results(self) -> AsyncResultsResource:
179
+ """Async form of :attr:`EfficientAI.results`."""
180
+ from efficientai_sdk.simulations.api import AsyncResultsResource
181
+
182
+ return AsyncResultsResource(self)
183
+
184
+ async def __aenter__(self) -> AsyncEfficientAI:
185
+ return self
186
+
187
+ async def __aexit__(
188
+ self,
189
+ exc_type: Optional[type[BaseException]],
190
+ exc: Optional[BaseException],
191
+ tb: Optional[TracebackType],
192
+ ) -> None:
193
+ await self.close()
194
+
195
+ def __repr__(self) -> str:
196
+ return f"AsyncEfficientAI(base_url={self.base_url!r}, workspace_id={self.workspace_id!r})"
@@ -0,0 +1,139 @@
1
+ """Client configuration: explicit arguments win, then environment variables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import threading
7
+ from dataclasses import dataclass
8
+ from typing import Optional
9
+ from urllib.parse import urlparse, urlunparse
10
+
11
+ from efficientai_sdk._exceptions import ConfigurationError
12
+
13
+ ENV_API_KEY = "EFFICIENTAI_API_KEY"
14
+ ENV_WORKSPACE_ID = "EFFICIENTAI_WORKSPACE_ID"
15
+ ENV_BASE_URL = "EFFICIENTAI_BASE_URL"
16
+ ENV_API_PREFIX = "EFFICIENTAI_API_PREFIX"
17
+ # Older name used by the in-framework trace helpers; still honoured.
18
+ ENV_BASE_URL_LEGACY = "EFFICIENTAI_API_BASE"
19
+
20
+ # EfficientAI is self-hosted; point EFFICIENTAI_BASE_URL at your deployment.
21
+ DEFAULT_BASE_URL = "http://localhost:8000"
22
+ DEFAULT_API_PREFIX = "/api/v1"
23
+ DEFAULT_TIMEOUT = 30.0
24
+ DEFAULT_MAX_RETRIES = 2
25
+
26
+ _dotenv_lock = threading.Lock()
27
+ _dotenv_loaded = False
28
+
29
+
30
+ def _load_dotenv_once() -> None:
31
+ global _dotenv_loaded
32
+ with _dotenv_lock:
33
+ if _dotenv_loaded:
34
+ return
35
+ try:
36
+ from dotenv import find_dotenv, load_dotenv
37
+ except ImportError:
38
+ _dotenv_loaded = True
39
+ return
40
+ path = find_dotenv(usecwd=True)
41
+ if path:
42
+ load_dotenv(path)
43
+ _dotenv_loaded = True
44
+
45
+
46
+ def _env(name: str) -> Optional[str]:
47
+ _load_dotenv_once()
48
+ value = os.environ.get(name)
49
+ if value is None:
50
+ return None
51
+ value = value.strip()
52
+ return value or None
53
+
54
+
55
+ def normalize_api_prefix(prefix: str) -> str:
56
+ cleaned = prefix.strip()
57
+ if not cleaned.startswith("/"):
58
+ cleaned = f"/{cleaned}"
59
+ return cleaned.rstrip("/") or DEFAULT_API_PREFIX
60
+
61
+
62
+ def normalize_base_url(url: str, *, api_prefix: str = DEFAULT_API_PREFIX) -> str:
63
+ """Strip a trailing API prefix from the URL path (not the hostname)."""
64
+ cleaned = url.strip()
65
+ if not cleaned.startswith(("http://", "https://")):
66
+ raise ConfigurationError(f"base_url must start with http:// or https:// (got {url!r})")
67
+ parsed = urlparse(cleaned)
68
+ if not parsed.scheme or not parsed.netloc:
69
+ raise ConfigurationError(f"base_url must include a hostname (got {url!r})")
70
+
71
+ path = (parsed.path or "").rstrip("/")
72
+ norm_prefix = normalize_api_prefix(api_prefix)
73
+ for suffix in (norm_prefix, DEFAULT_API_PREFIX):
74
+ if path == suffix:
75
+ path = ""
76
+ break
77
+ if path.endswith(suffix) and len(path) > len(suffix):
78
+ path = path[: -len(suffix)].rstrip("/")
79
+ break
80
+
81
+ normalized = urlunparse((parsed.scheme, parsed.netloc, path or "", "", "", ""))
82
+ return normalized.rstrip("/")
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class ClientConfig:
87
+ api_key: str
88
+ base_url: str
89
+ api_prefix: str
90
+ workspace_id: Optional[str]
91
+ timeout: float
92
+ max_retries: int
93
+
94
+ def api_path(self, suffix: str) -> str:
95
+ return f"{self.api_prefix}/{suffix.lstrip('/')}"
96
+
97
+ def __repr__(self) -> str: # never print the key
98
+ return (
99
+ f"ClientConfig(base_url={self.base_url!r}, api_prefix={self.api_prefix!r}, "
100
+ f"workspace_id={self.workspace_id!r}, "
101
+ f"timeout={self.timeout!r}, max_retries={self.max_retries!r}, api_key='***')"
102
+ )
103
+
104
+
105
+ def resolve_config(
106
+ *,
107
+ api_key: Optional[str] = None,
108
+ workspace_id: Optional[str] = None,
109
+ base_url: Optional[str] = None,
110
+ api_prefix: Optional[str] = None,
111
+ timeout: Optional[float] = None,
112
+ max_retries: Optional[int] = None,
113
+ ) -> ClientConfig:
114
+ key = (api_key or "").strip() or _env(ENV_API_KEY)
115
+ if not key:
116
+ raise ConfigurationError(
117
+ f"No API key provided. Pass api_key=... or set the {ENV_API_KEY} environment variable."
118
+ )
119
+
120
+ url = (base_url or "").strip() or _env(ENV_BASE_URL) or _env(ENV_BASE_URL_LEGACY)
121
+ prefix = (api_prefix or "").strip() or _env(ENV_API_PREFIX) or DEFAULT_API_PREFIX
122
+ norm_prefix = normalize_api_prefix(prefix)
123
+ workspace = (str(workspace_id).strip() if workspace_id else None) or _env(ENV_WORKSPACE_ID)
124
+
125
+ resolved_timeout = DEFAULT_TIMEOUT if timeout is None else float(timeout)
126
+ if resolved_timeout <= 0:
127
+ raise ConfigurationError("timeout must be greater than 0")
128
+ resolved_retries = DEFAULT_MAX_RETRIES if max_retries is None else int(max_retries)
129
+ if resolved_retries < 0:
130
+ raise ConfigurationError("max_retries must be 0 or greater")
131
+
132
+ return ClientConfig(
133
+ api_key=key,
134
+ base_url=normalize_base_url(url or DEFAULT_BASE_URL, api_prefix=norm_prefix),
135
+ api_prefix=norm_prefix,
136
+ workspace_id=workspace,
137
+ timeout=resolved_timeout,
138
+ max_retries=resolved_retries,
139
+ )