wikivectors 0.1.0__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.
- wikivectors-0.1.0/.gitignore +3 -0
- wikivectors-0.1.0/LICENSE +21 -0
- wikivectors-0.1.0/PKG-INFO +86 -0
- wikivectors-0.1.0/README.md +66 -0
- wikivectors-0.1.0/pyproject.toml +30 -0
- wikivectors-0.1.0/src/wikivectors/__init__.py +14 -0
- wikivectors-0.1.0/src/wikivectors/client.py +120 -0
- wikivectors-0.1.0/src/wikivectors/langchain.py +33 -0
- wikivectors-0.1.0/src/wikivectors/llamaindex.py +31 -0
- wikivectors-0.1.0/tests/test_client.py +185 -0
- wikivectors-0.1.0/tests/test_retrievers.py +57 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bionics LLC
|
|
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.
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: wikivectors
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Fresh English Wikipedia for AI apps: search, answers, pages, facts and a change feed. LangChain and LlamaIndex retrievers included.
|
|
5
|
+
Project-URL: Homepage, https://wikivectors.com
|
|
6
|
+
Project-URL: Documentation, https://wikivectors.com/docs
|
|
7
|
+
Author: WikiVectors
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: grounding,langchain,llamaindex,llm,rag,retrieval,search,wikipedia
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Provides-Extra: langchain
|
|
16
|
+
Requires-Dist: langchain-core>=0.3; extra == 'langchain'
|
|
17
|
+
Provides-Extra: llamaindex
|
|
18
|
+
Requires-Dist: llama-index-core>=0.12; extra == 'llamaindex'
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# wikivectors
|
|
22
|
+
|
|
23
|
+
Fresh English Wikipedia for AI apps. Ask in plain English and get the right paragraphs, each with its link and revision, updated within the hour. Also short cited answers, whole pages, infobox facts and a change feed.
|
|
24
|
+
|
|
25
|
+
Free key (1,000 searches a month): https://wikivectors.com/account · Docs: https://wikivectors.com/docs
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install wikivectors
|
|
29
|
+
export WIKIVECTORS_KEY=wv_live_...
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Search
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from wikivectors import WikiVectors
|
|
36
|
+
|
|
37
|
+
wv = WikiVectors() # reads WIKIVECTORS_KEY
|
|
38
|
+
for p in wv.search("who won the 2026 FIFA World Cup", limit=3):
|
|
39
|
+
print(p["title"], p["permalink"])
|
|
40
|
+
print(p["text"])
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Everything else
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
wv.answer("who won the 2026 FIFA World Cup") # short answer + sources, or answered=False
|
|
47
|
+
wv.pages(["Ada Lovelace", "Alan Turing"]) # whole pages
|
|
48
|
+
wv.facts("Ada Lovelace") # infobox as JSON: born, died, known for...
|
|
49
|
+
wv.identify("Michael Jordan", hint="professor, machine learning")
|
|
50
|
+
wv.titles(prefix="2025 in ")
|
|
51
|
+
wv.changes(pages=["Ada Lovelace"]) # recent edits; pass next_after back as after=
|
|
52
|
+
wv.watch(page="Ada Lovelace", callback_url="https://example.com/hook")
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Errors raise `WikiVectorsError` with `.status`, `.code`, `.message` and `.request_id`.
|
|
56
|
+
|
|
57
|
+
## LangChain
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install "wikivectors[langchain]"
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from wikivectors.langchain import WikiVectorsRetriever
|
|
65
|
+
|
|
66
|
+
retriever = WikiVectorsRetriever(k=3)
|
|
67
|
+
for doc in retriever.invoke("who won the 2026 FIFA World Cup"):
|
|
68
|
+
print(doc.metadata["title"], doc.metadata["permalink"])
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## LlamaIndex
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
pip install "wikivectors[llamaindex]"
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
from wikivectors.llamaindex import WikiVectorsRetriever
|
|
79
|
+
|
|
80
|
+
for n in WikiVectorsRetriever(k=3).retrieve("who won the 2026 FIFA World Cup"):
|
|
81
|
+
print(n.node.metadata["title"], n.node.metadata["permalink"])
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## License
|
|
85
|
+
|
|
86
|
+
The client is MIT. Wikipedia text is CC BY-SA 4.0: show the `attribution` line, or at least the link, wherever you show the text.
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# wikivectors
|
|
2
|
+
|
|
3
|
+
Fresh English Wikipedia for AI apps. Ask in plain English and get the right paragraphs, each with its link and revision, updated within the hour. Also short cited answers, whole pages, infobox facts and a change feed.
|
|
4
|
+
|
|
5
|
+
Free key (1,000 searches a month): https://wikivectors.com/account · Docs: https://wikivectors.com/docs
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install wikivectors
|
|
9
|
+
export WIKIVECTORS_KEY=wv_live_...
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## Search
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from wikivectors import WikiVectors
|
|
16
|
+
|
|
17
|
+
wv = WikiVectors() # reads WIKIVECTORS_KEY
|
|
18
|
+
for p in wv.search("who won the 2026 FIFA World Cup", limit=3):
|
|
19
|
+
print(p["title"], p["permalink"])
|
|
20
|
+
print(p["text"])
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Everything else
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
wv.answer("who won the 2026 FIFA World Cup") # short answer + sources, or answered=False
|
|
27
|
+
wv.pages(["Ada Lovelace", "Alan Turing"]) # whole pages
|
|
28
|
+
wv.facts("Ada Lovelace") # infobox as JSON: born, died, known for...
|
|
29
|
+
wv.identify("Michael Jordan", hint="professor, machine learning")
|
|
30
|
+
wv.titles(prefix="2025 in ")
|
|
31
|
+
wv.changes(pages=["Ada Lovelace"]) # recent edits; pass next_after back as after=
|
|
32
|
+
wv.watch(page="Ada Lovelace", callback_url="https://example.com/hook")
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
Errors raise `WikiVectorsError` with `.status`, `.code`, `.message` and `.request_id`.
|
|
36
|
+
|
|
37
|
+
## LangChain
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pip install "wikivectors[langchain]"
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from wikivectors.langchain import WikiVectorsRetriever
|
|
45
|
+
|
|
46
|
+
retriever = WikiVectorsRetriever(k=3)
|
|
47
|
+
for doc in retriever.invoke("who won the 2026 FIFA World Cup"):
|
|
48
|
+
print(doc.metadata["title"], doc.metadata["permalink"])
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## LlamaIndex
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
pip install "wikivectors[llamaindex]"
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from wikivectors.llamaindex import WikiVectorsRetriever
|
|
59
|
+
|
|
60
|
+
for n in WikiVectorsRetriever(k=3).retrieve("who won the 2026 FIFA World Cup"):
|
|
61
|
+
print(n.node.metadata["title"], n.node.metadata["permalink"])
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
## License
|
|
65
|
+
|
|
66
|
+
The client is MIT. Wikipedia text is CC BY-SA 4.0: show the `attribution` line, or at least the link, wherever you show the text.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "wikivectors"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Fresh English Wikipedia for AI apps: search, answers, pages, facts and a change feed. LangChain and LlamaIndex retrievers included."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "WikiVectors" }]
|
|
13
|
+
keywords = ["wikipedia", "rag", "retrieval", "langchain", "llamaindex", "search", "llm", "grounding"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
18
|
+
]
|
|
19
|
+
dependencies = []
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
langchain = ["langchain-core>=0.3"]
|
|
23
|
+
llamaindex = ["llama-index-core>=0.12"]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://wikivectors.com"
|
|
27
|
+
Documentation = "https://wikivectors.com/docs"
|
|
28
|
+
|
|
29
|
+
[tool.hatch.version]
|
|
30
|
+
path = "src/wikivectors/__init__.py"
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""WikiVectors: fresh English Wikipedia for AI apps.
|
|
2
|
+
|
|
3
|
+
from wikivectors import WikiVectors
|
|
4
|
+
wv = WikiVectors() # reads WIKIVECTORS_KEY
|
|
5
|
+
for p in wv.search("who won the 2026 FIFA World Cup", limit=3):
|
|
6
|
+
print(p["title"], p["permalink"])
|
|
7
|
+
|
|
8
|
+
Docs: https://wikivectors.com/docs
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from .client import DEFAULT_BASE_URL, WikiVectors, WikiVectorsError
|
|
12
|
+
|
|
13
|
+
__version__ = "0.1.0"
|
|
14
|
+
__all__ = ["WikiVectors", "WikiVectorsError", "DEFAULT_BASE_URL", "__version__"]
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""A small client for the WikiVectors API. Standard library only."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.parse
|
|
7
|
+
import urllib.request
|
|
8
|
+
|
|
9
|
+
DEFAULT_BASE_URL = "https://wikivectors.com"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class WikiVectorsError(Exception):
|
|
13
|
+
"""The API said no. status is the HTTP code; code, message and request_id come from the error body."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, status, code, message, request_id=None):
|
|
16
|
+
self.status, self.code, self.message, self.request_id = status, code, message, request_id
|
|
17
|
+
text = f"{status} {code}: {message}"
|
|
18
|
+
if request_id:
|
|
19
|
+
text += f" (request {request_id})"
|
|
20
|
+
super().__init__(text)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class WikiVectors:
|
|
24
|
+
"""One client per key. Every method returns the API's JSON as plain dicts and lists.
|
|
25
|
+
|
|
26
|
+
api_key defaults to the WIKIVECTORS_KEY environment variable.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
def __init__(self, api_key=None, base_url=DEFAULT_BASE_URL, timeout=30):
|
|
30
|
+
self.api_key = api_key or os.environ.get("WIKIVECTORS_KEY", "")
|
|
31
|
+
if not self.api_key:
|
|
32
|
+
raise ValueError("Pass api_key or set WIKIVECTORS_KEY. Get a free key at https://wikivectors.com/account")
|
|
33
|
+
self.base_url = base_url.rstrip("/")
|
|
34
|
+
self.timeout = timeout
|
|
35
|
+
|
|
36
|
+
# --- endpoints -------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
def search(self, query, limit=None):
|
|
39
|
+
"""Best-matching paragraphs, best first (POST /v1/search). Returns the results list."""
|
|
40
|
+
return self._request("POST", "/v1/search", _drop_none({"query": query, "limit": limit}))["results"]
|
|
41
|
+
|
|
42
|
+
def answer(self, query, options=None):
|
|
43
|
+
"""A short answer that cites its paragraphs, or answered=False (POST /v1/answer)."""
|
|
44
|
+
return self._request("POST", "/v1/answer", _drop_none({"query": query, "options": options}))
|
|
45
|
+
|
|
46
|
+
def pages(self, titles):
|
|
47
|
+
"""Whole pages by title, one string or a list (POST /v1/pages). Returns the pages list."""
|
|
48
|
+
if isinstance(titles, str):
|
|
49
|
+
titles = [titles]
|
|
50
|
+
return self._request("POST", "/v1/pages", {"titles": list(titles)})["pages"]
|
|
51
|
+
|
|
52
|
+
def facts(self, title):
|
|
53
|
+
"""A page's infobox as structured facts (GET /v1/pages/{title}/facts)."""
|
|
54
|
+
return self._request("GET", "/v1/pages/" + urllib.parse.quote(title, safe="") + "/facts")
|
|
55
|
+
|
|
56
|
+
def identify(self, name, hint=None, kind=None):
|
|
57
|
+
"""Which page a name means, e.g. ("Michael Jordan", hint="professor") (POST /v1/identify)."""
|
|
58
|
+
return self._request("POST", "/v1/identify", _drop_none({"name": name, "hint": hint, "kind": kind}))
|
|
59
|
+
|
|
60
|
+
def titles(self, prefix=None, pattern=None, sort=None, limit=None, offset=None):
|
|
61
|
+
"""Page titles by their start or a pattern (GET /v1/titles)."""
|
|
62
|
+
return self._request("GET", "/v1/titles", params=_drop_none(
|
|
63
|
+
{"prefix": prefix, "pattern": pattern, "sort": sort, "limit": limit, "offset": offset}))
|
|
64
|
+
|
|
65
|
+
def changes(self, pages=None, prefix=None, pattern=None, since=None, after=None, limit=None):
|
|
66
|
+
"""Recent edits we have loaded (GET /v1/changes). Pass next_after back as after to page on."""
|
|
67
|
+
if pages is not None and not isinstance(pages, str):
|
|
68
|
+
pages = "|".join(pages)
|
|
69
|
+
return self._request("GET", "/v1/changes", params=_drop_none(
|
|
70
|
+
{"pages": pages, "prefix": prefix, "pattern": pattern, "since": since, "after": after, "limit": limit}))
|
|
71
|
+
|
|
72
|
+
def watch(self, callback_url, page=None, prefix=None, pattern=None):
|
|
73
|
+
"""Get a POST to callback_url when a page (or a family of pages) changes (POST /v1/watches)."""
|
|
74
|
+
return self._request("POST", "/v1/watches", _drop_none(
|
|
75
|
+
{"page": page, "prefix": prefix, "pattern": pattern, "callback_url": callback_url}))
|
|
76
|
+
|
|
77
|
+
def watches(self):
|
|
78
|
+
"""Your watches (GET /v1/watches)."""
|
|
79
|
+
return self._request("GET", "/v1/watches")
|
|
80
|
+
|
|
81
|
+
def unwatch(self, watch_id):
|
|
82
|
+
"""Stop a watch (DELETE /v1/watches/{id})."""
|
|
83
|
+
return self._request("DELETE", f"/v1/watches/{int(watch_id)}")
|
|
84
|
+
|
|
85
|
+
# --- plumbing --------------------------------------------------------
|
|
86
|
+
|
|
87
|
+
def _request(self, method, path, body=None, params=None):
|
|
88
|
+
from . import __version__
|
|
89
|
+
|
|
90
|
+
url = self.base_url + path
|
|
91
|
+
if params:
|
|
92
|
+
url += "?" + urllib.parse.urlencode(params)
|
|
93
|
+
data = None
|
|
94
|
+
headers = {
|
|
95
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
96
|
+
"Accept": "application/json",
|
|
97
|
+
"User-Agent": f"wikivectors-python/{__version__}",
|
|
98
|
+
}
|
|
99
|
+
if body is not None:
|
|
100
|
+
data = json.dumps(body).encode()
|
|
101
|
+
headers["Content-Type"] = "application/json"
|
|
102
|
+
req = urllib.request.Request(url, data=data, headers=headers, method=method)
|
|
103
|
+
try:
|
|
104
|
+
with urllib.request.urlopen(req, timeout=self.timeout) as r:
|
|
105
|
+
return json.loads(r.read() or b"null")
|
|
106
|
+
except urllib.error.HTTPError as e:
|
|
107
|
+
raw = e.read()
|
|
108
|
+
try:
|
|
109
|
+
err = json.loads(raw).get("error") or {}
|
|
110
|
+
except (ValueError, AttributeError):
|
|
111
|
+
err = {}
|
|
112
|
+
raise WikiVectorsError(
|
|
113
|
+
e.code, err.get("code", "http_error"),
|
|
114
|
+
err.get("message") or raw.decode("utf-8", "replace")[:200] or e.reason,
|
|
115
|
+
err.get("request_id"),
|
|
116
|
+
) from None
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _drop_none(d):
|
|
120
|
+
return {k: v for k, v in d.items() if v is not None}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""LangChain retriever. pip install "wikivectors[langchain]"
|
|
2
|
+
|
|
3
|
+
from wikivectors.langchain import WikiVectorsRetriever
|
|
4
|
+
docs = WikiVectorsRetriever(k=3).invoke("who won the 2026 FIFA World Cup")
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from typing import Any, List, Optional
|
|
8
|
+
|
|
9
|
+
from langchain_core.documents import Document
|
|
10
|
+
from langchain_core.retrievers import BaseRetriever
|
|
11
|
+
from pydantic import PrivateAttr
|
|
12
|
+
|
|
13
|
+
from .client import DEFAULT_BASE_URL, WikiVectors
|
|
14
|
+
|
|
15
|
+
META = ("title", "url", "permalink", "revision_id", "attribution", "score", "passage_id")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class WikiVectorsRetriever(BaseRetriever):
|
|
19
|
+
"""Fresh English Wikipedia paragraphs, each with its link and revision. Each call is one search."""
|
|
20
|
+
|
|
21
|
+
api_key: Optional[str] = None
|
|
22
|
+
k: int = 5
|
|
23
|
+
base_url: str = DEFAULT_BASE_URL
|
|
24
|
+
_client: Any = PrivateAttr(default=None)
|
|
25
|
+
|
|
26
|
+
def model_post_init(self, __context: Any) -> None:
|
|
27
|
+
self._client = WikiVectors(api_key=self.api_key, base_url=self.base_url)
|
|
28
|
+
|
|
29
|
+
def _get_relevant_documents(self, query: str, *, run_manager=None) -> List[Document]:
|
|
30
|
+
return [
|
|
31
|
+
Document(page_content=p["text"], metadata={k: p[k] for k in META if k in p})
|
|
32
|
+
for p in self._client.search(query, limit=self.k)
|
|
33
|
+
]
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""LlamaIndex retriever. pip install "wikivectors[llamaindex]"
|
|
2
|
+
|
|
3
|
+
from wikivectors.llamaindex import WikiVectorsRetriever
|
|
4
|
+
nodes = WikiVectorsRetriever(k=3).retrieve("who won the 2026 FIFA World Cup")
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from llama_index.core.retrievers import BaseRetriever
|
|
8
|
+
from llama_index.core.schema import NodeWithScore, TextNode
|
|
9
|
+
|
|
10
|
+
from .client import DEFAULT_BASE_URL, WikiVectors
|
|
11
|
+
|
|
12
|
+
META = ("title", "url", "permalink", "revision_id", "attribution")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class WikiVectorsRetriever(BaseRetriever):
|
|
16
|
+
"""Fresh English Wikipedia paragraphs, each with its link and revision. Each call is one search."""
|
|
17
|
+
|
|
18
|
+
def __init__(self, api_key=None, k=5, base_url=DEFAULT_BASE_URL, **kwargs):
|
|
19
|
+
self._wv = WikiVectors(api_key=api_key, base_url=base_url)
|
|
20
|
+
self.k = k
|
|
21
|
+
super().__init__(**kwargs)
|
|
22
|
+
|
|
23
|
+
def _retrieve(self, query_bundle):
|
|
24
|
+
return [
|
|
25
|
+
NodeWithScore(
|
|
26
|
+
score=p.get("score"),
|
|
27
|
+
node=TextNode(text=p["text"], id_=str(p.get("passage_id", "")) or None,
|
|
28
|
+
metadata={k: p[k] for k in META if k in p}),
|
|
29
|
+
)
|
|
30
|
+
for p in self._wv.search(query_bundle.query_str, limit=self.k)
|
|
31
|
+
]
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Tests for the WikiVectors Python client, against a fake API on localhost."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import threading
|
|
5
|
+
import unittest
|
|
6
|
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
7
|
+
from urllib.parse import parse_qs, urlparse
|
|
8
|
+
|
|
9
|
+
import wikivectors
|
|
10
|
+
from wikivectors import WikiVectors, WikiVectorsError
|
|
11
|
+
|
|
12
|
+
PASSAGE = {
|
|
13
|
+
"passage_id": 7,
|
|
14
|
+
"title": "2026 FIFA World Cup",
|
|
15
|
+
"text": "Spain won the final.",
|
|
16
|
+
"url": "https://en.wikipedia.org/wiki/2026_FIFA_World_Cup",
|
|
17
|
+
"permalink": "https://en.wikipedia.org/w/index.php?oldid=1",
|
|
18
|
+
"revision_id": 1,
|
|
19
|
+
"attribution": "Wikipedia, CC BY-SA 4.0",
|
|
20
|
+
"score": 0.9,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Fake(BaseHTTPRequestHandler):
|
|
25
|
+
calls = []
|
|
26
|
+
|
|
27
|
+
def log_message(self, *a):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
def _reply(self, status, body):
|
|
31
|
+
data = json.dumps(body).encode()
|
|
32
|
+
self.send_response(status)
|
|
33
|
+
self.send_header("Content-Type", "application/json")
|
|
34
|
+
self.send_header("Content-Length", str(len(data)))
|
|
35
|
+
self.end_headers()
|
|
36
|
+
self.wfile.write(data)
|
|
37
|
+
|
|
38
|
+
def _record(self, body=None):
|
|
39
|
+
u = urlparse(self.path)
|
|
40
|
+
Fake.calls.append({
|
|
41
|
+
"method": self.command,
|
|
42
|
+
"path": u.path,
|
|
43
|
+
"query": {k: v[0] for k, v in parse_qs(u.query).items()},
|
|
44
|
+
"auth": self.headers.get("Authorization"),
|
|
45
|
+
"ua": self.headers.get("User-Agent"),
|
|
46
|
+
"body": body,
|
|
47
|
+
})
|
|
48
|
+
return u.path
|
|
49
|
+
|
|
50
|
+
def do_GET(self):
|
|
51
|
+
path = self._record()
|
|
52
|
+
if path.endswith("/facts"):
|
|
53
|
+
self._reply(200, {"title": "Ada Lovelace", "status": "ok", "infobox": {"born": "1815"}})
|
|
54
|
+
elif path == "/v1/changes":
|
|
55
|
+
self._reply(200, {"changes": [], "next_after": 5})
|
|
56
|
+
elif path == "/v1/titles":
|
|
57
|
+
self._reply(200, {"titles": ["2025 in film"]})
|
|
58
|
+
elif path == "/v1/watches":
|
|
59
|
+
self._reply(200, {"watches": []})
|
|
60
|
+
else:
|
|
61
|
+
self._reply(404, {"error": {"code": "not_found", "message": "no", "request_id": "r1"}})
|
|
62
|
+
|
|
63
|
+
def do_DELETE(self):
|
|
64
|
+
self._record()
|
|
65
|
+
self._reply(200, {"deleted": True})
|
|
66
|
+
|
|
67
|
+
def do_POST(self):
|
|
68
|
+
n = int(self.headers.get("Content-Length", 0))
|
|
69
|
+
body = json.loads(self.rfile.read(n) or b"{}")
|
|
70
|
+
path = self._record(body)
|
|
71
|
+
if self.headers.get("Authorization") == "Bearer bad":
|
|
72
|
+
self._reply(401, {"error": {"code": "invalid_api_key", "message": "That key is not valid.", "request_id": "r2"}})
|
|
73
|
+
elif path == "/v1/search":
|
|
74
|
+
self._reply(200, {"results": [PASSAGE]})
|
|
75
|
+
elif path == "/v1/answer":
|
|
76
|
+
self._reply(200, {"answer": "Spain", "answered": True, "sources": [PASSAGE]})
|
|
77
|
+
elif path == "/v1/pages":
|
|
78
|
+
self._reply(200, {"pages": [{"title": t} for t in body["titles"]]})
|
|
79
|
+
elif path == "/v1/identify":
|
|
80
|
+
self._reply(200, {"match": {"title": "Michael I. Jordan"}, "sure": True})
|
|
81
|
+
elif path == "/v1/watches":
|
|
82
|
+
self._reply(200, {"id": 3})
|
|
83
|
+
else:
|
|
84
|
+
self._reply(500, "not json")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class ClientTest(unittest.TestCase):
|
|
88
|
+
@classmethod
|
|
89
|
+
def setUpClass(cls):
|
|
90
|
+
cls.srv = HTTPServer(("127.0.0.1", 0), Fake)
|
|
91
|
+
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
|
|
92
|
+
cls.base = f"http://127.0.0.1:{cls.srv.server_port}"
|
|
93
|
+
|
|
94
|
+
@classmethod
|
|
95
|
+
def tearDownClass(cls):
|
|
96
|
+
cls.srv.shutdown()
|
|
97
|
+
|
|
98
|
+
def setUp(self):
|
|
99
|
+
Fake.calls.clear()
|
|
100
|
+
self.wv = WikiVectors(api_key="wv_live_test", base_url=self.base)
|
|
101
|
+
|
|
102
|
+
def last(self):
|
|
103
|
+
return Fake.calls[-1]
|
|
104
|
+
|
|
105
|
+
def test_search_sends_key_query_and_limit(self):
|
|
106
|
+
out = self.wv.search("who won the 2026 World Cup", limit=3)
|
|
107
|
+
self.assertEqual(out[0]["title"], "2026 FIFA World Cup")
|
|
108
|
+
c = self.last()
|
|
109
|
+
self.assertEqual(c["path"], "/v1/search")
|
|
110
|
+
self.assertEqual(c["auth"], "Bearer wv_live_test")
|
|
111
|
+
self.assertEqual(c["body"], {"query": "who won the 2026 World Cup", "limit": 3})
|
|
112
|
+
self.assertIn("wikivectors-python/", c["ua"])
|
|
113
|
+
|
|
114
|
+
def test_search_without_limit_leaves_it_out(self):
|
|
115
|
+
self.wv.search("x")
|
|
116
|
+
self.assertEqual(self.last()["body"], {"query": "x"})
|
|
117
|
+
|
|
118
|
+
def test_answer_with_and_without_options(self):
|
|
119
|
+
self.assertEqual(self.wv.answer("who won")["answer"], "Spain")
|
|
120
|
+
self.assertEqual(self.last()["body"], {"query": "who won"})
|
|
121
|
+
self.wv.answer("who won", options=["Spain", "Argentina"])
|
|
122
|
+
self.assertEqual(self.last()["body"], {"query": "who won", "options": ["Spain", "Argentina"]})
|
|
123
|
+
|
|
124
|
+
def test_pages_accepts_one_title_or_many(self):
|
|
125
|
+
self.assertEqual(self.wv.pages("Ada Lovelace"), [{"title": "Ada Lovelace"}])
|
|
126
|
+
self.assertEqual(self.last()["body"], {"titles": ["Ada Lovelace"]})
|
|
127
|
+
self.wv.pages(["A", "B"])
|
|
128
|
+
self.assertEqual(self.last()["body"], {"titles": ["A", "B"]})
|
|
129
|
+
|
|
130
|
+
def test_facts_quotes_the_title_in_the_path(self):
|
|
131
|
+
self.assertEqual(self.wv.facts("AC/DC (band)")["infobox"], {"born": "1815"})
|
|
132
|
+
self.assertEqual(self.last()["path"], "/v1/pages/AC%2FDC%20%28band%29/facts")
|
|
133
|
+
|
|
134
|
+
def test_identify_sends_hint_only_when_given(self):
|
|
135
|
+
self.wv.identify("Michael Jordan", hint="professor, machine learning")
|
|
136
|
+
self.assertEqual(self.last()["body"], {"name": "Michael Jordan", "hint": "professor, machine learning"})
|
|
137
|
+
self.wv.identify("Michael Jordan")
|
|
138
|
+
self.assertEqual(self.last()["body"], {"name": "Michael Jordan"})
|
|
139
|
+
|
|
140
|
+
def test_titles_and_changes_use_query_strings(self):
|
|
141
|
+
self.wv.titles(prefix="2025 in ", limit=10)
|
|
142
|
+
self.assertEqual(self.last()["query"], {"prefix": "2025 in ", "limit": "10"})
|
|
143
|
+
self.assertEqual(self.wv.changes(pages=["A", "B"], after=4)["next_after"], 5)
|
|
144
|
+
self.assertEqual(self.last()["query"], {"pages": "A|B", "after": "4"})
|
|
145
|
+
|
|
146
|
+
def test_watches(self):
|
|
147
|
+
self.assertEqual(self.wv.watch(page="Ada Lovelace", callback_url="https://x.test/h")["id"], 3)
|
|
148
|
+
self.assertEqual(self.last()["body"], {"page": "Ada Lovelace", "callback_url": "https://x.test/h"})
|
|
149
|
+
self.wv.watches()
|
|
150
|
+
self.assertEqual(self.last()["method"], "GET")
|
|
151
|
+
self.wv.unwatch(3)
|
|
152
|
+
self.assertEqual((self.last()["method"], self.last()["path"]), ("DELETE", "/v1/watches/3"))
|
|
153
|
+
|
|
154
|
+
def test_api_error_carries_code_message_and_request_id(self):
|
|
155
|
+
wv = WikiVectors(api_key="bad", base_url=self.base)
|
|
156
|
+
with self.assertRaises(WikiVectorsError) as e:
|
|
157
|
+
wv.search("x")
|
|
158
|
+
self.assertEqual((e.exception.status, e.exception.code, e.exception.request_id), (401, "invalid_api_key", "r2"))
|
|
159
|
+
self.assertIn("That key is not valid.", str(e.exception))
|
|
160
|
+
|
|
161
|
+
def test_non_json_error_still_raises(self):
|
|
162
|
+
with self.assertRaises(WikiVectorsError) as e:
|
|
163
|
+
self.wv._request("POST", "/v1/nothing", {})
|
|
164
|
+
self.assertEqual(e.exception.status, 500)
|
|
165
|
+
|
|
166
|
+
def test_key_from_env_and_missing_key(self):
|
|
167
|
+
import os
|
|
168
|
+
old = os.environ.pop("WIKIVECTORS_KEY", None)
|
|
169
|
+
try:
|
|
170
|
+
with self.assertRaises(ValueError):
|
|
171
|
+
WikiVectors()
|
|
172
|
+
os.environ["WIKIVECTORS_KEY"] = "wv_live_env"
|
|
173
|
+
WikiVectors(base_url=self.base).search("x")
|
|
174
|
+
self.assertEqual(self.last()["auth"], "Bearer wv_live_env")
|
|
175
|
+
finally:
|
|
176
|
+
os.environ.pop("WIKIVECTORS_KEY", None)
|
|
177
|
+
if old is not None:
|
|
178
|
+
os.environ["WIKIVECTORS_KEY"] = old
|
|
179
|
+
|
|
180
|
+
def test_version_is_set(self):
|
|
181
|
+
self.assertRegex(wikivectors.__version__, r"^\d+\.\d+\.\d+$")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
if __name__ == "__main__":
|
|
185
|
+
unittest.main()
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"""LangChain and LlamaIndex retrievers, against the same fake API. Skipped when the framework isn't installed."""
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
import unittest
|
|
5
|
+
from http.server import HTTPServer
|
|
6
|
+
|
|
7
|
+
from test_client import PASSAGE, Fake
|
|
8
|
+
|
|
9
|
+
try:
|
|
10
|
+
import langchain_core # noqa: F401
|
|
11
|
+
HAVE_LC = True
|
|
12
|
+
except ImportError:
|
|
13
|
+
HAVE_LC = False
|
|
14
|
+
try:
|
|
15
|
+
import llama_index.core # noqa: F401
|
|
16
|
+
HAVE_LI = True
|
|
17
|
+
except ImportError:
|
|
18
|
+
HAVE_LI = False
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class RetrieverTest(unittest.TestCase):
|
|
22
|
+
@classmethod
|
|
23
|
+
def setUpClass(cls):
|
|
24
|
+
cls.srv = HTTPServer(("127.0.0.1", 0), Fake)
|
|
25
|
+
threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
|
|
26
|
+
cls.base = f"http://127.0.0.1:{cls.srv.server_port}"
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def tearDownClass(cls):
|
|
30
|
+
cls.srv.shutdown()
|
|
31
|
+
|
|
32
|
+
def setUp(self):
|
|
33
|
+
Fake.calls.clear()
|
|
34
|
+
|
|
35
|
+
@unittest.skipUnless(HAVE_LC, "langchain-core not installed")
|
|
36
|
+
def test_langchain(self):
|
|
37
|
+
from wikivectors.langchain import WikiVectorsRetriever
|
|
38
|
+
r = WikiVectorsRetriever(api_key="wv_live_test", k=2, base_url=self.base)
|
|
39
|
+
docs = r.invoke("who won")
|
|
40
|
+
self.assertEqual(docs[0].page_content, PASSAGE["text"])
|
|
41
|
+
self.assertEqual(docs[0].metadata["permalink"], PASSAGE["permalink"])
|
|
42
|
+
self.assertEqual(docs[0].metadata["revision_id"], 1)
|
|
43
|
+
self.assertEqual(Fake.calls[-1]["body"], {"query": "who won", "limit": 2})
|
|
44
|
+
|
|
45
|
+
@unittest.skipUnless(HAVE_LI, "llama-index-core not installed")
|
|
46
|
+
def test_llamaindex(self):
|
|
47
|
+
from wikivectors.llamaindex import WikiVectorsRetriever
|
|
48
|
+
r = WikiVectorsRetriever(api_key="wv_live_test", k=2, base_url=self.base)
|
|
49
|
+
nodes = r.retrieve("who won")
|
|
50
|
+
self.assertEqual(nodes[0].node.text, PASSAGE["text"])
|
|
51
|
+
self.assertEqual(nodes[0].score, 0.9)
|
|
52
|
+
self.assertEqual(nodes[0].node.metadata["url"], PASSAGE["url"])
|
|
53
|
+
self.assertEqual(Fake.calls[-1]["body"], {"query": "who won", "limit": 2})
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
if __name__ == "__main__":
|
|
57
|
+
unittest.main()
|