diffbot-python 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- diffbot/__init__.py +29 -0
- diffbot/ask.py +48 -0
- diffbot/cli/__init__.py +399 -0
- diffbot/cli/__main__.py +4 -0
- diffbot/cli/_common.py +36 -0
- diffbot/cli/dql.py +308 -0
- diffbot/cli/entities.py +155 -0
- diffbot/cli/ontology.py +130 -0
- diffbot/client.py +285 -0
- diffbot/crawl.py +270 -0
- diffbot/errors.py +51 -0
- diffbot/extract.py +45 -0
- diffbot/kg.py +90 -0
- diffbot/nlp.py +37 -0
- diffbot/web_search.py +44 -0
- diffbot_python-0.1.0.dist-info/METADATA +218 -0
- diffbot_python-0.1.0.dist-info/RECORD +20 -0
- diffbot_python-0.1.0.dist-info/WHEEL +4 -0
- diffbot_python-0.1.0.dist-info/entry_points.txt +2 -0
- diffbot_python-0.1.0.dist-info/licenses/LICENSE +21 -0
diffbot/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""
|
|
2
|
+
diffbot - Python client library for the Diffbot APIs.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
__version__ = "0.1.0"
|
|
6
|
+
|
|
7
|
+
from .client import Diffbot, DiffbotAsync
|
|
8
|
+
from .crawl import CrawlEvent, CrawlEventType
|
|
9
|
+
from .errors import (
|
|
10
|
+
APIError,
|
|
11
|
+
AuthError,
|
|
12
|
+
DiffbotError,
|
|
13
|
+
ExtractionError,
|
|
14
|
+
RateLimitError,
|
|
15
|
+
ValidationError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"Diffbot",
|
|
20
|
+
"DiffbotAsync",
|
|
21
|
+
"CrawlEvent",
|
|
22
|
+
"CrawlEventType",
|
|
23
|
+
"DiffbotError",
|
|
24
|
+
"AuthError",
|
|
25
|
+
"ExtractionError",
|
|
26
|
+
"RateLimitError",
|
|
27
|
+
"APIError",
|
|
28
|
+
"ValidationError",
|
|
29
|
+
]
|
diffbot/ask.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Diffbot LLM RAG API: stream a chat completion."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from typing import TYPE_CHECKING, Any, AsyncIterator, Dict, Iterator, List
|
|
5
|
+
|
|
6
|
+
if TYPE_CHECKING:
|
|
7
|
+
from .client import Diffbot, DiffbotAsync
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _build_payload(client: Any, messages: List[Dict[str, str]]) -> tuple:
|
|
11
|
+
headers = {"Authorization": f"Bearer {client.token}"}
|
|
12
|
+
payload = {"model": "diffbot-small-xl", "messages": messages, "stream": True}
|
|
13
|
+
return headers, payload
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _parse_chunk(line: str):
|
|
17
|
+
try:
|
|
18
|
+
chunk = json.loads(line.replace("data: ", ""))
|
|
19
|
+
except json.JSONDecodeError:
|
|
20
|
+
return None
|
|
21
|
+
choices = chunk.get("choices")
|
|
22
|
+
if choices and choices[0].get("delta", {}).get("content"):
|
|
23
|
+
return choices[0]["delta"]["content"]
|
|
24
|
+
return None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def ask(client: "Diffbot", messages: List[Dict[str, str]]) -> Iterator[str]:
|
|
28
|
+
headers = {"Authorization": f"Bearer {client.token}"}
|
|
29
|
+
payload = {"model": "diffbot-small-xl", "messages": messages, "stream": True}
|
|
30
|
+
with client._http.stream("POST", client.llm_url, headers=headers, json=payload) as response:
|
|
31
|
+
client._raise_for_status(response)
|
|
32
|
+
for line in response.iter_lines():
|
|
33
|
+
if line:
|
|
34
|
+
content = _parse_chunk(line)
|
|
35
|
+
if content:
|
|
36
|
+
yield content
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
async def ask_async(client: "DiffbotAsync", messages: List[Dict[str, str]]) -> AsyncIterator[str]:
|
|
40
|
+
headers = {"Authorization": f"Bearer {client.token}"}
|
|
41
|
+
payload = {"model": "diffbot-small-xl", "messages": messages, "stream": True}
|
|
42
|
+
async with client._http.stream("POST", client.llm_url, headers=headers, json=payload) as response:
|
|
43
|
+
client._raise_for_status(response)
|
|
44
|
+
async for line in response.aiter_lines():
|
|
45
|
+
if line:
|
|
46
|
+
content = _parse_chunk(line)
|
|
47
|
+
if content:
|
|
48
|
+
yield content
|
diffbot/cli/__init__.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import re
|
|
3
|
+
import sys
|
|
4
|
+
import textwrap
|
|
5
|
+
from email.utils import parsedate_to_datetime
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
from rich.console import Console
|
|
9
|
+
from rich.live import Live
|
|
10
|
+
from rich.markdown import Markdown
|
|
11
|
+
from rich.progress import Progress, SpinnerColumn, TextColumn
|
|
12
|
+
from datetime import datetime
|
|
13
|
+
|
|
14
|
+
from diffbot import CrawlEventType, AuthError, ExtractionError, APIError
|
|
15
|
+
|
|
16
|
+
from ._common import get_client
|
|
17
|
+
|
|
18
|
+
console = Console()
|
|
19
|
+
is_interactive = sys.stdout.isatty()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def print_markdown(text):
|
|
23
|
+
if is_interactive:
|
|
24
|
+
console.print(Markdown(text))
|
|
25
|
+
else:
|
|
26
|
+
sys.stdout.write(text)
|
|
27
|
+
sys.stdout.write("\n")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@click.group()
|
|
31
|
+
def main():
|
|
32
|
+
"""
|
|
33
|
+
Diffbot 🤖 Structure the world's knowledge.
|
|
34
|
+
"""
|
|
35
|
+
pass
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@main.command(name="extract")
|
|
39
|
+
@click.argument("url")
|
|
40
|
+
@click.option("-o", "--output", type=click.Path(), help="Write output to file instead of stdout")
|
|
41
|
+
@click.option("-f", "--format", "fmt", type=click.Choice(["markdown", "json"]), default="markdown", help="Output format")
|
|
42
|
+
@click.option("-a", "--api", type=str, default="analyze", help="Diffbot API to use")
|
|
43
|
+
def extract(url, output, fmt, api):
|
|
44
|
+
"""Get structured content from a URL."""
|
|
45
|
+
db = get_client()
|
|
46
|
+
try:
|
|
47
|
+
if is_interactive and not output:
|
|
48
|
+
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), transient=True) as progress:
|
|
49
|
+
progress.add_task(description="Extracting content...", total=None)
|
|
50
|
+
data = db.extract(url, api=api, fmt=fmt)
|
|
51
|
+
else:
|
|
52
|
+
data = db.extract(url, api=api, fmt=fmt)
|
|
53
|
+
|
|
54
|
+
if fmt == "json":
|
|
55
|
+
output_str = json.dumps(data, indent=2)
|
|
56
|
+
else:
|
|
57
|
+
objects = data.get("objects", [])
|
|
58
|
+
if not objects:
|
|
59
|
+
output_str = json.dumps(data, indent=2)
|
|
60
|
+
else:
|
|
61
|
+
obj = objects[0]
|
|
62
|
+
title = obj.get("title", "")
|
|
63
|
+
url = obj.get("pageUrl", "")
|
|
64
|
+
content = obj.get("content", "")
|
|
65
|
+
output_str = f"Title: {title}\n\nURL: {url}\n\nContent: {content}"
|
|
66
|
+
|
|
67
|
+
if output:
|
|
68
|
+
with open(output, "w") as f:
|
|
69
|
+
f.write(output_str)
|
|
70
|
+
click.echo(f"Output written to {output}")
|
|
71
|
+
else:
|
|
72
|
+
print_markdown(output_str)
|
|
73
|
+
except ExtractionError as e:
|
|
74
|
+
click.echo(f"Extraction error {e.error_code}: {e.error}", err=True)
|
|
75
|
+
raise click.Abort()
|
|
76
|
+
except AuthError:
|
|
77
|
+
click.echo("Error: Invalid or unauthorized API token.", err=True)
|
|
78
|
+
raise click.Abort()
|
|
79
|
+
except APIError as e:
|
|
80
|
+
click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
|
|
81
|
+
raise click.Abort()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@main.command()
|
|
85
|
+
@click.argument("prompt")
|
|
86
|
+
@click.option("-o", "--output", type=click.Path(), help="Write output to file instead of stdout")
|
|
87
|
+
@click.option("--json", "as_json", is_flag=True, help="Output from LLM as JSON")
|
|
88
|
+
def ask(prompt: str, output: str = None, as_json: bool = False):
|
|
89
|
+
"""Ask a question to the Diffbot LLM"""
|
|
90
|
+
db = get_client()
|
|
91
|
+
stdin_content = sys.stdin.read() if not sys.stdin.isatty() else None
|
|
92
|
+
interactive_mode = is_interactive and not output and not as_json
|
|
93
|
+
|
|
94
|
+
messages = [
|
|
95
|
+
{
|
|
96
|
+
"role": "system",
|
|
97
|
+
"content": f"Current local time: {datetime.now().strftime('%A, %B %d, %Y, %I:%M:%S %p %Z')}",
|
|
98
|
+
},
|
|
99
|
+
{"role": "user", "content": prompt},
|
|
100
|
+
]
|
|
101
|
+
|
|
102
|
+
if as_json:
|
|
103
|
+
messages[1]["content"] += "\nReturn the output as a JSON object. Do not include any other text outside of the JSON object."
|
|
104
|
+
|
|
105
|
+
if stdin_content:
|
|
106
|
+
messages[1]["content"] = f"<input>{stdin_content}</input>\n" + messages[1]["content"]
|
|
107
|
+
|
|
108
|
+
try:
|
|
109
|
+
if interactive_mode:
|
|
110
|
+
response_text = ""
|
|
111
|
+
with Live("", auto_refresh=False, console=console) as live:
|
|
112
|
+
for chunk in db.ask(messages):
|
|
113
|
+
response_text += chunk
|
|
114
|
+
live.update(Markdown(response_text))
|
|
115
|
+
live.refresh()
|
|
116
|
+
|
|
117
|
+
messages.append({"role": "assistant", "content": response_text})
|
|
118
|
+
|
|
119
|
+
while True:
|
|
120
|
+
try:
|
|
121
|
+
sys.stdout.write("\n> ")
|
|
122
|
+
sys.stdout.flush()
|
|
123
|
+
user_input = input()
|
|
124
|
+
messages.append({"role": "user", "content": user_input})
|
|
125
|
+
except (KeyboardInterrupt, EOFError):
|
|
126
|
+
console.print("\nExiting chat...")
|
|
127
|
+
return
|
|
128
|
+
|
|
129
|
+
response_text = ""
|
|
130
|
+
with Live("", auto_refresh=False, console=console) as live:
|
|
131
|
+
for chunk in db.ask(messages):
|
|
132
|
+
response_text += chunk
|
|
133
|
+
live.update(Markdown(response_text))
|
|
134
|
+
live.refresh()
|
|
135
|
+
messages.append({"role": "assistant", "content": response_text})
|
|
136
|
+
else:
|
|
137
|
+
response = ""
|
|
138
|
+
if output:
|
|
139
|
+
for chunk in db.ask(messages):
|
|
140
|
+
response += chunk
|
|
141
|
+
with open(output, "w") as f:
|
|
142
|
+
f.write(response)
|
|
143
|
+
click.echo(f"Output written to {output}")
|
|
144
|
+
elif as_json:
|
|
145
|
+
buffer = ""
|
|
146
|
+
for chunk in db.ask(messages):
|
|
147
|
+
buffer += chunk
|
|
148
|
+
buffer = buffer[buffer.find("{") : buffer.rfind("}") + 1]
|
|
149
|
+
sys.stdout.write(buffer)
|
|
150
|
+
else:
|
|
151
|
+
for chunk in db.ask(messages):
|
|
152
|
+
sys.stdout.write(chunk)
|
|
153
|
+
except (KeyboardInterrupt, EOFError):
|
|
154
|
+
console.print("\nExiting chat...")
|
|
155
|
+
except AuthError:
|
|
156
|
+
click.echo("Error: Invalid or unauthorized API token.", err=True)
|
|
157
|
+
raise click.Abort()
|
|
158
|
+
except APIError as e:
|
|
159
|
+
click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
|
|
160
|
+
raise click.Abort()
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@main.command()
|
|
164
|
+
@click.argument("site")
|
|
165
|
+
@click.option("--hops", type=int, default=2, help="Maximum link depth from seed URLs")
|
|
166
|
+
@click.option("--job-name", type=str, help="Name for the crawler job (generated if not provided)")
|
|
167
|
+
@click.option("--max-to-crawl", type=int, default=100, help="Maximum number of pages to crawl")
|
|
168
|
+
@click.option("--max-to-process", type=int, default=100, help="Maximum number of pages to process")
|
|
169
|
+
@click.option("--restrict-domain", is_flag=True, default=True, help="Restrict crawling to the same domain as seeds")
|
|
170
|
+
@click.option("--api-url", type=str, default="", help="Diffbot API endpoint to use for processing")
|
|
171
|
+
@click.option("--crawl-delay", type=float, default=-1, help="Delay between requests to the same domain in seconds")
|
|
172
|
+
@click.option("--url-crawl-pattern", type=str, help="Only crawl URLs matching this pattern")
|
|
173
|
+
@click.option("--url-process-pattern", type=str, help="Only process URLs matching this pattern")
|
|
174
|
+
@click.option("--obey-robots", is_flag=True, help="Obey robots.txt rules")
|
|
175
|
+
@click.option("--use-proxies", is_flag=True, help="Use proxies for crawling")
|
|
176
|
+
@click.option("--custom-headers", type=str, help="Custom HTTP headers to send with requests (newline separated)")
|
|
177
|
+
@click.option("-o", "--output", type=click.Path(), help="Write output to file instead of stdout")
|
|
178
|
+
@click.option("-f", "--format", "fmt", type=click.Choice(["markdown", "json"]), default="markdown", help="Output format")
|
|
179
|
+
def crawl(site, hops, job_name, max_to_crawl, max_to_process, restrict_domain,
|
|
180
|
+
api_url, crawl_delay, url_crawl_pattern, url_process_pattern, obey_robots,
|
|
181
|
+
use_proxies, custom_headers, output, fmt):
|
|
182
|
+
"""Crawl a website using the Diffbot Crawler API."""
|
|
183
|
+
db = get_client()
|
|
184
|
+
events = []
|
|
185
|
+
try:
|
|
186
|
+
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), transient=True) as progress:
|
|
187
|
+
progress.add_task(description=f"Crawling {site}...", total=None)
|
|
188
|
+
|
|
189
|
+
for event in db.crawl(
|
|
190
|
+
site,
|
|
191
|
+
hops=hops,
|
|
192
|
+
job_name=job_name,
|
|
193
|
+
max_to_crawl=max_to_crawl,
|
|
194
|
+
max_to_process=max_to_process,
|
|
195
|
+
restrict_domain=restrict_domain,
|
|
196
|
+
api_url=api_url,
|
|
197
|
+
crawl_delay=crawl_delay,
|
|
198
|
+
url_crawl_pattern=url_crawl_pattern,
|
|
199
|
+
url_process_pattern=url_process_pattern,
|
|
200
|
+
obey_robots=obey_robots,
|
|
201
|
+
use_proxies=use_proxies,
|
|
202
|
+
custom_headers=custom_headers,
|
|
203
|
+
watch=True,
|
|
204
|
+
):
|
|
205
|
+
events.append(event)
|
|
206
|
+
if event.event_type == CrawlEventType.JOB_CREATED:
|
|
207
|
+
progress.console.print(f"Job created: {event.details['job_name']}")
|
|
208
|
+
elif event.event_type == CrawlEventType.URL_PROCESSED:
|
|
209
|
+
status = event.details.get("status", "")
|
|
210
|
+
icon = "✓" if status == "Success" else "!"
|
|
211
|
+
progress.console.print(f" [{icon}] {event.details['url']}")
|
|
212
|
+
|
|
213
|
+
if fmt == "json":
|
|
214
|
+
output_str = json.dumps(
|
|
215
|
+
[{"event_type": e.event_type.value, "timestamp": e.timestamp, "details": e.details} for e in events],
|
|
216
|
+
indent=2,
|
|
217
|
+
)
|
|
218
|
+
else:
|
|
219
|
+
lines = []
|
|
220
|
+
for event in events:
|
|
221
|
+
if event.event_type == CrawlEventType.JOB_CREATED:
|
|
222
|
+
lines.append(f"# Job: {event.details['job_name']}\n")
|
|
223
|
+
elif event.event_type == CrawlEventType.URL_PROCESSED:
|
|
224
|
+
lines.append(f"- [{event.details.get('status', 'unknown')}] {event.details['url']}")
|
|
225
|
+
output_str = "\n".join(lines)
|
|
226
|
+
|
|
227
|
+
if output:
|
|
228
|
+
with open(output, "w") as f:
|
|
229
|
+
f.write(output_str)
|
|
230
|
+
click.echo(f"Output written to {output}")
|
|
231
|
+
else:
|
|
232
|
+
print_markdown(output_str)
|
|
233
|
+
except AuthError:
|
|
234
|
+
click.echo("Error: Invalid or unauthorized API token.", err=True)
|
|
235
|
+
raise click.Abort()
|
|
236
|
+
except APIError as e:
|
|
237
|
+
click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
|
|
238
|
+
raise click.Abort()
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
@main.command()
|
|
242
|
+
@click.argument("job_name", required=False)
|
|
243
|
+
def crawl_list_jobs(job_name):
|
|
244
|
+
"""List Diffbot crawler jobs or get details for a specific job."""
|
|
245
|
+
db = get_client()
|
|
246
|
+
try:
|
|
247
|
+
if job_name:
|
|
248
|
+
job = db.crawl_get_job(job_name)
|
|
249
|
+
print_markdown(f"# Job: {job_name}\n\n```json\n{json.dumps(job, indent=2)}\n```")
|
|
250
|
+
else:
|
|
251
|
+
jobs = db.crawl_list_jobs()
|
|
252
|
+
if not jobs:
|
|
253
|
+
print_markdown("No crawler jobs found.")
|
|
254
|
+
return
|
|
255
|
+
lines = ["# Diffbot Crawler Jobs\n"]
|
|
256
|
+
for job in jobs:
|
|
257
|
+
name = job.get("name", "Unknown")
|
|
258
|
+
job_type = job.get("type", "Unknown")
|
|
259
|
+
status = job.get("jobStatus", {}).get("message", "Unknown")
|
|
260
|
+
lines.append(f"## {name}")
|
|
261
|
+
lines.append(f"Type: {job_type}")
|
|
262
|
+
lines.append(f"Status: {status}")
|
|
263
|
+
if "pageCrawlSuccesses" in job:
|
|
264
|
+
lines.append(f"Pages Crawled: {job['pageCrawlSuccesses']}")
|
|
265
|
+
if "pageProcessSuccesses" in job:
|
|
266
|
+
lines.append(f"Pages Processed: {job['pageProcessSuccesses']}")
|
|
267
|
+
lines.append("\n---\n")
|
|
268
|
+
print_markdown("\n".join(lines))
|
|
269
|
+
except AuthError:
|
|
270
|
+
click.echo("Error: Invalid or unauthorized API token.", err=True)
|
|
271
|
+
raise click.Abort()
|
|
272
|
+
except APIError as e:
|
|
273
|
+
click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
|
|
274
|
+
raise click.Abort()
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
@main.command()
|
|
278
|
+
@click.argument("job_name")
|
|
279
|
+
def crawl_delete_job(job_name):
|
|
280
|
+
"""Delete a Diffbot crawler job."""
|
|
281
|
+
db = get_client()
|
|
282
|
+
try:
|
|
283
|
+
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), transient=True) as progress:
|
|
284
|
+
progress.add_task(description=f"Deleting job {job_name}...", total=None)
|
|
285
|
+
db.crawl_delete_job(job_name)
|
|
286
|
+
progress.console.print(f"Job {job_name} deleted.")
|
|
287
|
+
except AuthError:
|
|
288
|
+
click.echo("Error: Invalid or unauthorized API token.", err=True)
|
|
289
|
+
raise click.Abort()
|
|
290
|
+
except APIError as e:
|
|
291
|
+
click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
|
|
292
|
+
raise click.Abort()
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def _format_date(date_str: str) -> str:
|
|
296
|
+
if not date_str:
|
|
297
|
+
return ""
|
|
298
|
+
try:
|
|
299
|
+
dt = parsedate_to_datetime(date_str)
|
|
300
|
+
return f"{dt.strftime('%b')} {dt.day}, {dt.year}"
|
|
301
|
+
except Exception:
|
|
302
|
+
return date_str[:12].strip()
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _score_color(score: float) -> str:
|
|
306
|
+
if score > 0.85:
|
|
307
|
+
return "bright_green"
|
|
308
|
+
elif score >= 0.7:
|
|
309
|
+
return "green"
|
|
310
|
+
elif score >= 0.5:
|
|
311
|
+
return "yellow"
|
|
312
|
+
return "red"
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _strip_markdown(text: str) -> str:
|
|
316
|
+
text = re.sub(r'!\[.*?\]\(.*?\)', '', text) # images
|
|
317
|
+
text = re.sub(r'\[([^\]]*)\]\([^)]*\)', r'\1', text) # links → label
|
|
318
|
+
text = re.sub(r'^#{1,6}\s+', '', text, flags=re.MULTILINE) # headings
|
|
319
|
+
text = re.sub(r'^\s*[-*+]\s+', '', text, flags=re.MULTILINE) # bullets
|
|
320
|
+
text = re.sub(r'^\s*\d+\.\s+', '', text, flags=re.MULTILINE) # numbered lists
|
|
321
|
+
text = re.sub(r'[`*_~]{1,3}', '', text) # inline code/bold/italic
|
|
322
|
+
text = re.sub(r'\s+', ' ', text)
|
|
323
|
+
return text.strip()
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
@main.command(name="web-search")
|
|
327
|
+
@click.argument("query")
|
|
328
|
+
@click.option("-n", "--num-results", type=int, default=None, help="Number of results to return")
|
|
329
|
+
@click.option("-m", "--max-tokens", type=int, default=None, help="Limit total response tokens (for agentic use cases)")
|
|
330
|
+
@click.option("-f", "--format", "fmt", type=click.Choice(["list", "json", "text"]), default="list", help="Output format (text is plain/agent-friendly)")
|
|
331
|
+
def web_search(query: str, num_results, max_tokens, fmt: str):
|
|
332
|
+
"""Search the web using the Diffbot LLM web search API."""
|
|
333
|
+
db = get_client()
|
|
334
|
+
try:
|
|
335
|
+
if is_interactive:
|
|
336
|
+
with Progress(SpinnerColumn(), TextColumn("[progress.description]{task.description}"), transient=True) as progress:
|
|
337
|
+
progress.add_task(description="Searching...", total=None)
|
|
338
|
+
data = db.web_search(query, num_results=num_results, max_tokens=max_tokens)
|
|
339
|
+
else:
|
|
340
|
+
data = db.web_search(query, num_results=num_results, max_tokens=max_tokens)
|
|
341
|
+
|
|
342
|
+
if fmt == "json":
|
|
343
|
+
sys.stdout.write(json.dumps(data, indent=2))
|
|
344
|
+
sys.stdout.write("\n")
|
|
345
|
+
return
|
|
346
|
+
|
|
347
|
+
results = data.get("search_results", [])
|
|
348
|
+
|
|
349
|
+
if fmt == "text":
|
|
350
|
+
for i, r in enumerate(results, 1):
|
|
351
|
+
date_fmt = _format_date(r.get("date", ""))
|
|
352
|
+
content = " ".join(r.get("content", "").split())
|
|
353
|
+
lines = [
|
|
354
|
+
f"[{i}] {r.get('title', '')} (score: {r.get('score', 0):.3f})",
|
|
355
|
+
f"URL: {r.get('pageUrl', '')}",
|
|
356
|
+
]
|
|
357
|
+
if date_fmt:
|
|
358
|
+
lines.append(f"Date: {date_fmt}")
|
|
359
|
+
lines += [f"Content: {content}", "---"]
|
|
360
|
+
sys.stdout.write("\n".join(lines) + "\n")
|
|
361
|
+
return
|
|
362
|
+
|
|
363
|
+
time_ms = data.get("timeMs", 0)
|
|
364
|
+
|
|
365
|
+
for i, r in enumerate(results, 1):
|
|
366
|
+
score = r.get("score", 0)
|
|
367
|
+
title = r.get("title", "")
|
|
368
|
+
url = r.get("pageUrl", "")
|
|
369
|
+
date = r.get("date", "")
|
|
370
|
+
content = _strip_markdown(r.get("content", ""))
|
|
371
|
+
|
|
372
|
+
date_fmt = _format_date(date)
|
|
373
|
+
color = _score_color(score)
|
|
374
|
+
prefix_len = len(date_fmt) + 3 if date_fmt else 0 # " — "
|
|
375
|
+
snippet_width = max(80, console.width * 2 - prefix_len)
|
|
376
|
+
snippet = textwrap.shorten(content, width=snippet_width, placeholder="...")
|
|
377
|
+
|
|
378
|
+
console.print(f"[bold]#{i}: {title}[/bold] [[{color}]{score:.3f}[/{color}]]")
|
|
379
|
+
console.print(f"[dim blue]{url}[/dim blue]")
|
|
380
|
+
if date_fmt:
|
|
381
|
+
console.print(f"[dim]{date_fmt}[/dim] — {snippet}")
|
|
382
|
+
else:
|
|
383
|
+
console.print(snippet)
|
|
384
|
+
console.print()
|
|
385
|
+
|
|
386
|
+
console.print(f"[dim]{len(results)} result(s) in {time_ms}ms[/dim]")
|
|
387
|
+
except AuthError:
|
|
388
|
+
click.echo("Error: Invalid or unauthorized API token.", err=True)
|
|
389
|
+
raise click.Abort()
|
|
390
|
+
except APIError as e:
|
|
391
|
+
click.echo(f"API error {e.status_code}: {e.message or e.body}", err=True)
|
|
392
|
+
raise click.Abort()
|
|
393
|
+
|
|
394
|
+
|
|
395
|
+
from .dql import dql as _dql_group # noqa: E402
|
|
396
|
+
from .entities import entities as _entities_cmd # noqa: E402
|
|
397
|
+
|
|
398
|
+
main.add_command(_dql_group)
|
|
399
|
+
main.add_command(_entities_cmd)
|
diffbot/cli/__main__.py
ADDED
diffbot/cli/_common.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import pathlib
|
|
3
|
+
|
|
4
|
+
import click
|
|
5
|
+
|
|
6
|
+
from diffbot import Diffbot
|
|
7
|
+
|
|
8
|
+
CREDENTIALS_PATH = pathlib.Path.home() / ".diffbot" / "credentials"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def resolve_token() -> str:
|
|
12
|
+
"""Return the Diffbot API token from the env var, falling back to ~/.diffbot/credentials."""
|
|
13
|
+
token = os.environ.get("DIFFBOT_API_TOKEN", "").strip()
|
|
14
|
+
if token:
|
|
15
|
+
return token
|
|
16
|
+
|
|
17
|
+
if CREDENTIALS_PATH.exists():
|
|
18
|
+
for line in CREDENTIALS_PATH.read_text().splitlines():
|
|
19
|
+
line = line.strip()
|
|
20
|
+
if line.startswith("DIFFBOT_API_TOKEN="):
|
|
21
|
+
return line[len("DIFFBOT_API_TOKEN="):].strip()
|
|
22
|
+
|
|
23
|
+
return ""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def get_client() -> Diffbot:
|
|
27
|
+
token = resolve_token()
|
|
28
|
+
if not token:
|
|
29
|
+
click.echo(
|
|
30
|
+
"Error: no Diffbot API token found.\n"
|
|
31
|
+
" Set a DIFFBOT_API_TOKEN environment variable, or\n"
|
|
32
|
+
f" write 'DIFFBOT_API_TOKEN=YOUR_TOKEN' to {CREDENTIALS_PATH}",
|
|
33
|
+
err=True,
|
|
34
|
+
)
|
|
35
|
+
raise click.Abort()
|
|
36
|
+
return Diffbot(token=token)
|