### Run integration tests with piighost-api server Source: https://github.com/athroniaeth/piighost/blob/master/docs/snippets/README.md Runs integration tests for server examples, requiring the piighost-api executable. The server is started per example on a free port with a fake OpenAI provider. ```bash PIIGHOST_API_BIN=../piighost-api/.venv/bin/piighost-api uv run pytest tests/docs -m integration ``` -------------------------------- ### Install OpenWiki and copy skills Source: https://github.com/athroniaeth/piighost/blob/master/examples/openwiki/README.md Commands to install OpenWiki 0.6.1 globally, install the Claude integration, copy the custom skills to the user-level Claude skills directory, and copy the brief into the openwiki folder. Run these before restarting Claude Code and asking to initialize OpenWiki. ```bash npm install -g openwiki@0.6.1 openwiki integrations install claude cp -r examples/openwiki/skills/* ~/.claude/skills/ cp examples/openwiki/INSTRUCTIONS.md openwiki/INSTRUCTIONS.md ``` -------------------------------- ### Run an example script with uv Source: https://github.com/athroniaeth/piighost/blob/master/examples/README.md Run any standalone PEP 723 script with `uv`, which resolves inline dependencies on the fly. ```bash uv run examples/anonymize_basic.py ``` -------------------------------- ### Install piighost with pip or uv Source: https://github.com/athroniaeth/piighost/blob/master/README.md Install the piighost package using pip or uv. The comment indicates the alternative command. ```bash pip install piighost # or: uv add piighost ``` -------------------------------- ### Install extras with uv sync Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-cli.md Installs the gliner2 and observation extras from a repository clone using uv sync. ```bash uv sync --extra gliner2 --extra observation ``` -------------------------------- ### Install piighost with client extra and start piighost-api Source: https://github.com/athroniaeth/piighost/blob/master/src/piighost/integrations/claude_code/README.md Install piighost with the client extra and start piighost-api on http://localhost:8000. Required before configuring the hooks. ```bash pip install "piighost[client]" # start piighost-api on http://localhost:8000 ``` -------------------------------- ### Run server with gliner2 extra via Docker Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-cli.md Starts the Docker image ghcr.io/athroniaeth/piighost-api with the EXTRA_PACKAGES environment variable to install the gliner2 extra at container startup. ```bash docker run -p 8000:8000 -e EXTRA_PACKAGES="piighost[gliner2]" ghcr.io/athroniaeth/piighost-api:latest ``` -------------------------------- ### Run documentation tests Source: https://github.com/athroniaeth/piighost/blob/master/docs/snippets/README.md Commands to run the documentation tests. The first runs examples that need nothing, the second runs integration tests that reach the catalog or load a model. ```bash uv run pytest tests/docs # the examples that need nothing uv run pytest tests/docs -m integration # the ones that reach the catalog or load a model ``` -------------------------------- ### Install extras with uv Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/getting-started/installation.md Install optional extras for piighost using uv. Extras include GLiNER2 NER detector, LangChain/LangGraph middleware, and all extras. Extras compose, e.g., `piighost[redis,crypto]` for encrypted Redis memory and `piighost[argon2]` for a more resistant key hash. ```bash uv add "piighost[gliner2]" # GLiNER2 NER detector uv add "piighost[langchain]" # LangChain/LangGraph middleware uv add "piighost[all]" # every extra ``` -------------------------------- ### Install dependencies with uv sync Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/community/contributing.md Install project dependencies using uv as the package manager. Requires Python 3.11+ and uv installed. ```bash uv sync ``` -------------------------------- ### Start the dev server with hot reload Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-docs/SKILL.md Starts the documentation site's dev server on localhost:5173, which reloads on changes to the content. Use for local iteration. ```bash PIIGHOST_CONTENT=$PWD pnpm -C ../piighost-docs/frontend dev # localhost:5173 ``` -------------------------------- ### Install piighost with config extra Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/cli.md Install the CLI with the `config` extra, which includes `typer`. If `typer` is missing, the CLI prints an install hint to stderr and exits with code 1. ```bash pip install "piighost[config]" ``` -------------------------------- ### Check installed version and upgrade piighost Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/community/upgrading.md Use these commands to check the installed release and upgrade to the latest version. The first command prints the installed version. The second upgrades via pip, with an alternative using uv. ```bash python -c "import piighost; print(piighost.__version__)" pip install -U piighost # or, with uv uv lock --upgrade-package piighost ``` -------------------------------- ### JSON configuration example Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/configuration/toml.md Shows the JSON file format for the same schema as the TOML example. A .json suffix selects the JSON parser. ```json { "detector": { "type": "regex", "patterns": { "EMAIL": "[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,}" } }, "linker": { "type": "exact" }, "anonymizer": { "placeholder": { "type": "redact" } } } ``` -------------------------------- ### Start the Piighost API server with Docker Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/getting-started/api-server.md Runs the piighost-api container, passing the API_KEY_DEV and SECRET_PEPPER environment variables exported earlier. EXTRA_PACKAGES installs the gliner2 extra (the model runtime) at startup; without a visible NVIDIA GPU, the CPU build of PyTorch (~1 GB) is used. The volumes persist the uv and Hugging Face caches across restarts. The configuration is fetched from the catalog at every start because the reference is not pinned to a commit; the log reports 'API keys loaded, auth enabled' and 'Pipeline ready: piighost/support-en: (detector: composite)', with uvicorn listening on http://0.0.0.0:8000. ```bash docker run --name piighost-api -p 8000:8000 \ -e API_KEY_DEV -e SECRET_PEPPER \ -e PIIGHOST_CONFIG=catalog:piighost/support-en \ -e EXTRA_PACKAGES="piighost[gliner2]" \ -v piighost-uv-cache:/root/.cache/uv \ -v piighost-hf-cache:/root/.cache/huggingface \ ghcr.io/athroniaeth/piighost-api:latest ``` -------------------------------- ### Example metrics table output Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-cli.md Example table output from `piighost-api dataset metrics` for the record above. Shows per-label tp/fp/fn, precision, recall, F1, macro/micro averages, and a label confusion section for same-span mismatches. ```text label tp fp fn P R F1 -------------------------------------------------------------- LOCATION 0 1 1 0.00 0.00 0.00 ORGANIZATION 0 0 1 0.00 0.00 0.00 PERSON 1 0 0 1.00 1.00 1.00 -------------------------------------------------------------- macro avg - - - 0.33 0.33 0.33 micro avg - - - 0.50 0.33 0.40 Label confusion (model -> human, same span): LOCATION -> ORGANIZATION: 1 ``` -------------------------------- ### Install extras with pip Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/getting-started/installation.md Install optional extras for piighost using pip. Extras include GLiNER2 NER detector, LangChain/LangGraph middleware, and all extras. Extras compose, e.g., `piighost[redis,crypto]` for encrypted Redis memory and `piighost[argon2]` for a more resistant key hash. ```bash pip install "piighost[gliner2]" pip install "piighost[langchain]" pip install "piighost[all]" ``` -------------------------------- ### Check installation with uv Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/getting-started/installation.md Print the installed piighost version using uv. The command prints a version number such as `2.0.0`. An `ImportError` means the package is not installed in the active environment. ```bash uv run python -c "import piighost; print(piighost.__version__)" ``` -------------------------------- ### Include a Python snippet from a file Source: https://github.com/athroniaeth/piighost/blob/master/docs/snippets/README.md Shows how a page includes a section of a Python example file using the --8<-- marker. The marker lines are not shown on the page. ```markdown ```python --8<-- "snippets/first_pipeline.py:run" ``` ``` -------------------------------- ### Prefer: data-driven dict dispatch Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Shown as the 'Prefer' example for rule 2. Uses a dict mapping keys to `(module, name)` tuples and resolves with `importlib.import_module`, preserving lazy imports and getting `KeyError` for missing keys for free. ```python _LAZY_DETECTORS: dict[str, tuple[str, str]] = { "lazy:gliner2": ("piighost.detector.gliner2", "Gliner2Detector"), "lazy:spacy": ("piighost.detector.spacy", "SpacyDetector"), } def _resolve_lazy_detector(key): module_path, class_name = _LAZY_DETECTORS[key] return getattr(importlib.import_module(module_path), class_name) ``` -------------------------------- ### Check installation with pip Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/getting-started/installation.md Print the installed piighost version using pip. The command prints a version number such as `2.0.0`. An `ImportError` means the package is not installed in the active environment. ```bash python -c "import piighost; print(piighost.__version__)" ``` -------------------------------- ### Start piighost-api server with patrick.toml Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/examples/anthropic-proxy.md Starts the piighost-api server using the patrick.toml configuration. Requires API_KEY_DEV to be exported in the shell, otherwise the server refuses to start. ```bash piighost-api serve --config patrick.toml ``` -------------------------------- ### Install piighost with config and fuzzy extras Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/getting-started/configuration.md Install the package with the `config` and `fuzzy` extras using either uv or pip. ```bash uv add "piighost[config,fuzzy]" ``` ```bash pip install "piighost[config,fuzzy]" ``` -------------------------------- ### Start serve with catalog config Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-cli.md Runs piighost-api serve with a catalog reference, binding to 0.0.0.0:8000. Requires a valid config or PIIGHOST_CONFIG; otherwise exits 1. ```bash piighost-api serve --config catalog:piighost/support-en --host 0.0.0.0 --port 8000 ``` -------------------------------- ### Install piighost extras with uv Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/deployment.md Adds the config, redis, crypto, and argon2 extras for the Redis memory and Argon2 hasher. Drop argon2 if using HMAC-SHA256 key derivation. ```bash uv add "piighost[config,redis,crypto,argon2]" ``` -------------------------------- ### Get CLI help Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/cli.md Displays help for the main CLI and the `anonymize` subcommand. ```bash $ piighost --help $ piighost anonymize --help ``` -------------------------------- ### Install piighost with pip Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/examples/basic.md Installs the piighost core package using pip. ```bash pip install piighost ``` -------------------------------- ### Run tests with all extras and groups Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/tests/run-and-write-tests.md Install all extras and groups, run pytest with -rs to show skip reasons, then sync back to the default environment. Use this to run tests that are skipped in CI because they require optional dependencies. ```bash uv sync --all-extras --all-groups uv run pytest -rs uv sync ``` -------------------------------- ### Prefer: Setup variables at top Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Shows preferred style of declaring accumulators and initial locals at the top of the function body, separated by a blank line. ```python def resolve(self, detections): kept = [] ordered = sorted(...) for d in ordered: ... ``` -------------------------------- ### Output of keyshield generate and pepper Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/getting-started/api-server.md Example output lines from the keyshield commands, showing the values to set in your .env file. ```text Set in your .env : "API_KEY_DEV=ak_v1-..." Set in your .env : "SECRET_PEPPER=..." ``` -------------------------------- ### Install piighost extras with pip Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/deployment.md Adds the config, redis, crypto, and argon2 extras for the Redis memory and Argon2 hasher. Drop argon2 if using HMAC-SHA256 key derivation. ```bash pip install "piighost[config,redis,crypto,argon2]" ``` -------------------------------- ### GET / Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-endpoints.md Returns basic service information including the API name, version, and a link to the Swagger documentation. ```APIDOC ## GET / ### Description Returns basic service information including the API name, version, and a link to the Swagger documentation. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **name** (string) - The API name. - **version** (string) - The installed piighost-api version. - **docs** (string) - URL to the Swagger documentation. #### Response Example { "name": "piighost-api", "version": "...", "docs": "/schema/swagger" } ``` -------------------------------- ### Install piighost with uv Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/examples/basic.md Adds the piighost core package to the project using the uv package manager. ```bash uv add piighost ``` -------------------------------- ### TOML configuration example Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/configuration/toml.md Shows the TOML file format for configuring detector, linker, and anonymizer sections. The suffix .toml (or any non-.json suffix) selects the TOML parser. ```toml [detector] type = "regex" patterns = { EMAIL = '[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}' } [linker] type = "exact" [anonymizer.placeholder] type = "redact" ``` -------------------------------- ### GET /v1/labels Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-endpoints.md Returns the list of labels that the configured detector can emit, along with detector metadata. ```APIDOC ## GET /v1/labels ### Description Returns the list of labels that the configured detector can emit, along with detector metadata. ### Method GET ### Endpoint /v1/labels ### Response #### Success Response (200) - **name** (string or null) - The configuration's name. - **detector** (string) - The type of [detector]. - **labels** (list of strings) - Every label [detector] can emit, sorted. #### Response Example { "name": "piighost/fr-default:e6990159", "detector": "regex", "labels": ["CREDIT_CARD", "EMAIL", "EU_VAT", "FR_IBAN", "FR_NIR", "FR_PHONE", "FR_SIREN", "FR_SIRET", "IBAN", "IPV4", "SWIFT_BIC", "URL"] } ``` -------------------------------- ### GET / Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-endpoints.md Root endpoint that returns basic service information. It is always accessible without authentication. ```APIDOC ## GET / ### Description Root endpoint that returns basic service information. It is always accessible without authentication. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **body** (JSON) - Service information #### Response Example { "service": "piighost-api" } ``` -------------------------------- ### Create a feature branch from master Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/community/contributing.md Always create a new branch from master. The example uses the branch name feat/my-feature. ```bash git checkout -b feat/my-feature ``` -------------------------------- ### Example JSONL record produced by piighost-api dataset extract Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-cli.md Shows the structure of a single JSONL record written by the command. Fields include `entities` (reference spans), `model_entities` (model spans), `labels_universe`, `source` (`hitl` or `model`), and trace/session identifiers. The command ends with `Wrote N records to FILE (M skipped).` ```json { "text": "Hi Jane Doe, from Acme in Boston", "entities": [[3, 11, "PERSON"], [18, 22, "ORGANIZATION"], [26, 32, "LOCATION"]], "model_entities": [[3, 11, "PERSON"], [18, 22, "LOCATION"]], "labels_universe": [], "source": "hitl", "trace_id": "...", "session_id": "...", "created_at": "..." } ``` -------------------------------- ### Print JSON Schema to file Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/cli.md Prints the JSON Schema of `PipelineConfig` to stdout. The schema is generated by Pydantic and always matches the installed version of `piighost`. ```bash $ piighost schema > schema.json ``` -------------------------------- ### Override memory with PIIGHOST_MEMORY Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-cli.md Sets a shared Redis memory via environment override and starts the server. Requires piighost[crypto] for the AES-GCM cipher. ```bash export PIIGHOST_MEMORY='{"type": "redis", "url": "redis://redis:6379/0", "hasher": {"type": "argon2"}, "cipher": {"type": "aesgcm"}}' piighost-api serve --config catalog:piighost/support-en ``` -------------------------------- ### Validate and anonymize pipeline from command line Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/operations/configuration-and-catalog.md Run `piighost validate` on a pipeline file to check configuration without building, then pipe text into `piighost anonymize` to build and run the pipeline. The validate command prints `OK: examples/config/pipeline.toml` on success; the anonymize command prints `Write to <>` for the given input. Requires the `config` extra (typer) installed, otherwise the CLI prints an error and exits with code 1. ```bash uv run piighost validate examples/config/pipeline.toml ``` ```bash echo "Write to claire.dubois@example.com" | uv run piighost anonymize --config examples/config/detector_only.toml ``` -------------------------------- ### GET /schema/swagger Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-endpoints.md Serves the Swagger UI for interactive API documentation. Requires authentication when API keys are loaded. ```APIDOC ## GET /schema/swagger ### Description Serves the Swagger UI for interactive API documentation. Requires authentication when API keys are loaded. ### Method GET ### Endpoint /schema/swagger ### Response #### Success Response (200) - **body** (HTML) - Swagger UI page #### Response Example ... ``` -------------------------------- ### Redis memory loader (Python) Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/multi-instance.md Loads the Redis-backed memory configuration for a pipeline. This snippet is part of the shared Redis setup and is used to initialize the memory backend. ```python --8<-- "snippets/redis_load.py:example" ``` -------------------------------- ### Set upstream provider for all clients Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/examples/openai-proxy.md Set the PIIGHOST_OPENAI_UPSTREAM environment variable before starting the server to forward all requests to a different OpenAI-compatible provider. ```bash export PIIGHOST_OPENAI_UPSTREAM="http://vllm.internal:8000/v1" ``` -------------------------------- ### Generate API key and pepper with keyshield Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/getting-started/api-server.md Generates an API key and a secret pepper using the keyshield command inside the Docker image. The server refuses to start without an API key unless PIIGHOST_ALLOW_ANONYMOUS=true is set. ```bash docker run --rm ghcr.io/athroniaeth/piighost-api:latest /app/.venv/bin/keyshield generate ``` ```bash docker run --rm ghcr.io/athroniaeth/piighost-api:latest /app/.venv/bin/keyshield pepper ``` -------------------------------- ### Run a regex-only configuration without a model Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/getting-started/api-server.md Starts the container with the French regex-only configuration (piighost/fr-default) and no EXTRA_PACKAGES, so it downloads only the configuration, not a model. It detects phone numbers, IBAN, NIR, SIREN, and emails among others. ```bash docker run --name piighost-api -p 8000:8000 \ -e API_KEY_DEV -e SECRET_PEPPER \ -e PIIGHOST_CONFIG=catalog:piighost/fr-default \ -v piighost-uv-cache:/root/.cache/uv \ -v piighost-hf-cache:/root/.cache/huggingface \ ghcr.io/athroniaeth/piighost-api:latest ``` -------------------------------- ### Validate a broken configuration Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/cli.md Example of a failed validation. The command prints an error message to stderr and exits with code 1, making it suitable for CI gates. ```bash $ piighost validate ./broken.toml invalid configuration in broken.toml: ... $ echo $? 1 ``` -------------------------------- ### Export API key and pepper as environment variables Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/getting-started/api-server.md Exports the generated API key and secret pepper as environment variables in the shell that will start the server. ```bash export API_KEY_DEV="ak_v1-..." export SECRET_PEPPER="..." ``` -------------------------------- ### Run content:check for both languages and the wiki Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-docs/SKILL.md Builds and verifies the documentation site using piighost-docs. Fails on broken links, missing images, or undefined/duplicate identifiers. Run after any doc change to check both languages. ```bash PIIGHOST_CONTENT=$PWD pnpm -C ../piighost-docs/frontend content:check # both languages and the wiki ``` -------------------------------- ### Anonymize a message with ExactMatchDetector Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/processes/protect-a-message.md Shows the minimal pipeline setup when only a detector is provided. Defaults to ExactEntityLinker, Anonymizer(LabelCounterPlaceholderFactory()) and ConfidenceOverlapResolver; expansion, entity resolution, override and guard are disabled. Outputs placeholders like <> and <>. ```python import asyncio from piighost.components.detector import ExactMatchDetector from piighost.pipeline import AnonymizationPipeline detector = ExactMatchDetector( {"Jean Dupont": "PERSON", "jean.dupont@exemple.fr": "EMAIL"} ) pipeline = AnonymizationPipeline(detector) async def main() -> None: result = await pipeline.anonymize("Write to Jean Dupont, jean.dupont@exemple.fr") print(result.text) # Write to <>, <> asyncio.run(main()) ``` -------------------------------- ### Avoid: if/elif dispatch cascade Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Shown as the 'Avoid' example for rule 2. Uses a chain of `if key == ...: return ...` to select a detector, which is discouraged in favor of a dict lookup. ```python def _resolve_lazy_detector(key): if key == "lazy:gliner2": from piighost.detector.gliner2 import Gliner2Detector return Gliner2Detector if key == "lazy:spacy": from piighost.detector.spacy import SpacyDetector return SpacyDetector raise KeyError(key) ``` -------------------------------- ### Avoid: None-guard ternary for fallback Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Shown as the 'Avoid' example for rule 1. Uses inline `x if x is not None else y` for fallback values, which is discouraged when the falsy-but-not-None edge is irrelevant. ```python return {"text": redact_as if redact_as is not None else self.text, ...} self.detections = detections if detections is not None else [] ``` -------------------------------- ### Content check command Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-docs/SKILL.md Run from the repository root to verify documentation content. Expect the output 'no problem'. ```bash PIIGHOST_CONTENT=$PWD pnpm -C ../piighost-docs/frontend content:check ``` -------------------------------- ### Prefer: Document data fields in Attributes and properties on themselves Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Class docstrings document public data attributes in an `Attributes:` section, and properties are documented on the property itself. This example shows the preferred pattern. ```python class Detection: """... Attributes: span: ... # a data field Raises: ConfidenceError: ... """ @property def label(self) -> str: """The PII label.""" # documented on the property itself ``` -------------------------------- ### Import PIIAnonymizationMiddleware and strategies Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/langchain.md Import the middleware and strategy classes from the piighost LangChain integration. Requires the `langchain` extra (`pip install piighost[langchain]`); importing the package does not pull in `langchain`, and a missing extra raises an `ImportError` naming the extra. ```python from piighost.integrations.langchain import ( EntityCreateByAssistantStrategy, InventedPlaceholderStrategy, PIIAnonymizationMiddleware, ToolCallStrategy, ) ``` -------------------------------- ### Run piighost-api dataset extract with output, since, and limit options Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-cli.md Reads traces from Langfuse and writes one JSONL record per trace. Requires the `dataset` extra and `LANGFUSE_PUBLIC_KEY`/`LANGFUSE_SECRET_KEY` from the environment or a `.env` file; exits `1` if missing. The `--output` option is required; `--since` and `--limit` are optional. ```bash piighost-api dataset extract --output dataset.jsonl --since 2026-09-01 --limit 1000 ``` -------------------------------- ### Clone and set up the piighost repository Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/community/contributing.md Fork the repository on GitHub, then clone your fork locally and add the upstream remote. Replace YOUR-USERNAME with your GitHub username. ```bash git clone https://github.com/YOUR-USERNAME/piighost.git cd piighost git remote add upstream https://github.com/Athroniaeth/piighost.git ``` -------------------------------- ### Set PIIGHOST_DATABASE_URL environment variable Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/deployment.md Export the database URL with an async driver (e.g., postgresql+asyncpg). The URL must use an async driver; create the schema at startup with await pipeline.memory.create_schema(). ```bash export PIIGHOST_DATABASE_URL="postgresql+asyncpg://user:pass@db.internal/piighost" ``` -------------------------------- ### GET /schema/openapi.json Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-endpoints.md Serves the OpenAPI schema for the API. Requires authentication when API keys are loaded. ```APIDOC ## GET /schema/openapi.json ### Description Serves the OpenAPI schema for the API. Requires authentication when API keys are loaded. ### Method GET ### Endpoint /schema/openapi.json ### Response #### Success Response (200) - **body** (JSON) - OpenAPI schema #### Response Example { "openapi": "3.0.0" } ``` -------------------------------- ### Configure PIIAnonymizationMiddleware with ToolCallStrategy Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/processes/let-a-tool-act.md Use this Python snippet to set up the middleware with a full tool strategy and raise on invented placeholders. The middleware requires a pipeline whose factory exposes a recognizer, otherwise it raises UnrecognizableFactoryError at construction. ```python from piighost.integrations.langchain import ( InventedPlaceholderStrategy, PIIAnonymizationMiddleware, ToolCallStrategy, ) middleware = PIIAnonymizationMiddleware( pipeline, tool_strategy=ToolCallStrategy.FULL, invented_strategy=InventedPlaceholderStrategy.RAISE, ) ``` -------------------------------- ### GET /v1/labels Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-endpoints.md Returns the list of labels used by the pipeline. It is always accessible without authentication. ```APIDOC ## GET /v1/labels ### Description Returns the list of labels used by the pipeline. It is always accessible without authentication. ### Method GET ### Endpoint /v1/labels ### Response #### Success Response (200) - **body** (JSON) - List of labels #### Response Example { "labels": ["PERSON", "EMAIL", "PHONE"] } ``` -------------------------------- ### piighost-api CLI usage overview Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-cli.md Shows the main commands: serve, dataset extract, and dataset metrics with their options. The server requires Python 3.12+ and piighost>=2.0,<3. ```text piighost-api serve [--config SOURCE] [--host HOST] [--port PORT] [--log-level LEVEL] piighost-api dataset extract --output FILE [--since DATE] [--until DATE] [--mode MODE] [--limit N] piighost-api dataset metrics --input FILE [--output FILE] [--output-format FORMAT] [--match-mode MODE] [--iou-threshold FLOAT] [--source SOURCE] ``` -------------------------------- ### GET /v1/threads/{thread_id}/tokens Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-endpoints.md Returns the thread's placeholder-to-value map, for a client that restores a stream itself. ```APIDOC ## GET /v1/threads/{thread_id}/tokens ### Description Returns the thread's placeholder-to-value map, for a client that restores a stream itself. ### Method GET ### Endpoint /v1/threads/{thread_id}/tokens ### Parameters #### Path Parameters - `thread_id` (string) - Required - The thread identifier. ### Request Example No request body required. ### Response #### Success Response (200) - `tokens` (object) - Map of placeholder to value. #### Response Example ```json {"tokens": {"<>": "Jane Doe", "<>": "jane.doe@example.com"}} ``` ``` -------------------------------- ### Run piighost-api dataset metrics Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-cli.md Scores the model against the reference of a JSONL file written by `dataset extract`, label by label. Requires the `--input` option; other options have defaults as documented. ```bash piighost-api dataset metrics --input dataset.jsonl ``` -------------------------------- ### GET /health Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-endpoints.md Health check endpoint that returns the service status. It is always accessible without authentication. ```APIDOC ## GET /health ### Description Health check endpoint that returns the service status. It is always accessible without authentication. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **body** (JSON) - Health status #### Response Example { "status": "ok" } ``` -------------------------------- ### piighost validate Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/operations/configuration-and-catalog.md Validates a configuration file or catalog entry without building the pipeline. Prints 'OK: ' on success. ```APIDOC ## [CLI] piighost validate ### Description Validates a configuration file or catalog entry without building the pipeline. Prints `OK: ` on success. ### Method CLI command ### Endpoint `piighost validate ` ### Parameters #### Positional Arguments - **file or catalog:…** (string) - Required - Path to a configuration file or a catalog reference. ### Response #### Success Response (exit code 0) - Prints `OK: `. #### Error Response (exit code 1) - On `ConfigError` or `CatalogError`. ### Example ```bash uv run piighost validate examples/config/pipeline.toml ``` ``` -------------------------------- ### GET /health Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-endpoints.md Health check endpoint that returns the service status and the detector type. Exempt from rate limiting. ```APIDOC ## GET /health ### Description Health check endpoint that returns the service status and the detector type. Exempt from rate limiting. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - The health status, e.g., "ok". - **detector** (string) - The type of the configuration's [detector] section. #### Response Example { "status": "ok", "detector": "composite" } ``` -------------------------------- ### GET /v1/threads/... Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/api-endpoints.md Thread-related endpoints for managing conversation threads. Requires authentication when API keys are loaded. ```APIDOC ## GET /v1/threads/... ### Description Thread-related endpoints for managing conversation threads. Requires authentication when API keys are loaded. ### Method GET ### Endpoint /v1/threads/... ### Response #### Success Response (200) - **body** (JSON) - Thread data #### Response Example { "threads": [] } ``` -------------------------------- ### GuardRail.check standalone Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/guard-rails.md Guards can be used standalone by calling await guard.check(text) and reading the verdict without raising. This is demonstrated in the examples. ```APIDOC ## GuardRail.check standalone ### Description Guards can be used standalone. Call `await guard.check(text)` and read the verdict without raising. ### Method async def check ### Signature `await guard.check(text)` ### Parameters - **text** (str) - Required - The text to check. ### Returns - **GuardVerdict** - The verdict indicating whether confidential values seem to remain. ``` -------------------------------- ### Check one-way coupling with grep Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/architecture/ports-and-extension.md Run this grep command to verify that the core never imports `piighost.config`. The output must be empty; any match indicates a violation of the one-way coupling rule. ```bash grep -rn "piighost.config" src/piighost --include=*.py | grep -v "^src/piighost/config\|^src/piighost/cli" ``` -------------------------------- ### Import guard rail classes Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/guard-rails.md Import the guard rail classes from the piighost.components.guard module. This is the starting point for using guard rails in a pipeline. ```python from piighost.components.guard import ( DetectorGuardRail, LLMGuardRail, ModerationGuardRail, ) ``` -------------------------------- ### Run LangChain integration tests Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/integrations/agents-and-tools.md Use this command to run the test suite for the LangChain middleware integration. It verifies conversation identifiers, block content, tool strategies, invented placeholders, assistant provenance, and refusal of non-delimited factories. ```bash uv run pytest tests/integrations/langchain ``` -------------------------------- ### Span.shift(offset) -> Span Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/models.md Returns a copy of the span translated by the given character offset. Raises an error if the shift would push the start below zero. ```APIDOC ## `shift(offset) -> Span` ### Description A copy translated by `offset` characters. It remaps a span found on a chunk or on normalized text back onto the original text. A shift that would push `start` below zero raises an error in the constructor rather than clamp the span. The bug therefore surfaces. ### Method `shift` ### Parameters - **offset** (int) - Required - The number of characters to shift the span by. ### Returns - **Span** - A new `Span` instance shifted by the given offset. ### Exceptions - **NegativeSpanStartError** - If the shift would cause `start` to become negative. ``` -------------------------------- ### Run detector contract and import tests Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/architecture/ports-and-extension.md Run the contract, import regression, and config tests, then lint. The contract test must report the same span (in code points), text, and external label as other detectors. ```bash uv run pytest tests/components/detector/test_contract.py tests/regression/test_imports.py tests/config make lint ``` -------------------------------- ### Set PIIGHOST_HASH_PEPPER and PIIGHOST_CIPHER_KEY environment variables Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/deployment.md Exports the hasher pepper and cipher key as environment variables at build time. PIIGHOST_HASH_PEPPER must be a non-empty string; PIIGHOST_CIPHER_KEY must be base64 of 16, 24, or 32 bytes (openssl rand -base64 32 yields an AES-256 key). Never write these secrets into the config file; a missing or malformed secret raises ConfigError at build time. ```bash export PIIGHOST_HASH_PEPPER="a-long-random-string" export PIIGHOST_CIPHER_KEY="$(openssl rand -base64 32)" ``` -------------------------------- ### Audit script command Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-docs/SKILL.md Run from the repository root to audit documentation. Expect the output '0 finding(s)'. ```bash python3 skills/piighost-docs/scripts/audit.py ``` -------------------------------- ### Import configuration loaders Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/configuration/toml.md Import the configuration loading functions from the piighost.config module. ```python from piighost.config import load_config, load_pipeline, load_thread_pipeline ``` -------------------------------- ### Module-level constant with trailing comment (Avoid) Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Avoid using a trailing comment to explain a module-level constant's value. This example is the discouraged form. ```python _NONCE_LENGTH = 12 # 96-bit nonce ``` -------------------------------- ### Minimal TOML configuration with regex detector (detector_only.toml) Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/operations/configuration-and-catalog.md Smallest valid configuration file, declaring only a regex detector. Entity linker, anonymizer, and overlap resolver use defaults; an address becomes `<>`. ```toml [detector] type = "regex" patterns = { EMAIL = '[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}' } ``` -------------------------------- ### Avoid: Documenting properties in Attributes Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Do not document properties in the `Attributes:` section of a class docstring; properties are documented on the property itself. This example shows the discouraged pattern. ```python class Detection: """... Args: span: ... Attributes: label: ... # a property; does not belong here """ ``` -------------------------------- ### Observation payload redaction example Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/security.md Illustrates how the observation redactor replaces detected values with a placeholder token before payloads leave for the trace backend. With RedactPlaceholderFactory(), every entity collapses to <>. ```text user text : "Patrick lives in Paris." observation payload : "<> lives in <>." ``` -------------------------------- ### load_thread_pipeline(path) Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/configuration/toml.md Builds a ThreadAnonymizationPipeline from a configuration file. Requires a [memory] section and raises ConfigError if it is missing. ```APIDOC ## load_thread_pipeline(path) ### Description Builds a ThreadAnonymizationPipeline from a configuration file. Requires a [memory] section and raises ConfigError if it is missing. ### Method Function ### Endpoint `load_thread_pipeline(path)` ### Parameters - **path** (string) - Required - Path to the configuration file (TOML or JSON). ### Returns - **ThreadAnonymizationPipeline** - The built thread pipeline. ### Errors - **ConfigError** - Raised if the file declares no `[memory]` section. ### Example ```python from piighost.config import load_thread_pipeline pipeline = load_thread_pipeline("config.toml") ``` ``` -------------------------------- ### Documentation directory layout (docs/) Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-docs/SKILL.md Shows the canonical English source tree under docs/ with mirrors for French, theme overrides, and nav configuration files. Use as a reference for where content lives and how the site is organized. ```text docs/ ├── en/ # canonical English source │ ├── index.md # home (use cases) │ ├── architecture.md # layered architecture │ ├── why-anonymize.md # threat-model intro │ ├── extending.md # protocol reference for users │ ├── limitations.md # known limits │ ├── security.md # threat model + scope │ ├── glossary.md │ ├── placeholder-factories.md # concept page │ ├── tool-call-strategies.md # concept page │ ├── community/ # contributing, faq, ... │ ├── examples/ # use-case walkthroughs │ ├── getting-started/ # installation, quickstart, ... │ ├── reference/ # API surface │ ├── stylesheets/extra.css # CSS overrides │ └── includes/abbreviations.md # snippet auto-loaded on every page ├── fr/ # mirrors en/, identical layout ├── overrides/main.html # theme override (analytics) ├── zensical.toml # EN nav, read by piighost-docs └── zensical.fr.toml # FR nav ``` -------------------------------- ### Check anonymization with a configuration file Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/processes/protect-a-message.md Pipes a phone number into the CLI with a custom configuration. Must return a placeholder in place of the number. ```bash echo "Tel. 06 12 34 56 78" | uv run piighost anonymize --config ``` -------------------------------- ### Import conversation memory backends Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/reference/memory.md Import the available conversation memory backends from the piighost.conversation_memory module. RedisConversationMemory and SqlAlchemyConversationMemory are lazily imported and raise ImportError if their extra is not installed. ```python from piighost.conversation_memory import ( InMemoryConversationMemory, RedisConversationMemory, SqlAlchemyConversationMemory, ) ``` -------------------------------- ### Docker Compose for piighost-api and Redis Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/deployment.md Run the piighost-api server with Redis memory. The mounted pipeline.toml must have its url set to redis://redis:6379/0. API_KEY_DEFAULT is required and can be generated with keyshield generate. EXTRA_PACKAGES adds the AES-GCM cipher. ```yaml services: piighost-api: image: ghcr.io/athroniaeth/piighost-api:latest ports: - "8000:8000" environment: - PIIGHOST_CONFIG=/app/pipeline.toml - API_KEY_DEFAULT=${API_KEY_DEFAULT} - SECRET_PEPPER=${SECRET_PEPPER} - PIIGHOST_HASH_PEPPER=${PIIGHOST_HASH_PEPPER} - PIIGHOST_CIPHER_KEY=${PIIGHOST_CIPHER_KEY} - EXTRA_PACKAGES=piighost[crypto] volumes: - ./pipeline.toml:/app/pipeline.toml - cache:/root/.cache depends_on: - redis redis: image: redis:7-alpine volumes: cache: ``` -------------------------------- ### SQLAlchemy memory configuration in pipeline.toml Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/deployment.md Configure the memory store to use SQLAlchemy with an async driver, Argon2 hasher, and AES-GCM cipher. The URL is read from the PIIGHOST_DATABASE_URL environment variable to keep credentials out of the file. Requires the piighost[config,sqlalchemy,crypto,argon2] package. ```toml [memory] type = "sqlalchemy" url_env = "PIIGHOST_DATABASE_URL" [memory.hasher] type = "argon2" [memory.cipher] type = "aesgcm" ``` -------------------------------- ### Test docstring as present-tense fact (Avoid) Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Avoid phrasing a test's one-line docstring as a restatement of the method name with a Should prefix. This example is the discouraged form. ```python def test_end(self) -> None: """Should test that end works correctly.""" ``` -------------------------------- ### Avoid: Debug prints and speculative tolerance Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Do not leave debug prints or add try/except tolerance for cases that do not exist yet. This example shows the discouraged pattern. ```python def test_every_module_imports_cleanly() -> None: for m in walk(): print(m) # debug leftover try: import_module(m.name) except ImportError as exc: # tolerance for a case that does not exist if "install piighost[" not in str(exc): raise ``` -------------------------------- ### Set PIIGHOST_ANTHROPIC_UPSTREAM environment variable Source: https://github.com/athroniaeth/piighost/blob/master/docs/en/examples/anthropic-proxy.md Sets the default upstream URL for the proxy when no X-PIIGhost-Upstream header is provided. Must be set before starting the server to apply to all clients. ```bash export PIIGHOST_ANTHROPIC_UPSTREAM="https://gateway.internal/v1" ``` -------------------------------- ### Run streaming tests Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/processes/show-a-streamed-reply.md Runs the test suite covering streaming decoder behavior, async streaming, and middleware stream restoration. ```bash uv run pytest tests/components/placeholder/test_streaming.py tests/components/placeholder/test_streaming_async.py tests/integrations/langchain/test_middleware_stream.py ``` -------------------------------- ### Module-level constant with attached docstring (Prefer) Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Preferred form for a module-level constant: a triple-quoted docstring on the line below it explaining its value, unit, or caveat. This example is the encouraged form. ```python _NONCE_LENGTH = 12 """AES-GCM nonce length in bytes, the 96-bit size the mode is defined for.""" ``` -------------------------------- ### Avoid: Generic ValueError for multiple failure modes Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Do not raise a generic `ValueError` with a single message for multiple distinct failure conditions. This example shows the discouraged pattern. ```python if start < 0 or end <= start: raise ValueError("bad span") # generic, one message for two failures ``` -------------------------------- ### Run tests for thread and HITL pipeline Source: https://github.com/athroniaeth/piighost/blob/master/openwiki/en/processes/follow-a-conversation.md Run the test suite covering thread pipeline, human-in-the-loop correction, and acceptance tests. Use after correcting a message by hand to verify the thread token map. ```bash uv run pytest tests/pipeline/test_thread.py tests/pipeline/test_thread_hitl.py tests/acceptance ``` -------------------------------- ### Test module skeleton with conformance-then-behavior (Prefer) Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Preferred layout for a pipeline component's test module: a module-level factory helper builds the fixture with defaults and a one-line docstring, a TestConformance class asserts the adapter satisfies its Any* port with a single isinstance check, then one Test class per behavior groups the cases. ```python def _detection(start: int, end: int, label: str = "PERSON") -> Detection: """Build a detection at a span with sensible defaults.""" ... class TestConformance: def test_satisfies_the_port(self) -> None: """ConfidenceOverlapResolver is an AnyOverlapResolver.""" assert isinstance(ConfidenceOverlapResolver(), AnyOverlapResolver) class TestResolve: ... ``` -------------------------------- ### Prefer: base.py holds port and template Source: https://github.com/athroniaeth/piighost/blob/master/skills/piighost-code-style/SKILL.md Shows preferred style of placing both the port and template base in base.py, with concrete implementations in sibling modules. ```text resolver/ base.py # AnyOverlapResolver (port) + BaseOverlapResolver (template) overlap.py # ConfidenceOverlapResolver ```