Skip to main content

Thesaurus

CI

Thesaurus is a co-development between GIA-UH and SYALIA S.R.L.

Thesaurus is an offline compiler that turns arbitrary corpora into multilingual lexical search artifacts.

LLMs and embeddings are used only at build time. The artifact is self-contained: a lexical search runtime can load it without models, embeddings, or network access.

corpus + config ──► compiler ──► artifact/ ──► Artifact API
                     (LLM,          │             (read-only,
                      embeddings)   │              no models)
                                    └──────────► thesaurus-search
                                                  (lexical, no models)

The compiler is the product; the artifact is the contract. The project has two separate HTTP planes:

Plane Purpose Writes Default
Build API Run compilation jobs Yes :8001
Artifact API Serve mounted artifacts No :8000

They are different FastAPI applications with different routes, auth, and lifecycle. The Build API never proxies artifact routes. The Artifact API never runs the compiler.

Install

From PyPI:

pip install thesaurus-ai
pip install "thesaurus-ai[api]"   # Build API and Artifact API

From source:

uv sync                 # compiler, CLIs, reader, and search runtime
uv sync --extra api     # Build API and Artifact API

Requires Python 3.12+.

Compile an artifact

uv run thesaurus build --config config.example.yaml

The default config reads examples/corpus.jsonl and writes artifact/:

languages:
  source: es
  targets: [en]

models:
  llm: gpt-4.1-mini
  embedding: text-embedding-3-small
  api_key_env: API_KEY

API keys are read from the environment named by models.api_key_env. They are never written to the artifact.

For the loaded LM Studio models, use config.lmstudio.yaml:

export LMSTUDIO_API_KEY=lm-studio
uv run thesaurus build --config config.lmstudio.yaml

LM Studio does not require a real key, but the OpenAI client requires a non-empty value.

CLI flags override the config:

uv run thesaurus build \
  --config config.yaml \
  --output ./artifacts/feria-2026 \
  --artifact-id feria-2026 \
  --overwrite

--serve builds and then starts the Artifact API for the new artifact:

uv run thesaurus build --config config.yaml --serve --port 8000

Compile from Python

import asyncio

from thesaurus import Compiler, load_config

config = load_config("config.yaml")
result = asyncio.run(Compiler(config).build())

print(result.artifact_id, result.path, result.counts)

For records already in memory:

from thesaurus import compile_records

# records: list[thesaurus.models.Record]
result = asyncio.run(compile_records(records, config))

Compiler accepts optional generator, translator, and embedder objects implementing the protocols in thesaurus.compiler.services; this is how the test suite runs without network access.

Incremental builds

The cache is enabled by default and lives next to the artifact in .thesaurus-cache/. It is content-addressed, atomic, and outside the artifact contract.

uv run thesaurus build --config config.yaml                    # default cache
uv run thesaurus build --config config.yaml --cache-dir ./cache # explicit path
uv run thesaurus build --config config.yaml --no-cache           # disable

A second build with unchanged corpus and configuration makes zero LLM, translation, and embedding calls. Translation, generation, and embedding entries are keyed by text, context, model, prompt version, glossary, and the semantic configuration. A fully cached rebuild does not need model credentials.

Cache hits, misses, writes, and errors are reported in BuildResult.cache and in the CLI JSON output. Corrupt entries are ignored and rebuilt. If the cache directory is not writable, the build continues and records a warning. The cache is safe to delete.

Search an artifact

The thesaurus_search runtime is a separate lexical layer. It never calls models, embeddings, or the network, and the Artifact API itself remains read-only and search-free.

uv run thesaurus-search query "robtóica" --artifact ./artifacts/feria-2026
uv run thesaurus-search query "pabell" --artifact ./artifacts/feria-2026 --mode prefix
uv run thesaurus-search query "robótica" --artifact ./artifacts/feria-2026 --mode exact

Fuzzy is the default. Exact search must be requested explicitly:

Mode Behavior
fuzzy (default) Exact + prefix + bounded typo correction + concept expansion
prefix Exact + prefix completion, no typos
exact Strict token equality only
from thesaurus_search import SearchClient

client = SearchClient.open("./artifacts/feria-2026")
response = client.search("robtóica")                  # fuzzy
response = client.search("pabell", mode="prefix")     # exact + prefix
response = client.search("robótica", mode="exact")    # strict

Fuzzy matching uses trigram candidates and bounded Damerau-Levenshtein distance, with distance 1 allowed for tokens of 5–7 characters and distance 2 for longer tokens. Short tokens, codes, and numbers are not expanded. Results are ranked with BM25 and include the exact, prefix, fuzzy, or expansion reason for every match.

Filters include language, view, statuses, field_paths, and form_types. The CLI also exposes thesaurus-search stats.

Browser search (vanilla JavaScript)

The js/ directory contains a dependency-free browser client. It loads the .tar.gz bundle directly, decompresses it with the native gzip stream, parses the TAR, and searches locally. No npm, Node, bundler, server, or model is required.

<script type="module">
  import { SearchClient } from "./js/index.js";

  const response = await fetch("./feria-2026.tar.gz");
  const client = await SearchClient.fromBundle(response);

  console.log(client.search("robtóica"));                 // fuzzy default
  console.log(client.search("pabell", { mode: "prefix" }));
  console.log(client.search("robótica", { mode: "exact" }));
</script>

It implements the same modes, BM25 ranking, concept expansion, filters, and result explanations as the Python runtime. See js/README.md for the API and the browser test page.

Use the reader from Python

from thesaurus import Artifact

artifact = Artifact.open("./artifacts/feria-2026")

artifact.manifest
artifact.documents.get("doc-3")
artifact.fields.filter(document_id="doc-3")
artifact.forms.filter(language="en", type="query")
artifact.concepts.get("concept-robotics")
artifact.relations.filter(source_id="concept-robotics")
artifact.views.get("lang-en")

bundle = artifact.bundle("doc-3", include={"fields", "forms", "concepts"})

Collections are lazy and indexed by id on first access. The reader never writes to the artifact directory.

Validate an artifact before serving or publishing it:

uv run thesaurus validate --artifact ./artifacts/feria-2026
uv run thesaurus validate --artifact ./artifacts/feria-2026 --json

Validation checks manifest hashes, collection counts, unique ids, foreign keys, form normalization, and view field paths.

Serve artifacts

uv run thesaurus artifact-api --scan ./artifacts --port 8000
# or mount explicit directories
uv run thesaurus artifact-api \
  --artifact ./artifacts/feria-2026 \
  --artifact ./artifacts/feria-2025 \
  --port 8000

Main endpoints:

Endpoint Returns
GET /artifacts Mounted artifacts
GET /artifacts/{id} Manifest
GET /artifacts/{id}/documents Documents
GET /artifacts/{id}/documents/{doc_id} One document
GET /artifacts/{id}/documents/{doc_id}/bundle Document + fields + forms + concepts + relations
GET /artifacts/{id}/fields Fields
GET /artifacts/{id}/forms Generated forms
GET /artifacts/{id}/concepts Concepts
GET /artifacts/{id}/relations Concept relations
GET /artifacts/{id}/links Field/form → concept links
GET /artifacts/{id}/views Views
GET /artifacts/{id}/export tar.gz bundle of the artifact

Listings support filters, pagination, sorting, and nested grouping:

curl 'http://127.0.0.1:8000/artifacts/feria-2026/forms?language=en&type=query&limit=20'
curl 'http://127.0.0.1:8000/artifacts/feria-2026/forms?group_by=language,type'
{
  "data": {
    "es": {"paraphrase": ["..."], "query": ["..."]},
    "en": {"paraphrase": ["..."], "query": ["..."]}
  },
  "meta": {"group_by": ["language", "type"], "count": 42}
}

Set THESAURUS_ARTIFACT_TOKEN to require Authorization: Bearer <token> or X-API-Key: <token>. Send SIGHUP to rescan mounts without a restart.

Build over HTTP

export THESAURUS_BUILD_TOKEN="change-me"
uv run thesaurus build-api --output ./artifacts --port 8001

The Build API refuses to start without a token.

curl -X POST http://127.0.0.1:8001/builds \
  -H "Authorization: Bearer $THESAURUS_BUILD_TOKEN" \
  -F config=@config.yaml \
  -F corpus=@examples/corpus.jsonl \
  -F artifact_id=feria-2026 \
  -F serve=true

Returns a job immediately:

{
  "data": {
    "build_id": "bld-01J...",
    "status": "queued",
    "links": {"self": "/builds/bld-01J...", "events": "/builds/bld-01J.../events"}
  }
}
Endpoint Purpose
POST /builds Start a build
GET /builds List jobs
GET /builds/{id} Status, phase, progress, counts
GET /builds/{id}/events Server-sent progress events
GET /builds/{id}/result Artifact id, path, manifest, counts
POST /builds/{id}/cancel Cancel a queued or running build
DELETE /builds/{id} Remove the job and its uploads
POST /servers Start an Artifact API for a directory
GET /servers List managed Artifact APIs
DELETE /servers/{id} Stop a managed Artifact API

serve=true asks the Build API to launch an Artifact API for the output root and return its URL. This is an in-process convenience for local use. In production, run the Artifact API separately and point both services at the same shared directory.

The handoff is the filesystem:

Build API writes {output_root}/{artifact_id}/
Artifact API mounts {output_root}/
Clients cross only artifact_id.

Artifact layout

artifact/
  manifest.json     # format version, languages, models, counts, file hashes
  documents.jsonl   # original documents and fields
  fields.jsonl      # canonical fields + translated variants
  forms.jsonl       # paraphrases, queries, terms, answers
  concepts.jsonl    # reusable concepts with labels per language
  relations.jsonl   # typed concept relations
  links.jsonl       # field/form → concept links
  views.json        # named projections
  audit.jsonl       # build events

The artifact is the source of truth. The reader and the Artifact API add no state and no data.

Portable bundles

An artifact directory is portable as-is. To move it between machines, export it as a tar.gz bundle, transfer the file, and extract it into the exact directory you want to use:

# Build into a chosen directory
uv run thesaurus build --config config.yaml --output ./artifacts/feria-2026

# Bundle it
uv run thesaurus export --artifact ./artifacts/feria-2026 --output ./feria-2026.tar.gz

# Extract into a chosen directory
uv run thesaurus extract --bundle ./feria-2026.tar.gz --output ./deploy/feria-2026

# Serve from the extracted path
uv run thesaurus artifact-api --artifact ./deploy/feria-2026 --port 8000

Both the Python reader and the browser client can read a bundle directly, without an explicit extraction step:

from thesaurus import Artifact

with Artifact.open("./feria-2026.tar.gz") as artifact:
    print(artifact.artifact_id)
    artifact.forms.filter(language="es")

Artifact.extract_bundle("./feria-2026.tar.gz", "./deploy/feria-2026")
artifact = Artifact.open("./deploy/feria-2026")
artifact.export_bundle("./backup.tar.gz")

Bundles are validated on export and extract, reject unsafe paths, and contain the artifact files at the archive root. There is no registry, object storage, or publication service: the tar.gz file is the transport and the extracted directory is what the Artifact API mounts.

How generation works

  1. The adapter reads JSON, JSONL, or CSV into canonical Record objects.
  2. Documents and fields are preserved; every field is a generation unit.
  3. The source field is translated per target language (default strategy).
  4. One structured LLM call per field and language produces candidates: paraphrases, queries, key terms, a short answer, concepts, and relations.
  5. Candidates are embedded, filtered by a per-type threshold, reduced to a Pareto front, and selected with greedy max-min diversity.
  6. Concepts are merged, relations deduplicated, and fields/forms linked.
  7. Views, audit events, and the layered artifact are written atomically.

Translation strategies:

  • translate_source (default): translate the field, then generate per language.
  • translate_candidates: generate in the source language, translate candidates.
  • select_then_translate: select in the source language, translate selected forms.

Context modes: field, document, auto (default). auto uses the full document when it fits; otherwise an extractive summary plus relevant sibling fields and metadata.

Configuration

See config.example.yaml. Semantic layers (concepts, relations, views) are artifact data, not configuration.

An optional glossary is a YAML mapping from a source term to its translations:

# glossary.yaml
robótica:
  en: robotics
  fr: robotique
translation:
  glossary: glossary.yaml
  preserve: [SKU, "Model X"]

Development

uv sync --extra api
uv run pytest -q
uv run ruff check .

The test suite uses deterministic generator, translator, and embedder doubles; no network or model credentials are required.

Status

MVP base implemented:

  • Execution configuration and validation
  • JSON/JSONL and CSV adapters with a registry
  • Field-level translation and candidate generation
  • Thresholds, Pareto front, and greedy max-min selection
  • Concepts, relations, links, views, and audit
  • Atomic layered artifact writer
  • Python artifact reader
  • Artifact validation with thesaurus validate
  • Portable tar.gz bundles with export, extract, and direct library reads
  • Incremental content-addressed build cache
  • Lexical search runtime with fuzzy default, prefix, and exact modes
  • Vanilla JavaScript browser search from a tar.gz bundle
  • Build API with jobs, progress, cancellation, and server lifecycle
  • Read-only Artifact API with filtering, grouping, bundles, and export
  • CLI: build, build-api, artifact-api, inspect, validate, export, extract, thesaurus-search

Not in the MVP: a search HTTP service, review UI, cross-artifact joins, persistent job storage, and automatic publication/registries. The portable artifact bundle is the supported transport. The Artifact API deliberately does not search; thesaurus_search is the runtime consumer.

See docs/spec.md for the consolidated design.

License

MIT. See LICENSE.

Changelog

See CHANGELOG.md.

Metadata

Release files for thesaurus-ai 0.2.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 thesaurus-ai 0.2.0
File Size Uploaded Provenance Actions
thesaurus_ai-0.2.0.tar.gz 73.8 kB Without provenance Details for thesaurus_ai-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for thesaurus-ai 0.2.0
File Interpreter ABI Platform Actions
thesaurus_ai-0.2.0-py3-none-any.whl Python 3 none any Details for thesaurus_ai-0.2.0-py3-none-any.whl

Total release size: 151.0 kB

Release files / thesaurus_ai-0.2.0.tar.gz

Download URL thesaurus_ai-0.2.0.tar.gz
Size 73.8 kB
Tags Source
SHA-256 checksum
How to use checksums
cde8dfb2c03df5f43dca1048f9853465dd0511072d399d8d33854a059b7eae1d
BLAKE2b-256 checksum
How to use checksums
3a2de556e57460187c5e5b5e19781188111d4b5a447b73438c114a00365e3447
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.8 {"installer":{"name":"uv","version":"0.11.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.10","id":"oracular","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / thesaurus_ai-0.2.0-py3-none-any.whl

Download URL thesaurus_ai-0.2.0-py3-none-any.whl
Size 77.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
5d191ddbc57efb280357202dbac5c5afdb9859407804dd0735c65437df0272d6
BLAKE2b-256 checksum
How to use checksums
93431cb550edc01de0fc26bcd548bf351aaaa4b5bc8cdb66231d76e9704178c0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.11.8 {"installer":{"name":"uv","version":"0.11.8","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.10","id":"oracular","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for thesaurus-ai 0.2.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.2.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