wikivectors 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.
- wikivectors/__init__.py +14 -0
- wikivectors/client.py +120 -0
- wikivectors/langchain.py +33 -0
- wikivectors/llamaindex.py +31 -0
- wikivectors-0.1.0.dist-info/METADATA +86 -0
- wikivectors-0.1.0.dist-info/RECORD +8 -0
- wikivectors-0.1.0.dist-info/WHEEL +4 -0
- wikivectors-0.1.0.dist-info/licenses/LICENSE +21 -0
wikivectors/__init__.py
ADDED
|
@@ -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__"]
|
wikivectors/client.py
ADDED
|
@@ -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}
|
wikivectors/langchain.py
ADDED
|
@@ -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,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,8 @@
|
|
|
1
|
+
wikivectors/__init__.py,sha256=Ytty6WMGE50zed-TR9twjgnUHyI0-aK8XmOiP4bPdwE,465
|
|
2
|
+
wikivectors/client.py,sha256=IO8ihTuLAZgGW7CTSQv6Hgh-L5pk546ePxB7600I5-U,5350
|
|
3
|
+
wikivectors/langchain.py,sha256=TrdUnq2p4IwQ3idbA5QGmmGEDgQ2JaTx2JGVtL6bBkM,1205
|
|
4
|
+
wikivectors/llamaindex.py,sha256=DYY4N_r2XK2ayfLtFjz9CbUsilGD9awicq6jgyWZ7lQ,1179
|
|
5
|
+
wikivectors-0.1.0.dist-info/METADATA,sha256=FAYDG7nmIz-zrKmN2cZQX9MLTKD6X9RMnn3kL_kl5oY,2853
|
|
6
|
+
wikivectors-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
7
|
+
wikivectors-0.1.0.dist-info/licenses/LICENSE,sha256=mcTEiWojja5z-ehuJKetmH_t5FXaPGGP5xJVKx1Lm54,1068
|
|
8
|
+
wikivectors-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|