freshguard 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.
freshguard/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+ """FreshGuard Python SDK: a thin client for the FreshGuard stale-answer detection API."""
2
+
3
+ from freshguard.async_client import AsyncFreshGuard
4
+ from freshguard.client import FreshGuard
5
+ from freshguard.errors import (
6
+ AuthError,
7
+ ConnectionFailed,
8
+ FreshGuardError,
9
+ NotFoundError,
10
+ RateLimitError,
11
+ ServerError,
12
+ ValidationError,
13
+ VerificationTimeout,
14
+ )
15
+ from freshguard.models import (
16
+ FRESH,
17
+ LABELS,
18
+ POTENTIALLY_STALE,
19
+ STALE,
20
+ UNVERIFIABLE,
21
+ Claim,
22
+ Evidence,
23
+ Page,
24
+ Verification,
25
+ )
26
+
27
+ __version__ = "0.1.0"
28
+
29
+ __all__ = [
30
+ "FRESH",
31
+ "LABELS",
32
+ "POTENTIALLY_STALE",
33
+ "STALE",
34
+ "UNVERIFIABLE",
35
+ "AsyncFreshGuard",
36
+ "AuthError",
37
+ "Claim",
38
+ "ConnectionFailed",
39
+ "Evidence",
40
+ "FreshGuard",
41
+ "FreshGuardError",
42
+ "NotFoundError",
43
+ "Page",
44
+ "RateLimitError",
45
+ "ServerError",
46
+ "ValidationError",
47
+ "Verification",
48
+ "VerificationTimeout",
49
+ "__version__",
50
+ ]
freshguard/_core.py ADDED
@@ -0,0 +1,152 @@
1
+ """Shared, I/O-free logic for the sync and async clients: request building, response parsing,
2
+ error mapping, retry timing. Easy to test without a network."""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Protocol
8
+
9
+ from freshguard.errors import (
10
+ AuthError,
11
+ FreshGuardError,
12
+ NotFoundError,
13
+ RateLimitError,
14
+ ServerError,
15
+ ValidationError,
16
+ )
17
+ from freshguard.models import Verification
18
+
19
+ MAX_SERVER_WAIT = 120 # the API caps ?wait=true&timeout= at this many seconds
20
+ DEFAULT_POLL_INTERVAL = 2.0
21
+
22
+
23
+ @dataclass(frozen=True)
24
+ class Response:
25
+ status: int
26
+ body: Any # parsed JSON, or None if the body was not JSON
27
+ headers: dict[str, str] = field(default_factory=dict) # lower-case names
28
+
29
+
30
+ class Transport(Protocol):
31
+ """Sync transport. Raises `ConnectionFailed` on network errors and timeouts."""
32
+
33
+ def request(
34
+ self,
35
+ method: str,
36
+ url: str,
37
+ *,
38
+ headers: dict[str, str],
39
+ json: Any = None,
40
+ params: dict[str, Any] | None = None,
41
+ timeout: float,
42
+ ) -> Response: ...
43
+
44
+ def close(self) -> None: ...
45
+
46
+
47
+ class AsyncTransport(Protocol):
48
+ async def request(
49
+ self,
50
+ method: str,
51
+ url: str,
52
+ *,
53
+ headers: dict[str, str],
54
+ json: Any = None,
55
+ params: dict[str, Any] | None = None,
56
+ timeout: float,
57
+ ) -> Response: ...
58
+
59
+ async def aclose(self) -> None: ...
60
+
61
+
62
+ def build_headers(api_key: str | None) -> dict[str, str]:
63
+ headers = {"accept": "application/json", "user-agent": "freshguard-python/0.1"}
64
+ if api_key:
65
+ headers["x-api-key"] = api_key
66
+ return headers
67
+
68
+
69
+ def submit_body(
70
+ question: str,
71
+ answer: str,
72
+ answer_generated_at: Any = None,
73
+ metadata: dict[str, Any] | None = None,
74
+ ) -> dict[str, Any]:
75
+ """Validate the obvious mistakes locally and build the JSON body."""
76
+ if not isinstance(question, str) or not question.strip():
77
+ raise ValidationError("question must be a non-empty string.")
78
+ if not isinstance(answer, str) or not answer.strip():
79
+ raise ValidationError("answer must be a non-empty string.")
80
+ body: dict[str, Any] = {"question": question, "answer": answer}
81
+ if answer_generated_at is not None:
82
+ stamp = answer_generated_at
83
+ body["answer_generated_at"] = stamp.isoformat() if hasattr(stamp, "isoformat") else stamp
84
+ if metadata:
85
+ body["metadata"] = {str(k): str(v) for k, v in metadata.items()}
86
+ return body
87
+
88
+
89
+ def raise_for_response(response: Response) -> None:
90
+ """Map a non-2xx response to the right exception. Does nothing for 2xx."""
91
+ if 200 <= response.status < 300:
92
+ return
93
+ request_id = response.headers.get("x-request-id")
94
+ code = message = None
95
+ if isinstance(response.body, dict) and isinstance(response.body.get("error"), dict):
96
+ code = response.body["error"].get("code")
97
+ message = response.body["error"].get("message")
98
+ message = message or f"HTTP {response.status}"
99
+ extra = {"status": response.status, "code": code, "request_id": request_id}
100
+ if response.status == 401:
101
+ raise AuthError(message, **extra)
102
+ if response.status == 404:
103
+ raise NotFoundError(message, **extra)
104
+ if response.status == 422:
105
+ raise ValidationError(message, **extra)
106
+ if response.status == 429:
107
+ raise RateLimitError(message, retry_after=_retry_after(response), **extra)
108
+ if response.status >= 500:
109
+ raise ServerError(message, **extra)
110
+ raise FreshGuardError(message, **extra)
111
+
112
+
113
+ def _retry_after(response: Response) -> float | None:
114
+ try:
115
+ return float(response.headers.get("retry-after", ""))
116
+ except ValueError:
117
+ return None
118
+
119
+
120
+ def expect_json(response: Response) -> dict[str, Any]:
121
+ if not isinstance(response.body, dict):
122
+ raise ServerError(
123
+ "The server returned something that is not FreshGuard JSON.",
124
+ status=response.status,
125
+ request_id=response.headers.get("x-request-id"),
126
+ )
127
+ return response.body
128
+
129
+
130
+ def parse_verification(response: Response) -> Verification:
131
+ data = expect_json(response)
132
+ if "id" not in data:
133
+ raise ServerError("Response has no 'id'.", status=response.status)
134
+ return Verification.from_dict(data)
135
+
136
+
137
+ def should_retry(response: Response) -> bool:
138
+ return response.status >= 500
139
+
140
+
141
+ def backoff_seconds(attempt: int) -> float:
142
+ """0.5s, 1s, 2s ... for retry number `attempt` (0-based)."""
143
+ return 0.5 * (2**attempt)
144
+
145
+
146
+ def list_params(limit: int, label: str | None, before: str | None) -> dict[str, Any]:
147
+ params: dict[str, Any] = {"limit": limit}
148
+ if label:
149
+ params["label"] = label
150
+ if before:
151
+ params["before"] = before
152
+ return params
freshguard/_http.py ADDED
@@ -0,0 +1,75 @@
1
+ """httpx-backed transports. The only module that imports httpx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ import httpx
8
+
9
+ from freshguard._core import Response
10
+ from freshguard.errors import ConnectionFailed
11
+
12
+
13
+ def _response(resp: httpx.Response) -> Response:
14
+ try:
15
+ body = resp.json()
16
+ except ValueError:
17
+ body = None
18
+ return Response(resp.status_code, body, {k.lower(): v for k, v in resp.headers.items()})
19
+
20
+
21
+ def _connection_error(exc: httpx.HTTPError) -> ConnectionFailed:
22
+ kind = "timed out" if isinstance(exc, httpx.TimeoutException) else "network error"
23
+ return ConnectionFailed(f"Could not reach the FreshGuard server ({kind}).")
24
+
25
+
26
+ class HttpxTransport:
27
+ def __init__(self, client: httpx.Client | None = None) -> None:
28
+ self._client = client or httpx.Client()
29
+
30
+ def request(
31
+ self,
32
+ method: str,
33
+ url: str,
34
+ *,
35
+ headers: dict[str, str],
36
+ json: Any = None,
37
+ params: dict[str, Any] | None = None,
38
+ timeout: float,
39
+ ) -> Response:
40
+ try:
41
+ resp = self._client.request(
42
+ method, url, headers=headers, json=json, params=params, timeout=timeout
43
+ )
44
+ except httpx.HTTPError as exc:
45
+ raise _connection_error(exc) from None
46
+ return _response(resp)
47
+
48
+ def close(self) -> None:
49
+ self._client.close()
50
+
51
+
52
+ class HttpxAsyncTransport:
53
+ def __init__(self, client: httpx.AsyncClient | None = None) -> None:
54
+ self._client = client or httpx.AsyncClient()
55
+
56
+ async def request(
57
+ self,
58
+ method: str,
59
+ url: str,
60
+ *,
61
+ headers: dict[str, str],
62
+ json: Any = None,
63
+ params: dict[str, Any] | None = None,
64
+ timeout: float,
65
+ ) -> Response:
66
+ try:
67
+ resp = await self._client.request(
68
+ method, url, headers=headers, json=json, params=params, timeout=timeout
69
+ )
70
+ except httpx.HTTPError as exc:
71
+ raise _connection_error(exc) from None
72
+ return _response(resp)
73
+
74
+ async def aclose(self) -> None:
75
+ await self._client.aclose()
@@ -0,0 +1,171 @@
1
+ """Asynchronous client (same methods as `FreshGuard`, awaitable)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import time
7
+ from collections.abc import Awaitable, Callable
8
+ from typing import Any
9
+
10
+ from freshguard import _core
11
+ from freshguard._core import AsyncTransport, Response
12
+ from freshguard.errors import ConnectionFailed, VerificationTimeout
13
+ from freshguard.models import Page, Verification
14
+
15
+
16
+ class AsyncFreshGuard:
17
+ """async with AsyncFreshGuard(base_url=..., api_key=...) as fg:
18
+ result = await fg.verify(question="...", answer="...")
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ base_url: str = "http://localhost:8000",
24
+ api_key: str | None = None,
25
+ *,
26
+ timeout: float = 30.0,
27
+ max_retries: int = 2,
28
+ transport: AsyncTransport | None = None,
29
+ sleep: Callable[[float], Awaitable[None]] = asyncio.sleep,
30
+ clock: Callable[[], float] = time.monotonic,
31
+ ) -> None:
32
+ self._base = base_url.rstrip("/")
33
+ self._headers = _core.build_headers(api_key)
34
+ self._timeout = timeout
35
+ self._max_retries = max(0, max_retries)
36
+ self._sleep = sleep
37
+ self._clock = clock
38
+ if transport is None:
39
+ from freshguard._http import HttpxAsyncTransport
40
+
41
+ transport = HttpxAsyncTransport()
42
+ self._transport = transport
43
+
44
+ async def __aenter__(self) -> AsyncFreshGuard:
45
+ return self
46
+
47
+ async def __aexit__(self, *exc: object) -> None:
48
+ await self.aclose()
49
+
50
+ async def aclose(self) -> None:
51
+ await self._transport.aclose()
52
+
53
+ async def health(self) -> bool:
54
+ try:
55
+ return (await self._send("GET", "/health", retry=False)).status == 200
56
+ except ConnectionFailed:
57
+ return False
58
+
59
+ async def submit(
60
+ self,
61
+ question: str,
62
+ answer: str,
63
+ *,
64
+ answer_generated_at: Any = None,
65
+ metadata: dict[str, Any] | None = None,
66
+ ) -> Verification:
67
+ body = _core.submit_body(question, answer, answer_generated_at, metadata)
68
+ resp = await self._send("POST", "/v1/verifications", json=body, retry=False)
69
+ _core.raise_for_response(resp)
70
+ return _core.parse_verification(resp)
71
+
72
+ async def reverify(self, verification_id: str) -> Verification:
73
+ """Async twin of `FreshGuard.reverify`."""
74
+ resp = await self._send(
75
+ "POST", f"/v1/verifications/{verification_id}/reverify", retry=False
76
+ )
77
+ _core.raise_for_response(resp)
78
+ return _core.parse_verification(resp)
79
+
80
+ async def get(self, verification_id: str) -> Verification:
81
+ resp = await self._send("GET", f"/v1/verifications/{verification_id}")
82
+ _core.raise_for_response(resp)
83
+ return _core.parse_verification(resp)
84
+
85
+ async def wait(
86
+ self,
87
+ verification_id: str,
88
+ timeout: float = 90.0,
89
+ poll_interval: float = _core.DEFAULT_POLL_INTERVAL,
90
+ ) -> Verification:
91
+ started = self._clock()
92
+ while True:
93
+ current = await self.get(verification_id)
94
+ if current.is_done:
95
+ return current
96
+ remaining = timeout - (self._clock() - started)
97
+ if remaining <= 0:
98
+ raise VerificationTimeout(verification_id, timeout)
99
+ await self._sleep(min(poll_interval, remaining))
100
+
101
+ async def verify(
102
+ self,
103
+ question: str,
104
+ answer: str,
105
+ *,
106
+ wait_seconds: float = 60.0,
107
+ answer_generated_at: Any = None,
108
+ metadata: dict[str, Any] | None = None,
109
+ ) -> Verification:
110
+ body = _core.submit_body(question, answer, answer_generated_at, metadata)
111
+ if wait_seconds > _core.MAX_SERVER_WAIT:
112
+ pending = await self.submit(question, answer, metadata=metadata)
113
+ return await self.wait(pending.id, timeout=wait_seconds)
114
+ server_wait = max(1, int(wait_seconds))
115
+ resp = await self._send(
116
+ "POST",
117
+ "/v1/verifications",
118
+ json=body,
119
+ params={"wait": "true", "timeout": server_wait},
120
+ timeout=max(self._timeout, server_wait + 10.0),
121
+ retry=False,
122
+ )
123
+ _core.raise_for_response(resp)
124
+ result = _core.parse_verification(resp)
125
+ if resp.status == 200 or result.is_done:
126
+ return result
127
+ raise VerificationTimeout(result.id, float(server_wait))
128
+
129
+ async def list(
130
+ self, *, limit: int = 20, label: str | None = None, before: str | None = None
131
+ ) -> Page:
132
+ resp = await self._send(
133
+ "GET", "/v1/verifications", params=_core.list_params(limit, label, before)
134
+ )
135
+ _core.raise_for_response(resp)
136
+ data = _core.expect_json(resp)
137
+ items = tuple(Verification.from_dict(d) for d in data.get("items") or ())
138
+ return Page(items=items, next_before=data.get("next_before"))
139
+
140
+ async def _send(
141
+ self,
142
+ method: str,
143
+ path: str,
144
+ *,
145
+ json: Any = None,
146
+ params: dict[str, Any] | None = None,
147
+ timeout: float | None = None,
148
+ retry: bool = True,
149
+ ) -> Response:
150
+ attempts = 1 + (self._max_retries if retry else 0)
151
+ for attempt in range(attempts):
152
+ last = attempt == attempts - 1
153
+ try:
154
+ resp = await self._transport.request(
155
+ method,
156
+ self._base + path,
157
+ headers=self._headers,
158
+ json=json,
159
+ params=params,
160
+ timeout=timeout or self._timeout,
161
+ )
162
+ except ConnectionFailed:
163
+ if last:
164
+ raise
165
+ await self._sleep(_core.backoff_seconds(attempt))
166
+ continue
167
+ if not last and _core.should_retry(resp):
168
+ await self._sleep(_core.backoff_seconds(attempt))
169
+ continue
170
+ return resp
171
+ raise AssertionError("unreachable")
freshguard/client.py ADDED
@@ -0,0 +1,181 @@
1
+ """Synchronous client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from collections.abc import Callable
7
+ from typing import Any
8
+
9
+ from freshguard import _core
10
+ from freshguard._core import Response, Transport
11
+ from freshguard.errors import ConnectionFailed, VerificationTimeout
12
+ from freshguard.models import Page, Verification
13
+
14
+
15
+ class FreshGuard:
16
+ """Thin client for the FreshGuard API. All verification logic runs on the server.
17
+
18
+ fg = FreshGuard(base_url="http://localhost:8000", api_key="dev-key")
19
+ result = fg.verify(question="...", answer="...", wait_seconds=90)
20
+ if result.should_warn:
21
+ print(result.suggested_correction)
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ base_url: str = "http://localhost:8000",
27
+ api_key: str | None = None,
28
+ *,
29
+ timeout: float = 30.0,
30
+ max_retries: int = 2,
31
+ transport: Transport | None = None,
32
+ sleep: Callable[[float], None] = time.sleep,
33
+ clock: Callable[[], float] = time.monotonic,
34
+ ) -> None:
35
+ self._base = base_url.rstrip("/")
36
+ self._headers = _core.build_headers(api_key)
37
+ self._timeout = timeout
38
+ self._max_retries = max(0, max_retries)
39
+ self._sleep = sleep
40
+ self._clock = clock
41
+ if transport is None:
42
+ from freshguard._http import HttpxTransport
43
+
44
+ transport = HttpxTransport()
45
+ self._transport = transport
46
+
47
+ def __enter__(self) -> FreshGuard:
48
+ return self
49
+
50
+ def __exit__(self, *exc: object) -> None:
51
+ self.close()
52
+
53
+ def close(self) -> None:
54
+ self._transport.close()
55
+
56
+ # ---- public API ------------------------------------------------------------------------
57
+ def health(self) -> bool:
58
+ """True if the server answers /health."""
59
+ try:
60
+ return self._send("GET", "/health", retry=False).status == 200
61
+ except ConnectionFailed:
62
+ return False
63
+
64
+ def submit(
65
+ self,
66
+ question: str,
67
+ answer: str,
68
+ *,
69
+ answer_generated_at: Any = None,
70
+ metadata: dict[str, Any] | None = None,
71
+ ) -> Verification:
72
+ """Start a verification and return at once (status "pending"). Not retried: a retry
73
+ could create a duplicate job."""
74
+ body = _core.submit_body(question, answer, answer_generated_at, metadata)
75
+ resp = self._send("POST", "/v1/verifications", json=body, retry=False)
76
+ _core.raise_for_response(resp)
77
+ return _core.parse_verification(resp)
78
+
79
+ def reverify(self, verification_id: str) -> Verification:
80
+ """Check the same question and answer again. Starts a NEW verification (status
81
+ "pending") whose metadata has `reverified_from`. Not retried (could duplicate)."""
82
+ resp = self._send("POST", f"/v1/verifications/{verification_id}/reverify", retry=False)
83
+ _core.raise_for_response(resp)
84
+ return _core.parse_verification(resp)
85
+
86
+ def get(self, verification_id: str) -> Verification:
87
+ resp = self._send("GET", f"/v1/verifications/{verification_id}")
88
+ _core.raise_for_response(resp)
89
+ return _core.parse_verification(resp)
90
+
91
+ def wait(
92
+ self,
93
+ verification_id: str,
94
+ timeout: float = 90.0,
95
+ poll_interval: float = _core.DEFAULT_POLL_INTERVAL,
96
+ ) -> Verification:
97
+ """Poll until the job finishes. Raises `VerificationTimeout` (the job keeps running)."""
98
+ started = self._clock()
99
+ while True:
100
+ current = self.get(verification_id)
101
+ if current.is_done:
102
+ return current
103
+ remaining = timeout - (self._clock() - started)
104
+ if remaining <= 0:
105
+ raise VerificationTimeout(verification_id, timeout)
106
+ self._sleep(min(poll_interval, remaining))
107
+
108
+ def verify(
109
+ self,
110
+ question: str,
111
+ answer: str,
112
+ *,
113
+ wait_seconds: float = 60.0,
114
+ answer_generated_at: Any = None,
115
+ metadata: dict[str, Any] | None = None,
116
+ ) -> Verification:
117
+ """Submit and wait for the result. A finished-but-failed job is returned with
118
+ `status == "failed"` (check `.error`), not raised. Raises `VerificationTimeout` if it
119
+ is not done within `wait_seconds`."""
120
+ body = _core.submit_body(question, answer, answer_generated_at, metadata)
121
+ if wait_seconds > _core.MAX_SERVER_WAIT:
122
+ pending = self.submit(question, answer, metadata=metadata)
123
+ return self.wait(pending.id, timeout=wait_seconds)
124
+ server_wait = max(1, int(wait_seconds))
125
+ resp = self._send(
126
+ "POST",
127
+ "/v1/verifications",
128
+ json=body,
129
+ params={"wait": "true", "timeout": server_wait},
130
+ timeout=max(self._timeout, server_wait + 10.0),
131
+ retry=False,
132
+ )
133
+ _core.raise_for_response(resp)
134
+ result = _core.parse_verification(resp)
135
+ if resp.status == 200 or result.is_done:
136
+ return result
137
+ raise VerificationTimeout(result.id, float(server_wait))
138
+
139
+ def list(self, *, limit: int = 20, label: str | None = None, before: str | None = None) -> Page:
140
+ resp = self._send(
141
+ "GET", "/v1/verifications", params=_core.list_params(limit, label, before)
142
+ )
143
+ _core.raise_for_response(resp)
144
+ data = _core.expect_json(resp)
145
+ items = tuple(Verification.from_dict(d) for d in data.get("items") or ())
146
+ return Page(items=items, next_before=data.get("next_before"))
147
+
148
+ # ---- internals -------------------------------------------------------------------------
149
+ def _send(
150
+ self,
151
+ method: str,
152
+ path: str,
153
+ *,
154
+ json: Any = None,
155
+ params: dict[str, Any] | None = None,
156
+ timeout: float | None = None,
157
+ retry: bool = True,
158
+ ) -> Response:
159
+ """One request. Safe (GET) requests are retried on network errors and 5xx."""
160
+ attempts = 1 + (self._max_retries if retry else 0)
161
+ for attempt in range(attempts):
162
+ last = attempt == attempts - 1
163
+ try:
164
+ resp = self._transport.request(
165
+ method,
166
+ self._base + path,
167
+ headers=self._headers,
168
+ json=json,
169
+ params=params,
170
+ timeout=timeout or self._timeout,
171
+ )
172
+ except ConnectionFailed:
173
+ if last:
174
+ raise
175
+ self._sleep(_core.backoff_seconds(attempt))
176
+ continue
177
+ if not last and _core.should_retry(resp):
178
+ self._sleep(_core.backoff_seconds(attempt))
179
+ continue
180
+ return resp
181
+ raise AssertionError("unreachable")
freshguard/errors.py ADDED
@@ -0,0 +1,60 @@
1
+ """Exceptions. Everything the SDK raises is a `FreshGuardError`."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class FreshGuardError(Exception):
7
+ """Base class. `status` is the HTTP status if there was one; `code` is the API error code."""
8
+
9
+ def __init__(
10
+ self,
11
+ message: str,
12
+ *,
13
+ status: int | None = None,
14
+ code: str | None = None,
15
+ request_id: str | None = None,
16
+ ) -> None:
17
+ super().__init__(message)
18
+ self.message = message
19
+ self.status = status
20
+ self.code = code
21
+ self.request_id = request_id
22
+
23
+
24
+ class AuthError(FreshGuardError):
25
+ """401: missing or wrong API key."""
26
+
27
+
28
+ class NotFoundError(FreshGuardError):
29
+ """404: unknown verification id."""
30
+
31
+
32
+ class ValidationError(FreshGuardError):
33
+ """422 (or a bad argument caught before sending)."""
34
+
35
+
36
+ class RateLimitError(FreshGuardError):
37
+ """429: too many requests. `retry_after` is the number of seconds to wait, if known."""
38
+
39
+ def __init__(self, message: str, *, retry_after: float | None = None, **kwargs) -> None:
40
+ super().__init__(message, **kwargs)
41
+ self.retry_after = retry_after
42
+
43
+
44
+ class ServerError(FreshGuardError):
45
+ """5xx, or a response that is not valid FreshGuard JSON."""
46
+
47
+
48
+ class ConnectionFailed(FreshGuardError):
49
+ """The server could not be reached (network error or timeout)."""
50
+
51
+
52
+ class VerificationTimeout(FreshGuardError):
53
+ """We stopped waiting. The job keeps running on the server: call `get` or `wait` again."""
54
+
55
+ def __init__(self, verification_id: str, waited: float) -> None:
56
+ super().__init__(
57
+ f"Verification {verification_id} not finished after {waited:g}s; it is still running."
58
+ )
59
+ self.verification_id = verification_id
60
+ self.waited = waited
freshguard/models.py ADDED
@@ -0,0 +1,116 @@
1
+ """Result objects. Plain frozen dataclasses built from the API's JSON (no extra dependencies)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime
7
+ from typing import Any
8
+
9
+ FRESH = "fresh"
10
+ STALE = "stale"
11
+ POTENTIALLY_STALE = "potentially_stale"
12
+ UNVERIFIABLE = "unverifiable"
13
+ LABELS = (FRESH, STALE, POTENTIALLY_STALE, UNVERIFIABLE)
14
+ DONE_STATUSES = ("completed", "failed")
15
+
16
+
17
+ def _dt(value: Any) -> datetime | None:
18
+ if not value:
19
+ return None
20
+ try:
21
+ return datetime.fromisoformat(str(value).replace("Z", "+00:00"))
22
+ except ValueError:
23
+ return None
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class Evidence:
28
+ url: str
29
+ tier: int
30
+ stance: str # "supports" | "contradicts" | "neutral"
31
+ quoted_span: str | None = None
32
+ published_at: datetime | None = None
33
+ fetched_at: datetime | None = None
34
+ integrity_ok: bool | None = None
35
+
36
+ @classmethod
37
+ def from_dict(cls, data: dict[str, Any]) -> Evidence:
38
+ return cls(
39
+ url=str(data.get("url", "")),
40
+ tier=int(data.get("tier", 3)),
41
+ stance=str(data.get("stance", "neutral")),
42
+ quoted_span=data.get("quoted_span"),
43
+ published_at=_dt(data.get("published_at")),
44
+ fetched_at=_dt(data.get("fetched_at")),
45
+ integrity_ok=data.get("integrity_ok"),
46
+ )
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class Claim:
51
+ text: str
52
+ label: str
53
+ volatility: str = "slow"
54
+ reasoning: str = ""
55
+ freshness_window_days: int | None = None
56
+ evidence: tuple[Evidence, ...] = ()
57
+
58
+ @classmethod
59
+ def from_dict(cls, data: dict[str, Any]) -> Claim:
60
+ return cls(
61
+ text=str(data.get("text", "")),
62
+ label=str(data.get("label", UNVERIFIABLE)),
63
+ volatility=str(data.get("volatility", "slow")),
64
+ reasoning=str(data.get("reasoning", "")),
65
+ freshness_window_days=data.get("freshness_window_days"),
66
+ evidence=tuple(Evidence.from_dict(e) for e in data.get("evidence") or ()),
67
+ )
68
+
69
+
70
+ @dataclass(frozen=True)
71
+ class Verification:
72
+ id: str
73
+ status: str # "pending" | "running" | "completed" | "failed"
74
+ label: str | None = None
75
+ confidence: float | None = None
76
+ suggested_correction: str | None = None
77
+ error: str | None = None
78
+ claims: tuple[Claim, ...] = ()
79
+ created_at: datetime | None = None
80
+ finished_at: datetime | None = None
81
+ metadata: dict[str, str] = field(default_factory=dict)
82
+
83
+ @classmethod
84
+ def from_dict(cls, data: dict[str, Any]) -> Verification:
85
+ return cls(
86
+ id=str(data["id"]),
87
+ status=str(data.get("status", "pending")),
88
+ label=data.get("label"),
89
+ confidence=data.get("confidence"),
90
+ suggested_correction=data.get("suggested_correction"),
91
+ error=data.get("error"),
92
+ claims=tuple(Claim.from_dict(c) for c in data.get("claims") or ()),
93
+ created_at=_dt(data.get("created_at")),
94
+ finished_at=_dt(data.get("finished_at")),
95
+ metadata=dict(data.get("metadata") or {}),
96
+ )
97
+
98
+ @property
99
+ def is_done(self) -> bool:
100
+ """True once the job has finished, successfully or not."""
101
+ return self.status in DONE_STATUSES
102
+
103
+ @property
104
+ def is_stale(self) -> bool:
105
+ return self.label == STALE
106
+
107
+ @property
108
+ def should_warn(self) -> bool:
109
+ """Show the user a warning: the answer is stale or possibly out of date."""
110
+ return self.label in (STALE, POTENTIALLY_STALE)
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class Page:
115
+ items: tuple[Verification, ...]
116
+ next_before: str | None = None
freshguard/py.typed ADDED
File without changes
@@ -0,0 +1,94 @@
1
+ Metadata-Version: 2.4
2
+ Name: freshguard
3
+ Version: 0.1.0
4
+ Summary: Python client for the FreshGuard stale-answer detection API
5
+ Requires-Python: >=3.9
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: httpx<1,>=0.27
8
+ Provides-Extra: dev
9
+ Requires-Dist: pytest>=8; extra == "dev"
10
+ Requires-Dist: ruff>=0.5; extra == "dev"
11
+
12
+ # FreshGuard Python SDK
13
+
14
+ A thin client for the FreshGuard API. It sends an AI answer to the server, which checks its factual
15
+ claims against current web sources and returns `fresh`, `stale`, `potentially_stale` or
16
+ `unverifiable`. All verification logic runs on the server.
17
+
18
+ Full API contract and chatbot integration plan: `docs/INTEGRATION_GUIDE.md`.
19
+
20
+ ## Install
21
+
22
+ From the repo root, in your app's virtual environment:
23
+
24
+ ```powershell
25
+ pip install -e ./sdk
26
+ ```
27
+
28
+ Requires Python 3.9+ (installs `httpx`).
29
+
30
+ ## Use
31
+
32
+ ```python
33
+ from freshguard import FreshGuard
34
+
35
+ fg = FreshGuard(base_url="http://localhost:8000", api_key="dev-key")
36
+
37
+ result = fg.verify(
38
+ question="Who is the CEO of Twitter?",
39
+ answer="Jack Dorsey is the CEO of Twitter.",
40
+ wait_seconds=90,
41
+ )
42
+ print(result.label, result.confidence) # "stale" 0.8
43
+ print(result.suggested_correction)
44
+ print(result.should_warn) # True for stale / potentially_stale
45
+ ```
46
+
47
+ Verification takes 10-60+ seconds, so in a chat app reply first and verify in the background:
48
+
49
+ ```python
50
+ job = fg.submit(question, answer, metadata={"message_id": "m-7"}) # returns at once
51
+ ...
52
+ result = fg.get(job.id) # status: pending | running | completed | failed
53
+ result = fg.wait(job.id, timeout=90) # or block, polling every 2 s
54
+ ```
55
+
56
+ See `examples/chatbot_pattern.py`. Async version: `from freshguard import AsyncFreshGuard` with
57
+ `async with AsyncFreshGuard(...) as fg:` and `await` on every method.
58
+
59
+ ## Methods
60
+
61
+ | Method | Does |
62
+ |---|---|
63
+ | `verify(question, answer, wait_seconds=60, metadata=None)` | submit and wait; returns the result, or raises `VerificationTimeout` |
64
+ | `submit(question, answer, metadata=None)` | start a job, returns a `pending` result at once |
65
+ | `get(id)` | current state of a job |
66
+ | `wait(id, timeout=90, poll_interval=2)` | poll until finished; raises `VerificationTimeout` (job keeps running) |
67
+ | `list(limit=20, label=None, before=None)` | recent results, newest first, with paging cursor `next_before` |
68
+ | `health()` | `True` if the server is reachable |
69
+
70
+ A job that finished but could not be checked (providers down) is **returned** with
71
+ `status == "failed"` and `.error` set; it is not raised.
72
+
73
+ ## Errors
74
+
75
+ All subclass `FreshGuardError`: `AuthError` (401), `NotFoundError` (404), `ValidationError`
76
+ (422, or a bad argument), `RateLimitError` (429, has `.retry_after`), `ServerError` (5xx),
77
+ `ConnectionFailed`, `VerificationTimeout`. Each has `.status`, `.code` and `.request_id` when known.
78
+ Reads (`get`, `wait`, `list`) are retried twice on network errors and 5xx; `submit` and `verify` are
79
+ never retried, because a retry could create a duplicate job.
80
+
81
+ ```python
82
+ try:
83
+ result = fg.verify(question, answer, wait_seconds=60)
84
+ except FreshGuardError:
85
+ result = None # show the answer without a badge
86
+ ```
87
+
88
+ ## Test
89
+
90
+ ```powershell
91
+ cd sdk
92
+ pip install -e ".[dev]"
93
+ python -m pytest -q
94
+ ```
@@ -0,0 +1,12 @@
1
+ freshguard/__init__.py,sha256=A5bcc9HosXc6-y6QBDLDzS34rSpMLXZIov3fdhkhxwE,1008
2
+ freshguard/_core.py,sha256=UIKONtH-ADdakDstacQAEhUzR2QB3tp6fRBOSeDDw4M,4928
3
+ freshguard/_http.py,sha256=3nW3b4APzlW_3IzXanhKmY011mIPBzj8WhHTyOB2_zQ,2210
4
+ freshguard/async_client.py,sha256=oeKSN008kMkzo5pc5-vWZ3huijjOwobJ9QikBQhQuNQ,6151
5
+ freshguard/client.py,sha256=KdxK5uDsms1AWMC1l_WwBNDNK9_ZZUrMMWRDbuPpT4A,6931
6
+ freshguard/errors.py,sha256=2C0NTEeg2cFoTrC1B8y24CsKtenv15nb8EGehOqFjoA,1843
7
+ freshguard/models.py,sha256=c9HoGmuPvWZEe29-RIZ06sxP0YikssQh44obenMg1qo,3759
8
+ freshguard/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ freshguard-0.1.0.dist-info/METADATA,sha256=GePBBqsNDMJGq_c852736-FZhgeTC7YhKpUljnPDLiw,3258
10
+ freshguard-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ freshguard-0.1.0.dist-info/top_level.txt,sha256=DJkSbCbPrpfnWdrJvHDSZRdf4xwUIM_NtWr4Z5cuIUs,11
12
+ freshguard-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ freshguard