pixelrag-langchain 0.2.1__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,32 @@
1
+ """LangChain integration for PixelRAG (screenshot-native visual search).
2
+
3
+ Unofficial community package. Not affiliated with or endorsed by
4
+ StarTrail-org, the maintainers of the upstream PixelRAG project
5
+ (https://github.com/StarTrail-org/PixelRAG).
6
+ """
7
+
8
+ from pixelrag_langchain.client import (
9
+ PixelRAGAPIError,
10
+ PixelRAGClient,
11
+ PixelRAGConnectionError,
12
+ PixelRAGError,
13
+ PixelRAGTile,
14
+ PixelRAGTimeoutError,
15
+ )
16
+ from pixelrag_langchain.config import PixelRAGConfig
17
+ from pixelrag_langchain.retriever import PixelRAGRetriever
18
+ from pixelrag_langchain.tool import PixelRAGSearchTool
19
+
20
+ __all__ = [
21
+ "PixelRAGConfig",
22
+ "PixelRAGClient",
23
+ "PixelRAGTile",
24
+ "PixelRAGError",
25
+ "PixelRAGConnectionError",
26
+ "PixelRAGTimeoutError",
27
+ "PixelRAGAPIError",
28
+ "PixelRAGRetriever",
29
+ "PixelRAGSearchTool",
30
+ ]
31
+
32
+ __version__ = "0.2.0"
@@ -0,0 +1,306 @@
1
+ """Thin HTTP client for a pixelrag-serve `/search` endpoint.
2
+
3
+ Request shape follows the upstream README's documented example:
4
+
5
+ POST /search
6
+ {"queries": [{"text": "What is the capital of France?"}], "n_docs": 5}
7
+
8
+ The authoritative schema is published by each server at `/openapi.json`.
9
+ PixelRAG is still pre-1.0, so parsing remains deliberately defensive: additive
10
+ fields are retained in `raw`, and malformed result containers degrade to an
11
+ empty result rather than crashing an agent mid-run.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import logging
17
+ from dataclasses import dataclass, field
18
+ from typing import Any
19
+ from urllib.parse import quote
20
+
21
+ import httpx
22
+
23
+ from pixelrag_langchain.config import PixelRAGConfig
24
+
25
+ logger = logging.getLogger(__name__)
26
+
27
+
28
+ class PixelRAGError(Exception):
29
+ """Base class for all errors raised by this client."""
30
+
31
+
32
+ class PixelRAGConnectionError(PixelRAGError):
33
+ """Could not reach the pixelrag-serve instance at all."""
34
+
35
+
36
+ class PixelRAGTimeoutError(PixelRAGError):
37
+ """Request exceeded the configured timeout."""
38
+
39
+
40
+ class PixelRAGAPIError(PixelRAGError):
41
+ """Server reachable but returned a non-2xx response."""
42
+
43
+ def __init__(self, status_code: int, body: str):
44
+ self.status_code = status_code
45
+ self.body = body
46
+ super().__init__(f"pixelrag-serve returned HTTP {status_code}: {body[:500]}")
47
+
48
+
49
+ @dataclass
50
+ class PixelRAGTile:
51
+ """One retrieved screenshot tile, parsed from the API response.
52
+
53
+ Field mapping verified against a live api.pixelrag.ai response (July
54
+ 2026), where each hit looks like:
55
+
56
+ {"score": 0.588, "vector_id": 18869670, "article_id": 5663927,
57
+ "tile_index": 0, "chunk_index": 7, "y_offset": 7168,
58
+ "tile_height": 1024,
59
+ "path": "shard_683/.../5663927.png.tiles/chunk_0000_07.png",
60
+ "url": "Outline_of_France", # NB: article TITLE, not a URL
61
+ "article_pages": "0:0-7,...", "image_base64": null}
62
+
63
+ Quirks preserved here on purpose:
64
+ - The server's "url" field holds the article title -> mapped to
65
+ `source`, NOT to `image_url`.
66
+ - "path" is a relative tile path within the server's tile store, not a
67
+ directly fetchable URL -> exposed as `tile_path`.
68
+ - Image bytes come back only when the server includes "image_base64".
69
+ Anything unmapped stays available in `raw`.
70
+ """
71
+
72
+ score: float
73
+ tile_id: str | None = None
74
+ source: str | None = None # article title (server's "url") or doc/article id
75
+ article_id: str | None = None
76
+ tile_index: int | None = None
77
+ chunk_index: int | None = None
78
+ tile_path: str | None = None # server-relative and informational only
79
+ image_url: str | None = None # only if server returns a real fetchable URL
80
+ image_base64: str | None = None # inline image bytes, when provided
81
+ caption: str | None = None # accompanying text/OCR, when provided
82
+ raw: dict[str, Any] = field(default_factory=dict) # untouched original record
83
+
84
+ @property
85
+ def has_tile_coordinates(self) -> bool:
86
+ """Whether this hit can be addressed through the `/tile` endpoint."""
87
+ return (
88
+ self.article_id is not None
89
+ and self.tile_index is not None
90
+ and self.chunk_index is not None
91
+ )
92
+
93
+ @classmethod
94
+ def from_api_record(cls, record: dict[str, Any]) -> "PixelRAGTile":
95
+ score = record.get("score", record.get("similarity", 0.0))
96
+ try:
97
+ score = float(score)
98
+ except (TypeError, ValueError):
99
+ score = 0.0
100
+
101
+ article_id = record.get("article_id") or record.get("doc_id")
102
+ tile_id = record.get("tile_id") or record.get("vector_id") or record.get("id")
103
+
104
+ def as_int(value: Any) -> int | None:
105
+ try:
106
+ return int(value)
107
+ except (TypeError, ValueError):
108
+ return None
109
+
110
+ # "url" is the article title in the live schema. Only treat it as a
111
+ # fetchable image URL if it actually looks like one.
112
+ url_field = record.get("url")
113
+ looks_like_real_url = isinstance(url_field, str) and url_field.startswith(
114
+ ("http://", "https://")
115
+ )
116
+
117
+ return cls(
118
+ score=score,
119
+ tile_id=str(tile_id) if tile_id is not None else None,
120
+ source=record.get("source")
121
+ or (url_field if not looks_like_real_url else None)
122
+ or (str(article_id) if article_id is not None else None),
123
+ article_id=str(article_id) if article_id is not None else None,
124
+ tile_index=as_int(record.get("tile_index")),
125
+ chunk_index=as_int(record.get("chunk_index")),
126
+ tile_path=record.get("path"),
127
+ image_url=record.get("image_url")
128
+ or (url_field if looks_like_real_url else None),
129
+ image_base64=record.get("image_base64") or record.get("image"),
130
+ caption=record.get("caption") or record.get("text"),
131
+ raw=record,
132
+ )
133
+
134
+
135
+ class PixelRAGClient:
136
+ """Synchronous client for a running pixelrag-serve instance.
137
+
138
+ Example:
139
+ >>> client = PixelRAGClient(PixelRAGConfig(base_url="http://localhost:30001"))
140
+ >>> tiles = client.search("capital of France", n_docs=3)
141
+ """
142
+
143
+ def __init__(self, config: PixelRAGConfig | None = None):
144
+ self.config = config or PixelRAGConfig()
145
+ headers = {}
146
+ if self.config.api_key:
147
+ headers["Authorization"] = f"Bearer {self.config.api_key}"
148
+ self._http = httpx.Client(timeout=self.config.timeout_s, headers=headers)
149
+
150
+ def search(
151
+ self,
152
+ query: str,
153
+ n_docs: int | None = None,
154
+ *,
155
+ include_images: bool = False,
156
+ ) -> list[PixelRAGTile]:
157
+ """Run one text query against the index and return ranked tiles.
158
+
159
+ Set `include_images=True` to request inline base64 images. The default
160
+ keeps search responses small; use `tile_url()` or `fetch_tile()` to
161
+ retrieve only the images needed downstream.
162
+
163
+ Raises:
164
+ PixelRAGConnectionError: server unreachable (wrong URL, not running).
165
+ PixelRAGTimeoutError: request exceeded `config.timeout_s`.
166
+ PixelRAGAPIError: server responded with an error status.
167
+ """
168
+ if not query or not query.strip():
169
+ return []
170
+
171
+ requested_n_docs = self.config.n_docs if n_docs is None else n_docs
172
+ if requested_n_docs < 1:
173
+ raise ValueError("n_docs must be at least 1")
174
+
175
+ payload: dict[str, Any] = {
176
+ "queries": [{"text": query}],
177
+ "n_docs": requested_n_docs,
178
+ }
179
+ if include_images:
180
+ payload["include_images"] = True
181
+
182
+ response = self._request("POST", self.config.search_url, json=payload)
183
+
184
+ try:
185
+ data = response.json()
186
+ except ValueError as exc:
187
+ raise PixelRAGAPIError(response.status_code, response.text) from exc
188
+
189
+ return self._parse_results(data)
190
+
191
+ def tile_url(self, tile: PixelRAGTile) -> str | None:
192
+ """Return the server URL for a tile, or `None` without coordinates."""
193
+ if not tile.has_tile_coordinates:
194
+ return None
195
+ return (
196
+ f"{self.config.base_url.rstrip('/')}/tile/"
197
+ f"{quote(tile.article_id, safe='')}/{tile.tile_index}/{tile.chunk_index}"
198
+ )
199
+
200
+ def fetch_tile(self, tile: PixelRAGTile) -> bytes:
201
+ """Download image bytes for one retrieved tile."""
202
+ url = self.tile_url(tile)
203
+ if url is None:
204
+ raise ValueError(
205
+ "Tile is missing article_id, tile_index, or chunk_index; "
206
+ "cannot construct its image URL."
207
+ )
208
+ return self._request("GET", url).content
209
+
210
+ def status(self) -> dict[str, Any]:
211
+ """Return server/index diagnostics from the public `/status` endpoint."""
212
+ response = self._request("GET", self.config.status_url)
213
+ try:
214
+ data = response.json()
215
+ except ValueError as exc:
216
+ raise PixelRAGAPIError(response.status_code, response.text) from exc
217
+ if not isinstance(data, dict):
218
+ raise PixelRAGAPIError(
219
+ response.status_code, "Expected a JSON object from /status"
220
+ )
221
+ return data
222
+
223
+ def health(self) -> bool:
224
+ """Best-effort check that the server is up. Never raises."""
225
+ try:
226
+ self._request("GET", self.config.health_url)
227
+ return True
228
+ except PixelRAGError:
229
+ return False
230
+
231
+ def _request(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
232
+ """Send one request and normalize all transport/API failures."""
233
+ try:
234
+ response = self._http.request(method, url, **kwargs)
235
+ except httpx.TimeoutException as exc:
236
+ raise PixelRAGTimeoutError(
237
+ f"Request to {url} timed out after {self.config.timeout_s}s."
238
+ ) from exc
239
+ except httpx.RequestError as exc:
240
+ raise PixelRAGConnectionError(
241
+ f"Could not reach pixelrag-serve at {self.config.base_url}: {exc}"
242
+ ) from exc
243
+
244
+ if response.status_code >= 400:
245
+ raise PixelRAGAPIError(response.status_code, response.text)
246
+ return response
247
+
248
+ def close(self) -> None:
249
+ self._http.close()
250
+
251
+ def __enter__(self) -> "PixelRAGClient":
252
+ return self
253
+
254
+ def __exit__(self, *exc_info: object) -> None:
255
+ self.close()
256
+
257
+ @staticmethod
258
+ def _parse_results(data: Any) -> list[PixelRAGTile]:
259
+ """Handle a couple of plausible top-level shapes without raising.
260
+
261
+ Known/expected shapes we defend against:
262
+ {"results": [[{...}, {...}]]} # per-query list of lists
263
+ {"results": [{...}, {...}]} # flat list (single query)
264
+ {"data": {"results": [...]}} # nested wrapper
265
+ Anything else logs a warning and returns an empty list rather than
266
+ raising, so a single malformed response doesn't take down an agent.
267
+ """
268
+ if not isinstance(data, dict):
269
+ logger.warning(
270
+ "Unrecognized pixelrag-serve response type: %s", type(data).__name__
271
+ )
272
+ return []
273
+
274
+ results = data.get("results")
275
+ if results is None and isinstance(data.get("data"), dict):
276
+ results = data["data"].get("results")
277
+
278
+ if results is None:
279
+ logger.warning(
280
+ "Unrecognized pixelrag-serve response shape (no 'results' key); "
281
+ "keys were: %s", list(data.keys()),
282
+ )
283
+ return []
284
+
285
+ if not isinstance(results, list):
286
+ logger.warning("pixelrag-serve 'results' field was not a list")
287
+ return []
288
+
289
+ # Real observed schema (api.pixelrag.ai, July 2026): results is a list
290
+ # of per-query objects, each wrapping its records in a "hits" list:
291
+ # {"results": [{"hits": [{...}, {...}]}]}
292
+ if results and isinstance(results[0], dict) and "hits" in results[0]:
293
+ results = results[0].get("hits") or []
294
+ # Older/alternate shape: list-of-lists grouped by query.
295
+ elif results and isinstance(results[0], list):
296
+ results = results[0]
297
+
298
+ if not isinstance(results, list):
299
+ logger.warning("pixelrag-serve 'hits' field was not a list")
300
+ return []
301
+
302
+ tiles: list[PixelRAGTile] = []
303
+ for record in results:
304
+ if isinstance(record, dict):
305
+ tiles.append(PixelRAGTile.from_api_record(record))
306
+ return tiles
@@ -0,0 +1,67 @@
1
+ """Connection configuration for a pixelrag-serve-compatible search API.
2
+
3
+ The constructor default points at a local `pixelrag serve` instance
4
+ (`pip install 'pixelrag[serve]'`) rather than any third-party host — a
5
+ library shouldn't silently route your queries somewhere you didn't choose.
6
+
7
+ Upstream PixelRAG (github.com/StarTrail-org/PixelRAG) also runs an officially
8
+ documented public production endpoint for its Wikipedia index, with no API key
9
+ required. Use `PixelRAGConfig.hosted()` to point at it — that's one explicit
10
+ line, not something this package assumes for you.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass
16
+
17
+
18
+ DEFAULT_BASE_URL = "http://localhost:30001"
19
+ # Documented in upstream's README as a first-class, intentional feature (not
20
+ # an internal/staging URL) — see the "Live, hosted endpoint" callout at
21
+ # https://github.com/StarTrail-org/PixelRAG#readme. It only serves their
22
+ # pre-built Wikipedia index, not your own documents.
23
+ PIXELRAG_HOSTED_BASE_URL = "https://api.pixelrag.ai"
24
+ DEFAULT_TIMEOUT_S = 30.0
25
+ DEFAULT_N_DOCS = 5
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class PixelRAGConfig:
30
+ """Settings for talking to a pixelrag-serve search API.
31
+
32
+ Attributes:
33
+ base_url: Root URL of a running pixelrag-serve instance. Defaults to
34
+ a local instance on the default port from the upstream README.
35
+ This is intentionally NOT defaulted to any third-party hosted
36
+ endpoint — point it there explicitly if you have one.
37
+ timeout_s: Per-request timeout in seconds.
38
+ n_docs: Default number of results to request per query.
39
+ api_key: Optional bearer token, for deployments that sit behind auth
40
+ (the local pixelrag-serve quickstart does not require one).
41
+ """
42
+
43
+ base_url: str = DEFAULT_BASE_URL
44
+ timeout_s: float = DEFAULT_TIMEOUT_S
45
+ n_docs: int = DEFAULT_N_DOCS
46
+ api_key: str | None = None
47
+
48
+ @classmethod
49
+ def hosted(cls, **overrides: object) -> "PixelRAGConfig":
50
+ """Point at upstream's public production endpoint (api.pixelrag.ai).
51
+
52
+ No API key needed. Searches their Wikipedia index only — not your own
53
+ documents. Self-host when you need private data or guaranteed capacity.
54
+ """
55
+ return cls(base_url=PIXELRAG_HOSTED_BASE_URL, **overrides) # type: ignore[arg-type]
56
+
57
+ @property
58
+ def search_url(self) -> str:
59
+ return f"{self.base_url.rstrip('/')}/search"
60
+
61
+ @property
62
+ def health_url(self) -> str:
63
+ return f"{self.base_url.rstrip('/')}/health"
64
+
65
+ @property
66
+ def status_url(self) -> str:
67
+ return f"{self.base_url.rstrip('/')}/status"
@@ -0,0 +1,90 @@
1
+ """LangChain-compatible retriever backed by a pixelrag-serve instance.
2
+
3
+ Note on Documents: LangChain's `Document` is a text-container. Screenshot
4
+ tiles are images, so we don't lie about that — `page_content` holds whatever
5
+ caption/OCR text the server gave us (often none), and the actual image
6
+ reference (URL or base64) lives in `metadata`. If your downstream chain needs
7
+ the pixels, read `metadata["image_url"]` (the fetchable coordinate URL) or
8
+ `metadata["image_base64"]` and pass it to a vision-capable model.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any
14
+
15
+ from langchain_core.callbacks import CallbackManagerForRetrieverRun
16
+ from langchain_core.documents import Document
17
+ from langchain_core.retrievers import BaseRetriever
18
+
19
+ from pixelrag_langchain.client import PixelRAGClient, PixelRAGError
20
+ from pixelrag_langchain.config import PixelRAGConfig
21
+
22
+
23
+ class PixelRAGRetriever(BaseRetriever):
24
+ """Retrieve screenshot tiles from a pixelrag-serve index as Documents.
25
+
26
+ Example:
27
+ >>> retriever = PixelRAGRetriever(config=PixelRAGConfig(base_url="http://localhost:30001"))
28
+ >>> docs = retriever.invoke("What is the capital of France?")
29
+ """
30
+
31
+ config: PixelRAGConfig = PixelRAGConfig()
32
+ n_docs: int | None = None
33
+ include_images: bool = False
34
+ """Request base64 images inline. Off by default to keep searches small."""
35
+ raise_on_error: bool = False
36
+ """If False (default), connection/timeout errors return [] instead of
37
+ raising, so a flaky visual index doesn't crash the whole chain. Set True
38
+ if you'd rather fail loudly and handle it yourself."""
39
+
40
+ _client: PixelRAGClient | None = None
41
+
42
+ model_config = {"arbitrary_types_allowed": True}
43
+
44
+ def _get_client(self) -> PixelRAGClient:
45
+ if self._client is None:
46
+ self._client = PixelRAGClient(self.config)
47
+ return self._client
48
+
49
+ def _get_relevant_documents(
50
+ self, query: str, *, run_manager: CallbackManagerForRetrieverRun
51
+ ) -> list[Document]:
52
+ client = self._get_client()
53
+ try:
54
+ tiles = client.search(
55
+ query,
56
+ n_docs=self.n_docs,
57
+ include_images=self.include_images,
58
+ )
59
+ except PixelRAGError as exc:
60
+ run_manager.on_retriever_error(exc)
61
+ if self.raise_on_error:
62
+ raise
63
+ return []
64
+
65
+ documents: list[Document] = []
66
+ for tile in tiles:
67
+ tile_url = client.tile_url(tile)
68
+ metadata: dict[str, Any] = {
69
+ "score": tile.score,
70
+ "tile_id": tile.tile_id,
71
+ "source": tile.source,
72
+ "article_id": tile.article_id,
73
+ "tile_index": tile.tile_index,
74
+ "chunk_index": tile.chunk_index,
75
+ "tile_path": tile.tile_path,
76
+ "tile_url": tile_url,
77
+ "image_url": tile.image_url or tile_url,
78
+ "image_base64": tile.image_base64,
79
+ "modality": "image",
80
+ }
81
+ documents.append(
82
+ Document(page_content=tile.caption or "", metadata=metadata)
83
+ )
84
+ return documents
85
+
86
+ def close(self) -> None:
87
+ """Release the lazily-created HTTP client, if any."""
88
+ if self._client is not None:
89
+ self._client.close()
90
+ self._client = None
@@ -0,0 +1,119 @@
1
+ """LangChain Tool wrapping PixelRAG visual search for use in agents.
2
+
3
+ Two entry points, because agents have two different needs:
4
+
5
+ - `PixelRAGSearchTool` — a standard `BaseTool`. `_run()` returns a plain
6
+ text summary (source, score, any caption) so it drops straight into a
7
+ normal text-only tool-calling agent loop.
8
+
9
+ - `PixelRAGSearchTool.search_tiles()` — returns the raw `PixelRAGTile`
10
+ objects, image data included. Use this in a LangGraph node (or anywhere
11
+ you control message construction) when you want to hand the retrieved
12
+ screenshots to a vision-capable model as actual image content, which is
13
+ the point of PixelRAG — reading pixels, not just a text summary of them.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from typing import Type
19
+
20
+ from langchain_core.callbacks import CallbackManagerForToolRun
21
+ from langchain_core.tools import BaseTool
22
+ from pydantic import BaseModel, Field
23
+
24
+ from pixelrag_langchain.client import PixelRAGClient, PixelRAGError, PixelRAGTile
25
+ from pixelrag_langchain.config import PixelRAGConfig
26
+
27
+
28
+ class PixelRAGSearchInput(BaseModel):
29
+ query: str = Field(description="Natural-language search query.")
30
+ n_docs: int = Field(default=5, ge=1, le=50, description="Number of tiles to retrieve.")
31
+
32
+
33
+ class PixelRAGSearchTool(BaseTool):
34
+ """Search a PixelRAG visual index and return the top matching tiles.
35
+
36
+ Requires a running pixelrag-serve instance (self-hosted by default —
37
+ see the upstream README: https://github.com/StarTrail-org/PixelRAG).
38
+ Point `config.base_url` at your own server; nothing is assumed for you.
39
+ """
40
+
41
+ name: str = "pixelrag_visual_search"
42
+ description: str = (
43
+ "Search an index of document screenshots (web pages, PDFs, images) "
44
+ "and return the most visually/semantically relevant tiles, with "
45
+ "similarity scores and source references. Prefer this over a plain "
46
+ "text search when the answer likely lives in a table, chart, "
47
+ "infographic, or other layout that plain text extraction would "
48
+ "mangle."
49
+ )
50
+ args_schema: Type[BaseModel] = PixelRAGSearchInput
51
+
52
+ config: PixelRAGConfig = PixelRAGConfig()
53
+ _client: PixelRAGClient | None = None
54
+
55
+ model_config = {"arbitrary_types_allowed": True}
56
+
57
+ def _get_client(self) -> PixelRAGClient:
58
+ if self._client is None:
59
+ self._client = PixelRAGClient(self.config)
60
+ return self._client
61
+
62
+ def search_tiles(
63
+ self,
64
+ query: str,
65
+ n_docs: int = 5,
66
+ *,
67
+ include_images: bool = False,
68
+ ) -> list[PixelRAGTile]:
69
+ """Return structured hits for use in LangGraph or custom pipelines."""
70
+ return self._get_client().search(
71
+ query, n_docs=n_docs, include_images=include_images
72
+ )
73
+
74
+ def tile_image_url(self, tile: PixelRAGTile) -> str | None:
75
+ """Return the fetchable coordinate-based image URL for a tile."""
76
+ return self._get_client().tile_url(tile)
77
+
78
+ def fetch_tile_bytes(self, tile: PixelRAGTile) -> bytes:
79
+ """Download image bytes for a retrieved tile."""
80
+ return self._get_client().fetch_tile(tile)
81
+
82
+ def _run(
83
+ self,
84
+ query: str,
85
+ n_docs: int = 5,
86
+ *,
87
+ run_manager: CallbackManagerForToolRun | None = None,
88
+ ) -> str:
89
+ try:
90
+ tiles = self.search_tiles(query, n_docs=n_docs)
91
+ except PixelRAGError as exc:
92
+ return f"pixelrag_visual_search failed: {exc}"
93
+
94
+ if not tiles:
95
+ return "No results found."
96
+
97
+ lines = [f"Top {len(tiles)} visual matches for: {query!r}"]
98
+ for i, tile in enumerate(tiles, start=1):
99
+ bits = [f"{i}. score={tile.score:.3f}"]
100
+ if tile.source:
101
+ bits.append(f"source={tile.source}")
102
+ if tile.tile_id:
103
+ bits.append(f"tile_id={tile.tile_id}")
104
+ if tile.caption:
105
+ bits.append(f'caption="{tile.caption[:200]}"')
106
+ image_url = tile.image_url or self.tile_image_url(tile)
107
+ if image_url:
108
+ bits.append(f"image={image_url}")
109
+ elif tile.image_base64:
110
+ bits.append("(inline image attached)")
111
+ lines.append(" " + " | ".join(bits))
112
+
113
+ return "\n".join(lines)
114
+
115
+ def close(self) -> None:
116
+ """Release the lazily-created HTTP client, if any."""
117
+ if self._client is not None:
118
+ self._client.close()
119
+ self._client = None
@@ -0,0 +1,181 @@
1
+ Metadata-Version: 2.5
2
+ Name: pixelrag-langchain
3
+ Version: 0.2.1
4
+ Summary: LangChain Tool + Retriever for PixelRAG (screenshot-native visual search) — unofficial community integration
5
+ Project-URL: Homepage, https://github.com/navneet-singh2907/pixelrag-langchain
6
+ Project-URL: Repository, https://github.com/navneet-singh2907/pixelrag-langchain
7
+ Project-URL: Upstream PixelRAG, https://github.com/StarTrail-org/PixelRAG
8
+ Project-URL: PixelRAG paper, https://papers.cool/arxiv/2606.28344
9
+ Author: Navneet Singh
10
+ License: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: agents,langchain,langgraph,pixelrag,rag,visual-search,vlm
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: httpx<0.28.0,>=0.27.0
20
+ Requires-Dist: langchain-core<0.4.0,>=0.3.0
21
+ Requires-Dist: pydantic<3.0.0,>=2.7.0
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest-httpx<0.31.0,>=0.30.0; extra == 'dev'
24
+ Requires-Dist: pytest<9.0.0,>=8.0.0; extra == 'dev'
25
+ Requires-Dist: respx<0.22.0,>=0.21.0; extra == 'dev'
26
+ Provides-Extra: render
27
+ Requires-Dist: playwright<2.0.0,>=1.45.0; extra == 'render'
28
+ Description-Content-Type: text/markdown
29
+
30
+ [![DeepSource](https://app.deepsource.com/gh/navneet-singh2907/pixelrag-langchain.svg/?label=code+coverage&show_trend=true&token=IxW1QBGxZ_fS27YFYgJ81_u6)](https://app.deepsource.com/gh/navneet-singh2907/pixelrag-langchain/)
31
+
32
+ [![CI](https://github.com/navneet-singh2907/pixelrag-langchain/actions/workflows/ci.yml/badge.svg)](https://github.com/navneet-singh2907/pixelrag-langchain/actions/workflows/ci.yml)
33
+
34
+ # pixelrag-langchain
35
+
36
+ A LangChain `Tool` + `Retriever` for [PixelRAG](https://github.com/StarTrail-org/PixelRAG) — visual, screenshot-native search for AI agents.
37
+
38
+ **This is an unofficial, community-built integration.** It is not affiliated with, endorsed by, or maintained by StarTrail-org or the PixelRAG paper authors. All credit for the underlying research and the `pixelrag-serve` engine belongs to them — see [Credits](#credits).
39
+
40
+ ## Why visual search
41
+
42
+ Most agent pipelines fetch a page, strip the HTML down to text, chunk it, and embed the chunks. That throws away tables, charts, and layout — information that's often exactly what answers the question. [PixelRAG](https://arxiv.org/abs/2606.28344) (Wang, Li, Wang, Teiletche, Jin, Zaharia, Gonzalez, Min — UC Berkeley, Princeton, EPFL, Databricks) skips the text step entirely: it renders documents to screenshot tiles, retrieves over the images directly, and hands the retrieved tiles to a vision-language model to read.
43
+
44
+ This package doesn't reimplement any of that. It just wraps the existing `pixelrag-serve` search API so it drops into a LangChain (or LangGraph) agent as a normal tool/retriever.
45
+
46
+ ## Architecture
47
+
48
+ ```mermaid
49
+ flowchart LR
50
+ A["Page / PDF"] --> B["pixelrag-render\n(screenshot tiles)"]
51
+ B --> C["pixelrag-embed\n(Qwen3-VL-Embedding)"]
52
+ C --> D["FAISS index\n(pixelrag-serve)"]
53
+ D -- "this package talks to D" --> E["PixelRAGRetriever /\nPixelRAGSearchTool"]
54
+ E --> F["Your LangChain / LangGraph agent"]
55
+ F --> G["VLM reader\n(your model of choice)"]
56
+ ```
57
+
58
+ Everything left of the dotted line (`render` → `embed` → `index` → `serve`) is upstream PixelRAG, run by you. This package is the box on the right: a client + LangChain adapters.
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ pip install pixelrag-langchain
64
+ ```
65
+
66
+ This installs only the LangChain adapter (`httpx`, `langchain-core`, `pydantic`) — no GPU, no `torch`, no CUDA. It talks to a `pixelrag-serve` instance over HTTP; it doesn't run embedding or indexing itself.
67
+
68
+ ## Quickstart — zero setup
69
+
70
+ Upstream PixelRAG runs an official public production endpoint — no API key or index download required. Nothing to install beyond this package:
71
+
72
+ ```python
73
+ from pixelrag_langchain import PixelRAGRetriever, PixelRAGConfig
74
+
75
+ retriever = PixelRAGRetriever(config=PixelRAGConfig.hosted())
76
+ docs = retriever.invoke("What is the capital of France?")
77
+
78
+ for doc in docs:
79
+ print(doc.metadata["score"], doc.metadata["source"])
80
+ print(doc.metadata["image_url"]) # fetchable PNG URL
81
+ ```
82
+
83
+ `PixelRAGConfig.hosted()` points at `https://api.pixelrag.ai`, upstream's documented production endpoint. It uses their infrastructure and Wikipedia index, not your documents. PixelRAG does not publish throughput, latency, or rate-limit guarantees; self-host when you need guaranteed capacity or private data.
84
+
85
+ ## Retrieving the actual tile images
86
+
87
+ Search results identify each screenshot with `article_id`, `tile_index`, and `chunk_index`. Version 0.2 turns those coordinates into the upstream-supported `/tile/...` URL; the server-relative `path` field is informational and should not be used to construct URLs.
88
+
89
+ Use the client when you want explicit control over image downloads:
90
+
91
+ ```python
92
+ from pixelrag_langchain import PixelRAGClient, PixelRAGConfig
93
+
94
+ with PixelRAGClient(PixelRAGConfig.hosted()) as client:
95
+ tile = client.search("diagram of a transformer architecture", n_docs=1)[0]
96
+ print(client.tile_url(tile))
97
+ png_bytes = client.fetch_tile(tile)
98
+ ```
99
+
100
+ The separate `GET /tile/{article_id}/{tile_index}/{chunk_index}` request is the recommended default because it keeps search responses small. If you need every image inline, explicitly request base64 data:
101
+
102
+ ```python
103
+ with PixelRAGClient(PixelRAGConfig.hosted()) as client:
104
+ tiles = client.search("quarterly revenue chart", include_images=True)
105
+ print(tiles[0].image_base64)
106
+ ```
107
+
108
+ `PixelRAGRetriever` exposes the coordinate URL in both `metadata["tile_url"]` and `metadata["image_url"]`. `PixelRAGSearchTool` provides `tile_image_url()` and `fetch_tile_bytes()` for structured LangGraph workflows. See [`examples/langgraph_node.py`](examples/langgraph_node.py) for a complete multimodal-message handoff.
109
+
110
+ The API is currently pre-1.0. Its authoritative machine-readable contract is served at [`/openapi.json`](https://api.pixelrag.ai/openapi.json); this package parses additive hit fields leniently.
111
+
112
+ For operational checks, `client.health()` returns a best-effort boolean and `client.status()` returns the server's current index diagnostics.
113
+
114
+ ## Quickstart — your own documents
115
+
116
+ For real use — your own PDFs, internal docs, scraped pages — run `pixelrag serve` yourself:
117
+
118
+ ```bash
119
+ pip install 'pixelrag[serve]'
120
+
121
+ # Download a pre-built Wikipedia index, or build your own from `pip install 'pixelrag[index]'`
122
+ huggingface-cli download StarTrail-org/pixelrag-faiss-indexes \
123
+ --repo-type dataset --include "search_index_normed_v2/*" --local-dir ./index
124
+
125
+ pixelrag serve --index-dir ./index/search_index_normed_v2 --port 30001
126
+ ```
127
+
128
+ ```python
129
+ from pixelrag_langchain import PixelRAGRetriever, PixelRAGConfig
130
+
131
+ retriever = PixelRAGRetriever(config=PixelRAGConfig(base_url="http://localhost:30001"))
132
+ docs = retriever.invoke("What is the capital of France?")
133
+ ```
134
+
135
+ ## As an agent tool
136
+
137
+ ```python
138
+ from langchain.agents import create_agent
139
+ from pixelrag_langchain import PixelRAGSearchTool, PixelRAGConfig
140
+
141
+ tool = PixelRAGSearchTool(config=PixelRAGConfig.hosted()) # or base_url="http://localhost:30001"
142
+ agent = create_agent(model="your-model", tools=[tool])
143
+ ```
144
+
145
+ Nothing here defaults to a single host silently — `PixelRAGConfig(base_url=...)` accepts any pixelrag-serve-compatible URL, including your own deployment; `.hosted()` is one explicit opt-in line, not a hidden default.
146
+
147
+ ## What this package is *not*
148
+
149
+ - Not a reimplementation of PixelRAG's render/embed/index/serve pipeline — install the [upstream project](https://github.com/StarTrail-org/PixelRAG) for that.
150
+ - Not a hosted service itself. `PixelRAGConfig.hosted()` is a convenience pointer to *upstream's* public endpoint, not infrastructure we run.
151
+ - Not affiliated with StarTrail-org, Berkeley Sky Computing Lab, BAIR, or the Berkeley NLP Group, who built the actual PixelRAG engine and research this wraps.
152
+
153
+ ## Benchmarks (from the upstream paper, not measured by this package)
154
+
155
+ Reported in [PIXELRAG: Web Screenshots Beat Text for Retrieval-Augmented Generation](https://arxiv.org/abs/2606.28344) (arXiv:2606.28344):
156
+
157
+ | Metric | Text-based RAG | PixelRAG | Context |
158
+ |---|---|---|---|
159
+ | Prompt tokens, agentic benchmark | 37.5M | 3.6M | MoNaCo multi-step agent benchmark |
160
+ | Accuracy gain | baseline | up to +18.1% | vs. text-based RAG baselines, across NQ/SimpleQA/MMSearch/LiveVQA |
161
+ | Token cost via image compression | — | up to 3x reduction | lower-resolution tiles, accuracy preserved |
162
+
163
+ These are the paper's own reported numbers, not something we independently reproduced — treat them as a starting point for your own evaluation on your workload, not a guarantee.
164
+
165
+ ## Development
166
+
167
+ ```bash
168
+ git clone https://github.com/navneet-singh2907/pixelrag-langchain
169
+ cd pixelrag-langchain
170
+ pip install -e ".[dev]"
171
+ pytest
172
+ ```
173
+
174
+ ## Credits
175
+
176
+ - **PixelRAG** engine, paper, and research: Yichuan Wang, Zhifei Li, Zirui Wang, Paul Teiletche, Lesheng Jin, Matei Zaharia, Joseph E. Gonzalez, Sewon Min. [Paper](https://arxiv.org/abs/2606.28344) · [Code](https://github.com/StarTrail-org/PixelRAG) (Apache-2.0).
177
+ - This package: an independent, unofficial LangChain adapter around that work.
178
+
179
+ ## License
180
+
181
+ Apache-2.0 — see [LICENSE](LICENSE). This is a new work built to talk to PixelRAG over HTTP; it does not vendor or redistribute any upstream PixelRAG code, so no NOTICE carryover is required, but attribution is given above regardless because it's their research this is built on.
@@ -0,0 +1,9 @@
1
+ pixelrag_langchain/__init__.py,sha256=Gm4aBTxc-coRQhOCC6GR9QTZcCwsnQ33Clthg7NntyM,853
2
+ pixelrag_langchain/client.py,sha256=j2kLeHoFdPwwYgEQxyCLFFw3vpIcpRc_WNDpQYFU-rs,11608
3
+ pixelrag_langchain/config.py,sha256=TlUzEsegzmaTFHRWNmbrv7cH4egtUDhUplXz-RRkH9U,2631
4
+ pixelrag_langchain/retriever.py,sha256=D53T4pdG18g3uelohwR3vGjMciTAwsFA-etpmZLK4Ns,3369
5
+ pixelrag_langchain/tool.py,sha256=XkiF9tqCnM00EEOvXWLkytc0odhWhGZo44ymxEG68Lc,4467
6
+ pixelrag_langchain-0.2.1.dist-info/METADATA,sha256=kWxGT7LCqTGC5NYzTanMj74en-iI80k0EMnsGsG-l9Y,9584
7
+ pixelrag_langchain-0.2.1.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
8
+ pixelrag_langchain-0.2.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ pixelrag_langchain-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.