axveritas 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.
- axveritas-0.1.0/.gitignore +3 -0
- axveritas-0.1.0/LICENSE +21 -0
- axveritas-0.1.0/PKG-INFO +135 -0
- axveritas-0.1.0/README.md +109 -0
- axveritas-0.1.0/pyproject.toml +36 -0
- axveritas-0.1.0/src/axveritas/__init__.py +76 -0
- axveritas-0.1.0/src/axveritas/client.py +207 -0
- axveritas-0.1.0/src/axveritas/crewai.py +58 -0
- axveritas-0.1.0/src/axveritas/errors.py +58 -0
- axveritas-0.1.0/src/axveritas/langchain.py +105 -0
- axveritas-0.1.0/src/axveritas/protect.py +190 -0
axveritas-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 axveritasprotocol
|
|
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.
|
axveritas-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: axveritas
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Know if a website will block your AI agent before it fetches, and get clean pages ~90% smaller. Python client, one-line retrofit, LangChain and CrewAI tools.
|
|
5
|
+
Project-URL: Homepage, https://axveritas.com
|
|
6
|
+
Project-URL: Documentation, https://axveritas.com/docs
|
|
7
|
+
Project-URL: Source, https://github.com/axveritasprotocol/axveritas
|
|
8
|
+
Project-URL: Issues, https://github.com/axveritasprotocol/axveritas/issues
|
|
9
|
+
Author-email: Axveritas <support@axveritas.com>
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ai-agents,crewai,langchain,llm,mcp,preflight,rag,web-scraping,x402
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Requires-Python: >=3.9
|
|
20
|
+
Requires-Dist: httpx>=0.24
|
|
21
|
+
Provides-Extra: crewai
|
|
22
|
+
Requires-Dist: crewai>=0.80; extra == 'crewai'
|
|
23
|
+
Provides-Extra: langchain
|
|
24
|
+
Requires-Dist: langchain-core>=0.2; extra == 'langchain'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# axveritas
|
|
28
|
+
|
|
29
|
+
**Stop paying your AI agent to read junk.** 1 in 4 popular websites block bots (44% of retail, travel and finance sites in our test), and most of the rest send pages that are mostly code. Axveritas tells your agent which pages are dead ends *before* it fetches them, and hands it clean pages about 90% smaller.
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
pip install axveritas
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Quick start
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import axveritas
|
|
39
|
+
|
|
40
|
+
axveritas.get_trial_key("you@company.com") # free: 100 checks + 10 clean pages, no card (also emailed to you)
|
|
41
|
+
|
|
42
|
+
v = axveritas.check("https://www.icloud.com")
|
|
43
|
+
print(v.verdict, v.category, v.reason) # DEAD_END js_shell JavaScript-only page: no readable content...
|
|
44
|
+
|
|
45
|
+
page = axveritas.scrape("https://en.wikipedia.org/wiki/Web_scraping")
|
|
46
|
+
print(page.reduction_pct, page.text[:200]) # 93.0 Web scraping, web harvesting, ...
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
Already have a key? Set `AXVERITAS_API_KEY` in your environment and skip `get_trial_key`.
|
|
50
|
+
|
|
51
|
+
## Already have agents running? Retrofit them in one line
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
import axveritas
|
|
55
|
+
axveritas.protect()
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
That's it. Every `GET` your agent makes with **requests** or **httpx** is checked first:
|
|
59
|
+
|
|
60
|
+
- **Dead ends** (bot walls, timeouts, JavaScript-only pages, CAPTCHA walls served as "200 OK", soft 404s) raise `axveritas.DeadEndError` **before anything is downloaded**, so your agent's normal error handling skips them.
|
|
61
|
+
- **Verdicts are cached per site for 6 hours**, so crawling 500 pages of one site costs one check, not 500.
|
|
62
|
+
- **It never breaks your agent.** If Axveritas can't answer (no key, out of credits, network trouble), the request goes ahead exactly as before.
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
axveritas.protect(
|
|
66
|
+
mode="warn", # log dead ends instead of raising
|
|
67
|
+
skip_domains=["api.mycompany.com"], # never check your own services
|
|
68
|
+
on_dead_end=lambda v: metrics.incr("dead_end", tags=[v.category]),
|
|
69
|
+
)
|
|
70
|
+
axveritas.unprotect() # back to normal
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Building agents for clients? Add the line to each client's agent and give each client its own key, so usage shows up per client. Ask about agency pricing: support@axveritas.com.
|
|
74
|
+
|
|
75
|
+
## LangChain
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
pip install "axveritas[langchain]"
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
**Drop-in loader** (swap it in for `WebBaseLoader`):
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from axveritas.langchain import AxveritasLoader
|
|
85
|
+
|
|
86
|
+
loader = AxveritasLoader(urls) # checks each URL, skips dead ends, returns clean pages
|
|
87
|
+
docs = loader.load()
|
|
88
|
+
print(loader.skipped) # [(url, "blocked: HTTP 403 ..."), ...]
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
**Tools for agents:**
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from axveritas.langchain import get_tools
|
|
95
|
+
tools = get_tools() # axveritas_preflight_check + axveritas_scrape
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## CrewAI
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
pip install "axveritas[crewai]"
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
from axveritas.crewai import get_tools
|
|
106
|
+
researcher = Agent(role="Researcher", goal="...", backstory="...", tools=get_tools())
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
## MCP (Claude, Cursor and other AI apps)
|
|
110
|
+
|
|
111
|
+
No package needed: add `https://axveritas.com/mcp` as a remote MCP server. 10 free checks a day without a key.
|
|
112
|
+
|
|
113
|
+
## The client
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
from axveritas import Axveritas
|
|
117
|
+
|
|
118
|
+
with Axveritas(api_key="axv_...") as ax:
|
|
119
|
+
v = ax.check(url) # Verdict: .passable, .dead_end, .category, .reason
|
|
120
|
+
page = ax.fetch_if_passable(url) # clean Page, or None if it's a dead end (no scrape credit used)
|
|
121
|
+
print(ax.usage()) # credits left, dead ends avoided, tokens saved
|
|
122
|
+
ax.report_problem("Said DEAD_END but loads fine", url=url) # free; wrong verdicts get fixed
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Errors all inherit from `axveritas.AxveritasError`: `MissingKey`, `InvalidKey`, `OutOfCredits` (message includes upgrade links), `PaymentRequired`, `RateLimited`, `ScrapeFailed`, `BadRequest`, `DeadEndError`.
|
|
126
|
+
|
|
127
|
+
## Pricing
|
|
128
|
+
|
|
129
|
+
Free trial: 100 checks + 10 clean pages. Plans from $19/month (from $0.001 per check), 30-day money-back. Autonomous agents can also pay per call in USDC on Base (x402), no account needed. Details: https://axveritas.com/#pricing
|
|
130
|
+
|
|
131
|
+
## How it works and how accurate it is
|
|
132
|
+
|
|
133
|
+
From a test of 1,000 popular sites and 108 retail, travel and finance sites, with the full method and code: [BENCHMARK_RESULTS.md](https://github.com/axveritasprotocol/axveritas/blob/main/BENCHMARK_RESULTS.md). Axveritas only tells your agent where it's blocked; it doesn't get around blocks. Found a wrong verdict? `axveritas.report_problem(...)` or https://axveritas.com/report.
|
|
134
|
+
|
|
135
|
+
MIT licensed.
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# axveritas
|
|
2
|
+
|
|
3
|
+
**Stop paying your AI agent to read junk.** 1 in 4 popular websites block bots (44% of retail, travel and finance sites in our test), and most of the rest send pages that are mostly code. Axveritas tells your agent which pages are dead ends *before* it fetches them, and hands it clean pages about 90% smaller.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
pip install axveritas
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
import axveritas
|
|
13
|
+
|
|
14
|
+
axveritas.get_trial_key("you@company.com") # free: 100 checks + 10 clean pages, no card (also emailed to you)
|
|
15
|
+
|
|
16
|
+
v = axveritas.check("https://www.icloud.com")
|
|
17
|
+
print(v.verdict, v.category, v.reason) # DEAD_END js_shell JavaScript-only page: no readable content...
|
|
18
|
+
|
|
19
|
+
page = axveritas.scrape("https://en.wikipedia.org/wiki/Web_scraping")
|
|
20
|
+
print(page.reduction_pct, page.text[:200]) # 93.0 Web scraping, web harvesting, ...
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Already have a key? Set `AXVERITAS_API_KEY` in your environment and skip `get_trial_key`.
|
|
24
|
+
|
|
25
|
+
## Already have agents running? Retrofit them in one line
|
|
26
|
+
|
|
27
|
+
```python
|
|
28
|
+
import axveritas
|
|
29
|
+
axveritas.protect()
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
That's it. Every `GET` your agent makes with **requests** or **httpx** is checked first:
|
|
33
|
+
|
|
34
|
+
- **Dead ends** (bot walls, timeouts, JavaScript-only pages, CAPTCHA walls served as "200 OK", soft 404s) raise `axveritas.DeadEndError` **before anything is downloaded**, so your agent's normal error handling skips them.
|
|
35
|
+
- **Verdicts are cached per site for 6 hours**, so crawling 500 pages of one site costs one check, not 500.
|
|
36
|
+
- **It never breaks your agent.** If Axveritas can't answer (no key, out of credits, network trouble), the request goes ahead exactly as before.
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
axveritas.protect(
|
|
40
|
+
mode="warn", # log dead ends instead of raising
|
|
41
|
+
skip_domains=["api.mycompany.com"], # never check your own services
|
|
42
|
+
on_dead_end=lambda v: metrics.incr("dead_end", tags=[v.category]),
|
|
43
|
+
)
|
|
44
|
+
axveritas.unprotect() # back to normal
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Building agents for clients? Add the line to each client's agent and give each client its own key, so usage shows up per client. Ask about agency pricing: support@axveritas.com.
|
|
48
|
+
|
|
49
|
+
## LangChain
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
pip install "axveritas[langchain]"
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
**Drop-in loader** (swap it in for `WebBaseLoader`):
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from axveritas.langchain import AxveritasLoader
|
|
59
|
+
|
|
60
|
+
loader = AxveritasLoader(urls) # checks each URL, skips dead ends, returns clean pages
|
|
61
|
+
docs = loader.load()
|
|
62
|
+
print(loader.skipped) # [(url, "blocked: HTTP 403 ..."), ...]
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
**Tools for agents:**
|
|
66
|
+
|
|
67
|
+
```python
|
|
68
|
+
from axveritas.langchain import get_tools
|
|
69
|
+
tools = get_tools() # axveritas_preflight_check + axveritas_scrape
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## CrewAI
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
pip install "axveritas[crewai]"
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
from axveritas.crewai import get_tools
|
|
80
|
+
researcher = Agent(role="Researcher", goal="...", backstory="...", tools=get_tools())
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## MCP (Claude, Cursor and other AI apps)
|
|
84
|
+
|
|
85
|
+
No package needed: add `https://axveritas.com/mcp` as a remote MCP server. 10 free checks a day without a key.
|
|
86
|
+
|
|
87
|
+
## The client
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
from axveritas import Axveritas
|
|
91
|
+
|
|
92
|
+
with Axveritas(api_key="axv_...") as ax:
|
|
93
|
+
v = ax.check(url) # Verdict: .passable, .dead_end, .category, .reason
|
|
94
|
+
page = ax.fetch_if_passable(url) # clean Page, or None if it's a dead end (no scrape credit used)
|
|
95
|
+
print(ax.usage()) # credits left, dead ends avoided, tokens saved
|
|
96
|
+
ax.report_problem("Said DEAD_END but loads fine", url=url) # free; wrong verdicts get fixed
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Errors all inherit from `axveritas.AxveritasError`: `MissingKey`, `InvalidKey`, `OutOfCredits` (message includes upgrade links), `PaymentRequired`, `RateLimited`, `ScrapeFailed`, `BadRequest`, `DeadEndError`.
|
|
100
|
+
|
|
101
|
+
## Pricing
|
|
102
|
+
|
|
103
|
+
Free trial: 100 checks + 10 clean pages. Plans from $19/month (from $0.001 per check), 30-day money-back. Autonomous agents can also pay per call in USDC on Base (x402), no account needed. Details: https://axveritas.com/#pricing
|
|
104
|
+
|
|
105
|
+
## How it works and how accurate it is
|
|
106
|
+
|
|
107
|
+
From a test of 1,000 popular sites and 108 retail, travel and finance sites, with the full method and code: [BENCHMARK_RESULTS.md](https://github.com/axveritasprotocol/axveritas/blob/main/BENCHMARK_RESULTS.md). Axveritas only tells your agent where it's blocked; it doesn't get around blocks. Found a wrong verdict? `axveritas.report_problem(...)` or https://axveritas.com/report.
|
|
108
|
+
|
|
109
|
+
MIT licensed.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.21"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "axveritas"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Know if a website will block your AI agent before it fetches, and get clean pages ~90% smaller. Python client, one-line retrofit, LangChain and CrewAI tools."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{ name = "Axveritas", email = "support@axveritas.com" }]
|
|
14
|
+
keywords = ["ai-agents", "llm", "web-scraping", "langchain", "crewai", "mcp", "x402", "preflight", "rag"]
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Intended Audience :: Developers",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
20
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
21
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
22
|
+
]
|
|
23
|
+
dependencies = ["httpx>=0.24"]
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
langchain = ["langchain-core>=0.2"]
|
|
27
|
+
crewai = ["crewai>=0.80"]
|
|
28
|
+
|
|
29
|
+
[project.urls]
|
|
30
|
+
Homepage = "https://axveritas.com"
|
|
31
|
+
Documentation = "https://axveritas.com/docs"
|
|
32
|
+
Source = "https://github.com/axveritasprotocol/axveritas"
|
|
33
|
+
Issues = "https://github.com/axveritasprotocol/axveritas/issues"
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.wheel]
|
|
36
|
+
packages = ["src/axveritas"]
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Axveritas: know if a website will block your AI agent before it fetches, and get clean pages ~90% smaller.
|
|
2
|
+
|
|
3
|
+
Quick start:
|
|
4
|
+
import axveritas
|
|
5
|
+
axveritas.get_trial_key("you@company.com") # free: 100 checks + 10 scrapes, no card
|
|
6
|
+
axveritas.check("https://example.com") # Verdict(verdict='PASSABLE', ...)
|
|
7
|
+
axveritas.scrape("https://example.com").text # clean page text
|
|
8
|
+
|
|
9
|
+
Retrofit existing agents in one line:
|
|
10
|
+
axveritas.protect()
|
|
11
|
+
|
|
12
|
+
Docs: https://axveritas.com/docs
|
|
13
|
+
"""
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from typing import Any, Dict, Optional, Sequence
|
|
17
|
+
|
|
18
|
+
from .client import Axveritas, Page, Verdict
|
|
19
|
+
from .errors import (
|
|
20
|
+
AxveritasError,
|
|
21
|
+
BadRequest,
|
|
22
|
+
DeadEndError,
|
|
23
|
+
InvalidKey,
|
|
24
|
+
MissingKey,
|
|
25
|
+
OutOfCredits,
|
|
26
|
+
PaymentRequired,
|
|
27
|
+
RateLimited,
|
|
28
|
+
ScrapeFailed,
|
|
29
|
+
)
|
|
30
|
+
from .protect import protect, unprotect
|
|
31
|
+
|
|
32
|
+
__version__ = "0.1.0"
|
|
33
|
+
__all__ = [
|
|
34
|
+
"Axveritas", "Verdict", "Page", "check", "scrape", "fetch_if_passable", "usage", "get_trial_key",
|
|
35
|
+
"report_problem", "protect", "unprotect", "AxveritasError", "MissingKey", "InvalidKey", "PaymentRequired",
|
|
36
|
+
"OutOfCredits", "RateLimited", "ScrapeFailed", "BadRequest", "DeadEndError",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
_default: Optional[Axveritas] = None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _client() -> Axveritas:
|
|
43
|
+
global _default
|
|
44
|
+
if _default is None:
|
|
45
|
+
_default = Axveritas()
|
|
46
|
+
return _default
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def check(url: str, force_live: bool = False) -> Verdict:
|
|
50
|
+
"""Pre-flight check: PASSABLE or DEAD_END with the reason."""
|
|
51
|
+
return _client().check(url, force_live=force_live)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def scrape(url: str, required_keys: Sequence[str] = ("title", "text")) -> Page:
|
|
55
|
+
"""The page as clean, verified data."""
|
|
56
|
+
return _client().scrape(url, required_keys)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def fetch_if_passable(url: str, required_keys: Sequence[str] = ("title", "text")) -> Optional[Page]:
|
|
60
|
+
"""Check first; return the clean page only if it's worth reading, else None."""
|
|
61
|
+
return _client().fetch_if_passable(url, required_keys)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def usage() -> Dict[str, Any]:
|
|
65
|
+
"""Credits left and savings for your key."""
|
|
66
|
+
return _client().usage()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def get_trial_key(email: str) -> str:
|
|
70
|
+
"""Free trial key by email (also emailed to you). The module starts using it right away."""
|
|
71
|
+
return _client().get_trial_key(email, use_it=True)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def report_problem(message: str, url: Optional[str] = None, kind: str = "wrong_verdict", **kw: Any) -> str:
|
|
75
|
+
"""Report a wrong verdict, bug or idea (free)."""
|
|
76
|
+
return _client().report_problem(message, url=url, kind=kind, **kw)
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
"""Core Axveritas client: pre-flight checks, clean verified pages, usage, free trial keys, problem reports."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any, Dict, List, Optional, Sequence
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from .errors import (
|
|
12
|
+
AxveritasError,
|
|
13
|
+
BadRequest,
|
|
14
|
+
InvalidKey,
|
|
15
|
+
MissingKey,
|
|
16
|
+
OutOfCredits,
|
|
17
|
+
PaymentRequired,
|
|
18
|
+
RateLimited,
|
|
19
|
+
ScrapeFailed,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
DEFAULT_BASE_URL = "https://axveritas.com"
|
|
23
|
+
USER_AGENT = "axveritas-python/0.1.0"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass
|
|
27
|
+
class Verdict:
|
|
28
|
+
"""Result of a pre-flight check: should your agent fetch this URL at all?"""
|
|
29
|
+
|
|
30
|
+
url: str
|
|
31
|
+
verdict: str # "PASSABLE" or "DEAD_END"
|
|
32
|
+
category: str # ok, blocked, timeout, js_shell, soft_block, soft_404, ...
|
|
33
|
+
reason: str
|
|
34
|
+
http_status: int
|
|
35
|
+
needs_javascript: bool = False
|
|
36
|
+
from_shared_cache: bool = False
|
|
37
|
+
credits_remaining: Optional[int] = None
|
|
38
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False)
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def passable(self) -> bool:
|
|
42
|
+
return self.verdict == "PASSABLE"
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def dead_end(self) -> bool:
|
|
46
|
+
return self.verdict == "DEAD_END"
|
|
47
|
+
|
|
48
|
+
def __bool__(self) -> bool: # `if axveritas.check(url):` reads naturally
|
|
49
|
+
return self.passable
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Page:
|
|
54
|
+
"""A page cleaned for an LLM: title, description, headings, links and visible text."""
|
|
55
|
+
|
|
56
|
+
url: str
|
|
57
|
+
title: str
|
|
58
|
+
description: str
|
|
59
|
+
headings: List[str]
|
|
60
|
+
links: List[str]
|
|
61
|
+
text: str
|
|
62
|
+
raw_chars: int = 0
|
|
63
|
+
returned_chars: int = 0
|
|
64
|
+
reduction_pct: float = 0.0
|
|
65
|
+
credits_remaining: Optional[int] = None
|
|
66
|
+
raw: Dict[str, Any] = field(default_factory=dict, repr=False)
|
|
67
|
+
|
|
68
|
+
def to_text(self) -> str:
|
|
69
|
+
"""Title, description, headings and text joined into one string, ready for a prompt."""
|
|
70
|
+
parts = [self.title, self.description, " | ".join(self.headings), self.text]
|
|
71
|
+
return "\n".join(p for p in parts if p)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class Axveritas:
|
|
75
|
+
"""Client for the Axveritas API.
|
|
76
|
+
|
|
77
|
+
>>> from axveritas import Axveritas
|
|
78
|
+
>>> ax = Axveritas() # reads AXVERITAS_API_KEY from the environment
|
|
79
|
+
>>> ax.check("https://example.com").verdict
|
|
80
|
+
'PASSABLE'
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(
|
|
84
|
+
self,
|
|
85
|
+
api_key: Optional[str] = None,
|
|
86
|
+
base_url: Optional[str] = None,
|
|
87
|
+
timeout: float = 30.0,
|
|
88
|
+
agent_id: Optional[str] = None,
|
|
89
|
+
http_client: Optional[httpx.Client] = None,
|
|
90
|
+
max_retry_wait: float = 15.0,
|
|
91
|
+
) -> None:
|
|
92
|
+
self.max_retry_wait = max_retry_wait # wait out short rate limits once instead of failing
|
|
93
|
+
self.api_key = (api_key or os.environ.get("AXVERITAS_API_KEY") or "").strip() or None
|
|
94
|
+
self.base_url = (base_url or os.environ.get("AXVERITAS_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
|
|
95
|
+
self.agent_id = agent_id or os.environ.get("AXVERITAS_AGENT_ID") or "axveritas-python"
|
|
96
|
+
self._http = http_client or httpx.Client(timeout=timeout, headers={"User-Agent": USER_AGENT})
|
|
97
|
+
|
|
98
|
+
# ── helpers ──────────────────────────────────────────────────────────────
|
|
99
|
+
def _headers(self, need_key: bool) -> Dict[str, str]:
|
|
100
|
+
if self.api_key:
|
|
101
|
+
return {"X-API-Key": self.api_key}
|
|
102
|
+
if need_key:
|
|
103
|
+
raise MissingKey()
|
|
104
|
+
return {}
|
|
105
|
+
|
|
106
|
+
def _send(self, method: str, path: str, need_key: bool, payload: Optional[Dict[str, Any]] = None) -> httpx.Response:
|
|
107
|
+
headers = self._headers(need_key)
|
|
108
|
+
resp = self._http.request(method, self.base_url + path, json=payload, headers=headers)
|
|
109
|
+
retry = resp.headers.get("Retry-After", "")
|
|
110
|
+
if resp.status_code == 429 and retry.isdigit() and 0 < int(retry) <= self.max_retry_wait:
|
|
111
|
+
time.sleep(int(retry))
|
|
112
|
+
resp = self._http.request(method, self.base_url + path, json=payload, headers=headers)
|
|
113
|
+
return resp
|
|
114
|
+
|
|
115
|
+
def _post(self, path: str, payload: Dict[str, Any], need_key: bool = True) -> Dict[str, Any]:
|
|
116
|
+
return self._handle(self._send("POST", path, need_key, payload), path)
|
|
117
|
+
|
|
118
|
+
def _get(self, path: str, need_key: bool = True) -> Dict[str, Any]:
|
|
119
|
+
return self._handle(self._send("GET", path, need_key), path)
|
|
120
|
+
|
|
121
|
+
@staticmethod
|
|
122
|
+
def _detail(resp: httpx.Response) -> Any:
|
|
123
|
+
try:
|
|
124
|
+
body = resp.json()
|
|
125
|
+
except ValueError:
|
|
126
|
+
return resp.text[:300]
|
|
127
|
+
return body.get("detail", body) if isinstance(body, dict) else body
|
|
128
|
+
|
|
129
|
+
def _handle(self, resp: httpx.Response, path: str) -> Dict[str, Any]:
|
|
130
|
+
if resp.status_code < 400:
|
|
131
|
+
return resp.json()
|
|
132
|
+
detail = self._detail(resp)
|
|
133
|
+
text = detail if isinstance(detail, str) else str(detail)
|
|
134
|
+
if resp.status_code == 401:
|
|
135
|
+
raise InvalidKey(text, status=401)
|
|
136
|
+
if resp.status_code == 402:
|
|
137
|
+
if isinstance(detail, str) and "credits" in detail.lower():
|
|
138
|
+
raise OutOfCredits(text, status=402)
|
|
139
|
+
raise PaymentRequired(
|
|
140
|
+
"This call needs an Axveritas key (free trial: axveritas.get_trial_key('you@company.com')) "
|
|
141
|
+
"or an x402 USDC payment.", status=402, payment=detail if isinstance(detail, dict) else None)
|
|
142
|
+
if resp.status_code == 429:
|
|
143
|
+
retry = resp.headers.get("Retry-After")
|
|
144
|
+
raise RateLimited(text, status=429, retry_after=int(retry) if retry and retry.isdigit() else None)
|
|
145
|
+
if resp.status_code == 422 and path == "/v1/scrape":
|
|
146
|
+
raise ScrapeFailed(text, status=422)
|
|
147
|
+
if resp.status_code in (400, 403, 413, 422):
|
|
148
|
+
raise BadRequest(text, status=resp.status_code)
|
|
149
|
+
raise AxveritasError(f"HTTP {resp.status_code}: {text}", status=resp.status_code)
|
|
150
|
+
|
|
151
|
+
# ── API ──────────────────────────────────────────────────────────────────
|
|
152
|
+
def check(self, url: str, force_live: bool = False) -> Verdict:
|
|
153
|
+
"""Pre-flight check: PASSABLE or DEAD_END (blocked, timeout, JavaScript-only, CAPTCHA wall, soft 404...)."""
|
|
154
|
+
d = self._post("/v1/preflight", {"target_url": url, "caller_agent_id": self.agent_id,
|
|
155
|
+
"force_live_probe": bool(force_live)})
|
|
156
|
+
return Verdict(
|
|
157
|
+
url=d.get("target_url", url), verdict=d.get("verdict", ""), category=d.get("category", ""),
|
|
158
|
+
reason=d.get("reason", ""), http_status=int(d.get("http_status") or 0),
|
|
159
|
+
needs_javascript=bool(d.get("needs_javascript")),
|
|
160
|
+
from_shared_cache=d.get("telemetry_source") == "WAZE_SHARED_TELEMETRY",
|
|
161
|
+
credits_remaining=d.get("credits_remaining"), raw=d)
|
|
162
|
+
|
|
163
|
+
def scrape(self, url: str, required_keys: Sequence[str] = ("title", "text")) -> Page:
|
|
164
|
+
"""Fetch a page as clean, verified data (~90%+ smaller than raw HTML). Raises ScrapeFailed if
|
|
165
|
+
the page is blocked or a required field is missing."""
|
|
166
|
+
d = self._post("/v1/scrape", {"target_url": url, "required_keys": list(required_keys),
|
|
167
|
+
"caller_agent_id": self.agent_id})
|
|
168
|
+
v = d.get("verified_data") or {}
|
|
169
|
+
s = d.get("savings") or {}
|
|
170
|
+
return Page(
|
|
171
|
+
url=v.get("url", url), title=v.get("title", ""), description=v.get("description", ""),
|
|
172
|
+
headings=list(v.get("headings") or []), links=list(v.get("links") or []), text=v.get("text", ""),
|
|
173
|
+
raw_chars=int(s.get("raw_page_chars") or 0), returned_chars=int(s.get("returned_chars") or 0),
|
|
174
|
+
reduction_pct=float(s.get("reduction_pct") or 0.0), credits_remaining=d.get("credits_remaining"), raw=d)
|
|
175
|
+
|
|
176
|
+
def fetch_if_passable(self, url: str, required_keys: Sequence[str] = ("title", "text")) -> Optional[Page]:
|
|
177
|
+
"""Check first; return the clean page only if it's worth reading, else None (no scrape credit used)."""
|
|
178
|
+
return self.scrape(url, required_keys) if self.check(url).passable else None
|
|
179
|
+
|
|
180
|
+
def usage(self) -> Dict[str, Any]:
|
|
181
|
+
"""Credits left, dead ends avoided and tokens saved for this key."""
|
|
182
|
+
return self._get("/v1/usage")
|
|
183
|
+
|
|
184
|
+
def get_trial_key(self, email: str, use_it: bool = True) -> str:
|
|
185
|
+
"""Get a free trial key (100 pre-flight checks + 10 scrapes, no card). It is also emailed to you.
|
|
186
|
+
With use_it=True this client starts using it right away."""
|
|
187
|
+
d = self._post("/v1/trial-key", {"email": email}, need_key=False)
|
|
188
|
+
key = d.get("api_key", "")
|
|
189
|
+
if use_it and key:
|
|
190
|
+
self.api_key = key
|
|
191
|
+
return key
|
|
192
|
+
|
|
193
|
+
def report_problem(self, message: str, url: Optional[str] = None, kind: str = "wrong_verdict",
|
|
194
|
+
verdict_seen: Optional[str] = None, contact: Optional[str] = None) -> str:
|
|
195
|
+
"""Report a wrong verdict, a bug or an idea. Free, no key needed. Returns the report id."""
|
|
196
|
+
d = self._post("/v1/feedback", {"message": message, "kind": kind, "target_url": url,
|
|
197
|
+
"verdict_seen": verdict_seen, "contact": contact}, need_key=False)
|
|
198
|
+
return d.get("report_id", "")
|
|
199
|
+
|
|
200
|
+
def close(self) -> None:
|
|
201
|
+
self._http.close()
|
|
202
|
+
|
|
203
|
+
def __enter__(self) -> "Axveritas":
|
|
204
|
+
return self
|
|
205
|
+
|
|
206
|
+
def __exit__(self, *exc: Any) -> None:
|
|
207
|
+
self.close()
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""CrewAI integration: Axveritas tools for your crews.
|
|
2
|
+
|
|
3
|
+
pip install "axveritas[crewai]"
|
|
4
|
+
|
|
5
|
+
from axveritas.crewai import get_tools
|
|
6
|
+
researcher = Agent(role="Researcher", tools=get_tools(), ...)
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, List, Optional, Type
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
from crewai.tools import BaseTool
|
|
14
|
+
from pydantic import BaseModel, Field
|
|
15
|
+
except ImportError as e: # pragma: no cover
|
|
16
|
+
raise ImportError('CrewAI support needs crewai: pip install "axveritas[crewai]"') from e
|
|
17
|
+
|
|
18
|
+
from .client import Axveritas
|
|
19
|
+
from .errors import ScrapeFailed
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class _UrlInput(BaseModel):
|
|
23
|
+
url: str = Field(..., description="Full URL, e.g. https://example.com/page")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class AxveritasPreflightTool(BaseTool):
|
|
27
|
+
name: str = "Axveritas pre-flight check"
|
|
28
|
+
description: str = (
|
|
29
|
+
"Check a URL before fetching it. Returns PASSABLE or DEAD_END with the reason (bot wall, timeout, "
|
|
30
|
+
"JavaScript-only page, CAPTCHA wall, soft 404). Don't fetch DEAD_END URLs."
|
|
31
|
+
)
|
|
32
|
+
args_schema: Type[BaseModel] = _UrlInput
|
|
33
|
+
client: Any = None
|
|
34
|
+
|
|
35
|
+
def _run(self, url: str) -> str:
|
|
36
|
+
v = (self.client or Axveritas()).check(url)
|
|
37
|
+
return f"{v.verdict} ({v.category}): {v.reason}"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class AxveritasScrapeTool(BaseTool):
|
|
41
|
+
name: str = "Axveritas clean page"
|
|
42
|
+
description: str = (
|
|
43
|
+
"Read a web page as clean, verified text, much smaller than raw HTML. Fails clearly if the page "
|
|
44
|
+
"is blocked or empty."
|
|
45
|
+
)
|
|
46
|
+
args_schema: Type[BaseModel] = _UrlInput
|
|
47
|
+
client: Any = None
|
|
48
|
+
|
|
49
|
+
def _run(self, url: str) -> str:
|
|
50
|
+
try:
|
|
51
|
+
return (self.client or Axveritas()).scrape(url).to_text()
|
|
52
|
+
except ScrapeFailed as e:
|
|
53
|
+
return f"Could not read {url}: {e}"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def get_tools(client: Optional[Axveritas] = None) -> List[BaseTool]:
|
|
57
|
+
c = client or Axveritas()
|
|
58
|
+
return [AxveritasPreflightTool(client=c), AxveritasScrapeTool(client=c)]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Errors raised by the Axveritas client. All inherit from AxveritasError."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any, Dict, Optional
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class AxveritasError(Exception):
|
|
8
|
+
def __init__(self, message: str, status: Optional[int] = None) -> None:
|
|
9
|
+
super().__init__(message)
|
|
10
|
+
self.status = status
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MissingKey(AxveritasError):
|
|
14
|
+
def __init__(self) -> None:
|
|
15
|
+
super().__init__(
|
|
16
|
+
"No Axveritas key. Set AXVERITAS_API_KEY, pass api_key=..., or get a free one in code: "
|
|
17
|
+
"axveritas.get_trial_key('you@company.com') (100 checks + 10 scrapes, no card)."
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class InvalidKey(AxveritasError):
|
|
22
|
+
"""The key is wrong or switched off."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class PaymentRequired(AxveritasError):
|
|
26
|
+
"""No key and no x402 payment. `payment` holds the x402 payment details for wallet-enabled agents."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, message: str, status: Optional[int] = 402, payment: Optional[Dict[str, Any]] = None) -> None:
|
|
29
|
+
super().__init__(message, status)
|
|
30
|
+
self.payment = payment
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class OutOfCredits(PaymentRequired):
|
|
34
|
+
"""The key has no credits left. The message includes upgrade links."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class RateLimited(AxveritasError):
|
|
38
|
+
def __init__(self, message: str, status: Optional[int] = 429, retry_after: Optional[int] = None) -> None:
|
|
39
|
+
super().__init__(message, status)
|
|
40
|
+
self.retry_after = retry_after
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class ScrapeFailed(AxveritasError):
|
|
44
|
+
"""The page was blocked, unavailable, or missing a required field (nothing useful to read)."""
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class BadRequest(AxveritasError):
|
|
48
|
+
"""The URL or input was rejected (for example a private or malformed link)."""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class DeadEndError(AxveritasError):
|
|
52
|
+
"""Raised by protect() when an agent tries to fetch a URL Axveritas reports as a dead end."""
|
|
53
|
+
|
|
54
|
+
def __init__(self, url: str, category: str, reason: str) -> None:
|
|
55
|
+
super().__init__(f"Axveritas: skipping dead end {url} ({category}: {reason})")
|
|
56
|
+
self.url = url
|
|
57
|
+
self.category = category
|
|
58
|
+
self.reason = reason
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""LangChain integration: tools for agents and a drop-in document loader.
|
|
2
|
+
|
|
3
|
+
pip install "axveritas[langchain]"
|
|
4
|
+
|
|
5
|
+
from axveritas.langchain import AxveritasLoader, get_tools
|
|
6
|
+
docs = AxveritasLoader(urls).load() # swap in for WebBaseLoader: dead ends skipped, pages ~90% smaller
|
|
7
|
+
tools = get_tools() # pre-flight + clean scrape tools for any LangChain agent
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
from typing import Any, Iterator, List, Optional, Sequence, Type
|
|
13
|
+
|
|
14
|
+
try:
|
|
15
|
+
from langchain_core.document_loaders import BaseLoader
|
|
16
|
+
from langchain_core.documents import Document
|
|
17
|
+
from langchain_core.tools import BaseTool
|
|
18
|
+
from pydantic import BaseModel, Field
|
|
19
|
+
except ImportError as e: # pragma: no cover
|
|
20
|
+
raise ImportError('LangChain support needs langchain-core: pip install "axveritas[langchain]"') from e
|
|
21
|
+
|
|
22
|
+
from .client import Axveritas
|
|
23
|
+
from .errors import AxveritasError, ScrapeFailed
|
|
24
|
+
|
|
25
|
+
log = logging.getLogger("axveritas")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _UrlInput(BaseModel):
|
|
29
|
+
url: str = Field(description="Full URL to check, e.g. https://example.com/page")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class AxveritasPreflightTool(BaseTool):
|
|
33
|
+
"""Tells the agent if a URL is worth fetching before it spends time and tokens on it."""
|
|
34
|
+
|
|
35
|
+
name: str = "axveritas_preflight_check"
|
|
36
|
+
description: str = (
|
|
37
|
+
"Check a URL before fetching it. Returns PASSABLE or DEAD_END with the reason (blocked by a bot wall, "
|
|
38
|
+
"timeout, JavaScript-only page, CAPTCHA wall, soft 404). Skip any URL that is a DEAD_END."
|
|
39
|
+
)
|
|
40
|
+
args_schema: Type[BaseModel] = _UrlInput
|
|
41
|
+
client: Any = None
|
|
42
|
+
|
|
43
|
+
def _run(self, url: str, **_: Any) -> str:
|
|
44
|
+
v = (self.client or Axveritas()).check(url)
|
|
45
|
+
return f"{v.verdict} ({v.category}): {v.reason}"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AxveritasScrapeTool(BaseTool):
|
|
49
|
+
"""Returns a page as clean text, usually ~90% smaller than raw HTML."""
|
|
50
|
+
|
|
51
|
+
name: str = "axveritas_scrape"
|
|
52
|
+
description: str = (
|
|
53
|
+
"Get a web page as clean, verified text (title, headings, main text), much smaller than raw HTML. "
|
|
54
|
+
"Use it instead of a raw fetch. Fails clearly if the page is blocked or empty."
|
|
55
|
+
)
|
|
56
|
+
args_schema: Type[BaseModel] = _UrlInput
|
|
57
|
+
client: Any = None
|
|
58
|
+
|
|
59
|
+
def _run(self, url: str, **_: Any) -> str:
|
|
60
|
+
try:
|
|
61
|
+
return (self.client or Axveritas()).scrape(url).to_text()
|
|
62
|
+
except ScrapeFailed as e:
|
|
63
|
+
return f"Could not read {url}: {e}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def get_tools(client: Optional[Axveritas] = None) -> List[BaseTool]:
|
|
67
|
+
"""Both Axveritas tools, ready to hand to a LangChain agent."""
|
|
68
|
+
c = client or Axveritas()
|
|
69
|
+
return [AxveritasPreflightTool(client=c), AxveritasScrapeTool(client=c)]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class AxveritasLoader(BaseLoader):
|
|
73
|
+
"""Drop-in replacement for WebBaseLoader: checks each URL first, skips dead ends, returns clean pages.
|
|
74
|
+
|
|
75
|
+
Each Document carries metadata: source, title, description, reduction_pct.
|
|
76
|
+
Skipped URLs are listed in `loader.skipped` as (url, reason).
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
def __init__(self, urls: Sequence[str] | str, client: Optional[Axveritas] = None,
|
|
80
|
+
check_first: bool = True, required_keys: Sequence[str] = ("title", "text")) -> None:
|
|
81
|
+
self.urls = [urls] if isinstance(urls, str) else list(urls)
|
|
82
|
+
self.client = client or Axveritas()
|
|
83
|
+
self.check_first = check_first
|
|
84
|
+
self.required_keys = tuple(required_keys)
|
|
85
|
+
self.skipped: List[tuple] = []
|
|
86
|
+
|
|
87
|
+
def lazy_load(self) -> Iterator[Document]:
|
|
88
|
+
for url in self.urls:
|
|
89
|
+
try:
|
|
90
|
+
if self.check_first:
|
|
91
|
+
v = self.client.check(url)
|
|
92
|
+
if v.dead_end:
|
|
93
|
+
self.skipped.append((url, f"{v.category}: {v.reason}"))
|
|
94
|
+
continue
|
|
95
|
+
page = self.client.scrape(url, self.required_keys)
|
|
96
|
+
except ScrapeFailed as e:
|
|
97
|
+
self.skipped.append((url, str(e)))
|
|
98
|
+
continue
|
|
99
|
+
except AxveritasError:
|
|
100
|
+
raise
|
|
101
|
+
yield Document(
|
|
102
|
+
page_content=page.to_text(),
|
|
103
|
+
metadata={"source": page.url, "title": page.title, "description": page.description,
|
|
104
|
+
"reduction_pct": page.reduction_pct},
|
|
105
|
+
)
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""protect(): add Axveritas to existing agents with one line.
|
|
2
|
+
|
|
3
|
+
import axveritas
|
|
4
|
+
axveritas.protect() # every GET your agent makes with requests or httpx is checked first
|
|
5
|
+
|
|
6
|
+
Dead ends (blocked pages, timeouts, JavaScript-only shells, CAPTCHA walls, soft 404s) raise DeadEndError
|
|
7
|
+
before any bytes are fetched, so the agent's normal error handling skips them. Verdicts are cached per site
|
|
8
|
+
for 6 hours, so a crawl of one site costs one check, not one per page.
|
|
9
|
+
|
|
10
|
+
It fails open: if Axveritas can't answer (no key, out of credits, network trouble), the request goes ahead
|
|
11
|
+
exactly as before and a single warning is logged. It never makes an agent worse.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import ipaddress
|
|
16
|
+
import logging
|
|
17
|
+
import threading
|
|
18
|
+
import time
|
|
19
|
+
from typing import Callable, Dict, Iterable, Optional, Tuple
|
|
20
|
+
from urllib.parse import urlparse
|
|
21
|
+
|
|
22
|
+
from .errors import AxveritasError, DeadEndError
|
|
23
|
+
|
|
24
|
+
log = logging.getLogger("axveritas")
|
|
25
|
+
|
|
26
|
+
PAGE_LEVEL = {"broken", "soft_404"} # these verdicts are about one page, not the whole site
|
|
27
|
+
_CACHE_SECONDS = 6 * 3600
|
|
28
|
+
|
|
29
|
+
_state = {"on": False, "client": None, "mode": "raise", "on_dead_end": None, "skip": (), "warned": False}
|
|
30
|
+
_cache: Dict[str, Tuple[float, object]] = {}
|
|
31
|
+
_lock = threading.Lock()
|
|
32
|
+
_local = threading.local()
|
|
33
|
+
_originals: Dict[str, Callable] = {}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _should_check(method: str, url: str) -> bool:
|
|
37
|
+
if (method or "").upper() != "GET":
|
|
38
|
+
return False
|
|
39
|
+
try:
|
|
40
|
+
u = urlparse(str(url))
|
|
41
|
+
except Exception:
|
|
42
|
+
return False
|
|
43
|
+
host = (u.hostname or "").lower()
|
|
44
|
+
if u.scheme not in ("http", "https") or not host:
|
|
45
|
+
return False
|
|
46
|
+
client = _state["client"]
|
|
47
|
+
if client is not None and host == (urlparse(client.base_url).hostname or "").lower():
|
|
48
|
+
return False # never check calls to Axveritas itself
|
|
49
|
+
if host in ("localhost",) or host.endswith(".local") or host.endswith(".internal"):
|
|
50
|
+
return False
|
|
51
|
+
try:
|
|
52
|
+
ip = ipaddress.ip_address(host)
|
|
53
|
+
if ip.is_private or ip.is_loopback or ip.is_link_local:
|
|
54
|
+
return False
|
|
55
|
+
except ValueError:
|
|
56
|
+
pass
|
|
57
|
+
return not any(host == s or host.endswith("." + s) for s in _state["skip"])
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _cached(url: str):
|
|
61
|
+
host = (urlparse(url).hostname or "").lower()
|
|
62
|
+
now = time.time()
|
|
63
|
+
with _lock:
|
|
64
|
+
for key in (url, host):
|
|
65
|
+
hit = _cache.get(key)
|
|
66
|
+
if hit and now - hit[0] < _CACHE_SECONDS:
|
|
67
|
+
return hit[1]
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _remember(url: str, verdict) -> None:
|
|
72
|
+
key = url if verdict.category in PAGE_LEVEL else (urlparse(url).hostname or "").lower()
|
|
73
|
+
with _lock:
|
|
74
|
+
_cache[key] = (time.time(), verdict)
|
|
75
|
+
if len(_cache) > 5000:
|
|
76
|
+
_cache.pop(next(iter(_cache)))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _guard(method: str, url: str) -> None:
|
|
80
|
+
"""Runs before an outgoing request. Raises DeadEndError, or returns to let the request proceed."""
|
|
81
|
+
if not _state["on"] or getattr(_local, "busy", False) or not _should_check(method, url):
|
|
82
|
+
return
|
|
83
|
+
url = str(url)
|
|
84
|
+
verdict = _cached(url)
|
|
85
|
+
if verdict is None:
|
|
86
|
+
_local.busy = True
|
|
87
|
+
try:
|
|
88
|
+
verdict = _state["client"].check(url)
|
|
89
|
+
except AxveritasError as e:
|
|
90
|
+
if not _state["warned"]:
|
|
91
|
+
log.warning("axveritas.protect(): check skipped, request allowed (%s)", e)
|
|
92
|
+
_state["warned"] = True
|
|
93
|
+
return
|
|
94
|
+
except Exception as e: # network trouble etc.: fail open
|
|
95
|
+
log.debug("axveritas.protect(): check failed, request allowed (%s)", e)
|
|
96
|
+
return
|
|
97
|
+
finally:
|
|
98
|
+
_local.busy = False
|
|
99
|
+
_remember(url, verdict)
|
|
100
|
+
if verdict.dead_end:
|
|
101
|
+
if _state["on_dead_end"] is not None:
|
|
102
|
+
_state["on_dead_end"](verdict)
|
|
103
|
+
if _state["mode"] == "warn":
|
|
104
|
+
log.warning("axveritas: %s is a dead end (%s: %s)", url, verdict.category, verdict.reason)
|
|
105
|
+
return
|
|
106
|
+
raise DeadEndError(url, verdict.category, verdict.reason)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def _patch_requests() -> None:
|
|
110
|
+
try:
|
|
111
|
+
import requests
|
|
112
|
+
except ImportError:
|
|
113
|
+
return
|
|
114
|
+
original = requests.Session.request
|
|
115
|
+
_originals["requests"] = original
|
|
116
|
+
|
|
117
|
+
def request(self, method, url, *args, **kwargs):
|
|
118
|
+
_guard(method, url)
|
|
119
|
+
return original(self, method, url, *args, **kwargs)
|
|
120
|
+
|
|
121
|
+
requests.Session.request = request
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _patch_httpx() -> None:
|
|
125
|
+
try:
|
|
126
|
+
import httpx
|
|
127
|
+
except ImportError:
|
|
128
|
+
return
|
|
129
|
+
sync_send, async_send = httpx.Client.send, httpx.AsyncClient.send
|
|
130
|
+
_originals["httpx.Client.send"], _originals["httpx.AsyncClient.send"] = sync_send, async_send
|
|
131
|
+
|
|
132
|
+
def send(self, request, *args, **kwargs):
|
|
133
|
+
_guard(request.method, str(request.url))
|
|
134
|
+
return sync_send(self, request, *args, **kwargs)
|
|
135
|
+
|
|
136
|
+
async def asend(self, request, *args, **kwargs):
|
|
137
|
+
import asyncio
|
|
138
|
+
await asyncio.to_thread(_guard, request.method, str(request.url))
|
|
139
|
+
return await async_send(self, request, *args, **kwargs)
|
|
140
|
+
|
|
141
|
+
httpx.Client.send = send
|
|
142
|
+
httpx.AsyncClient.send = asend
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def protect(
|
|
146
|
+
api_key: Optional[str] = None,
|
|
147
|
+
mode: str = "raise",
|
|
148
|
+
on_dead_end: Optional[Callable] = None,
|
|
149
|
+
skip_domains: Iterable[str] = (),
|
|
150
|
+
client=None,
|
|
151
|
+
) -> None:
|
|
152
|
+
"""Check every GET made with `requests` or `httpx` before it goes out.
|
|
153
|
+
|
|
154
|
+
mode="raise" (default): dead ends raise axveritas.DeadEndError, so the agent skips them.
|
|
155
|
+
mode="warn": dead ends are only logged and the request still goes out.
|
|
156
|
+
on_dead_end: optional callback(verdict) for your own logging or metrics.
|
|
157
|
+
skip_domains: sites you never want checked (e.g. your own APIs).
|
|
158
|
+
"""
|
|
159
|
+
from .client import Axveritas
|
|
160
|
+
|
|
161
|
+
if mode not in ("raise", "warn"):
|
|
162
|
+
raise ValueError("mode must be 'raise' or 'warn'")
|
|
163
|
+
_state.update(client=client or Axveritas(api_key=api_key), mode=mode, on_dead_end=on_dead_end,
|
|
164
|
+
skip=tuple(s.lower().lstrip(".") for s in skip_domains), warned=False)
|
|
165
|
+
if not _state["on"]:
|
|
166
|
+
_patch_requests()
|
|
167
|
+
_patch_httpx()
|
|
168
|
+
_state["on"] = True
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def unprotect() -> None:
|
|
172
|
+
"""Undo protect(): requests and httpx go back to normal."""
|
|
173
|
+
if not _state["on"]:
|
|
174
|
+
return
|
|
175
|
+
try:
|
|
176
|
+
import requests
|
|
177
|
+
if "requests" in _originals:
|
|
178
|
+
requests.Session.request = _originals["requests"]
|
|
179
|
+
except ImportError:
|
|
180
|
+
pass
|
|
181
|
+
try:
|
|
182
|
+
import httpx
|
|
183
|
+
if "httpx.Client.send" in _originals:
|
|
184
|
+
httpx.Client.send = _originals["httpx.Client.send"]
|
|
185
|
+
httpx.AsyncClient.send = _originals["httpx.AsyncClient.send"]
|
|
186
|
+
except ImportError:
|
|
187
|
+
pass
|
|
188
|
+
_state["on"] = False
|
|
189
|
+
with _lock:
|
|
190
|
+
_cache.clear()
|