Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

unique-search-proxy (client)

Part of Unique Search Proxy · PyPI: unique-search-proxy · Helm: unique-search-proxy


1. What this package is

The client is the proxy pod. It is the only deployable service in the stack — a FastAPI application that owns secrets, outbound networking, provider adapters, and observability.

Platform services do not talk to Google or Tavily directly. They call this server's HTTP API (usually via the SDK). Shared types and config models come from core.

Package Question it answers
Core What can be configured and what does a valid request/response look like?
Client (this) How are provider calls executed at runtime?
SDK How do callers reach the proxy over HTTP?

2. Role in the system

flowchart LR
    SDK["unique_search_proxy_sdk"]
    Client["unique_search_proxy_client\n(this package)"]
    Core["unique_search_proxy_core"]
    Pool["HttpClientPool"]
    Providers["Google · Brave · Bing · …"]

    SDK -->|"POST /v1/*"| Client
    Client --> Core
    Client --> Pool
    Pool --> Providers
    Client --> Providers

System overview → ../README.md

What the client owns: HTTP routes, provider registry, credential loading, httpx egress pool, Prometheus, Docker/Helm deployment.

What it does not own: Deployment config JSON Schema, LLM exposed-params derivation, config/invocation merge — those live in core (as config-class methods) and run in caller processes.


3. Internal architecture

Requests flow through four layers inside the FastAPI app:

flowchart TB
    subgraph client_pkg["unique_search_proxy_client.web"]
        API["api/ — route handlers"]
        Reg["core/registry.py — provider lookup"]
        Svc["core/*/service.py — provider adapters"]
        Pool["core/client/ — HttpClientPool"]
        Settings["settings/ — env & secrets"]
        Mon["monitoring/ — Prometheus"]
    end

    API --> Reg
    Reg --> Svc
    Svc --> Pool
    Svc --> Settings
    API --> Mon
Layer Path Responsibility
Entry app.py App factory, lifespan (start/stop pool), router mount
API api/health.py, api/v1/*.py Validate body via core models, dispatch, record metrics
Registry core/registry.py, core/providers.py Register built-in engines/crawlers at startup
Services core/search_engines/, core/agent_engines/, core/crawlers/ Provider-specific HTTP/SDK calls, response curation
Egress core/client/service.py Shared httpx client (optional corporate proxy / mTLS)
Settings settings/providers/*, settings/client.py Per-provider credentials; unset → NOT_PROVIDED → 503
Monitoring monitoring/ Search / agent / crawl latency and error counters
Deploy deploy/ Dockerfile, Helm chart, uvicorn entrypoint

Built-in providers register in register_builtin_providers() during create_app().


4. HTTP API

Endpoint Description
GET /health Liveness
GET /ready Readiness (httpx pool + registered providers)
GET /v1/configuration/providers Registered search engine, agent engine, and crawler ids
POST /v1/search Standard search (flat body: engine, query, provider params, timeout)
POST /v1/agent-search Grounded agent search — opaque answer + provider citations + raw
POST /v1/agent-search/stream Same, streamed as SSE (delta + done)
POST /v1/crawl Crawl URLs (flat body: crawler, urls, timeout, …)
GET /metrics Prometheus (when enabled)
/docs Swagger UI with preset examples (only when EXPOSE_DOCS=true)

OpenAPI spec: openapi.json (input for SDK codegen).

4.1 Request context and usage

/v1/* routes read these headers into a request context that prefixes every log line:

Header Required Use
x-unique-company-id, x-unique-user-id, x-unique-chat-id Yes (REQUIRE_CONTEXT_HEADERS, default true) Tenant identity
x-unique-entry-point No, defaults to unknown Where the request entered the platform (chat_tool, public_api, conduct, ...)
x-unique-message-id No Reserved for analytics; recorded in the usage line only
x-service-id No, defaults to unknown Calling service; logged as caller=, never enforced

A request whose company or user id is not numeric (local, blank, junk) is unattributed: it logs a warning and increments unique_search_proxy_unattributed_requests_total{entry_point}. Set REJECT_UNATTRIBUTED_REQUESTS=true to return 400 instead. /v1/configuration/* skips this check.

/v1/search, /v1/agent-search (sync and stream) and /v1/crawl write one JSON usage line per request (event="web_search_usage") and increment unique_search_proxy_requests_total{company_id, entry_point, endpoint, provider, status}. company_id is unattributed unless both ids are numeric. The line holds no query text or URLs.

units is 1 per search or agent search. For a crawl it is the number of URLs that passed URL safety, so 0 when nothing reached the provider. Failed and timed-out requests keep their units, so filter on status when counting billable work. Search records also carry fetch_size, the number of results requested: Google and Brave page through results (10 and 20 per call), so one search unit can be several provider calls.

The usage line goes through its own logger (unique_search_proxy_core.usage) with a bare message format, fixed at INFO, so Loki | json can parse it regardless of LOG_LEVEL. Nothing verifies these headers: any in-cluster caller can set them.


5. Providers

5.1 Summary

Provider Type Upstream Credentials
Google Search Custom Search JSON API GOOGLE_SEARCH_API_KEY, GOOGLE_SEARCH_ENGINE_ID
Brave Search Brave Search API BRAVE_SEARCH_API_KEY
Perplexity Search Perplexity API PERPLEXITY_SEARCH_API_KEY
Bing Agent Azure AI Projects grounding BING_AGENT_*
VertexAI Agent Google GenAI + grounding VERTEXAI_AGENT_* or ADC
Basic Crawl Direct httpx + HTML/PDF processors (none)
Tavily Crawl Tavily extract API TAVILY_API_KEY
Jina Crawl Jina Reader API JINA_API_KEY
Firecrawl Crawl Firecrawl scrape (with polling) FIRECRAWL_API_KEY

Unconfigured providers return 503 ENGINE_NOT_CONFIGURED with missing env var names. GET /v1/configuration/providers lists what is registered in the running pod.

5.2 Search (POST /v1/search)

Flat request — tooling merges deployment config with LLM args in core before calling the proxy:

{
  "engine": "google",
  "query": "example query",
  "fetchSize": 10,
  "gl": "de",
  "dateRestrict": "d7",
  "timeout": 30
}

Response includes curated normalised results and opaque raw provider payload:

{
  "engine": "google",
  "query": "example query",
  "raw": { "pages": [{ "pageIndex": 1, "response": {} }] },
  "curated": [
    { "url": "https://example.com", "title": "Example", "snippet": "...", "content": "" }
  ]
}

For Google, snippet is Google's snippet followed, on its own line, by the page's own description from pagemap.metatags (og:description, else twitter:description), unless that is a placeholder such as null. For Brave, it is the description followed by the extra snippets, one per line.

Customized API endpoints must return a JSON object with a results array:

{
  "results": [
    {
      "url": "https://example.com",
      "title": "Example",
      "snippet": "Result summary",
      "content": "Optional full content"
    }
  ]
}

Each result requires url, title, and snippet; content is optional.

5.3 Agent search (POST /v1/agent-search)

Thin egress — proxy returns opaque agent text and the citations the provider attached to it (Bing: Foundry url_citation annotations, with offsets into the answer); callers own parsing:

{
  "engine": "bing",
  "query": "latest EU AI Act timeline",
  "generationInstructions": "...",
  "fetchSize": 5,
  "timeout": 120
}

Streaming (/v1/agent-search/stream) emits SSE { "type": "delta", "text": "..." } chunks and a terminal { "type": "done", "response": { … } }.

Bing auto-provisioned agents: the proxy creates Foundry agents named unique-grounding-with-bing-<hash> (hash of model, fetch size, and instructions) on first miss. Set BING_AGENT_CLEANUP_ON_START=true to delete those prefix-matched agents on process start (best-effort; failures and multi-worker/replica races are logged and never block boot; create-on-miss recovers transient misses).

5.4 Crawl (POST /v1/crawl)

Per-URL outcomes — one URL failing does not fail the batch:

{
  "urls": ["https://example.com"],
  "crawler": "Basic",
  "timeout": 30
}

Crawler discriminators: Basic, Tavily, Jina, Firecrawl.

Timeout: with Basic, URLs still loading just before timeout come back as per-URL UPSTREAM_TIMEOUT results next to the finished pages. A busy worker can send the response up to 5 s after timeout, so set your HTTP client timeout at least 5 s above it. The other crawlers fail the whole batch with a 504 at timeout.

PDFs: with contentTypes.pdf on (off by default), Basic returns a PDF's text in content; raw is always null for PDFs. The default pypdf extractor runs in SubprocessExtractionRunner: a short-lived child process that starts with an empty environment, has memory and CPU limits, and is killed at its time limit or the request deadline. Each worker reads PDF_MAX_CONCURRENT_EXTRACTIONS PDFs at a time (default 1); the rest wait. PDFs longer than PDF_MAX_PDF_PAGES or PDF_MAX_EXTRACTED_CHARS come back truncated, led by a note saying so. A PDF that can't be read fails its own URL (PDF_UNSUPPORTED, UPSTREAM_ERROR, or UPSTREAM_TIMEOUT). Extractors are adapters behind PdfExtractor in processing/processors/pdf/adapters/, selected with PDF_EXTRACTOR.

5.5 Errors

Structured envelope on all non-2xx responses:

{
  "error": {
    "code": "ENGINE_NOT_CONFIGURED",
    "message": "Provider is not configured. Set environment variable(s): GOOGLE_SEARCH_API_KEY",
    "retryable": false
  }
}

Error types are defined in core and raised by the SDK on the caller side.

5.6 Hooks

A hook is a service you deploy that the proxy asks before it serves a request. It answers allow or block. This section is the operator reference; the system README explains how hooks operate, and the hooks developer guide how to build one. Hooks run at hook points:

Hook point Endpoint Payload
search.before_request POST /v1/search query, engine
agent_search.before_request POST /v1/agent-search, /v1/agent-search/stream query, engine
crawl.before_request POST /v1/crawl urls, crawler

Configuring hooks. Operators declare hook services by name; there is nothing hook-specific in the code. In Helm this is the hooks block (see the system README for full examples). It reaches the proxy as these env vars, which you set yourself when not using Helm:

Variable Content
HOOKS_REQUIRE JSON list of hook points that must be covered by an enabled service. Default [].
HOOKS_SERVICES JSON object of the hook services by name. Default {}.
HOOKS_API_KEY_<NAME> API key of one service, e.g. HOOKS_API_KEY_GUARD, HOOKS_API_KEY_CRAWL_POLICY. Only for auth.type: apiKey.
HOOKS_REQUIRE='["search.before_request","agent_search.before_request"]'
HOOKS_SERVICES='{"guard": {"apiUrl": "https://guard.example.com/hooks", "contract": "1.1", "auth": {"type": "apiKey"}, "hookPoints": ["search.before_request", "agent_search.before_request"]}}'
HOOKS_API_KEY_GUARD=…

Settings of one service (unknown keys are rejected):

Key Default Meaning
apiUrl required URL hook requests are POSTed to.
contract required Hook contract the service was built against, e.g. "1.1".
auth required {"type": "none"}, {"type": "apiKey", "header"?}, {"type": "azureWorkloadIdentity", "scope"} or {"type": "gcpWorkloadIdentity", "audience"}.
hookPoints required Hook points the service is asked at.
stage 1 Services of the same stage run together; stages run in ascending order.
timeoutSeconds 5 How long to wait for one decision.
verifyContract true Asks the service which contracts it implements and flags a mismatch.
enabled true Set false to switch the service off without removing it.
allowInsecureHttp false Credentials are only sent to an https:// apiUrl. Set true to allow http:// on a trusted network (localhost, in-cluster).

Service names are lowercase words joined by -.

Authentication. apiKey sends the key as Authorization: Bearer <key>, or as is in header when set. The workload identity types send a short-lived token of the pod's own identity as a bearer token; the proxy caches it and renews it before it expires. azureWorkloadIdentity uses the Azure credential chain of the pod (workload identity in AKS), gcpWorkloadIdentity requests a Google ID token for audience. The pod's identity must be set up for these, as for Bing and Vertex AI agent search.

Outcomes. A request is served only when every hook asked allowed it.

Outcome Response
Every hook allows request is served
A hook blocks 403 HOOK_BLOCKED, with the hook's name, reason and categories
A hook times out 504 HOOK_TIMEOUT
A hook is unreachable, or its credentials cannot be obtained 503 HOOK_UNAVAILABLE
A hook answers with an error status or a malformed body 502 HOOK_UNAVAILABLE
The hook service rejects the contract (HTTP 409) 502 HOOK_CONTRACT_MISMATCH

The first block or failure ends the run: later stages are skipped and hooks still running in the same stage are cancelled.

Logging. For every hook call the proxy logs the hook, the hook point, the outcome, the categories and the duration. Request content (query, URLs), the hook's reason and its response body are never logged, and there is no setting to turn that on. A blocked request's reason reaches the caller in the error details.

Startup and deploy checks. The proxy refuses to start, and the Helm chart refuses to render, when the hook configuration is not in place:

  • a hook point in HOOKS_REQUIRE is not covered by an enabled service;
  • a service is incomplete (URL, hook points, auth type and its settings, API key);
  • a service's apiUrl is not an http(s) URL with a host, holds credentials (user:password@), or is http:// while the service is sent credentials without allowInsecureHttp;
  • a service's contract is not the contract the release sends, or names a version it no longer supports.

The message lists every problem and names the service or hook point. A service with enabled: false is not checked.

The hook contract. What the proxy sends and expects back is a versioned contract, written <version>.<revision>, defined in core. An additive change bumps the revision; a breaking change gets a new version. A hook service is upgraded on its owner's schedule, so each service pins the contract it was built against and a release that sends another one does not deploy until the pin is updated.

A mismatch in the running service is flagged, not fatal. The proxy asks GET <apiUrl>/contract at startup and then about every 5 minutes: it checks the services one after the other and waits 5 minutes after each pass, so slow or unreachable services stretch the interval. A service that reports another contract version, or cannot be asked, sets unique_search_proxy_hook_contract_compatible{hook} to 0, logs a warning and shows as "Check service" on the Grafana dashboard's Hooks row. A service on a newer revision of the same version stays compatible and is logged, since it may use something this proxy does not know yet. The row shows "No contract data" when no service is checked, including services with verifyContract: false.

Network. Hooks are called directly, not through the HTTP_CLIENT_ corporate proxy. The Helm chart adds a Cilium toFQDNs egress rule for the host of each enabled service's apiUrl; a hook running as a service in the same cluster needs its own network policy rule.

Metrics. unique_search_proxy_hook_runs_total and unique_search_proxy_hook_duration_seconds, by hook, hook_point and outcome (allowed, blocked, failed).

In-process hooks. A check that needs no service is a Python class registered with in_process_hook(...) in web/hooks/registrations.py. web/hooks/ also holds the registry, the runner, the HTTP hook and the authenticators.


6. Configuration

Settings use pydantic-settings with per-provider env vars. Copy .env.example to .env for an annotated template.

Component Prefix / vars Example
Google search (none) GOOGLE_SEARCH_API_KEY, GOOGLE_SEARCH_ENGINE_ID
Brave search (none) BRAVE_SEARCH_API_KEY, BRAVE_SEARCH_API_ENDPOINT
Perplexity (none) PERPLEXITY_SEARCH_API_KEY
Tavily TAVILY_ TAVILY_API_KEY
Jina JINA_ JINA_API_KEY, JINA_DEPLOYMENT
Firecrawl FIRECRAWL_ FIRECRAWL_API_KEY, FIRECRAWL_API_VERSION
Bing agent BING_AGENT_ BING_AGENT_ENDPOINT, BING_AGENT_BING_RESOURCE_CONNECTION_STRING, optional BING_AGENT_CLEANUP_ON_START, BING_AGENT_DEFAULT_MARKET
VertexAI agent VERTEXAI_AGENT_ VERTEXAI_AGENT_SERVICE_ACCOUNT_CREDENTIALS (optional)
HTTP client HTTP_CLIENT_ HTTP_CLIENT_PROXY_HOST, HTTP_CLIENT_POOL_TIMEOUT_SECONDS
Request context (none) REQUIRE_CONTEXT_HEADERS, REJECT_UNATTRIBUTED_REQUESTS
Prometheus PROMETHEUS_ PROMETHEUS_ENABLED
URL safety URL_SAFETY_ URL_SAFETY_ENABLED
Hooks HOOKS_ HOOKS_SERVICES, HOOKS_REQUIRE, HOOKS_API_KEY_<NAME>
PDF processing PDF_ PDF_EXTRACTOR, PDF_MAX_PDF_PAGES, PDF_EXTRACTION_TIMEOUT_SECONDS
Container (shell) HOST, PORT, WORKERS, LOG_LEVEL

URL_SAFETY_ENABLED defaults to true when unset. Setting it to false disables application-level SSRF checks and is accepted only when every request uses a configured authenticated corporate proxy; incompatible direct or partial proxy routing fails during startup. The application cannot verify that the proxy implements equivalent URL-safety controls, so this state is highlighted in the Prometheus metric and Grafana dashboard.

CUSTOM_WEB_SEARCH_API_TRUSTED_PRIVATE_HOSTS is a JSON array of exact operator-approved Customized API hostnames or IPs that may use RFC 1918 or IPv6 unique-local addresses. It does not apply to crawler targets, permit localhost or cloud metadata targets, or configure network routing or private DNS.

With WORKERS > 1, the entrypoint sets PROMETHEUS_MULTIPROC_DIR for correct metric aggregation.

Sizing. By default a pod runs 2 workers (WORKERS), and each worker runs up to 4 crawls at once (REQUEST_LIMITS_MAX_CONCURRENT_CRAWLS), so 8 per pod. The Helm chart requests 1 CPU and 2 GiB of memory with a 4 GiB limit, and the image sets MALLOC_ARENA_MAX=2. Each worker is a separate Python process with its own memory, so add replicas rather than workers for more capacity. Run at least 2 replicas in production. When PDFs are enabled, each PDF being read adds a subprocess of typically about 150 MiB, capped at PDF_MAX_EXTRACTION_MEMORY_MB (512 MiB), so the default adds at most about 1 GiB per pod.


7. Quick start

Prerequisites: Python 3.12+, uv

uv sync
cp .env.example .env
# Edit .env: set GOOGLE_SEARCH_API_KEY and GOOGLE_SEARCH_ENGINE_ID for live /v1/search
uv run python -m unique_search_proxy_client.web.app
# or
uv run uvicorn unique_search_proxy_client.web.app:app --reload --port 2349

Call from Python via the SDK:

from unique_search_proxy_sdk import UniqueSearchProxyClient

async with UniqueSearchProxyClient("http://localhost:2349") as client:
    result = await client.search.search("unique ag", engine="google", fetchSize=10)

Regenerate SDK after API changes:

uv run python scripts/generate_sdk.py

8. Dev testing

  1. Start the server and configure .env (.env.example sets REQUIRE_CONTEXT_HEADERS=false for local use; production keeps enforcement enabled).
  2. Swagger (if EXPOSE_DOCS=true) — /docs → Try it out on /v1/search or /v1/crawl → pick an Examples preset. Context headers default to local in the UI.
  3. CLI — same presets from the terminal (scripts/try_presets.py sends the same local context headers):
uv run python scripts/try_presets.py list
uv run python scripts/try_presets.py run google_minimal
uv run python scripts/try_presets.py run-all --kind crawl
uv run python scripts/try_presets.py run google_minimal --base-url http://127.0.0.1:8080

Presets live in web/presets/ (shared with Swagger examples). Add --strict to exit non-zero on any non-2xx response.


9. Project structure

unique_search_proxy_client/
├── openapi.json              # Exported spec (SDK codegen input)
├── scripts/
│   ├── generate_sdk.py
│   └── try_presets.py
├── deploy/                   # Dockerfile, Helm chart
├── tests/
└── unique_search_proxy_client/web/
    ├── app.py
    ├── api/                  # health + v1 routes
    ├── core/                 # registry, services, HttpClientPool
    ├── hooks/                # hook registry, runner, HTTP hook, authenticators
    ├── settings/             # env & provider credentials
    ├── monitoring/
    └── presets/

10. Development

uv run ruff check .
uv run ruff format .
uv run pytest
uv run basedpyright

License

Proprietary — Unique AG

Metadata

Release files for unique-search-proxy 2026.50.0.dev1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for unique-search-proxy 2026.50.0.dev1
File Size Uploaded Provenance Actions
unique_search_proxy-2026.50.0.dev1.tar.gz 102.1 kB Without provenance Details for unique_search_proxy-2026.50.0.dev1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for unique-search-proxy 2026.50.0.dev1
File Interpreter ABI Platform Actions
unique_search_proxy-2026.50.0.dev1-py3-none-any.whl Python 3 none any Details for unique_search_proxy-2026.50.0.dev1-py3-none-any.whl

Total release size: 275.1 kB

Release files / unique_search_proxy-2026.50.0.dev1.tar.gz

Download URL unique_search_proxy-2026.50.0.dev1.tar.gz
Size 102.1 kB
Tags Source
SHA-256 checksum
How to use checksums
1e613f9f3a56b9b33fc7cf7fb97dab4988d0c50405d7cdc027cea4e94d2f7c05
BLAKE2b-256 checksum
How to use checksums
0a717eab7cd0cde3df99f7df3bab275a8d6f3ae73dd824209fdf9b124c2483d7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / unique_search_proxy-2026.50.0.dev1-py3-none-any.whl

Download URL unique_search_proxy-2026.50.0.dev1-py3-none-any.whl
Size 173.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
36872c26e447ef973ec306d83e55cbd2646c94d4b822828301d558ddf4bfa706
BLAKE2b-256 checksum
How to use checksums
93bc22c5dd66ab6e01709dc5e4f2769a57804529f10070df95ab38086d1064ba
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for unique-search-proxy 2026.50.0.dev1

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A 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.

Release history Release notifications | RSS feed

This release
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page