Skip to content

Commit 4a83898

Browse files
shixishclaude
andcommitted
feat(web-search): accept 1-5 text values; snippet_length validation parity
text may be a str or 1-5 strings (repeated text= params on the existing GET); 0 or >5 raises ValidationError. snippet_length is case-normalized and validated like the TS SDK; invalid values now raise ValidationError. Docstrings label snippet_length/rerank as undocumented. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1 parent b110b40 commit 4a83898

5 files changed

Lines changed: 127 additions & 12 deletions

File tree

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,9 @@ for r in results["search_results"]:
270270
# "short" (~1-1.5 KB per result), "medium", "long" (default), or "full"
271271
results = db.web_search("diffbot knowledge graph", num_results=5, snippet_length="short")
272272

273+
# 1-5 queries in one call (sent as repeated text= params); 0 or >5 raises ValidationError
274+
results = db.web_search(["diffbot knowledge graph", "diffbot crawl api"], num_results=3)
275+
273276
# "full" with a url: query returns the whole stored page
274277
page = db.web_search("url:https://en.wikipedia.org/wiki/Knowledge_graph", snippet_length="full")
275278
```

‎src/diffbot/client.py‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -427,18 +427,22 @@ def dql_fetch_ontology(self) -> Ontology:
427427

428428
def web_search(
429429
self,
430-
text: str,
430+
text: Union[str, Sequence[str]],
431431
*,
432432
num_results: Optional[int] = None,
433433
max_tokens: Optional[int] = None,
434434
snippet_length: Optional[SnippetLength] = None,
435435
) -> WebSearchResponse:
436436
"""Search the web via the Diffbot LLM web search API.
437437
438-
snippet_length: "short", "medium", "long" or "full" — how much of each
438+
text: one query string, or 1-5 strings (sent as repeated ``text=`` params);
439+
anything else raises ``ValidationError``.
440+
441+
snippet_length (undocumented upstream; ``rerank`` is set internally): "short", "medium", "long" or "full" — how much of each
439442
page's matching content to return. Omit for the API default (long).
440443
"full" returns the whole stored page (reranking is disabled for it);
441-
use it with a url:<URL> query.
444+
use it with a url:<URL> query. Values are case-insensitive; anything else
445+
raises ``ValidationError``.
442446
"""
443447
return _web_search(self, text, num_results=num_results, max_tokens=max_tokens, snippet_length=snippet_length)
444448

@@ -788,18 +792,22 @@ async def dql_fetch_ontology(self) -> Ontology:
788792

789793
async def web_search(
790794
self,
791-
text: str,
795+
text: Union[str, Sequence[str]],
792796
*,
793797
num_results: Optional[int] = None,
794798
max_tokens: Optional[int] = None,
795799
snippet_length: Optional[SnippetLength] = None,
796800
) -> WebSearchResponse:
797801
"""Search the web via the Diffbot LLM web search API.
798802
799-
snippet_length: "short", "medium", "long" or "full" — how much of each
803+
text: one query string, or 1-5 strings (sent as repeated ``text=`` params);
804+
anything else raises ``ValidationError``.
805+
806+
snippet_length (undocumented upstream; ``rerank`` is set internally): "short", "medium", "long" or "full" — how much of each
800807
page's matching content to return. Omit for the API default (long).
801808
"full" returns the whole stored page (reranking is disabled for it);
802-
use it with a url:<URL> query.
809+
use it with a url:<URL> query. Values are case-insensitive; anything else
810+
raises ``ValidationError``.
803811
"""
804812
return await _web_search_async(self, text, num_results=num_results, max_tokens=max_tokens, snippet_length=snippet_length)
805813

‎src/diffbot/web_search.py‎

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,47 @@
11
"""Diffbot web search API."""
22

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

55
from ._constants import LLM_BASE
6+
from .errors import ValidationError
67
from .types import SnippetLength, WebSearchResponse
78

89
if TYPE_CHECKING:
910
from .client import Diffbot, DiffbotAsync
1011

1112
WEB_SEARCH_BASE = f"{LLM_BASE}/api/v1/web_search"
1213

14+
SNIPPET_LENGTHS = get_args(SnippetLength)
15+
MAX_TEXT_VALUES = 5
16+
1317

1418
def _build_web_search_request(
1519
client: Any,
16-
text: str,
20+
text: Union[str, Sequence[str]],
1721
num_results: Optional[int],
1822
max_tokens: Optional[int],
1923
snippet_length: Optional[SnippetLength],
2024
) -> Any:
2125
headers = {"Authorization": f"Bearer {client.token}"}
22-
params: Dict[str, Any] = {"text": text}
26+
params: Dict[str, Any] = {}
27+
if isinstance(text, str):
28+
params["text"] = text
29+
else:
30+
values = list(text)
31+
if not 1 <= len(values) <= MAX_TEXT_VALUES:
32+
raise ValidationError(f"text must be a string or 1-{MAX_TEXT_VALUES} strings; got {len(values)}")
33+
params["text"] = values # sent as repeated text= params
2334
if num_results is not None:
2435
params["size"] = num_results
2536
if max_tokens is not None:
2637
params["maxTokens"] = max_tokens
2738
if snippet_length is not None:
28-
params["snippetLength"] = snippet_length.upper()
39+
length = snippet_length.lower() if isinstance(snippet_length, str) else snippet_length
40+
if length not in SNIPPET_LENGTHS:
41+
raise ValidationError(
42+
f"snippet_length must be one of {', '.join(SNIPPET_LENGTHS)}; got {snippet_length!r}"
43+
)
44+
params["snippetLength"] = length.upper()
2945
if params["snippetLength"] == "FULL":
3046
# the reranker always chunks; only the unranked path returns the stored page
3147
params["rerank"] = "none"
@@ -34,7 +50,7 @@ def _build_web_search_request(
3450

3551
def web_search(
3652
client: "Diffbot",
37-
text: str,
53+
text: Union[str, Sequence[str]],
3854
*,
3955
num_results: Optional[int] = None,
4056
max_tokens: Optional[int] = None,
@@ -47,7 +63,7 @@ def web_search(
4763

4864
async def web_search_async(
4965
client: "DiffbotAsync",
50-
text: str,
66+
text: Union[str, Sequence[str]],
5167
*,
5268
num_results: Optional[int] = None,
5369
max_tokens: Optional[int] = None,

‎tests/test_readme_examples.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,17 @@ def handler(request: httpx.Request) -> httpx.Response:
229229
assert r["content"] == "AI-powered web data."
230230

231231

232+
def test_readme_sync_web_search_multiple_text():
233+
def handler(request: httpx.Request) -> httpx.Response:
234+
assert request.url.params.get_list("text") == ["diffbot knowledge graph", "diffbot crawl api"]
235+
assert request.url.params["size"] == "3"
236+
return httpx.Response(200, json={"search_results": []})
237+
238+
db = Diffbot(token="test-token", transport=httpx.MockTransport(handler))
239+
results = db.web_search(["diffbot knowledge graph", "diffbot crawl api"], num_results=3)
240+
assert results["search_results"] == []
241+
242+
232243
@pytest.mark.anyio
233244
async def test_readme_async_web_search():
234245
def handler(request: httpx.Request) -> httpx.Response:

‎tests/test_web_search.py‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,3 +49,80 @@ def handler(request: httpx.Request) -> httpx.Response:
4949
db.web_search("url:https://example.com", snippet_length="full")
5050
assert seen["snippetLength"] == "FULL"
5151
assert seen["rerank"] == "none"
52+
53+
54+
"""
55+
Multi-value text and snippet_length validation (S2)
56+
"""
57+
58+
import httpx # noqa: E402
59+
60+
from diffbot import Diffbot, DiffbotAsync, ValidationError # noqa: E402
61+
62+
63+
def _cap():
64+
seen = []
65+
66+
def handler(request: httpx.Request) -> httpx.Response:
67+
seen.append(request)
68+
return httpx.Response(200, json={"search_results": []})
69+
70+
return seen, handler
71+
72+
73+
@pytest.mark.parametrize("n", [1, 2, 5])
74+
def test_web_search_text_sequence_sends_repeated_params(n):
75+
seen, handler = _cap()
76+
db = Diffbot(token="t", transport=httpx.MockTransport(handler))
77+
texts = [f"q{i}" for i in range(n)]
78+
db.web_search(texts)
79+
(req,) = seen
80+
assert req.method == "GET"
81+
assert req.url.params.get_list("text") == texts
82+
assert req.headers["authorization"] == "Bearer t"
83+
84+
85+
def test_web_search_single_string_unchanged():
86+
seen, handler = _cap()
87+
db = Diffbot(token="t", transport=httpx.MockTransport(handler))
88+
db.web_search("one query", num_results=1)
89+
assert seen[0].url.params.get_list("text") == ["one query"]
90+
assert seen[0].url.params["size"] == "1"
91+
92+
93+
@pytest.mark.parametrize("texts", [[], [f"q{i}" for i in range(6)]])
94+
def test_web_search_text_out_of_range_raises(texts):
95+
seen, handler = _cap()
96+
db = Diffbot(token="t", transport=httpx.MockTransport(handler))
97+
with pytest.raises(ValidationError, match="1-5"):
98+
db.web_search(texts)
99+
assert seen == []
100+
101+
102+
def test_web_search_snippet_length_case_normalized_and_validated():
103+
seen, handler = _cap()
104+
db = Diffbot(token="t", transport=httpx.MockTransport(handler))
105+
db.web_search("q", snippet_length="Medium") # type: ignore[arg-type]
106+
assert seen[0].url.params["snippetLength"] == "MEDIUM"
107+
with pytest.raises(ValidationError, match="snippet_length"):
108+
db.web_search("q", snippet_length="huge") # type: ignore[arg-type]
109+
assert len(seen) == 1
110+
111+
112+
@pytest.mark.anyio
113+
async def test_async_web_search_multi_text_and_validation():
114+
seen, handler = _cap()
115+
db = DiffbotAsync(token="t", transport=httpx.MockTransport(handler))
116+
await db.web_search(["a", "b"], snippet_length="full")
117+
assert seen[0].url.params.get_list("text") == ["a", "b"]
118+
assert seen[0].url.params["snippetLength"] == "FULL"
119+
assert seen[0].url.params["rerank"] == "none"
120+
await db.web_search("solo")
121+
assert seen[1].url.params.get_list("text") == ["solo"]
122+
with pytest.raises(ValidationError):
123+
await db.web_search([])
124+
with pytest.raises(ValidationError):
125+
await db.web_search(["x"] * 6)
126+
with pytest.raises(ValidationError, match="snippet_length"):
127+
await db.web_search("q", snippet_length="nope") # type: ignore[arg-type]
128+
assert len(seen) == 2

0 commit comments

Comments
 (0)