Skip to content

Commit a605945

Browse files
shixishclaude
andcommitted
feat(transport): Phase 0 foundation — per-host bases, full HTTP capability set, retry policy, and error hierarchy
Mirrors the TypeScript SDK's Phase 0 transport work (same branch) in Python idiom: - Shared sync/async request-shaping and response-handling helpers in a new _transport.py, replacing the duplicated Diffbot/DiffbotAsync._raise_for_status methods and the repeated client._http.get(...) + raise pattern across every handler module with a single client.request(method, url, ...) used by both. - Per-host base URLs (api_base/kg_base/llm_base/nlp_base) with the existing per-endpoint *_url constructor options kept as winning aliases (additive). No standalone "endpoint registry" data structure — Phase 0 adds zero new endpoints, so the only thing it would serve today is base-URL resolution (done directly in client.py) and a retryable flag (done ad hoc), matching the TypeScript SDK's same call on this branch (see its PHASE0_LEFTOVERS.md). - Repeated query parameters (declared via a Sequence-typed QueryParams; httpx already encodes list-valued params as repeated keys). - DELETE + arbitrary method/body/Content-Type, form-encoded (data=) and raw (content=) request bodies, per-call timeout override, and a follow_redirects override, all threaded through client.request(). - A default-on retry policy (RetryPolicy dataclass) for 429/5xx/connection errors with backoff, jitter, and Retry-After support, capped at 3 attempts; disable client-wide with retry=False or per call with retryable=False. crawl_delete_job/_async now pass retryable=False since it's a GET-shaped mutation that must not be retried blindly. - Response headers surfaced on APIError (and subclasses) via a new headers field, populated from the error response. - NotFoundError (404) and JobError, both subclassing APIError so existing `except APIError` call sites are unaffected. crawl's job-failure path now raises JobError instead of a synthesized APIError(500, ...). - fix(ask): read the response body before raising on a non-2xx streaming response (sync and async). Previously client._raise_for_status accessed response.text immediately after opening the stream, which raises httpx.ResponseNotRead instead of AuthError/RateLimitError once the connection is genuinely still streaming (tests use a real byte-stream mock transport, since httpx.MockTransport's content= pre-fills the body and masks this). ask()/ask_json() now go through client.request(..., stream=True), which also means they pick up the retry policy like every other handler. - web_search.py's sync/async bodies, previously 100% duplicated, now share a single _build_web_search_request() helper. Also adds additive TypedDict/Literal type aliases (types.py) for existing surfaces only — ChatMessage, ResponseFormat, ExportFormat, SnippetLength — used in ask()/dql()/web_search() signatures. No Pydantic, no runtime behavior change; Python floor stays >=3.9 (stdlib typing only). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
1 parent 8040ce7 commit a605945

17 files changed

Lines changed: 1012 additions & 172 deletions

‎src/diffbot/__init__.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,10 +41,14 @@ def _installed_version(dist: str):
4141
AuthError,
4242
DiffbotError,
4343
ExtractionError,
44+
JobError,
45+
NotFoundError,
4446
RateLimitError,
4547
ValidationError,
4648
)
4749
from .ontology import Ontology
50+
from ._transport import RetryPolicy
51+
from .types import ChatMessage, ExportFormat, ResponseFormat, SnippetLength
4852

4953
__all__ = [
5054
"Diffbot",
@@ -54,9 +58,16 @@ def _installed_version(dist: str):
5458
"CrawlEvent",
5559
"CrawlEventType",
5660
"Ontology",
61+
"RetryPolicy",
62+
"ChatMessage",
63+
"ResponseFormat",
64+
"ExportFormat",
65+
"SnippetLength",
5766
"DiffbotError",
5867
"AuthError",
5968
"ExtractionError",
69+
"JobError",
70+
"NotFoundError",
6071
"RateLimitError",
6172
"APIError",
6273
"ValidationError",

‎src/diffbot/_constants.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
"""Per-host base URLs and shared transport defaults.
2+
3+
Overridable via ``api_base``/``kg_base``/``llm_base``/``nlp_base`` on the client
4+
constructors; the older per-endpoint ``*_url`` options still win over these when set.
5+
"""
6+
7+
API_BASE = "https://api.diffbot.com"
8+
KG_BASE = "https://kg.diffbot.com"
9+
LLM_BASE = "https://llm.diffbot.com"
10+
NLP_HOST_BASE = "https://nl.diffbot.com"
11+
12+
DEFAULT_TIMEOUT = 30.0

‎src/diffbot/_transport.py‎

Lines changed: 207 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,207 @@
1+
"""Shared request-shaping and response-handling helpers for the sync and async clients.
2+
3+
Both ``Diffbot`` and ``DiffbotAsync`` delegate here so the two don't carry duplicate
4+
copies of retry/timeout/error-raising logic; the only difference between them is
5+
whether the underlying ``httpx.Client``/``httpx.AsyncClient`` call is awaited.
6+
"""
7+
8+
import asyncio
9+
import random
10+
import time
11+
from dataclasses import dataclass
12+
from email.utils import parsedate_to_datetime
13+
from typing import Any, Dict, Optional, Sequence, Union
14+
15+
import httpx
16+
17+
from .errors import APIError, AuthError, NotFoundError, RateLimitError
18+
19+
QueryParamValue = Union[str, int, float, bool]
20+
QueryParams = Dict[str, Union[QueryParamValue, Sequence[QueryParamValue], None]]
21+
22+
23+
@dataclass
24+
class RetryPolicy:
25+
"""Retry policy for transient failures (429, 5xx, connection errors).
26+
27+
``max_attempts`` counts the initial try, so ``3`` means up to 2 retries. Disable
28+
per client with ``retry=False`` on the client constructor; disable per call with
29+
``retryable=False`` — required for GET-shaped mutations (e.g. ``crawl?delete=1``)
30+
that must never be retried blindly.
31+
"""
32+
33+
max_attempts: int = 3
34+
base_delay: float = 0.25
35+
max_delay: float = 5.0
36+
jitter: bool = True
37+
38+
39+
DEFAULT_RETRY_POLICY = RetryPolicy()
40+
41+
42+
def resolve_retry_policy(retry: Union[RetryPolicy, bool, None]) -> Optional[RetryPolicy]:
43+
"""``None``/``True`` -> default policy (retries on by default); ``False`` -> disabled."""
44+
if retry is False:
45+
return None
46+
if retry is None or retry is True:
47+
return DEFAULT_RETRY_POLICY
48+
return retry
49+
50+
51+
def _is_retryable_status(status_code: int) -> bool:
52+
return status_code == 429 or status_code >= 500
53+
54+
55+
def _compute_delay(attempt: int, retry_after: Optional[str], policy: RetryPolicy) -> float:
56+
"""Parses ``Retry-After`` as seconds or an HTTP date; falls back to exponential backoff."""
57+
if retry_after:
58+
try:
59+
return max(0.0, float(retry_after))
60+
except ValueError:
61+
pass
62+
try:
63+
dt = parsedate_to_datetime(retry_after)
64+
return max(0.0, dt.timestamp() - time.time())
65+
except (TypeError, ValueError):
66+
pass
67+
exponential = min(policy.max_delay, policy.base_delay * (2 ** (attempt - 1)))
68+
return exponential * (0.5 + random.random() * 0.5) if policy.jitter else exponential
69+
70+
71+
def raise_for_status(response: httpx.Response) -> None:
72+
if response.is_success:
73+
return
74+
status = response.status_code
75+
body = response.text
76+
headers = dict(response.headers)
77+
if status in (401, 403):
78+
raise AuthError(status, body, headers=headers)
79+
if status == 404:
80+
raise NotFoundError(status, body, headers=headers)
81+
if status == 429:
82+
raise RateLimitError(status, body, retry_after=response.headers.get("retry-after"), headers=headers)
83+
raise APIError(status, body, headers=headers)
84+
85+
86+
def _build_kwargs(
87+
params: Optional[QueryParams],
88+
headers: Optional[Dict[str, str]],
89+
json: Optional[Any],
90+
content: Optional[Union[str, bytes]],
91+
data: Optional[Dict[str, Any]],
92+
timeout: Optional[float],
93+
) -> Dict[str, Any]:
94+
kwargs: Dict[str, Any] = {}
95+
if params is not None:
96+
kwargs["params"] = params
97+
if headers is not None:
98+
kwargs["headers"] = headers
99+
if json is not None:
100+
kwargs["json"] = json
101+
if content is not None:
102+
kwargs["content"] = content
103+
if data is not None:
104+
kwargs["data"] = data
105+
if timeout is not None:
106+
kwargs["timeout"] = timeout
107+
return kwargs
108+
109+
110+
def request(
111+
http: httpx.Client,
112+
retry_policy: Optional[RetryPolicy],
113+
method: str,
114+
url: str,
115+
*,
116+
params: Optional[QueryParams] = None,
117+
headers: Optional[Dict[str, str]] = None,
118+
json: Optional[Any] = None,
119+
content: Optional[Union[str, bytes]] = None,
120+
data: Optional[Dict[str, Any]] = None,
121+
timeout: Optional[float] = None,
122+
retryable: bool = True,
123+
follow_redirects: Optional[bool] = None,
124+
stream: bool = False,
125+
) -> httpx.Response:
126+
"""Send a request, retrying on 429/5xx/connection errors per ``retry_policy``, then
127+
raise for a non-2xx status. The request is rebuilt fresh on each attempt so a
128+
request body is never resent from an already-consumed stream.
129+
130+
With ``stream=True`` the response body is left unread on success (the caller
131+
must iterate it and call ``.close()``), but is still read before raising on a
132+
non-2xx status — without that, accessing the error body (e.g. via
133+
``RateLimitError.message``) would raise ``httpx.ResponseNotRead``.
134+
"""
135+
kwargs = _build_kwargs(params, headers, json, content, data, timeout)
136+
send_kwargs: Dict[str, Any] = {} if follow_redirects is None else {"follow_redirects": follow_redirects}
137+
if stream:
138+
send_kwargs["stream"] = True
139+
policy = retry_policy if retryable else None
140+
max_attempts = policy.max_attempts if policy else 1
141+
attempt = 1
142+
while True:
143+
req = http.build_request(method, url, **kwargs)
144+
try:
145+
response = http.send(req, **send_kwargs)
146+
except httpx.TransportError:
147+
if policy and attempt < max_attempts:
148+
time.sleep(_compute_delay(attempt, None, policy))
149+
attempt += 1
150+
continue
151+
raise
152+
if policy and attempt < max_attempts and _is_retryable_status(response.status_code):
153+
if stream:
154+
response.close()
155+
time.sleep(_compute_delay(attempt, response.headers.get("retry-after"), policy))
156+
attempt += 1
157+
continue
158+
if response.is_success:
159+
return response
160+
response.read()
161+
raise_for_status(response)
162+
163+
164+
async def request_async(
165+
http: httpx.AsyncClient,
166+
retry_policy: Optional[RetryPolicy],
167+
method: str,
168+
url: str,
169+
*,
170+
params: Optional[QueryParams] = None,
171+
headers: Optional[Dict[str, str]] = None,
172+
json: Optional[Any] = None,
173+
content: Optional[Union[str, bytes]] = None,
174+
data: Optional[Dict[str, Any]] = None,
175+
timeout: Optional[float] = None,
176+
retryable: bool = True,
177+
follow_redirects: Optional[bool] = None,
178+
stream: bool = False,
179+
) -> httpx.Response:
180+
"""Async twin of :func:`request`."""
181+
kwargs = _build_kwargs(params, headers, json, content, data, timeout)
182+
send_kwargs: Dict[str, Any] = {} if follow_redirects is None else {"follow_redirects": follow_redirects}
183+
if stream:
184+
send_kwargs["stream"] = True
185+
policy = retry_policy if retryable else None
186+
max_attempts = policy.max_attempts if policy else 1
187+
attempt = 1
188+
while True:
189+
req = http.build_request(method, url, **kwargs)
190+
try:
191+
response = await http.send(req, **send_kwargs)
192+
except httpx.TransportError:
193+
if policy and attempt < max_attempts:
194+
await asyncio.sleep(_compute_delay(attempt, None, policy))
195+
attempt += 1
196+
continue
197+
raise
198+
if policy and attempt < max_attempts and _is_retryable_status(response.status_code):
199+
if stream:
200+
await response.aclose()
201+
await asyncio.sleep(_compute_delay(attempt, response.headers.get("retry-after"), policy))
202+
attempt += 1
203+
continue
204+
if response.is_success:
205+
return response
206+
await response.aread()
207+
raise_for_status(response)

‎src/diffbot/ask.py‎

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, Iterator, List, Optional
66

77
from .errors import ValidationError
8+
from .types import ChatMessage, ResponseFormat
89

910
if TYPE_CHECKING:
1011
from .client import Diffbot, DiffbotAsync
@@ -20,7 +21,7 @@
2021
_JSON_FENCE = re.compile(r"^```(?:json)?\s*|\s*```$", re.MULTILINE)
2122

2223

23-
def json_schema_format(schema: Dict[str, Any], *, name: str = "response") -> Dict[str, Any]:
24+
def json_schema_format(schema: Dict[str, Any], *, name: str = "response") -> ResponseFormat:
2425
"""Build a ``response_format`` value that constrains output to ``schema``.
2526
2627
The endpoint requires the schema nested under ``json_schema.schema``; passing
@@ -36,7 +37,7 @@ def json_schema_format(schema: Dict[str, Any], *, name: str = "response") -> Dic
3637
return {"type": "json_schema", "json_schema": {"name": name, "schema": schema}}
3738

3839

39-
def _validate_response_format(response_format: Optional[Dict[str, Any]]) -> None:
40+
def _validate_response_format(response_format: Optional[ResponseFormat]) -> None:
4041
"""Reject shapes the endpoint would accept but silently not enforce."""
4142
if response_format is None:
4243
return
@@ -61,9 +62,9 @@ def _validate_response_format(response_format: Optional[Dict[str, Any]]) -> None
6162

6263
def _build_payload(
6364
client: Any,
64-
messages: List[Dict[str, str]],
65+
messages: List[ChatMessage],
6566
*,
66-
response_format: Optional[Dict[str, Any]] = None,
67+
response_format: Optional[ResponseFormat] = None,
6768
) -> tuple:
6869
_validate_response_format(response_format)
6970
headers = {"Authorization": f"Bearer {client.token}"}
@@ -119,8 +120,8 @@ def _extract_json(text: str) -> Any:
119120

120121
def _resolve_format(
121122
schema: Optional[Dict[str, Any]],
122-
response_format: Optional[Dict[str, Any]],
123-
) -> Dict[str, Any]:
123+
response_format: Optional[ResponseFormat],
124+
) -> ResponseFormat:
124125
if schema is not None and response_format is not None:
125126
raise ValidationError("pass either schema or response_format, not both")
126127
if response_format is not None:
@@ -141,42 +142,46 @@ def _check_tool_call_leak(parsed: Any) -> Any:
141142

142143
def ask(
143144
client: "Diffbot",
144-
messages: List[Dict[str, str]],
145+
messages: List[ChatMessage],
145146
*,
146-
response_format: Optional[Dict[str, Any]] = None,
147+
response_format: Optional[ResponseFormat] = None,
147148
) -> Iterator[str]:
148149
headers, payload = _build_payload(client, messages, response_format=response_format)
149-
with client._http.stream("POST", client.llm_url, headers=headers, json=payload) as response:
150-
client._raise_for_status(response)
150+
response = client.request("POST", client.llm_url, headers=headers, json=payload, stream=True)
151+
try:
151152
for line in response.iter_lines():
152153
if line:
153154
content = _parse_chunk(line)
154155
if content:
155156
yield content
157+
finally:
158+
response.close()
156159

157160

158161
async def ask_async(
159162
client: "DiffbotAsync",
160-
messages: List[Dict[str, str]],
163+
messages: List[ChatMessage],
161164
*,
162-
response_format: Optional[Dict[str, Any]] = None,
165+
response_format: Optional[ResponseFormat] = None,
163166
) -> AsyncIterator[str]:
164167
headers, payload = _build_payload(client, messages, response_format=response_format)
165-
async with client._http.stream("POST", client.llm_url, headers=headers, json=payload) as response:
166-
client._raise_for_status(response)
168+
response = await client.request("POST", client.llm_url, headers=headers, json=payload, stream=True)
169+
try:
167170
async for line in response.aiter_lines():
168171
if line:
169172
content = _parse_chunk(line)
170173
if content:
171174
yield content
175+
finally:
176+
await response.aclose()
172177

173178

174179
def ask_json(
175180
client: "Diffbot",
176-
messages: List[Dict[str, str]],
181+
messages: List[ChatMessage],
177182
schema: Optional[Dict[str, Any]] = None,
178183
*,
179-
response_format: Optional[Dict[str, Any]] = None,
184+
response_format: Optional[ResponseFormat] = None,
180185
) -> Any:
181186
fmt = _resolve_format(schema, response_format)
182187
text = "".join(ask(client, messages, response_format=fmt))
@@ -185,10 +190,10 @@ def ask_json(
185190

186191
async def ask_json_async(
187192
client: "DiffbotAsync",
188-
messages: List[Dict[str, str]],
193+
messages: List[ChatMessage],
189194
schema: Optional[Dict[str, Any]] = None,
190195
*,
191-
response_format: Optional[Dict[str, Any]] = None,
196+
response_format: Optional[ResponseFormat] = None,
192197
) -> Any:
193198
fmt = _resolve_format(schema, response_format)
194199
chunks = [chunk async for chunk in ask_async(client, messages, response_format=fmt)]

0 commit comments

Comments
 (0)