Skip to content

Commit 85a9e5c

Browse files
shixishclaude
andcommitted
feat: response TypedDicts, dql overloads and csv/jsonl fix, account/verify_token, crawl_download, extract options
- types.py: stdlib TypedDict(total=False) response shapes (DqlResponse, WebSearchResponse, EntitiesResponse, ExtractResponse + per-API, CrawlJob, AccountResponse, AskChunk) and per-API extract option/field Literals. - dql: @Overloads by format/raw; csv -> str, jsonl -> iterator of entities (previously both crashed in response.json() without raw=True). - account(days=None) / verify_token() (GET /v4/account); only AuthError -> False. - crawl_download(name, format, type, num); the crawl watcher reuses it. - extract: keyword-only timeout/mode/fields/etc; transport timeout raised to at least timeout + 10s; extra for proxy/proxyAuth. - pyright dev dependency + config (basic on src/, strict on types.py), CLI annotation fixes, tests/typing assert_type checks. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent a291377 commit 85a9e5c

19 files changed

Lines changed: 1622 additions & 86 deletions

‎pyproject.toml‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ dependencies = [
5151
[project.optional-dependencies]
5252
dev = [
5353
"pytest>=8.0.0",
54+
"pyright>=1.1.390",
5455
]
5556

5657
[project.urls]
@@ -77,3 +78,9 @@ include = [
7778
[tool.pytest.ini_options]
7879
markers = ["live: marks tests as live integration tests requiring a real DIFFBOT_API_TOKEN"]
7980
addopts = "-m 'not live'"
81+
82+
[tool.pyright]
83+
include = ["src", "tests/typing"]
84+
pythonVersion = "3.9"
85+
typeCheckingMode = "basic"
86+
strict = ["src/diffbot/types.py"]

‎src/diffbot/__init__.py‎

Lines changed: 96 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,57 @@ def _installed_version(dist: str):
4848
)
4949
from .ontology import Ontology
5050
from ._transport import RetryPolicy
51-
from .types import ChatMessage, ExportFormat, ResponseFormat, SnippetLength
51+
from .types import (
52+
ChatMessage,
53+
CrawlJobStatusCode,
54+
ExportFormat,
55+
ResponseFormat,
56+
SnippetLength,
57+
AccountResponse,
58+
AccountUsage,
59+
AnalyzeExtractOptions,
60+
ArticleExtractOptions,
61+
ArticleExtractResponse,
62+
ArticleObject,
63+
ArticleTag,
64+
AskChunk,
65+
CrawlDataRecord,
66+
CrawlDownloadFormat,
67+
CrawlJob,
68+
CrawlJobStatus,
69+
CustomExtractOptions,
70+
DiscussionExtractOptions,
71+
DiscussionExtractResponse,
72+
DiscussionObject,
73+
DqlEntity,
74+
DqlResponse,
75+
DqlRewrite,
76+
EntitiesResponse,
77+
EventExtractOptions,
78+
EventExtractResponse,
79+
EventObject,
80+
ExtractApi,
81+
ExtractObject,
82+
ExtractResponse,
83+
ImageExtractOptions,
84+
ImageExtractResponse,
85+
ImageObject,
86+
JobExtractOptions,
87+
JobExtractResponse,
88+
JobObject,
89+
ListExtractOptions,
90+
ListExtractResponse,
91+
ListObject,
92+
NlpEntity,
93+
ProductExtractOptions,
94+
ProductExtractResponse,
95+
ProductObject,
96+
VideoExtractOptions,
97+
VideoExtractResponse,
98+
VideoObject,
99+
WebSearchResponse,
100+
WebSearchResult,
101+
)
52102

53103
__all__ = [
54104
"Diffbot",
@@ -63,6 +113,51 @@ def _installed_version(dist: str):
63113
"ResponseFormat",
64114
"ExportFormat",
65115
"SnippetLength",
116+
"CrawlJobStatusCode",
117+
"AccountResponse",
118+
"AccountUsage",
119+
"AnalyzeExtractOptions",
120+
"ArticleExtractOptions",
121+
"ArticleExtractResponse",
122+
"ArticleObject",
123+
"ArticleTag",
124+
"AskChunk",
125+
"CrawlDataRecord",
126+
"CrawlDownloadFormat",
127+
"CrawlJob",
128+
"CrawlJobStatus",
129+
"CustomExtractOptions",
130+
"DiscussionExtractOptions",
131+
"DiscussionExtractResponse",
132+
"DiscussionObject",
133+
"DqlEntity",
134+
"DqlResponse",
135+
"DqlRewrite",
136+
"EntitiesResponse",
137+
"EventExtractOptions",
138+
"EventExtractResponse",
139+
"EventObject",
140+
"ExtractApi",
141+
"ExtractObject",
142+
"ExtractResponse",
143+
"ImageExtractOptions",
144+
"ImageExtractResponse",
145+
"ImageObject",
146+
"JobExtractOptions",
147+
"JobExtractResponse",
148+
"JobObject",
149+
"ListExtractOptions",
150+
"ListExtractResponse",
151+
"ListObject",
152+
"NlpEntity",
153+
"ProductExtractOptions",
154+
"ProductExtractResponse",
155+
"ProductObject",
156+
"VideoExtractOptions",
157+
"VideoExtractResponse",
158+
"VideoObject",
159+
"WebSearchResponse",
160+
"WebSearchResult",
66161
"DiffbotError",
67162
"AuthError",
68163
"ExtractionError",

‎src/diffbot/account.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
"""Diffbot Account API: usage and token verification (``GET /v4/account``)."""
2+
3+
from typing import TYPE_CHECKING, Any, Dict, Optional
4+
5+
from .errors import AuthError
6+
from .types import AccountResponse
7+
8+
if TYPE_CHECKING:
9+
from .client import Diffbot, DiffbotAsync
10+
11+
12+
def _params(client: Any, days: Optional[int]) -> Dict[str, Any]:
13+
params: Dict[str, Any] = {"token": client.token}
14+
if days is not None:
15+
params["days"] = days
16+
return params
17+
18+
19+
def account(client: "Diffbot", days: Optional[int] = None) -> AccountResponse:
20+
response = client.request("GET", client.account_url, params=_params(client, days))
21+
return response.json()
22+
23+
24+
async def account_async(client: "DiffbotAsync", days: Optional[int] = None) -> AccountResponse:
25+
response = await client.request("GET", client.account_url, params=_params(client, days))
26+
return response.json()
27+
28+
29+
def verify_token(client: "Diffbot") -> bool:
30+
"""``True`` if the token is accepted. Only :class:`AuthError` maps to ``False``;
31+
every other failure (network, 5xx, rate limit) propagates."""
32+
try:
33+
account(client, days=1)
34+
except AuthError:
35+
return False
36+
return True
37+
38+
39+
async def verify_token_async(client: "DiffbotAsync") -> bool:
40+
try:
41+
await account_async(client, days=1)
42+
except AuthError:
43+
return False
44+
return True

‎src/diffbot/cli/__init__.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import re
33
import sys
44
import textwrap
5+
from typing import List, Optional
56
from email.utils import parsedate_to_datetime
67

78
import click
@@ -17,6 +18,7 @@
1718
AuthError,
1819
ExtractionError,
1920
APIError,
21+
ChatMessage,
2022
ValidationError,
2123
json_schema_format,
2224
)
@@ -100,7 +102,7 @@ def extract(url, output, fmt, api):
100102
type=click.Path(exists=True, dir_okay=False),
101103
help="JSON Schema file constraining the output (implies --json)",
102104
)
103-
def ask(prompt: str, output: str = None, as_json: bool = False, schema_path: str = None):
105+
def ask(prompt: str, output: Optional[str] = None, as_json: bool = False, schema_path: Optional[str] = None):
104106
"""Ask a question to the Diffbot LLM"""
105107
db = get_client()
106108
stdin_content = sys.stdin.read() if not sys.stdin.isatty() else None
@@ -119,7 +121,7 @@ def ask(prompt: str, output: str = None, as_json: bool = False, schema_path: str
119121
# permissive default; --json alone must not become {"type": "json_object"}.
120122
interactive_mode = is_interactive and not output and not as_json
121123

122-
messages = [
124+
messages: List[ChatMessage] = [
123125
{
124126
"role": "system",
125127
"content": f"Current local time: {datetime.now().strftime('%A, %B %d, %Y, %I:%M:%S %p %Z')}",

‎src/diffbot/cli/dql.py‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@
55
import re
66
import shutil
77
import time
8+
from typing import cast
89

910
import click
1011
import sys
1112
from rich.console import Console
1213
from rich.progress import Progress, SpinnerColumn, TextColumn
1314
from rich.table import Table
1415

15-
from diffbot import DiffbotError
16+
from diffbot import DiffbotError, ExportFormat
1617

1718
from . import ontology
1819
from diffbot import resolve_token
@@ -258,7 +259,7 @@ def export(query: str, out, fmt: str, exportspec, size: int, from_: int, filter_
258259
query,
259260
size=size,
260261
from_=from_,
261-
format=fmt,
262+
format=cast(ExportFormat, fmt),
262263
exportspec=resolved_spec or None,
263264
filter=filter_,
264265
raw=True,

‎src/diffbot/cli/entities.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def entities(text, fmt, lang):
129129
color = _PALETTE[i % len(_PALETTE)]
130130
name = e.get("name") or e.get("label") or ""
131131
all_types = e.get("allTypes") or []
132-
etype = all_types[0]["name"] if all_types else (e.get("type") or "")
132+
etype = all_types[0].get("name", "") if all_types else (e.get("type") or "")
133133
confidence = e.get("confidence")
134134
salience = e.get("salience")
135135
sentiment = e.get("sentiment")

0 commit comments

Comments
 (0)