langchain-diffbot 0.1.0__tar.gz → 0.1.1__tar.gz

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.
@@ -14,3 +14,6 @@ build/
14
14
 
15
15
  # Claude Code harness runtime artifacts
16
16
  **/.claude/scheduled_tasks.lock
17
+
18
+ # Claude Code personal/local settings
19
+ .claude/settings.local.json
@@ -0,0 +1,377 @@
1
+ Metadata-Version: 2.4
2
+ Name: langchain-diffbot
3
+ Version: 0.1.1
4
+ Summary: LangChain integration for the Diffbot Knowledge Graph and Extract APIs
5
+ Project-URL: Homepage, https://www.diffbot.com/
6
+ Project-URL: Repository, https://github.com/diffbot/langchain-diffbot
7
+ Project-URL: Issues, https://github.com/diffbot/langchain-diffbot/issues
8
+ Author: Diffbot
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Requires-Python: <4.0,>=3.10
21
+ Requires-Dist: diffbot-python>=0.2.1
22
+ Requires-Dist: httpx<1.0,>=0.27
23
+ Requires-Dist: langchain-core<2.0,>=1.0
24
+ Provides-Extra: examples
25
+ Requires-Dist: fastapi<1.0,>=0.115; extra == 'examples'
26
+ Requires-Dist: langchain-anthropic<2.0,>=1.4; extra == 'examples'
27
+ Requires-Dist: langchain<2.0,>=1.3; extra == 'examples'
28
+ Requires-Dist: langsmith<1.0,>=0.1; extra == 'examples'
29
+ Requires-Dist: python-dotenv<2.0,>=1.0; extra == 'examples'
30
+ Requires-Dist: uvicorn[standard]<1.0,>=0.30; extra == 'examples'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # langchain-diffbot
34
+
35
+ [![CI](https://github.com/diffbot/langchain-diffbot/actions/workflows/ci.yml/badge.svg)](https://github.com/diffbot/langchain-diffbot/actions/workflows/ci.yml)
36
+
37
+ A thin LangChain integration over the official [`diffbot-python`](https://github.com/diffbot/diffbot-python) SDK. Every Diffbot API gets the closest LangChain primitive:
38
+
39
+ | Diffbot API | LangChain class(es) |
40
+ | --- | --- |
41
+ | Knowledge Graph (DQL) | `DiffbotKnowledgeGraphRetriever`, `DiffbotKnowledgeGraphTool` |
42
+ | Web Search | `DiffbotWebSearchRetriever`, `DiffbotWebSearchTool` |
43
+ | Extract (Analyze) | `DiffbotExtractTool`, `DiffbotExtractLoader` |
44
+ | NLP entities | `DiffbotEntitiesTool` |
45
+ | Crawl | `DiffbotCrawlLoader` |
46
+ | LLM RAG (`ask`) | `ChatDiffbot` (with native streaming), `DiffbotAskTool` |
47
+
48
+ ## Installation
49
+
50
+ ```bash
51
+ pip install langchain-diffbot
52
+ ```
53
+
54
+ ## Authentication & clients
55
+
56
+ Get an API token at https://app.diffbot.com/get-started/.
57
+
58
+ Every component takes a pre-built SDK client — you build a `diffbot.Diffbot` (sync) and/or `diffbot.DiffbotAsync` (async) and pass it via `client=` / `async_client=`. That's the only way to give a component HTTP access, and it keeps configuration in one place: customize the client (token, `timeout`, `transport=`, custom URLs) however the SDK allows, and share one client across many components to reuse a single connection pool. The component uses the client as-is and never closes it — you own its lifecycle.
59
+
60
+ ```python
61
+ import os
62
+ from diffbot import Diffbot
63
+
64
+ db = Diffbot(token=os.environ["DIFFBOT_API_TOKEN"])
65
+ ```
66
+
67
+ Pick your execution mode by which client you build: `Diffbot` for the sync surface (`invoke`, `stream`, `load`), `DiffbotAsync` for the async surface (`ainvoke`, `astream`, `alazy_load`). Pass both if a component is used both ways.
68
+
69
+ ## Quickstart — Knowledge Graph retriever
70
+
71
+ ```python
72
+ import os
73
+ from diffbot import Diffbot
74
+ from langchain_diffbot import DiffbotKnowledgeGraphRetriever
75
+
76
+ db = Diffbot(token=os.environ["DIFFBOT_API_TOKEN"])
77
+ retriever = DiffbotKnowledgeGraphRetriever(client=db, k=5)
78
+ docs = retriever.invoke("type:Organization industries:\"Artificial Intelligence\" location.city.name:\"Boston\"")
79
+ for d in docs:
80
+ print(d.metadata["name"], "—", d.page_content[:120])
81
+ ```
82
+
83
+ The query string is a [DQL (Diffbot Query Language)](https://docs.diffbot.com/reference/dql-quickstart) expression.
84
+
85
+ ## Shaping the output
86
+
87
+ Diffbot KG entities and web-search results are large. Dumping them straight into an LLM prompt can blow past per-minute input-token limits in a single call. Both retrievers expose three shaping knobs:
88
+
89
+ ```python
90
+ import os
91
+ from diffbot import Diffbot
92
+ from langchain_core.documents import Document
93
+ from langchain_diffbot import DiffbotKnowledgeGraphRetriever
94
+
95
+ db = Diffbot(token=os.environ["DIFFBOT_API_TOKEN"])
96
+
97
+ # 1. Project only the top-level fields you care about. Drops everything else
98
+ # from `metadata`. Recommended for agent / tool-use scenarios.
99
+ retriever = DiffbotKnowledgeGraphRetriever(
100
+ client=db,
101
+ k=5,
102
+ fields=["id", "type", "name", "homepageUri", "nbEmployees"],
103
+ )
104
+
105
+ # 2. Choose which field becomes `page_content`. First non-empty value wins.
106
+ retriever = DiffbotKnowledgeGraphRetriever(
107
+ client=db,
108
+ content_fields=["summary", "description", "name"],
109
+ )
110
+
111
+ # 3. For total control, pass a `document_mapper` that turns a raw entity
112
+ # dict into whatever Document shape you want.
113
+ def mapper(entity: dict) -> Document:
114
+ return Document(
115
+ page_content=entity.get("summary", ""),
116
+ metadata={"id": entity["id"], "name": entity["name"]},
117
+ )
118
+
119
+ retriever = DiffbotKnowledgeGraphRetriever(client=db, document_mapper=mapper)
120
+ ```
121
+
122
+ `fields` and `content_fields` are ignored when `document_mapper` is set. The same knobs work on `DiffbotWebSearchRetriever`.
123
+
124
+ ## Web search
125
+
126
+ ```python
127
+ import os
128
+ from diffbot import Diffbot
129
+ from langchain_diffbot import DiffbotWebSearchRetriever
130
+
131
+ db = Diffbot(token=os.environ["DIFFBOT_API_TOKEN"])
132
+ web = DiffbotWebSearchRetriever(client=db, k=5, fields=["title", "pageUrl", "score"])
133
+ docs = web.invoke("diffbot knowledge graph llm grounding")
134
+ ```
135
+
136
+ ## Extract a URL
137
+
138
+ ```python
139
+ import os
140
+ from diffbot import Diffbot
141
+ from langchain_diffbot import DiffbotExtractTool, DiffbotExtractLoader
142
+
143
+ db = Diffbot(token=os.environ["DIFFBOT_API_TOKEN"])
144
+
145
+ # Single URL
146
+ tool = DiffbotExtractTool(client=db)
147
+ page = tool.invoke({"url": "https://www.diffbot.com/products/extract/"})
148
+
149
+ # Batch — yields one Document per URL (the same client is reused)
150
+ loader = DiffbotExtractLoader(client=db, urls=["https://example.com", "https://diffbot.com"])
151
+ for doc in loader.lazy_load():
152
+ print(doc.metadata["title"], doc.page_content[:200])
153
+ ```
154
+
155
+ `DiffbotExtractTool` returns a structured `{"error": ..., "errorCode": ...}` dict when Diffbot reports an extraction failure (200 with `errorCode`), so agents can react and try another URL instead of catching an exception. Auth / rate-limit errors propagate as `diffbot.errors.AuthError` / `RateLimitError`.
156
+
157
+ ## Crawl a site
158
+
159
+ `DiffbotCrawlLoader` drives a Diffbot crawl job and yields one `Document` per crawled URL. The `page_content` is the URL itself (the crawl API surfaces URLs, not page contents) — chain it with `DiffbotExtractLoader` to fetch the content of each URL.
160
+
161
+ ```python
162
+ import os
163
+ from diffbot import Diffbot
164
+ from langchain_diffbot import DiffbotCrawlLoader
165
+
166
+ db = Diffbot(token=os.environ["DIFFBOT_API_TOKEN"])
167
+ loader = DiffbotCrawlLoader(client=db, site="https://www.diffbot.com")
168
+ for doc in loader.lazy_load():
169
+ print(doc.metadata["url"], doc.metadata["status"])
170
+ ```
171
+
172
+ ## ChatDiffbot
173
+
174
+ ```python
175
+ import os
176
+ from diffbot import Diffbot
177
+ from langchain.messages import HumanMessage
178
+ from langchain_diffbot import ChatDiffbot
179
+
180
+ llm = ChatDiffbot(client=Diffbot(token=os.environ["DIFFBOT_API_TOKEN"]))
181
+
182
+ for chunk in llm.stream([HumanMessage(content="What is the Diffbot Knowledge Graph?")]):
183
+ print(chunk.content, end="", flush=True)
184
+ ```
185
+
186
+ `_stream` / `_astream` are native — no thread-pool fallback. `.invoke()` aggregates the stream into a single message.
187
+
188
+ To let a tool-calling agent *consult* Diffbot's LLM (rather than use it as the primary model), hand it `DiffbotAskTool` instead — it answers a natural-language question from the Knowledge Graph + live web and returns a synthesized string:
189
+
190
+ ```python
191
+ import os
192
+ from diffbot import Diffbot
193
+ from langchain_diffbot import DiffbotAskTool
194
+
195
+ ask = DiffbotAskTool(client=Diffbot(token=os.environ["DIFFBOT_API_TOKEN"]))
196
+ print(ask.invoke({"question": "Who founded Diffbot, and when?"}))
197
+ ```
198
+
199
+ ## Agent tools
200
+
201
+ Every Diffbot API is also exposed as an agent-callable `BaseTool`. Hand a tool-calling agent only the tools you want — they all share whatever client you pass. `DiffbotExtractTool` and `DiffbotAskTool` are shown above; the rest:
202
+
203
+ ### DiffbotWebSearchTool
204
+
205
+ Runs a Diffbot web search and returns the result list — each item with `title`, `pageUrl`, `score`, and `content`. (Use `DiffbotWebSearchRetriever` when you want `Document` output instead.)
206
+
207
+ ```python
208
+ import os
209
+ from diffbot import Diffbot
210
+ from langchain_diffbot import DiffbotWebSearchTool
211
+
212
+ tool = DiffbotWebSearchTool(client=Diffbot(token=os.environ["DIFFBOT_API_TOKEN"]))
213
+ results = tool.invoke({"text": "diffbot knowledge graph"})
214
+ ```
215
+
216
+ ### DiffbotKnowledgeGraphTool
217
+
218
+ Runs a DQL query against the Knowledge Graph from within an agent and returns the raw response dict. (Use `DiffbotKnowledgeGraphRetriever` when you want `Document` output instead.)
219
+
220
+ ```python
221
+ import os
222
+ from diffbot import Diffbot
223
+ from langchain_diffbot import DiffbotKnowledgeGraphTool
224
+
225
+ tool = DiffbotKnowledgeGraphTool(client=Diffbot(token=os.environ["DIFFBOT_API_TOKEN"]))
226
+ body = tool.invoke({"query": 'type:Organization name:"Diffbot"'})
227
+ ```
228
+
229
+ ### DiffbotEntitiesTool
230
+
231
+ Identifies named entities and sentiment in text via Diffbot's NLP API. The returned entity IDs can be looked up in the Knowledge Graph (e.g. `id:or("E1","E2")`).
232
+
233
+ ```python
234
+ import os
235
+ from diffbot import Diffbot
236
+ from langchain_diffbot import DiffbotEntitiesTool
237
+
238
+ tool = DiffbotEntitiesTool(client=Diffbot(token=os.environ["DIFFBOT_API_TOKEN"]))
239
+ result = tool.invoke({"text": "Diffbot was founded in Menlo Park."})
240
+ ```
241
+
242
+ ### Authoring DQL on the fly: DiffbotOntologyTool + DiffbotDQLProbeTool
243
+
244
+ So an agent can build valid DQL instead of guessing field names, two tools wrap Diffbot's DQL-authoring helpers. The intended loop is **introspect (ontology) → probe → run (`DiffbotKnowledgeGraphTool`) → refine**.
245
+
246
+ `DiffbotOntologyTool` navigates the KG ontology — discover real entity types, field paths, taxonomy, and enum values before querying. The ontology is fetched once over HTTP and cached on the tool instance for the rest of its lifetime.
247
+
248
+ ```python
249
+ import os
250
+ from diffbot import Diffbot
251
+ from langchain_diffbot import DiffbotOntologyTool
252
+
253
+ tool = DiffbotOntologyTool(client=Diffbot(token=os.environ["DIFFBOT_API_TOKEN"]))
254
+ types = tool.invoke({"op": "types"})
255
+ ```
256
+
257
+ `DiffbotDQLProbeTool` probes query variants at `size=0` (hit counts only), so an agent can check selectivity — not zero, not millions — before committing to a full query.
258
+
259
+ ```python
260
+ import os
261
+ from diffbot import Diffbot
262
+ from langchain_diffbot import DiffbotDQLProbeTool
263
+
264
+ tool = DiffbotDQLProbeTool(client=Diffbot(token=os.environ["DIFFBOT_API_TOKEN"]))
265
+ counts = tool.invoke({"queries": ['type:Organization name:"Diffbot"', "type:Person"]})
266
+ ```
267
+
268
+ ## Using a retriever in a chain
269
+
270
+ The retrievers are standard `BaseRetriever`s, so they slot into LCEL like any other:
271
+
272
+ ```python
273
+ import os
274
+ from diffbot import Diffbot
275
+ from langchain_anthropic import ChatAnthropic
276
+ from langchain_core.output_parsers import StrOutputParser
277
+ from langchain_core.prompts import ChatPromptTemplate
278
+ from langchain_core.runnables import RunnablePassthrough
279
+ from langchain_diffbot import DiffbotKnowledgeGraphRetriever
280
+
281
+ retriever = DiffbotKnowledgeGraphRetriever(
282
+ client=Diffbot(token=os.environ["DIFFBOT_API_TOKEN"]),
283
+ k=5,
284
+ fields=["id", "name", "homepageUri", "nbEmployees", "industries"],
285
+ )
286
+
287
+ prompt = ChatPromptTemplate.from_template(
288
+ "Answer using only this Diffbot KG context:\n\n{context}\n\nQuestion: {question}"
289
+ )
290
+
291
+
292
+ def _format(docs):
293
+ return "\n---\n".join(
294
+ f"{d.metadata.get('name')} (id={d.metadata.get('id')}): {d.page_content}"
295
+ for d in docs
296
+ )
297
+
298
+
299
+ chain = (
300
+ {"context": retriever | _format, "question": RunnablePassthrough()}
301
+ | prompt
302
+ | ChatAnthropic(model="claude-sonnet-4-6")
303
+ | StrOutputParser()
304
+ )
305
+
306
+ chain.invoke('type:Organization location.city.name:"Boston" industries:"Biotech"')
307
+ ```
308
+
309
+ ## Sharing a client across components
310
+
311
+ Because every component takes a client, you configure the SDK once and hand the same client to as many components as you like — they share its connection pool, and there's no per-call pool churn. Build the tools/retrievers you actually want and add only those to your agent; the client is the shared resource, not a bundle.
312
+
313
+ ```python
314
+ import os
315
+ from diffbot import Diffbot
316
+ from langchain_diffbot import (
317
+ DiffbotKnowledgeGraphTool,
318
+ DiffbotAskTool,
319
+ DiffbotWebSearchRetriever,
320
+ )
321
+
322
+ # One client, configured once (timeout, transport, custom URLs, ...),
323
+ # shared across every component.
324
+ db = Diffbot(token=os.environ["DIFFBOT_API_TOKEN"], timeout=60.0)
325
+
326
+ kg = DiffbotKnowledgeGraphTool(client=db)
327
+ ask = DiffbotAskTool(client=db)
328
+ web = DiffbotWebSearchRetriever(client=db, k=5)
329
+
330
+ # `db.close()` when you're done — the components never close it for you.
331
+ ```
332
+
333
+ Anything the SDK supports (custom URLs, `transport=`, headers via a custom transport) is configured on the client you build — there's no second configuration surface to learn. For async, build a `diffbot.DiffbotAsync` and pass `async_client=` instead (or both, if a component is used both ways).
334
+
335
+ ## Components reference
336
+
337
+ | Class | Abstraction | Import path |
338
+ |-------|-------------|-------------|
339
+ | `ChatDiffbot` | Chat model | `from langchain_diffbot import ChatDiffbot` |
340
+ | `DiffbotKnowledgeGraphRetriever` | Retriever | `from langchain_diffbot import DiffbotKnowledgeGraphRetriever` |
341
+ | `DiffbotWebSearchRetriever` | Retriever | `from langchain_diffbot import DiffbotWebSearchRetriever` |
342
+ | `DiffbotExtractLoader` | Document loader | `from langchain_diffbot import DiffbotExtractLoader` |
343
+ | `DiffbotCrawlLoader` | Document loader | `from langchain_diffbot import DiffbotCrawlLoader` |
344
+ | `DiffbotExtractTool` | Tool | `from langchain_diffbot import DiffbotExtractTool` |
345
+ | `DiffbotWebSearchTool` | Tool | `from langchain_diffbot import DiffbotWebSearchTool` |
346
+ | `DiffbotKnowledgeGraphTool` | Tool | `from langchain_diffbot import DiffbotKnowledgeGraphTool` |
347
+ | `DiffbotEntitiesTool` | Tool | `from langchain_diffbot import DiffbotEntitiesTool` |
348
+ | `DiffbotAskTool` | Tool | `from langchain_diffbot import DiffbotAskTool` |
349
+ | `DiffbotOntologyTool` | Tool | `from langchain_diffbot import DiffbotOntologyTool` |
350
+ | `DiffbotDQLProbeTool` | Tool | `from langchain_diffbot import DiffbotDQLProbeTool` |
351
+
352
+ ## Examples
353
+
354
+ The [`examples/`](./examples) folder has runnable demos:
355
+
356
+ - [`examples/quickstart/`](./examples/quickstart) — full tour: every public class, output shaping, async, and a multi-tool research agent.
357
+ - [`examples/company_research/`](./examples/company_research) — the same multi-tool agent as a one-shot CLI: `cd examples && python -m company_research "your question"`. The agent combines KG search + web search + URL extract.
358
+
359
+ Both need `langchain` + `langchain-anthropic` on top of the base package — install the extra:
360
+
361
+ ```bash
362
+ pip install "langchain-diffbot[examples]"
363
+ ```
364
+
365
+ ## Development
366
+
367
+ ```bash
368
+ uv sync --all-groups
369
+ uv run pytest tests/unit_tests
370
+ ```
371
+
372
+ Integration tests hit the live Diffbot API and require `DIFFBOT_API_TOKEN`:
373
+
374
+ ```bash
375
+ uv run pytest tests/integration_tests
376
+ ```
377
+