langchain-webcite 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.
@@ -0,0 +1,19 @@
1
+ """LangChain integration for Webcite: claim verification, source search and document parsing."""
2
+
3
+ from langchain_webcite.retrievers import WebciteRetriever
4
+ from langchain_webcite.tools import (
5
+ WebciteExtractDocumentTool,
6
+ WebciteSearchSourcesTool,
7
+ WebciteToolkit,
8
+ WebciteVerifyClaimTool,
9
+ )
10
+
11
+ __all__ = [
12
+ "WebciteExtractDocumentTool",
13
+ "WebciteRetriever",
14
+ "WebciteSearchSourcesTool",
15
+ "WebciteToolkit",
16
+ "WebciteVerifyClaimTool",
17
+ ]
18
+
19
+ __version__ = "0.1.0"
@@ -0,0 +1,73 @@
1
+ """Turn Webcite API responses into compact text a model can read.
2
+
3
+ The full response is always returned as the tool artifact, so nothing is dropped; these
4
+ helpers only choose what goes into the model's context.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from collections.abc import Mapping, Sequence
11
+ from typing import Any
12
+
13
+
14
+ def _citations(response: Mapping[str, Any]) -> list[Mapping[str, Any]]:
15
+ groups = response.get("claim_groups") or []
16
+ if groups and groups[0].get("citations") is not None:
17
+ return list(groups[0]["citations"])
18
+ return list(response.get("citations") or [])
19
+
20
+
21
+ def citation_summary(citation: Mapping[str, Any]) -> dict[str, Any]:
22
+ """The fields of one citation that identify the source and the bound passage."""
23
+ passage = citation.get("passage") or {}
24
+ summary = {
25
+ "id": citation.get("id"),
26
+ "url": citation.get("url"),
27
+ "title": citation.get("title"),
28
+ "stance": citation.get("stance"),
29
+ "passage": passage.get("text") or citation.get("snippet"),
30
+ }
31
+ return {key: value for key, value in summary.items() if value is not None}
32
+
33
+
34
+ def verification_text(response: Mapping[str, Any], max_citations: int) -> str:
35
+ groups = response.get("claim_groups") or []
36
+ verdict: Mapping[str, Any] = (groups[0].get("verdict") if groups else None) or {}
37
+ body = {
38
+ "claim": verdict.get("claim") or (groups[0].get("claim") if groups else None),
39
+ "verdict": verdict.get("result"),
40
+ "summary": verdict.get("summary"),
41
+ "citations": [citation_summary(c) for c in _citations(response)[:max_citations]],
42
+ "credits": (response.get("usage") or {}).get("credits"),
43
+ }
44
+ return json.dumps({k: v for k, v in body.items() if v is not None}, ensure_ascii=False)
45
+
46
+
47
+ def search_results(response: Mapping[str, Any], limit: int | None) -> list[dict[str, Any]]:
48
+ found = [citation_summary(c) for c in _citations(response)]
49
+ return found[:limit] if limit else found
50
+
51
+
52
+ def search_text(response: Mapping[str, Any], limit: int | None) -> str:
53
+ return json.dumps(search_results(response, limit), ensure_ascii=False)
54
+
55
+
56
+ def extraction_text(response: Mapping[str, Any], max_chars: int | None) -> str:
57
+ markdown = str(response.get("markdown") or "")
58
+ truncated = max_chars is not None and len(markdown) > max_chars
59
+ header: dict[str, Any] = {
60
+ "state": response.get("state"),
61
+ "pages": (response.get("usage") or {}).get("pages"),
62
+ "credits": (response.get("usage") or {}).get("credits"),
63
+ }
64
+ if response.get("reason"):
65
+ header["reason"] = response.get("reason")
66
+ if truncated:
67
+ header["truncated_to_chars"] = max_chars
68
+ text = markdown[:max_chars] if truncated else markdown
69
+ return json.dumps({k: v for k, v in header.items() if v is not None}) + "\n\n" + text
70
+
71
+
72
+ def compact_list(values: Sequence[str] | None) -> list[str] | None:
73
+ return list(values) if values else None
File without changes
@@ -0,0 +1,40 @@
1
+ """A LangChain retriever over Webcite source search."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from langchain_core.callbacks import CallbackManagerForRetrieverRun
6
+ from langchain_core.documents import Document
7
+ from langchain_core.retrievers import BaseRetriever
8
+ from pydantic import ConfigDict, Field
9
+ from webcite import Webcite
10
+
11
+ from langchain_webcite._format import search_results
12
+
13
+
14
+ class WebciteRetriever(BaseRetriever):
15
+ """Return sources for a query as Documents: the passage as content, URL and title as metadata.
16
+
17
+ Each query is one source search (2 credits, https://webcite.co/pricing).
18
+ """
19
+
20
+ model_config = ConfigDict(arbitrary_types_allowed=True)
21
+
22
+ client: Webcite = Field(default_factory=Webcite, exclude=True)
23
+ k: int | None = 5
24
+
25
+ def _get_relevant_documents(
26
+ self,
27
+ query: str,
28
+ *,
29
+ run_manager: CallbackManagerForRetrieverRun,
30
+ k: int | None = None,
31
+ ) -> list[Document]:
32
+ limit = k if k is not None else self.k
33
+ response = self.client.search(query, limit=limit)
34
+ return [
35
+ Document(
36
+ page_content=str(item.get("passage") or item.get("title") or item.get("url")),
37
+ metadata={key: val for key, val in item.items() if key != "passage"},
38
+ )
39
+ for item in search_results(response, limit)
40
+ ]
@@ -0,0 +1,130 @@
1
+ """LangChain tools for the Webcite API: claim verification, source search, document parsing."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Literal
6
+
7
+ from langchain_core.callbacks import CallbackManagerForToolRun
8
+ from langchain_core.tools import BaseTool, BaseToolkit
9
+ from pydantic import BaseModel, ConfigDict, Field
10
+ from webcite import Webcite
11
+
12
+ from langchain_webcite._format import (
13
+ compact_list,
14
+ extraction_text,
15
+ search_text,
16
+ verification_text,
17
+ )
18
+
19
+
20
+ class _WebciteTool(BaseTool):
21
+ """Shared client handling. ``client`` defaults to ``Webcite()``, which reads WEBCITE_API_KEY."""
22
+
23
+ model_config = ConfigDict(arbitrary_types_allowed=True)
24
+
25
+ client: Webcite = Field(default_factory=Webcite, exclude=True)
26
+ response_format: Literal["content", "content_and_artifact"] = "content_and_artifact"
27
+
28
+
29
+ class VerifyClaimInput(BaseModel):
30
+ claim: str = Field(description="One factual statement to check, in plain language.")
31
+ source_urls: list[str] | None = Field(
32
+ default=None,
33
+ description="Optional URLs to check the claim against instead of searching the web.",
34
+ )
35
+
36
+
37
+ class WebciteVerifyClaimTool(_WebciteTool):
38
+ """Check a claim against sources and return a verdict with citations bound to passages.
39
+
40
+ A verification with stance and verdict uses 4 credits (https://webcite.co/pricing).
41
+ The full API response is returned as the tool message artifact.
42
+ """
43
+
44
+ name: str = "webcite_verify_claim"
45
+ description: str = (
46
+ "Check whether a factual claim is supported or contradicted by sources. Returns a "
47
+ "verdict, a short summary and citations, each with its URL, stance and the source "
48
+ "passage it rests on. Input is one claim; optionally the URLs to check it against."
49
+ )
50
+ args_schema: type[BaseModel] = VerifyClaimInput
51
+ max_citations: int = 5
52
+
53
+ def _run(
54
+ self,
55
+ claim: str,
56
+ source_urls: list[str] | None = None,
57
+ run_manager: CallbackManagerForToolRun | None = None,
58
+ ) -> tuple[str, dict[str, Any]]:
59
+ response = self.client.verify(claim, source_urls=compact_list(source_urls))
60
+ return verification_text(response, self.max_citations), dict(response)
61
+
62
+
63
+ class SearchSourcesInput(BaseModel):
64
+ query: str = Field(description="What to find sources for.")
65
+ limit: int | None = Field(default=None, description="Maximum number of sources.")
66
+
67
+
68
+ class WebciteSearchSourcesTool(_WebciteTool):
69
+ """Find sources for a query, without stance or verdict. Uses 2 credits per search."""
70
+
71
+ name: str = "webcite_search_sources"
72
+ description: str = (
73
+ "Search for sources relevant to a query. Returns a list of sources with URL, title "
74
+ "and the matching passage. Use it to find evidence before writing or citing."
75
+ )
76
+ args_schema: type[BaseModel] = SearchSourcesInput
77
+
78
+ def _run(
79
+ self,
80
+ query: str,
81
+ limit: int | None = None,
82
+ run_manager: CallbackManagerForToolRun | None = None,
83
+ ) -> tuple[str, dict[str, Any]]:
84
+ response = self.client.search(query, limit=limit)
85
+ return search_text(response, limit), dict(response)
86
+
87
+
88
+ class ExtractDocumentInput(BaseModel):
89
+ url: str = Field(description="Direct HTTPS URL of a PDF, image, spreadsheet or office file.")
90
+
91
+
92
+ class WebciteExtractDocumentTool(_WebciteTool):
93
+ """Read a document at a URL into Markdown, with every page read before it returns.
94
+
95
+ Extraction is metered per page at cost (https://webcite.co/pricing). Check ``state`` in
96
+ the first line of the output: anything other than ``complete`` names what was not read.
97
+ """
98
+
99
+ name: str = "webcite_extract_document"
100
+ description: str = (
101
+ "Read a document (PDF, scan, image, spreadsheet, DOCX, PPTX) from a direct URL and "
102
+ "return its text as Markdown, with tables kept as tables. The first line is a JSON "
103
+ "header with the extraction state, page count and credits used."
104
+ )
105
+ args_schema: type[BaseModel] = ExtractDocumentInput
106
+ mode: Literal["standard", "lite"] | None = None
107
+ max_chars: int | None = 50_000
108
+
109
+ def _run(
110
+ self,
111
+ url: str,
112
+ run_manager: CallbackManagerForToolRun | None = None,
113
+ ) -> tuple[str, dict[str, Any]]:
114
+ response = self.client.extract(asset_url=url, mode=self.mode)
115
+ return extraction_text(response, self.max_chars), dict(response)
116
+
117
+
118
+ class WebciteToolkit(BaseToolkit):
119
+ """The three Webcite tools sharing one client."""
120
+
121
+ model_config = ConfigDict(arbitrary_types_allowed=True)
122
+
123
+ client: Webcite = Field(default_factory=Webcite, exclude=True)
124
+
125
+ def get_tools(self) -> list[BaseTool]:
126
+ return [
127
+ WebciteVerifyClaimTool(client=self.client),
128
+ WebciteSearchSourcesTool(client=self.client),
129
+ WebciteExtractDocumentTool(client=self.client),
130
+ ]
@@ -0,0 +1,159 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-webcite
3
+ Version: 0.1.0
4
+ Summary: LangChain tools and retriever for Webcite: verify claims with citations bound to source passages, search sources, and parse documents to Markdown.
5
+ Project-URL: Homepage, https://webcite.co
6
+ Project-URL: Documentation, https://github.com/strategyconnect/langchain-webcite#readme
7
+ Project-URL: Repository, https://github.com/strategyconnect/langchain-webcite
8
+ Project-URL: API reference, https://webcite.co/api-docs
9
+ Author: Webcite
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: ai-agents,citations,claim-verification,document-parsing,fact-checking,langchain,pdf-to-markdown,rag,retriever,webcite
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: langchain-core<2.0.0,>=0.3.0
21
+ Requires-Dist: webcite<0.2.0,>=0.1.0
22
+ Description-Content-Type: text/markdown
23
+
24
+ # langchain-webcite
25
+
26
+ LangChain tools and a retriever for [Webcite](https://webcite.co), one evidence suite for AI
27
+ apps and agents: document parsing and OCR to Markdown, claim verification with verdicts,
28
+ citations bound to source passages, and source search.
29
+
30
+ | Class | Kind | What it does | Credits |
31
+ |---|---|---|---|
32
+ | `WebciteVerifyClaimTool` | Tool | Checks a claim and returns a verdict, a summary and citations with URL, stance and the source passage | 4 per claim |
33
+ | `WebciteSearchSourcesTool` | Tool | Finds sources for a query, with the matching passage | 2 per search |
34
+ | `WebciteExtractDocumentTool` | Tool | Reads a PDF, scan, image, spreadsheet or office file at a URL into Markdown | Per page, at cost |
35
+ | `WebciteRetriever` | Retriever | Source search as LangChain `Document`s (passage as content, URL, title and stance as metadata) | 2 per query |
36
+ | `WebciteToolkit` | Toolkit | The three tools sharing one client | |
37
+
38
+ Prices are on [webcite.co/pricing](https://webcite.co/pricing). The Free plan includes 100
39
+ credits, renewing every 30 days while credits remain.
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install langchain-webcite
45
+ export WEBCITE_API_KEY=... # create one at https://webcite.co/api-keys
46
+ ```
47
+
48
+ Python 3.10 or newer. Depends on `langchain-core` and the official
49
+ [`webcite`](https://github.com/strategyconnect/webcite-python) Python SDK.
50
+
51
+ ## Use the tools in an agent
52
+
53
+ ```python
54
+ from langchain.agents import create_agent
55
+ from langchain_webcite import WebciteToolkit
56
+
57
+ agent = create_agent(
58
+ "anthropic:claude-sonnet-5",
59
+ tools=WebciteToolkit().get_tools(),
60
+ system_prompt="Check each claim with webcite_verify_claim and cite the URLs it returns.",
61
+ )
62
+ agent.invoke({"messages": [{"role": "user", "content": "Can you see the Great Wall from the Moon?"}]})
63
+ ```
64
+
65
+ ## Verify a claim
66
+
67
+ ```python
68
+ from langchain_webcite import WebciteVerifyClaimTool
69
+
70
+ tool = WebciteVerifyClaimTool(max_citations=2)
71
+ print(tool.invoke({"claim": "The Great Wall of China is visible from the Moon with the naked eye."}))
72
+ ```
73
+
74
+ Output, rendered from the response recorded from the API on 24 November 2026
75
+ ([webcite.co/samples/claim-great-wall.json](https://webcite.co/samples/claim-great-wall.json)),
76
+ shortened here:
77
+
78
+ ```json
79
+ {"claim": "The Great Wall of China is visible from the Moon with the naked eye.",
80
+ "verdict": "contradicted",
81
+ "summary": "The claim that the Great Wall of China is visible from the Moon with the naked eye is false ...",
82
+ "citations": [{"id": "1", "url": "https://www.nasa.gov/image-article/great-wall/", "title": "nasa.gov",
83
+ "stance": "contradicts",
84
+ "passage": "... Despite myths to the contrary, the wall isn't visible from the moon, ..."}, ...],
85
+ "credits": 4}
86
+ ```
87
+
88
+ Pass `source_urls` to check the claim against specific pages instead of searching the web.
89
+ When the tool is called by a model (with a `ToolCall`), the full API response is attached as the
90
+ `ToolMessage` artifact, so nothing is lost when the model only sees the compact text.
91
+
92
+ ## Parse a document to Markdown
93
+
94
+ ```python
95
+ from langchain_webcite import WebciteExtractDocumentTool
96
+
97
+ tool = WebciteExtractDocumentTool() # mode="lite" for the faster, cheaper read
98
+ print(tool.invoke({"url": "https://www.irs.gov/pub/irs-pdf/fw9.pdf"}))
99
+ ```
100
+
101
+ The first line is a JSON header; the Markdown follows. Recorded output for page 1 of the form
102
+ ([webcite.co/samples/doc-irs-w9.json](https://webcite.co/samples/doc-irs-w9.json)):
103
+
104
+ ```text
105
+ {"state": "complete", "pages": 1, "credits": 0.4966}
106
+
107
+ Form **W-9**
108
+ (Rev. March 2024)
109
+ ...
110
+ ```
111
+
112
+ Check `state`: anything other than `complete` comes with a `reason` naming what was not read.
113
+ Long documents are cut at `max_chars` (50,000 by default) and the header says so.
114
+
115
+ ## Retrieve sources
116
+
117
+ ```python
118
+ from langchain_webcite import WebciteRetriever
119
+
120
+ retriever = WebciteRetriever(k=3)
121
+ for doc in retriever.invoke("Apple total net sales fiscal 2024"):
122
+ print(doc.metadata["url"], doc.page_content[:80])
123
+ ```
124
+
125
+ ## Configuration
126
+
127
+ Every class takes an optional `client`, a `webcite.Webcite` instance. Without one it creates
128
+ `Webcite()`, which reads `WEBCITE_API_KEY` (and `WEBCITE_API_URL` if set). Pass your own client to
129
+ set a timeout, retries or a custom `httpx` client:
130
+
131
+ ```python
132
+ from webcite import Webcite
133
+ from langchain_webcite import WebciteToolkit
134
+
135
+ tools = WebciteToolkit(client=Webcite(timeout=120, max_retries=2)).get_tools()
136
+ ```
137
+
138
+ The same capabilities are also available to any MCP client from the hosted server at
139
+ `https://api.webcite.co/mcp` (OAuth or API key).
140
+
141
+ ## Development
142
+
143
+ ```bash
144
+ make install # uv sync --all-groups
145
+ make check # ruff, mypy, pytest
146
+ make build # wheel and sdist in dist/
147
+ ```
148
+
149
+ Tests run the LangChain standard tool and retriever tests (`langchain-tests`) against recorded
150
+ API responses in `tests/fixtures`; sockets are disabled, so no test reaches the network or spends
151
+ credits. Examples are in [`examples/`](examples).
152
+
153
+ ## Links
154
+
155
+ - [Webcite API reference](https://webcite.co/api-docs)
156
+ - [Webcite Python SDK](https://github.com/strategyconnect/webcite-python)
157
+ - Support: support@webcite.co
158
+
159
+ MIT licensed.
@@ -0,0 +1,9 @@
1
+ langchain_webcite/__init__.py,sha256=ide9dpt2HAbrNxnC2UrrymTD79wab2EF4DdEpnkfw9c,486
2
+ langchain_webcite/_format.py,sha256=7Fm3tQ_yrNPDTc2yZYbFynPP0uxLmP_UI4WVPn1vJfk,2946
3
+ langchain_webcite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ langchain_webcite/retrievers.py,sha256=xz6laSQMY7sIps2D2PASxJM6p-n1Bx9pQs8w2tQDgqM,1349
5
+ langchain_webcite/tools.py,sha256=OiEcc8V_CrivMDEsja4Ep876K2iaeFopvJGB4B_sTOw,4845
6
+ langchain_webcite-0.1.0.dist-info/METADATA,sha256=y-65Lm3PlOAbsFhu3BzRmTE_xWYswOWtVAsOwCyVxfI,6151
7
+ langchain_webcite-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ langchain_webcite-0.1.0.dist-info/licenses/LICENSE,sha256=ZfHdQvjcMlOV3tvWbiik9xYRbscmZNE4pMkIeHbUSMA,1063
9
+ langchain_webcite-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marvin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.