SeekRelay
One async Python interface for web search in AI agents and RAG pipelines, with Tavily, Brave Search, Exa and a self-hosted SearXNG behind it.
from seekrelay import SeekRelay
async with SeekRelay.from_env() as relay:
response = await relay.search("fastapi lifespan events", max_results=3, time_range="year")
prompt_block = response.to_llm_context() # escaped, marked as untrusted web content
If Tavily runs out of credits, the same call is served by Brave; if Brave is rate-limited, by Exa or your own SearXNG. Application code never changes.
How it works
Nothing leaves the process until the query has passed the checks in the top row. Providers are then tried in your order: a passing error is retried, a lasting one sends the call to the next provider, and every step is reported to your code if you ask for it.
Why
Search APIs for agents differ in price, quality, latency and failure modes, and any one of them can change its pricing, run out of quota or go down. Hard-wiring one SDK into an agent makes all of that your problem. SeekRelay puts a small, typed layer in between:
| Problem | What SeekRelay does |
|---|---|
| Vendor lock-in, price changes | Providers are interchangeable behind SearchProvider; order is configuration |
| Credits run out mid-month (requests just stop) | A monthly quota per provider: quota_low at 80%, then the provider is skipped until the next period and the next one answers. A QuotaExceededError from the provider itself also pauses it |
| 5xx, 429, timeouts | Retries 5xx and 429 with exponential back-off, honours short Retry-After, falls back on long ones and skips that provider until then; a timed-out request goes straight to the next provider |
| An agent stuck waiting while every provider is slow | time_budget (30 s by default) caps one call across all providers and retries |
| A fallback hides that a provider is down | on_event, stats() and status() hand your code alerts and counters; nothing is stored and no service is built in |
| An agent in a loop burns the credits | max_requests_per_minute, at most 100 URLs per extract, at most 8 requests in flight per provider |
| Different response shapes | One normalised SearchResponse / SearchResult model |
| Prompt injection via web pages | to_llm_context() removes invisible characters, escapes all web text and labels it untrusted |
| Agents leaking personal data or keys into queries | PIIGuard blocks e-mails, card numbers, IBANs, Ukrainian tax numbers and secrets before any request |
| Paying twice for the same lookup | TTL cache for identical queries; with cache_path, a SQLite file shared by processes and kept across restarts |
Duplicate URLs (utm_*, www., trailing /) |
Canonical-URL de-duplication |
Providers
| Tavily | Brave Search | Exa | SearXNG | |
|---|---|---|---|---|
| Type | AI-native search API | Independent web index | Search by meaning, own index | Self-hosted metasearch |
| Web search | yes | yes | yes | yes |
| News search | yes | yes | yes (news category) |
yes (news category) |
| Page extraction | yes (extract) |
no | no | no |
| Domain filter | native | site: + client-side |
native + client-side | site: + client-side |
| Time filter | day/week/month/year | day/week/month/year | day/week/month/year | day/week/month/year* |
| Cost | credits (free tier) | per request | per request (free tier) | your server only |
* depends on the upstream engines. Details, limits and pricing notes: docs/PROVIDERS.md.
SeekRelay is a search layer: it finds links and snippets. extract stays as it is, through
Tavily only; for JavaScript-heavy pages, whole sites or structured data use a dedicated
extraction tool next to it, such as a self-hosted Firecrawl or Crawl4AI.
Install
Requires Python 3.10+. The only runtime dependency is httpx.
pip install seekrelay
export TAVILY_API_KEY=tvly-... # or BRAVE_API_KEY, or SEARXNG_BASE_URL
seekrelay search "fastapi background tasks" -n 3
To keep settings in a file, save
.env.example as .env and
fill in what you have. A .env file is read only when you name it: ./.env may belong to a
repository you have just cloned, and it could send your queries elsewhere or switch the PII
guard off. On the command line, put --env-file .env before the command, or export the
variables. In code, SeekRelay.from_env() reads only the process environment; pass an
absolute path to read a file too, such as env_file=Path(__file__).with_name(".env").
Variables already set in the environment win.
Usage
Async
import asyncio
from seekrelay import SeekRelay, AllProvidersFailedError, QueryRejectedError
async def main() -> None:
async with SeekRelay.from_env() as relay:
try:
response = await relay.search(
"remote python developer vacancy",
max_results=10,
time_range="week",
include_domains=["djinni.co", "jobs.dou.ua"],
language="uk",
country="ua",
)
except QueryRejectedError as exc: # personal data or a secret in the query
print(exc)
return
except AllProvidersFailedError as exc: # every provider failed / in cooldown
print(exc.attempts)
return
print(response.provider, response.latency_ms, response.attempts)
for result in response.results:
print(result.title, result.url, result.snippet)
pages = await relay.extract([r.url for r in response.results[:3]])
print(pages.to_llm_context())
asyncio.run(main())
Sync (scripts, notebooks without a running loop)
from seekrelay import SeekRelay
with SeekRelay.from_env() as relay:
response = relay.search_sync("python 3.13 free-threading", max_results=5)
Explicit providers
from seekrelay import (
BraveProvider,
RetryPolicy,
SeekRelay,
SearXNGProvider,
TavilyProvider,
)
relay = SeekRelay(
[
SearXNGProvider("http://127.0.0.1:8888"), # free, first
BraveProvider(api_key="..."),
TavilyProvider(api_key="tvly-...", include_answer=True),
],
retry=RetryPolicy(max_attempts=3),
cache_ttl=900,
fallback_on_empty=True,
)
As an agent tool
examples/agent_tool.py contains a framework-neutral tool
definition (JSON schema) and a handler that returns to_llm_context() text and turns
errors into short messages the model can act on.
Monitoring
def on_event(event): # a plain function; it runs inside the call, so keep it fast
if event.severity == "alert": # a provider went down or came back
alert_queue.put_nowait(f"{event.provider}: {event.kind} ({event.error})")
relay = SeekRelay.from_env(
on_event=on_event,
quotas={"tavily": 1000}, # quota_low at 80%, skipped at 100% until the 1st
cache_path="seekrelay.sqlite", # cache and quota counts survive a restart
)
relay.stats().providers["tavily"].served_as_backup # counters since start
relay.status()["tavily"].state # "up" or "down"
relay.status()["tavily"].quota_left # credits left this month
Events never hold the query, URLs or keys. docs/MONITORING.md lists every event; examples/telegram_alerts.py sends the alerts to a Telegram chat.
CLI
seekrelay --env-file .env providers
seekrelay --env-file .env search "fastapi background tasks" -n 3
seekrelay search "LLM engineer remote" --time-range week \
--include-domain djinni.co --include-domain jobs.dou.ua --format json
seekrelay --providers searxng,tavily search "rag evaluation" --format llm
seekrelay extract https://docs.searxng.org/dev/search_api.html
Exit codes: 0 ok, 1 provider failure, 2 usage/configuration error,
3 blocked by the PII guard.
Configuration
Everything can be set via environment variables or a .env file you name with --env-file;
see .env.example and docs/CONFIGURATION.md.
Providers without credentials are skipped, so one .env works everywhere.
Documentation
| Document | Contents |
|---|---|
| docs/ARCHITECTURE.md | Components, request flow, error model, design decisions |
| docs/PROVIDERS.md | Parameter mapping, limits and pricing notes per provider |
| docs/CONFIGURATION.md | Environment variables and constructor options |
| docs/MONITORING.md | Events, counters and provider state: how to see that search is degrading |
| docs/SECURITY.md | Threat model: prompt injection, data leakage, keys, self-hosting |
| docs/EXTENDING.md | Adding a provider and its price list |
| docs/DEPLOY_SEARXNG.md | Private SearXNG on a VPS with Docker Compose |
| docs/LIVE_CHECK.md | Results of runs against real services, compared with the code's assumptions |
Development
git clone https://github.com/MaksicosUA/SeekRelay.git && cd SeekRelay
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
pytest # no network access needed: HTTP is mocked
ruff check . && ruff format --check .
mypy # strict
Project layout:
src/seekrelay/
├── relay.py # SeekRelay, RetryPolicy, de-duplication
├── events.py # RelayEvent, stats() and status()
├── models.py # SearchQuery, SearchResponse, ... + to_llm_context()
├── errors.py # exception hierarchy (retryable / fallback flags)
├── pii.py # PIIGuard
├── _text.py # characters that must not reach a terminal or a model
├── cache.py # TTL + LRU cache
├── store.py # optional SQLite file: cache on disk, quota counts
├── quota.py # credits per provider and month
├── config.py # env-based construction, .env reader
├── cli.py # seekrelay command
└── providers/
├── base.py # SearchProvider ABC, HTTP + error mapping
├── tavily.py
├── brave.py
├── exa.py
└── searxng.py
Status and limitations
- All providers are covered by tests against mocked HTTP responses built from the providers' documentation (October and November 2026). SearXNG, Tavily and Exa have also been checked live; the Brave Search API has not yet, so run a smoke test with your key before relying on it.
- Only Tavily implements
extract, andextractgets no new providers: SeekRelay is a search layer. - The counters and the rate limit are per-process and in-memory. The cache and the quota
counts are too, unless
cache_pathnames a file; quota counts are the relay's own estimate (sync_quotas()raises it to Tavily's number when that is higher). PIIGuardis a seatbelt for obvious identifiers, not a DLP system. It prefers letting an unusual spelling through to blocking ordinary queries; the known gaps are listed in docs/SECURITY.md.- In
--format llmandto_llm_context(), URLs are percent-encoded, so a Cyrillic path shows as%D0%...and a Cyrillic host in punycode. Zero-width joiners and variation selectors are removed, which also affects Persian text and emoji sequences.
Live check (October 2026)
SearXNG. About 100 real requests against the private instance from deploy/searxng. Every
assumption the SearXNG provider makes held: response fields and types, HTTP 400 for
invalid language codes (which the language fix avoids), site:a OR site:b filters
(28 of 28 results on the requested domains) and punycode filters for internationalised
domains (30 of 30). Measured on one machine:
| Search latency through SeekRelay | 0.45-2.3 s, median about 1.0 s |
| Cache hit | 0.05 ms |
| Default engines under a burst | one run stopped answering after about 7 searches in 10 s; in another brave dropped out at search 12 and only duckduckgo was left |
Burst of 12 searches with SEARXNG_ENGINES=brave,bing,duckduckgo,yahoo |
12 of 12 answered, median 0.8 s |
| Pace that kept working with the default engines | one search every 15-20 s |
| Engines that answered | bing, duckduckgo, yahoo, brave (google and qwant: access denied) |
A private SearXNG suits scheduled jobs and occasional lookups better than heavy traffic; keep a paid provider behind it.
Tavily. About 30 real requests on the free plan. Response fields, language codes, domain filters (10 of 10 results on the requested domains, punycode included), extraction and the fallback after a bad key all worked.
| Search latency through SeekRelay | 1.2-2.9 s, median 1.9 s |
depth="advanced" |
3.9 s |
| Extracting 4 URLs | 0.9 s: 3 pages, 1 reported as failed |
Results for max_results=5 / 20 |
2-5 / 11: an upper bound, not a promise |
A second run of about 30 requests with the built package, after the security changes, showed the same behaviour: search 1.1-3.5 s, median 2.1 s.
Tavily accepted a query with an e-mail address, so rely on PIIGuard rather than on
provider-side checks. Full results and how to reproduce them:
docs/LIVE_CHECK.md.
License
Metadata
Release files for seekrelay 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| seekrelay-0.4.0.tar.gz | 198.9 kB | With provenance | Details for seekrelay-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| seekrelay-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for seekrelay-0.4.0-py3-none-any.whl |
Total release size: 289.5 kB
Release files / seekrelay-0.4.0.tar.gz
| Download URL | seekrelay-0.4.0.tar.gz |
|---|---|
| Size | 198.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
6564d7cb2380bc274f1c7f4c5d19640c62e3a1b9a63e9ed3e2e3460765704a40
|
|
BLAKE2b-256 checksum How to use checksums |
d69d5db059a1fe858a2a783cd234d16405fce67ae9b3b4616276583393dadaea
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.
Transparency logRelease files / seekrelay-0.4.0-py3-none-any.whl
| Download URL | seekrelay-0.4.0-py3-none-any.whl |
|---|---|
| Size | 90.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f771aa79e38ad75b288ff7ea51740c24207ab1df337b33eca9dcb79d96397fd5
|
|
BLAKE2b-256 checksum How to use checksums |
d66066b839029db30875dbac4f609545894716a66822a410742df0949f76b375
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.
Transparency logSecurity for seekrelay 0.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for seekrelay-0.4.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.