Skip to main content

web-search-helper

🇫🇷  |  🇬🇧

License Python PHP CI

Search a private corpus from a website, with PHP as the only server. You index the corpus on your machine; one PHP file answers the questions; the page embeds each question in the browser. The corpus is never published: a visitor receives a few sentences of what answers the question, or an honest "I cannot answer" and nothing else.

web-search-helper belongs to the AI Helpers suite. It works in French and in English out of the box (stopwords, answer composition, interface), one index per language, and in any other language with a stopword file. By default no LLM is involved: the answer is made of the corpus's own sentences. Optionally, a small language model runs in the visitor's browser and writes the answer from the excerpts, citing them; which model depends on the visitor's machine and line, as planned by best-engine-ai-helper.

The Promise

web-search-helper is private by construction. Three honest cases:

  1. Guaranteed: the corpus is never published. The index lives in a PHP file that answers an empty 404 when requested by URL, in a folder whose .htaccess denies everything. search.php returns excerpts of what answers the question, or nothing. The question goes to your own server only, which keeps a salted hash of the visitor's address and the times of its calls of the last day, for the quota, and nothing else. No telemetry, no account, no third-party search service.
  2. The caveats. Model weights travel: sentence-transformers downloads the embedding model once on your machine, and the visitor's browser downloads its twin (about 120 MB) through transformers.js, then keeps it. The optional written answer fetches a larger model (3.1 to 5.6 GB) into the visitor's browser, only when they press its button; to decide whether to offer it, the page first times a slice of its files. And someone patient, with thousands of well-chosen questions, can still collect a good part of the corpus excerpt by excerpt: the protections below make that slow, not impossible.
  3. Your decision. check-online verifies after each upload that no byte of the corpus is served, and the thresholds that decide when to refuse are yours to measure with calibrate.

Documentation

💻 Documentation

🗺️ Landscape

📋 Examples

Why

A fully client-side search must ship the corpus to the browser, because the browser can only search what it has. That is fine for public documentation and wrong for a manuscript, a course or an internal knowledge base. Encrypting the file does not help: the key has to be in the page too.

Most hosting offers PHP and nothing else: no Python, no Node, no vector database. web-search-helper fits there.

Where What runs Needs
your machine cut, embed and index the corpus; measure the thresholds Python ≥ 3.10, sentence-transformers
the server search.php: BM25 + cosines + fusion + verdict, returns excerpts PHP ≥ 7.4 with mbstring
the browser web-search.js: embeds the question (transformers.js), composes an extractive answer, optionally writes one with an in-browser LLM an ES-module browser; WebGPU for the written answer

How it works

How web-search-helper works: index on your machine, search in one PHP file, embed and answer in the visitor's browser

How it searches

  • Words: BM25, with a conjunctive pass first (when some passages contain every word, only they compete) and a timid typo tolerance (elefant finds éléphant, but only because elefant is absent from the corpus).
  • Meaning: passages are cut into windows the model reads entirely; a passage scores the cosine of its best window. Each section also has a centroid.
  • Fusion: reciprocal rank fusion of the two rankings.
  • Verdict: the engine answers only when one of three routes says the corpus treats the question: the best window and the best section are close in meaning, or every word was found with a strong BM25, or (for a one-word query) the word appears in enough passages. Otherwise it returns nothing. Ranking always returns something; only an absolute measure can say "no".

The search is exhaustive. ann-router would pick HNSW from 1 000 vectors at a 10 ms budget, but that budget is numpy's, the corpus sizes here are small, and the verdict judges the absolute best cosine, which an approximate index can miss. web-search-helper bench measures the PHP time on your index and fails when it goes over budget.

Protections against scraping

  1. Nothing is returned when the corpus does not treat the question.
  2. A passage comes back as an excerpt: its best window and the better of its neighbours, snapped to sentence boundaries. Never the whole passage.
  3. A quota per address, per hour and per day (salted hash of the address; no other trace kept).
  4. The index file is a PHP script: requested by URL, it answers an empty 404. The data folder also gets a .htaccess that denies everything, in case.

Someone patient with thousands of well-chosen questions can still collect a good part of the corpus. These measures make that slow, not impossible.

Installation

Two machines, two needs. Where you index (your own computer): Python 3.10 or later. Where the site is served: PHP 7.4 or later with mbstring, nothing else; no Python, no database.

pip install web-search-helper                 # engine, PHP export, CLI; hashing embedder only
pip install 'web-search-helper[embed]'        # + sentence-transformers, the real embedder
pip install 'web-search-helper[api,mcp,embed]'  # + the HTTP API, /gui and the MCP server
pip install 'web-search-helper[route]'        # + ann-router's advice next to the PHP timing

From a clone:

git clone https://github.com/warith-harchaoui/web-search-helper.git
cd web-search-helper
pip install -e '.[embed,api,mcp,dev]'
git config core.hooksPath .githooks     # the pre-push gate: ruff, then the full test suite

The tests that compare engine.py with search.php need php on the PATH (brew install php on macOS, sudo apt install php-cli php-mbstring on Ubuntu).

Quick start

pip install 'web-search-helper[embed]'

# 1. Index: a .jsonl (one passage per line), a Markdown file or a folder of them.
web-search-helper build corpus/ -o build/fr.php --lang fr

# 2. Measure the thresholds on questions the corpus answers and questions it does not.
web-search-helper calibrate build/fr.php --inside inside.txt --outside outside.txt --write

# 3. Try a question, as the server will answer it.
web-search-helper search build/fr.php "Quelle est la parabole de l'éléphant ?" --explain

# 4. Copy the endpoint, the client and the index into the site; serve it locally.
web-search-helper install site/ build/fr.php build/en.php --demo
web-search-helper serve site/        # http://127.0.0.1:8765/demo.html?lang=fr (or ?lang=en)

# 5. Time the PHP engine; after upload, check that nothing leaks.
web-search-helper bench build/fr.php
web-search-helper check-online https://example.org/search/ --lang fr

JSONL records: {"text": "...", "doc": "Book title", "section": "Chapter 2", "url": "page.html#x", "meta": {...}}. meta is passed through to the browser untouched.

In the page

<script type="module">
  import { WebSearch, composeAnswer } from './web-search.js';
  const ws = new WebSearch({ endpoint: 'search.php', lang: 'fr' });
  const r = await ws.ask(question, { onLexical: (first) => { /* early answer */ } });
  if (!r.sure) showUnknown();
  else show(await composeAnswer(r, { lang: 'fr', embed: ws }), r.hits);
</script>

ask makes two calls: words only first (instant, before the model has loaded), then words and meaning. The answer composed by composeAnswer is made of corpus sentences, verbatim, chosen by maximal marginal relevance; nothing is generated. Types are in web-search.d.ts. mount(form, output, options) wires a minimal widget.

A written answer, in the visitor's browser

mount(form, output, { …, writer: true }) adds a button under a sure result: a small language model, run by transformers.js on WebGPU in the visitor's browser, rewrites the excerpts into an answer that cites them as [1], [2]… Nothing leaves the browser and the server does not change.

Which model is not decided in this package. writer-plan.json, written by best-engine-ai-helper browser plan --usage rag-answer, is an ordered ladder ranked by scores measured on this very task: Gemma 4 E4B (0.722) then Gemma 4 E2B (0.667), each in q4f16 and q4, with exact files and sizes (3.1 to 5.6 GB). LFM2 1.2B was measured too (0.167: most of its answers cite nothing) and left out, so a machine that cannot fetch a Gemma keeps the extractive answer rather than one it would set aside. scripts/eval_writer.py reruns the measurement on your own corpus; scripts/make_writer_plan.py rewrites the plan from best-engine. The page probes the machine (WebGPU, shader-f16, device memory, storage, mobile, data saver), checks the browser cache, measures the bandwidth on a Range request to the model's own files, and takes the first rung it can fetch within max_download_s (180 s). Nothing fits: no button, and the extractive answer stands. chooseRung is tested against best-engine's Python browser.choose on 2 251 simulated devices.

The written answer is checked before it is shown: the model only sees a sure result, it is told to use the excerpts only and to say when they fall short, and every sentence it writes must find most of its content words in the excerpts it cites (checkGrounding). Otherwise the page sets the written answer aside and keeps the extractive one. The excerpts stay listed below it, verbatim.

import { Writer } from './web-search.js';
const { writer, reason } = await Writer.create('writer-plan.json');  // null when nothing fits
const answer = writer && await writer.write(result, { question, lang: 'fr', onText: show });
if (answer && answer.grounded) show(answer.text);

The suite's other doors

Like every AI Helper, the engine is also reachable over HTTP and MCP, for agents, scripts and local testing without PHP (search.php stays the production server):

pip install 'web-search-helper[api,mcp,embed]'
WSH_DATA_DIR=site/search-data web-search-helper-api    # http://127.0.0.1:8040/docs, /gui
WSH_DATA_DIR=site/search-data web-search-helper-mcp    # MCP at http://127.0.0.1:8041/mcp

Routes: POST /query speaks search.php's protocol, so web-search.js can point at it (that is what /gui does); POST /search takes a plain question and embeds it server-side; GET /indexes; POST /calibrate (writes nothing); POST /check-online. The MCP tools are indexes, search, calibrate and check_online. The agent skill lives in skills/web-search-helper/; TRIGGERS.md lists what should reach for this helper and what should not, and a test keeps it identical to the skill's copy.

The API also ships as a container (Dockerfile, docker-compose.yml): it reads the indexes from ./search-data, mounted read-only, and serves port 8040 with a /health probe. GUI.md describes the /gui page.

docker compose up --build      # http://localhost:8040/gui?lang=fr

Bring your own embeddings

A site that already embeds its corpus can keep its vectors and only hand the engine over: from_vectors(rows, vectors, lang, model) builds the index from passages (t, c, s, the window ends o, optional u and m) and one normalised vector per window; vectors_from_int8 reads int8 vectors back the way a browser would. That is how "Interroger le livre" moved from an all-in-the-browser search to search.php with the SAME vectors, stopwords and thresholds, so that only the place of the computation changed.

Python

import web_search_helper as wsh

idx = wsh.build(wsh.read_corpus("corpus/"), wsh.SentenceTransformerEmbedder(), "fr")
wsh.save(idx, "build/fr.php")
print(wsh.search(idx, "the data wall", explain=True))

engine.py is the reference twin of search.php; tests/test_php_parity.py runs both on the same questions and fails if they disagree.

Limits

  • The question's vector is computed by transformers.js in the page and the index by sentence-transformers here: same weights, cosines equal to about 1e-2. Calibration reports its margins; a threshold with less margin than that is fragile.
  • One index per language; the page says which language it asks.
  • The first question downloads the model in the browser (about 120 MB for the default multilingual MiniLM), then the browser keeps it.

Author

Warith HARCHAOUI, Ph.D.

License

BSD-3-Clause; see LICENSE.

Metadata

Release files for web-search-helper 0.3.0

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

Source distribution (sdist)

Source distribution for web-search-helper 0.3.0
File Size Uploaded Provenance Actions
web_search_helper-0.3.0.tar.gz 74.1 kB Without provenance Details for web_search_helper-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for web-search-helper 0.3.0
File Interpreter ABI Platform Actions
web_search_helper-0.3.0-py3-none-any.whl Python 3 none any Details for web_search_helper-0.3.0-py3-none-any.whl

Total release size: 133.8 kB

Release files / web_search_helper-0.3.0.tar.gz

Download URL web_search_helper-0.3.0.tar.gz
Size 74.1 kB
Tags Source
SHA-256 checksum
How to use checksums
a402c3a070da4086e238b44a9c11c17cc8bc09c4de73e61a3f331491561b20cc
BLAKE2b-256 checksum
How to use checksums
c7ab04778a6fef3694afac7d0e7388212042f8374107c3908c55cd9bb4baaeab
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Release files / web_search_helper-0.3.0-py3-none-any.whl

Download URL web_search_helper-0.3.0-py3-none-any.whl
Size 59.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
216ea20bfc6e86d78bfeb05a6606d3b26c0231200bceccb08b4caeb1aac0c26a
BLAKE2b-256 checksum
How to use checksums
6675c23def6acb747cae4147be20dd06fd82f949274e0f0509cf4b7d29dbd8d2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.13

Security for web-search-helper 0.3.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.

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

0.3.0 This release

2 release files No provenance

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