"""Small typed standard-library client for the optional HTTP API."""
from __future__ import annotations
import json
import math
from pathlib import Path
from typing import Any
from urllib.error import HTTPError
from urllib.parse import quote, urlencode, urlsplit
from urllib.request import Request, urlopen
[docs]
class ADPClientError(RuntimeError):
"""An HTTP/API response error raised by :class:`ADPClient`."""
[docs]
def __init__(self, status_code: int, detail: str):
self.status_code = status_code
self.detail = detail
super().__init__(f"ADP API returned HTTP {status_code}: {detail}")
[docs]
class ADPClient:
"""Synchronous API client with no third-party runtime dependencies.
Args:
base_url: API origin, for example ``http://127.0.0.1:8000``.
api_key: Optional API key. When supplied it is sent in ``X-API-Key``.
timeout: Per-request timeout in seconds.
The client does not upload document bytes. ``submit_job`` sends a path that
must exist on the API server and be within its configured allowed roots.
"""
[docs]
def __init__(
self,
base_url: str = "http://127.0.0.1:8000",
*,
api_key: str | None = None,
timeout: float = 10.0,
) -> None:
parsed = urlsplit(base_url)
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
raise ValueError("base_url must be an absolute http:// or https:// URL")
if parsed.username is not None or parsed.password is not None:
raise ValueError("base_url must not contain embedded credentials")
if parsed.query or parsed.fragment:
raise ValueError("base_url must not contain a query or fragment")
if (
isinstance(timeout, bool)
or not isinstance(timeout, (int, float))
or not math.isfinite(timeout)
or timeout <= 0
):
raise ValueError("timeout must be a finite positive number")
if api_key is not None and (
not isinstance(api_key, str) or not api_key.strip()
):
raise ValueError("api_key must be a non-empty string when provided")
self.base_url = base_url.rstrip("/")
self._api_key = api_key
self.timeout = float(timeout)
def _request(
self,
method: str,
path: str,
*,
payload: dict[str, Any] | None = None,
headers: dict[str, str] | None = None,
) -> dict[str, Any]:
request_headers = {"Accept": "application/json"}
if self._api_key is not None:
request_headers["X-API-Key"] = self._api_key
if headers:
request_headers.update(headers)
body = None
if payload is not None:
body = json.dumps(payload, ensure_ascii=False, allow_nan=False).encode(
"utf-8"
)
request_headers["Content-Type"] = "application/json"
request = Request(
f"{self.base_url}{path}", data=body, headers=request_headers, method=method
)
try:
with urlopen(request, timeout=self.timeout) as response:
raw = response.read()
status_code = response.status
except HTTPError as exc:
raw = exc.read()
try:
error_payload = json.loads(raw) if raw else {}
detail = (
error_payload.get("detail", "request failed")
if isinstance(error_payload, dict)
else "request failed"
)
except (UnicodeDecodeError, json.JSONDecodeError):
detail = "request failed"
raise ADPClientError(exc.code, str(detail)) from None
if not raw:
return {}
try:
result = json.loads(raw)
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise ADPClientError(status_code, "API returned invalid JSON") from exc
if not isinstance(result, dict):
raise ADPClientError(status_code, "API returned an unexpected JSON shape")
return result
[docs]
def submit_job(
self, source: str | Path, *, idempotency_key: str | None = None
) -> dict[str, Any]:
"""Submit a server-local document path for background ingestion."""
headers = {"Idempotency-Key": idempotency_key} if idempotency_key else None
return self._request(
"POST", "/v1/jobs", payload={"source": str(source)}, headers=headers
)
[docs]
def get_job(self, job_id: str) -> dict[str, Any]:
"""Retrieve one job by its opaque job ID."""
return self._request("GET", f"/v1/jobs/{quote(job_id, safe='')}")
[docs]
def list_jobs(
self, *, limit: int = 50, status: str | None = None
) -> dict[str, Any]:
"""List recent jobs with optional status filtering."""
if (
isinstance(limit, bool)
or not isinstance(limit, int)
or not 1 <= limit <= 500
):
raise ValueError("limit must be between 1 and 500")
query: dict[str, str | int] = {"limit": limit}
if status is not None:
query["status"] = status
return self._request("GET", f"/v1/jobs?{urlencode(query)}")
[docs]
def cancel_job(self, job_id: str) -> dict[str, Any]:
"""Cancel a job that is still queued."""
return self._request("DELETE", f"/v1/jobs/{quote(job_id, safe='')}")
[docs]
def retry_job(self, job_id: str) -> dict[str, Any]:
"""Manually requeue a terminal failed job."""
return self._request("POST", f"/v1/jobs/{quote(job_id, safe='')}/retry")
[docs]
def search(self, query: str, *, limit: int = 5) -> dict[str, Any]:
"""Search indexed chunks using the API's configured embedding backend."""
if not isinstance(query, str) or not query.strip():
raise ValueError("query must not be empty")
if (
isinstance(limit, bool)
or not isinstance(limit, int)
or not 1 <= limit <= 100
):
raise ValueError("limit must be between 1 and 100")
return self._request(
"GET", f"/v1/search?{urlencode({'q': query, 'limit': limit})}"
)