Skip to content

Commit b110b40

Browse files
shixishclaude
andcommitted
feat(nlp): nlp() on the existing NL endpoint, entities() unchanged
nlp(text, *, fields, lang, format, document_type, custom_summary) plus async twin, single document. Adds NlpField/NlpFormat/NlpCustomSummary/NlpResponse types, README snippet and its test. entities() keeps hard-coding fields=entities,sentiment. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent e3570af commit b110b40

8 files changed

Lines changed: 267 additions & 2 deletions

File tree

‎README.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,23 @@ for entity in result["entities"]:
285285
print("sentiment:", result.get("sentiment"))
286286
```
287287

288+
### NLP: other fields (`nlp`)
289+
`entities()` always requests `entities` and `sentiment`. `nlp()` reaches the rest of the
290+
same endpoint for a single document.
291+
```python
292+
from diffbot import Diffbot
293+
294+
db = Diffbot(token="YOUR_TOKEN")
295+
result = db.nlp(
296+
"Acme Launches Rocket\n\nAcme announced a new rocket today.",
297+
fields=["summary", "categories", "language"],
298+
format="plain text with title",
299+
document_type="news article",
300+
custom_summary={"max_number_of_sentences": 1},
301+
)
302+
print(result.get("summary"))
303+
```
304+
288305
## Async Usage
289306

290307
### Extract structured content

‎src/diffbot/__init__.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ def _installed_version(dist: str):
5656
DqlOptions,
5757
DqlType,
5858
ExportFormat,
59+
NlpCustomSummary,
60+
NlpField,
61+
NlpFormat,
62+
NlpResponse,
5963
ResponseFormat,
6064
SnippetLength,
6165
AccountResponse,
@@ -120,6 +124,10 @@ def _installed_version(dist: str):
120124
"DqlOptions",
121125
"DqlType",
122126
"ExportFormat",
127+
"NlpCustomSummary",
128+
"NlpField",
129+
"NlpFormat",
130+
"NlpResponse",
123131
"SnippetLength",
124132
"CrawlJobStatusCode",
125133
"AccountResponse",

‎src/diffbot/client.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@
4545
JobExtractResponse,
4646
ListExtractOptions,
4747
ListExtractResponse,
48+
NlpCustomSummary,
49+
NlpField,
50+
NlpFormat,
51+
NlpResponse,
4852
ProductExtractOptions,
4953
ProductExtractResponse,
5054
ResponseFormat,
@@ -96,6 +100,8 @@
96100
from .nlp import (
97101
entities as _entities,
98102
entities_async as _entities_async,
103+
nlp as _nlp,
104+
nlp_async as _nlp_async,
99105
)
100106

101107

@@ -459,6 +465,28 @@ def entities(self, text: str, *, lang: str = "auto") -> EntitiesResponse:
459465
"""
460466
return _entities(self, text, lang=lang)
461467

468+
def nlp(
469+
self,
470+
text: str,
471+
*,
472+
fields: Optional[Sequence[NlpField]] = None,
473+
lang: str = "auto",
474+
format: NlpFormat = "plain text",
475+
document_type: Optional[str] = None,
476+
custom_summary: Optional[NlpCustomSummary] = None,
477+
) -> NlpResponse:
478+
"""Run the NL endpoint on a single document and return the requested ``fields``.
479+
480+
fields: any of ``"entities"``, ``"sentiment"``, ``"facts"``, ``"records"``,
481+
``"categories"``, ``"sentences"``, ``"language"``, ``"summary"``; omit for the API
482+
default (``entities,sentiment,facts,records,sentences``). format:
483+
``"plain text"`` or ``"plain text with title"`` (title, two line breaks, body).
484+
document_type gives the model context; custom_summary
485+
``{"max_number_of_sentences": 1..10}`` shapes the ``summary`` field.
486+
Multi-document batches are not supported; :meth:`entities` is unchanged.
487+
"""
488+
return _nlp(self, text, fields=fields, lang=lang, format=format, document_type=document_type, custom_summary=custom_summary)
489+
462490

463491
class DiffbotAsync:
464492
"""Async client for Diffbot APIs.
@@ -797,3 +825,25 @@ async def entities(self, text: str, *, lang: str = "auto") -> EntitiesResponse:
797825
id:or("id1","id2","id3") — no type: declaration required.
798826
"""
799827
return await _entities_async(self, text, lang=lang)
828+
829+
async def nlp(
830+
self,
831+
text: str,
832+
*,
833+
fields: Optional[Sequence[NlpField]] = None,
834+
lang: str = "auto",
835+
format: NlpFormat = "plain text",
836+
document_type: Optional[str] = None,
837+
custom_summary: Optional[NlpCustomSummary] = None,
838+
) -> NlpResponse:
839+
"""Run the NL endpoint on a single document and return the requested ``fields``.
840+
841+
fields: any of ``"entities"``, ``"sentiment"``, ``"facts"``, ``"records"``,
842+
``"categories"``, ``"sentences"``, ``"language"``, ``"summary"``; omit for the API
843+
default (``entities,sentiment,facts,records,sentences``). format:
844+
``"plain text"`` or ``"plain text with title"`` (title, two line breaks, body).
845+
document_type gives the model context; custom_summary
846+
``{"max_number_of_sentences": 1..10}`` shapes the ``summary`` field.
847+
Multi-document batches are not supported; :meth:`entities` is unchanged.
848+
"""
849+
return await _nlp_async(self, text, fields=fields, lang=lang, format=format, document_type=document_type, custom_summary=custom_summary)

‎src/diffbot/nlp.py‎

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
"""Diffbot NLP API: entity identification, resolution, and sentiment."""
22

3-
from typing import TYPE_CHECKING, Any, Dict
3+
from typing import TYPE_CHECKING, Any, Dict, Optional, Sequence
44

55
from ._constants import NLP_HOST_BASE
6-
from .types import EntitiesResponse
6+
from .types import EntitiesResponse, NlpCustomSummary, NlpField, NlpFormat, NlpResponse
77

88
if TYPE_CHECKING:
99
from .client import Diffbot, DiffbotAsync
@@ -36,3 +36,57 @@ async def entities_async(
3636
response = await client.request("POST", client.nlp_url, params=params, json=payload)
3737
data = response.json()
3838
return data[0] if isinstance(data, list) else data
39+
40+
41+
def _build_nlp_request(
42+
client: Any,
43+
text: str,
44+
fields: Optional[Sequence[NlpField]],
45+
lang: str,
46+
format: NlpFormat,
47+
document_type: Optional[str],
48+
custom_summary: Optional[NlpCustomSummary],
49+
) -> Any:
50+
params: Dict[str, Any] = {"token": client.token}
51+
if fields is not None:
52+
params["fields"] = fields if isinstance(fields, str) else ",".join(fields)
53+
document: Dict[str, Any] = {"lang": lang, "format": format, "content": text}
54+
if document_type is not None:
55+
document["documentType"] = document_type
56+
if custom_summary is not None:
57+
max_sentences = custom_summary.get("max_number_of_sentences")
58+
if max_sentences is not None:
59+
document["customSummary"] = {"maxNumberOfSentences": max_sentences}
60+
return params, [document]
61+
62+
63+
def nlp(
64+
client: "Diffbot",
65+
text: str,
66+
*,
67+
fields: Optional[Sequence[NlpField]] = None,
68+
lang: str = "auto",
69+
format: NlpFormat = "plain text",
70+
document_type: Optional[str] = None,
71+
custom_summary: Optional[NlpCustomSummary] = None,
72+
) -> NlpResponse:
73+
params, payload = _build_nlp_request(client, text, fields, lang, format, document_type, custom_summary)
74+
response = client.request("POST", client.nlp_url, params=params, json=payload)
75+
data = response.json()
76+
return data[0] if isinstance(data, list) else data
77+
78+
79+
async def nlp_async(
80+
client: "DiffbotAsync",
81+
text: str,
82+
*,
83+
fields: Optional[Sequence[NlpField]] = None,
84+
lang: str = "auto",
85+
format: NlpFormat = "plain text",
86+
document_type: Optional[str] = None,
87+
custom_summary: Optional[NlpCustomSummary] = None,
88+
) -> NlpResponse:
89+
params, payload = _build_nlp_request(client, text, fields, lang, format, document_type, custom_summary)
90+
response = await client.request("POST", client.nlp_url, params=params, json=payload)
91+
data = response.json()
92+
return data[0] if isinstance(data, list) else data

‎src/diffbot/types.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,36 @@ class EntitiesResponse(TypedDict, total=False):
175175
sentiment: float
176176

177177

178+
#: Fields ``nlp()`` can request (``fields`` query param of the NL endpoint).
179+
NlpField = Literal["entities", "sentiment", "facts", "records", "categories", "sentences", "language", "summary"]
180+
181+
#: ``format`` of the submitted document.
182+
NlpFormat = Literal["plain text", "plain text with title"]
183+
184+
185+
class NlpCustomSummary(TypedDict, total=False):
186+
"""Summary generation options (wire: ``customSummary.maxNumberOfSentences``)."""
187+
188+
max_number_of_sentences: int
189+
190+
191+
class NlpResponse(TypedDict, total=False):
192+
"""What :meth:`Diffbot.nlp` returns: any of the requested ``fields`` may be present.
193+
194+
Only the ones with a documented shape here are typed in detail; the rest are
195+
left loose (``Any``) because the spec examples are the only source.
196+
"""
197+
198+
entities: List[NlpEntity]
199+
sentiment: float
200+
facts: List[Any]
201+
records: List[Any]
202+
categories: List[Any]
203+
sentences: List[Any]
204+
language: str
205+
summary: str
206+
207+
178208
# ---- Extract (api.diffbot.com/v3/{api}) ----
179209

180210
#: Built-in Extract APIs; any other string is a Custom API name.

‎tests/test_nlp.py‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
import json
2+
3+
import httpx
4+
import pytest
5+
6+
from diffbot import Diffbot, DiffbotAsync
7+
8+
DOC = [{"entities": [], "sentiment": 0.1, "summary": "s"}]
9+
10+
11+
def _capture():
12+
seen = []
13+
14+
def handler(request: httpx.Request) -> httpx.Response:
15+
seen.append(request)
16+
return httpx.Response(200, json=DOC)
17+
18+
return seen, handler
19+
20+
21+
def test_nlp_defaults_omit_fields_and_unwraps_list():
22+
seen, handler = _capture()
23+
db = Diffbot(token="tok", transport=httpx.MockTransport(handler))
24+
assert db.nlp("hello") == DOC[0]
25+
(req,) = seen
26+
assert req.method == "POST"
27+
assert str(req.url).startswith("https://nl.diffbot.com/v1/")
28+
assert dict(req.url.params) == {"token": "tok"}
29+
assert json.loads(req.content) == [{"lang": "auto", "format": "plain text", "content": "hello"}]
30+
31+
32+
def test_nlp_options_shape_request():
33+
seen, handler = _capture()
34+
db = Diffbot(token="tok", transport=httpx.MockTransport(handler))
35+
db.nlp("t", fields=["summary", "facts"], lang="en", document_type="blog",
36+
custom_summary={"max_number_of_sentences": 2})
37+
(req,) = seen
38+
assert req.url.params["fields"] == "summary,facts"
39+
assert json.loads(req.content) == [{
40+
"lang": "en", "format": "plain text", "content": "t", "documentType": "blog",
41+
"customSummary": {"maxNumberOfSentences": 2},
42+
}]
43+
44+
45+
def test_entities_unchanged_still_hardcodes_fields():
46+
seen, handler = _capture()
47+
db = Diffbot(token="tok", transport=httpx.MockTransport(handler))
48+
db.entities("x")
49+
assert seen[0].url.params["fields"] == "entities,sentiment"
50+
assert json.loads(seen[0].content) == [{"lang": "auto", "format": "plain text", "content": "x"}]
51+
52+
53+
@pytest.mark.anyio
54+
async def test_async_nlp_options_shape_request():
55+
seen, handler = _capture()
56+
db = DiffbotAsync(token="tok", transport=httpx.MockTransport(handler))
57+
assert await db.nlp("t") == DOC[0]
58+
await db.nlp("Title\n\nBody", fields=["language"], format="plain text with title",
59+
custom_summary={"max_number_of_sentences": 3})
60+
assert "fields" not in seen[0].url.params
61+
assert seen[1].url.params["fields"] == "language"
62+
assert json.loads(seen[1].content) == [{
63+
"lang": "auto", "format": "plain text with title", "content": "Title\n\nBody",
64+
"customSummary": {"maxNumberOfSentences": 3},
65+
}]
66+
seen.clear()
67+
await db.entities("x")
68+
assert seen[0].url.params["fields"] == "entities,sentiment"

‎tests/test_readme_examples.py‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,31 @@ def handler(request: httpx.Request) -> httpx.Response:
290290
assert result["sentiment"] == 0.3
291291

292292

293+
def test_readme_sync_nlp():
294+
seen = []
295+
296+
def handler(request: httpx.Request) -> httpx.Response:
297+
seen.append(request)
298+
return httpx.Response(200, json=[{"summary": "Acme launched a rocket.", "language": "en"}])
299+
300+
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
301+
result = db.nlp(
302+
"Acme Launches Rocket\n\nAcme announced a new rocket today.",
303+
fields=["summary", "categories", "language"],
304+
format="plain text with title",
305+
document_type="news article",
306+
custom_summary={"max_number_of_sentences": 1},
307+
)
308+
assert result["summary"] == "Acme launched a rocket."
309+
(req,) = seen
310+
assert req.url.params["fields"] == "summary,categories,language"
311+
assert json.loads(req.content) == [{
312+
"lang": "auto", "format": "plain text with title",
313+
"content": "Acme Launches Rocket\n\nAcme announced a new rocket today.",
314+
"documentType": "news article", "customSummary": {"maxNumberOfSentences": 1},
315+
}]
316+
317+
293318
# ---------------------------------------------------------------------------
294319
# Authentication
295320
# ---------------------------------------------------------------------------

‎tests/typing/test_types.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
DqlEntity,
1919
DqlResponse,
2020
EntitiesResponse,
21+
NlpResponse,
2122
ExtractResponse,
2223
ImageExtractResponse,
2324
ProductExtractResponse,
@@ -120,3 +121,15 @@ def _dql_named_option_types() -> None:
120121
assert_type(db.dql("q", non_canonical_facts=True, no_dedup_articles=True, filter_exclude="a"), DqlResponse)
121122
db.dql("q", type="bogus") # type: ignore[call-overload]
122123
db.dql("q", cluster="nope") # type: ignore[call-overload]
124+
125+
126+
def _nlp_types() -> None:
127+
assert_type(db.nlp("x"), NlpResponse)
128+
assert_type(db.nlp("x", fields=["summary", "language"], custom_summary={"max_number_of_sentences": 2}), NlpResponse)
129+
assert_type(db.entities("x"), EntitiesResponse)
130+
db.nlp("x", fields=["bogus"]) # type: ignore[list-item]
131+
db.nlp("x", format="html") # type: ignore[arg-type]
132+
133+
134+
async def _nlp_async_types() -> None:
135+
assert_type(await adb.nlp("x", format="plain text with title"), NlpResponse)

0 commit comments

Comments
 (0)