Skip to content

Commit f15d9c1

Browse files
authored
Merge pull request #10 from diffbot/feat/sdk-s2
Release diffbot 3.4.0
2 parents 4cd21ee + b7937a8 commit f15d9c1

38 files changed

Lines changed: 4695 additions & 373 deletions

‎.github/workflows/live-tests.yml‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
name: Live tests
2+
3+
# Real-API tests (`pytest -m live`). Deliberately never run on pull requests,
4+
# so a fork or PR can neither spend credits nor reach the secret.
5+
on:
6+
push:
7+
branches: [main]
8+
workflow_dispatch:
9+
schedule:
10+
- cron: "17 14 1,15 * *"
11+
12+
permissions:
13+
contents: read
14+
15+
jobs:
16+
live:
17+
if: github.event_name != 'pull_request'
18+
runs-on: ubuntu-latest
19+
concurrency:
20+
group: live-tests
21+
cancel-in-progress: false
22+
env:
23+
DIFFBOT_TOKEN: ${{ secrets.DIFFBOT_TOKEN }}
24+
# The SDK's own credential lookup reads DIFFBOT_API_TOKEN.
25+
DIFFBOT_API_TOKEN: ${{ secrets.DIFFBOT_TOKEN }}
26+
steps:
27+
- uses: actions/checkout@v4
28+
29+
- name: Install uv
30+
uses: astral-sh/setup-uv@v5
31+
with:
32+
python-version: "3.12"
33+
34+
- name: Install dependencies (locked)
35+
run: uv sync --frozen --extra dev
36+
37+
- name: Run live tests
38+
run: uv run pytest -m live -v

‎.github/workflows/release.yml‎

Lines changed: 121 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,110 @@
1-
name: Release Binaries
1+
name: Release
22

3-
# Builds the self-contained `db` CLI binary for each supported platform and
4-
# publishes them (with SHA256 checksums) to a GitHub Release. Triggered by
5-
# pushing a version tag (e.g. v0.2.1); also runnable manually for dry runs.
3+
# One workflow for a release. Triggered by pushing a version tag (e.g. v3.4.0);
4+
# also runnable manually (workflow_dispatch) as a dry run that verifies and
5+
# builds everything but never publishes.
6+
#
7+
# verify -> build-dist (sdist + wheel) --\
8+
# verify -> build-binaries (db CLI) -----+-> publish-pypi -> github-release
9+
#
10+
# PyPI publishing uses trusted publishing (OIDC), so no API token is stored.
11+
# One-time setup (maintainer): on pypi.org > diffbot > Manage > Publishing, add
12+
# a GitHub publisher with owner `diffbot`, repository `diffbot-python`,
13+
# workflow `release.yml`, and NO environment (leave it blank).
614
on:
715
push:
816
tags: ["v*"]
917
workflow_dispatch:
1018

1119
permissions:
12-
contents: write
20+
contents: read
1321

14-
# Re-pushing a tag (or re-dispatching) cancels an in-flight run for the same
15-
# ref so a stuck build can't pile up behind a newer attempt.
22+
# Never cancel an in-flight run: a cancelled publish could leave PyPI with only
23+
# some of the files for a version (PyPI doesn't allow re-uploading them) or
24+
# leave PyPI and the GitHub Release out of sync. Runs for the same ref queue.
1625
concurrency:
1726
group: release-${{ github.ref }}
18-
cancel-in-progress: true
27+
cancel-in-progress: false
1928

2029
jobs:
21-
build:
30+
verify:
31+
name: Verify version, tests, and types
32+
runs-on: ubuntu-latest
33+
timeout-minutes: 20
34+
steps:
35+
- uses: actions/checkout@v4
36+
37+
- name: Install uv
38+
uses: astral-sh/setup-uv@v5
39+
with:
40+
python-version: "3.12"
41+
42+
- name: Install dependencies (locked)
43+
run: uv sync --frozen --extra dev
44+
45+
# __version__ is read from the installed distribution metadata, so this
46+
# checks that pyproject.toml's version is what the package reports.
47+
- name: Check tag matches package version
48+
run: |
49+
set -euo pipefail
50+
pkg=$(grep -m1 '^version' pyproject.toml | cut -d'"' -f2)
51+
runtime=$(uv run --frozen python -c 'import diffbot; print(diffbot.__version__)')
52+
if [ "$pkg" != "$runtime" ]; then
53+
echo "::error::pyproject.toml version ${pkg} does not match diffbot.__version__ ${runtime}."
54+
exit 1
55+
fi
56+
if [ "${GITHUB_REF_TYPE}" = "tag" ]; then
57+
tag=${GITHUB_REF_NAME#v}
58+
if [ "$pkg" != "$tag" ]; then
59+
echo "::error::Tag v${tag} does not match pyproject.toml version ${pkg}. Bump pyproject.toml (e.g. 'make bump-patch') and re-tag."
60+
exit 1
61+
fi
62+
fi
63+
echo "Package version: ${pkg}"
64+
65+
# Unit tests only: pyproject's addopts deselect `-m live` by default.
66+
- name: Run tests
67+
run: uv run --frozen pytest
68+
69+
- name: Run pyright
70+
run: uv run --frozen pyright
71+
72+
build-dist:
73+
name: Build sdist and wheel
74+
needs: verify
75+
runs-on: ubuntu-latest
76+
timeout-minutes: 15
77+
steps:
78+
- uses: actions/checkout@v4
79+
80+
- name: Install uv
81+
uses: astral-sh/setup-uv@v5
82+
with:
83+
python-version: "3.12"
84+
85+
- name: Build
86+
run: uv build --sdist --wheel --out-dir dist
87+
88+
- name: Check distributions
89+
run: uvx twine check --strict dist/*
90+
91+
- name: Check built version matches pyproject.toml
92+
run: |
93+
set -euo pipefail
94+
pkg=$(grep -m1 '^version' pyproject.toml | cut -d'"' -f2)
95+
ls dist
96+
test -f "dist/diffbot-${pkg}.tar.gz"
97+
test -f "dist/diffbot-${pkg}-py3-none-any.whl"
98+
99+
- name: Upload artifact
100+
uses: actions/upload-artifact@v4
101+
with:
102+
name: python-dist
103+
path: dist/
104+
if-no-files-found: error
105+
106+
build-binaries:
107+
needs: verify
22108
name: Build ${{ matrix.target_os }}-${{ matrix.arch }}
23109
runs-on: ${{ matrix.runner }}
24110
# Cap the wait so a capacity-starved runner fails this leg in minutes
@@ -46,20 +132,6 @@ jobs:
46132
steps:
47133
- uses: actions/checkout@v4
48134

49-
# Fail fast if the tag doesn't match pyproject.toml's version, so the
50-
# GitHub Release name can never disagree with the version the binaries
51-
# report (db --version) or the one published to PyPI.
52-
- name: Check tag matches package version
53-
if: startsWith(github.ref, 'refs/tags/')
54-
run: |
55-
pkg=$(grep -m1 '^version' pyproject.toml | cut -d'"' -f2)
56-
tag=${GITHUB_REF_NAME#v}
57-
if [ "$pkg" != "$tag" ]; then
58-
echo "::error::Tag v${tag} does not match pyproject.toml version ${pkg}. Bump pyproject.toml (e.g. 'make bump-patch') and re-tag."
59-
exit 1
60-
fi
61-
echo "Tag and package version agree: ${pkg}"
62-
63135
- name: Install uv
64136
uses: astral-sh/setup-uv@v5
65137
with:
@@ -86,12 +158,35 @@ jobs:
86158
dist/db-${{ matrix.target_os }}-${{ matrix.arch }}.sha256
87159
if-no-files-found: error
88160

89-
release:
161+
publish-pypi:
162+
name: Publish to PyPI
163+
# Only after the sdist/wheel AND all db binaries built successfully.
164+
needs: [build-dist, build-binaries]
165+
# Tag pushes only; workflow_dispatch stops after the builds.
166+
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
167+
runs-on: ubuntu-latest
168+
timeout-minutes: 15
169+
# No GitHub environment: the PyPI trusted publisher has none configured.
170+
permissions:
171+
id-token: write
172+
steps:
173+
- name: Download artifact
174+
uses: actions/download-artifact@v4
175+
with:
176+
name: python-dist
177+
path: dist/
178+
179+
- name: Publish
180+
uses: pypa/gh-action-pypi-publish@release/v1
181+
182+
github-release:
90183
name: Publish GitHub Release
91-
needs: build
184+
needs: [build-dist, build-binaries, publish-pypi]
92185
runs-on: ubuntu-latest
93186
# Only publish for real tag pushes; workflow_dispatch runs just build + verify.
94-
if: startsWith(github.ref, 'refs/tags/')
187+
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
188+
permissions:
189+
contents: write
95190
steps:
96191
- name: Download all artifacts
97192
uses: actions/download-artifact@v4

‎.github/workflows/tests.yml‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,24 @@ jobs:
2828
- name: Run tests
2929
run: uv run pytest
3030

31+
# Static typing gate: pyright (basic on src/, strict on types.py) plus the
32+
# assert_type checks in tests/typing. One Python version is enough.
33+
typecheck:
34+
runs-on: ubuntu-latest
35+
steps:
36+
- uses: actions/checkout@v4
37+
38+
- name: Install uv
39+
uses: astral-sh/setup-uv@v5
40+
with:
41+
python-version: "3.12"
42+
43+
- name: Install dependencies (locked)
44+
run: uv sync --frozen --extra dev
45+
46+
- name: Run pyright
47+
run: uv run pyright
48+
3149
# Catch breakage against the lowest dependency versions our ranges allow,
3250
# which the pinned lockfile would otherwise hide.
3351
test-lowest:

‎CHANGELOG.md‎

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
# Changelog
2+
3+
All notable changes to the `diffbot` Python package are documented here. The format
4+
follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5+
[Semantic Versioning](https://semver.org/).
6+
7+
## [3.4.0] - 2026-11-17
8+
9+
First release since 3.1.1 (and includes everything in it). It rolls up three development lines that were never
10+
published on their own: the shared transport, sync/async de-duplication and DQL over
11+
POST (planned as 3.2.0), response types plus `account`/`verify_token`/`crawl_download`/
12+
extract options (3.3.0), and named options on existing endpoints plus `nlp()` (3.4.0).
13+
No new Diffbot API areas are added.
14+
15+
### ⚠ Breaking changes
16+
17+
- **DQL is sent as `POST` with a JSON body.** `dql()`, `dql_parallel()` and their async
18+
twins keep the same signature and results, but mocks, proxies, or mirrors keyed on
19+
`GET` + `?query=` stop matching. See [Migrating DQL](#migrating-dql-mocks-and-proxies)
20+
below.
21+
- **`crawl()` raises `APIError` when the create call answers HTTP 200 with
22+
`errorCode`/`error`** (for example errorCode 505, job name over 30 characters). It used
23+
to yield `JOB_CREATED` for a job that was never created. The error keeps the real
24+
status (200), body, and headers.
25+
- **A `Retry-After` above `RetryPolicy.max_delay` (default 5.0 s) is no longer waited
26+
out or retried.** The call raises at once: `RateLimitError` with `retry_after` = raw
27+
header, or `APIError` with `headers["retry-after"]` for a 5xx (sync, async, and
28+
streamed). Raise `max_delay` to keep waiting.
29+
- **Requests are now retried by default** (`429`, `5xx`, connection errors; 3 attempts
30+
with backoff and jitter). `crawl_delete_job` is never retried. Pass `retry=False` for
31+
the old single-attempt behavior.
32+
- **`web_search(snippet_length=...)` is validated:** anything other than `short`,
33+
`medium`, `long`, `full` (case-insensitive) raises `ValidationError` instead of being
34+
sent upstream.
35+
- **`dql()` raises `ValidationError` when `extra` repeats one of the new named options**
36+
(`type`, `col`, `filter_exclude`, ...).
37+
- **Type-level:** `dql`, `extract`, `web_search`, `entities`, `crawl_list_jobs`,
38+
`crawl_get_job` return `TypedDict`s instead of `Dict[str, Any]`, and several methods
39+
gained `@overload`s. Runtime values are unchanged; a type checker may flag undeclared
40+
keys (escape hatch: `typing.cast(Dict[str, Any], resp)`).
41+
42+
### Added
43+
44+
- **Transport:** per-host base URLs (`api_base`, `kg_base`, `llm_base`, `nlp_base` on
45+
`Diffbot` and `DiffbotAsync`; the older `*_url` options still win when both are set);
46+
documented repeated query params; `client.request(method, url, ...)` with `DELETE`,
47+
form (`data=`) and raw (`content=`) bodies, a per-call `timeout`, and a
48+
`follow_redirects` override; the `RetryPolicy` dataclass and `retry` option with
49+
per-call `retryable=False`.
50+
- **Errors:** `NotFoundError` (404) and `JobError`, both subclasses of `APIError`;
51+
`APIError.headers` from the error response.
52+
- **Types:** request aliases (`ChatMessage`, `ResponseFormat`, `ExportFormat`,
53+
`SnippetLength`) and response `TypedDict`s exported from `diffbot` (`DqlResponse`/
54+
`DqlEntity`, `WebSearchResponse`/`WebSearchResult`, `EntitiesResponse`,
55+
`ExtractResponse` and per-API variants, `CrawlJob`, `CrawlDataRecord`,
56+
`AccountResponse`, `AskChunk`, ...). stdlib only, Python 3.9-compatible, no Pydantic.
57+
- `account(days=None)` and `verify_token()` (sync and async) over `GET /v4/account`.
58+
`verify_token()` returns `False` only on an auth failure. The account response carries
59+
`token` and `childTokens`; don't log it whole.
60+
- `crawl_download(name, *, format="json", type=None, num=None)` (sync and async) over
61+
`GET /v3/crawl/data`. `format="csv"` or `type="urls"` returns `str`, otherwise a list
62+
of records; a non-list JSON body (e.g. unknown job) raises `JobError`. The crawl
63+
watcher uses it. For tools that can't block: `crawl(..., watch=False)` ->
64+
`crawl_get_job` -> `crawl_download`.
65+
- `extract()` keyword-only options: `timeout` (server-side ms, default 30000), `mode`,
66+
`fields` (per-API `Literal` names), `fallback`, `discussion`, `paging`, `max_pages`,
67+
`natural_language`, `summary_num_sentences`, `max_tags`, `tag_confidence`,
68+
`category_confidence`, `use_proxy`, and `extra` (`proxy`/`proxyAuth`; collisions with a
69+
named option or `token`/`url` raise `ValidationError`). Setting `timeout` raises the
70+
per-call transport timeout to at least `timeout + 10s`.
71+
- `dql()`/`dql_async()` (and `dql_parallel`) keyword-only options `type` (`"query"`,
72+
`"text"`, `"queryTextFallback"`, `"crawl"`), `col`, `filter_exclude`,
73+
`exportseparator`, `exportfile`, `jsonmode`, `non_canonical_facts`,
74+
`no_dedup_articles`, `cluster`, sent in the POST body. `report` and `view` stay
75+
reachable via `extra`. Types: `DqlType`, `DqlJsonMode`, `DqlCluster`, `DqlOptions`.
76+
- `crawl()` create options `url_crawl_regex`, `url_process_regex`,
77+
`page_process_pattern`, `max_to_crawl_per_subdomain`, `max_to_process_per_subdomain`,
78+
`use_canonical`, `notify_webhook`, `notify_email`; `custom_headers` accepts a string or
79+
a sequence (repeated params). The 30-character job-name limit is documented.
80+
- `nlp(text, *, fields, lang, format, document_type, custom_summary)` (sync and async) on
81+
the existing NL endpoint, single document. `entities()` is unchanged. Types:
82+
`NlpField`, `NlpFormat`, `NlpCustomSummary`, `NlpResponse`.
83+
- `web_search(text=...)` accepts a string or 1-5 strings (repeated `text=`);
84+
out-of-range lengths raise `ValidationError` before any request.
85+
- `dql_fetch_ontology_text()` (sync and async); `dql_refresh_ontology` on
86+
`DiffbotAsync` (module function `diffbot.kg.dql_refresh_ontology_async`).
87+
- Dev: `pyright` gate (basic on `src/`, strict on `types.py`, plus `tests/typing`) in CI;
88+
live test workflow (push to `main`, manual dispatch, twice-monthly cron; never on PRs).
89+
90+
### Changed
91+
92+
- `dql()` request shape: `POST {dql_url}?token=…` with `{"query", "size", "from"?,
93+
"format"?, "filter"?, "exportspec"?, …extra}`. The token stays in the query string;
94+
the query text no longer appears in URLs, and the URL length limit is gone. `extra` is
95+
typed `Mapping[str, Any]` and its values go into the JSON body verbatim.
96+
- A failed crawl job raises `JobError` (carrying the job name) instead of a synthesized
97+
`APIError(500, ...)`. `JobError` subclasses `APIError`, so `except APIError` still
98+
catches it.
99+
- Internal: shared sync/async transport helpers in `_transport.py` replace the
100+
per-handler `_http.get(...)` + raise pattern.
101+
102+
### Fixed
103+
104+
- `ask()`/`ask_json()` (sync and async): a non-2xx response while streaming raises
105+
`AuthError`/`RateLimitError`/`APIError` as documented instead of
106+
`httpx.ResponseNotRead`.
107+
- `dql(format="csv")` and `dql(format="jsonl")` without `raw=True` crashed in
108+
`response.json()`. `csv` now returns `str`, `xls`/`xlsx` return `bytes`, and `jsonl`
109+
returns an iterator of entities (`AsyncIterator` on the async client).
110+
- `crawl()` no longer reports `JOB_CREATED` for a create that failed with HTTP 200 +
111+
`errorCode`.
112+
- `APIError.message` falls back to the body's `error` field (the `{errorCode, error}`
113+
shape), matching the TypeScript SDK.
114+
- `Retry-After: inf` no longer crashes `time.sleep` with `OverflowError`; non-finite
115+
values fall back to backoff.
116+
117+
### Known limitations
118+
119+
- `extra` can still override the pre-existing DQL keys (`size`, `from`, `format`,
120+
`filter`, `exportspec`); only the new named keys are collision-checked.
121+
- `crawl()` has no `extra`; recurring-crawl admin (`repeat`, `maxRounds`, ...) is not
122+
exposed. `Diffbot.crawl(**kwargs)` does not type-check the new create options.
123+
- `nlp()` returns one `NlpResponse` `TypedDict` (all fields optional), not a per-`fields`
124+
type. `custom_summary` reads only the Python key `max_number_of_sentences`.
125+
- `crawl_get_job` still returns `{}` for a missing job (the TypeScript SDK returns
126+
`undefined`).
127+
- No generic success-path response headers.
128+
129+
### Migrating DQL: mocks and proxies
130+
131+
Test mocks keyed on `GET` and `?query=` stop matching. Before/after:
132+
133+
```python
134+
# before (3.1.x)
135+
def handler(request: httpx.Request) -> httpx.Response:
136+
assert request.method == "GET"
137+
assert request.url.params["query"] == "type:Organization"
138+
return httpx.Response(200, json={"data": []})
139+
140+
# after (3.4.0)
141+
def handler(request: httpx.Request) -> httpx.Response:
142+
assert request.method == "POST"
143+
assert json.loads(request.content)["query"] == "type:Organization"
144+
return httpx.Response(200, json={"data": []})
145+
```
146+
147+
GET-only proxies, caches, or a custom `dql_url` mirror may reject or not cache
148+
POSTs. If you need the old wire format, use the low-level call (no new API):
149+
150+
```python
151+
db.request("GET", db.dql_url, params={"token": db.token, "query": q, "size": 10})
152+
```
153+
154+
or pin `diffbot<3.4` (3.1.x).

0 commit comments

Comments
 (0)