Skip to main content

piloto-ai-cli

A Python command-line client for Perú Compras catalogs.

Installation

The package is published on PyPI as perucompras-cli. It installs the pc command and the piloto_ai_cli import package:

pip install perucompras-cli
pc --version

Requirements

  • Python 3.15
  • uv

Getting started

uv sync --locked --group dev
uv run pc --version

Configuration

Settings reads PILOTO_-prefixed environment variables and, by default, an optional .env file in the current directory. Applications can load another profile file with Settings(_env_file="path/to/profile.env"); environment variables take precedence over values in the file.

Environment variable Default Description
PILOTO_PROFILE pilot pilot requires database and LLM credentials; ci-mock selects in-memory SQLite and a mock LLM.
PILOTO_DATABASE_URL Required for pilot; sqlite:///:memory: for ci-mock SQLAlchemy database URL. Stored as a secret.
PILOTO_PAYLOAD_STORE_PATH .piloto-ai/payloads Directory for stored request payloads.
PILOTO_PAYLOAD_STAGE Unset Optional unquoted Snowflake internal stage, such as @db.schema.payloads.
PILOTO_LLM_PROVIDER anthropic (mock for ci-mock) anthropic (the Claude API, for local runs), snowflake (Snowflake Cortex, used inside SPCS) or mock.
PILOTO_LLM_MODEL claude-sonnet-4-5 (mock for ci-mock) LLM model identifier.
PILOTO_LLM_PROMPT_VERSION v2 Version used to identify extraction prompts.
PILOTO_LLM_API_KEY Required for pilot with anthropic, or snowflake with pat auth; unset otherwise The Claude API key, or a Snowflake PAT for Cortex outside SPCS. Stored as a secret.
PILOTO_LLM_SNOWFLAKE_AUTH spcs_oauth Cortex authentication: spcs_oauth uses the SPCS service's session token, re-read on every request; pat uses PILOTO_LLM_API_KEY.
PILOTO_LLM_SNOWFLAKE_HOST SNOWFLAKE_HOST (set by SPCS) Snowflake host for Cortex, such as <org>-<account>.snowflakecomputing.com; required with snowflake. The SNOWFLAKE_HOST fallback is read from the process environment, only for snowflake with spcs_oauth and only when this setting is unset (in the environment or .env); pat needs this setting.
PILOTO_LLM_SNOWFLAKE_TOKEN_PATH /snowflake/session/token SPCS session token file for spcs_oauth.
PILOTO_LLM_INPUT_USD_PER_MTOK Unset USD per million input tokens for PILOTO_LLM_MODEL; set it with the output rate, or neither (then extraction cost is not recorded). For Cortex, the credit rate per million tokens times the account's USD per credit.
PILOTO_LLM_OUTPUT_USD_PER_MTOK Unset USD per million output tokens, as above.
PILOTO_CONFIDENCE_THRESHOLD 0.8 Deployment threshold in the inclusive range 0–1; queries may override it.
PILOTO_MAX_ITEMS 100 Maximum fichas processed per call.
PILOTO_HTTP_USER_AGENT perucompras-cli/<installed version> (+https://github.com/GrupoJaedmik-PeruCompras/piloto-ai-cli/issues) Identifying User-Agent with a contact URL.
PILOTO_PER_CALL_IN_FLIGHT_LIMIT 5 Per-call concurrent page limit, between 1 and the process-wide hard cap of 20.
PILOTO_HTTP_CONNECT_TIMEOUT_SECONDS 10 HTTP connection timeout in seconds.
PILOTO_HTTP_READ_TIMEOUT_SECONDS 30 HTTP read timeout in seconds.
PILOTO_LLM_TIMEOUT_SECONDS 120 LLM request timeout in seconds.
PILOTO_ENRICHMENT_RETRY_BASE_SECONDS 900 (15 minutes) Wait before retrying a ficha whose enrichment (PDF download or LLM pass) failed; it doubles with each consecutive failure under the same site stamp.
PILOTO_ENRICHMENT_RETRY_CAP_SECONDS 86400 (1 day) Longest wait between enrichment retries; must be at least the base. A new site stamp resets the wait.
PILOTO_CARD_LOOKUP_RETRY_BASE_SECONDS 900 (15 minutes) Wait before looking up a ficha's card by part number again after a lookup that failed at the site (an error status, the error page, an undecodable answer, its own card unparseable, or a transport error) or whose card failed to be stored; it doubles with each consecutive failure under the same site stamp.
PILOTO_CARD_LOOKUP_RETRY_CAP_SECONDS 86400 (1 day) Longest wait between those lookups; must be at least the base. A new site stamp resets the wait.

Tests can use the mock profile without service credentials:

from piloto_ai_cli.settings import Settings

settings = Settings(profile="ci-mock")

Settings keeps database URLs and API keys in SecretStr fields so their representations are masked. Do not pass credentials to request_log or logs.

Use make_payload_store(settings, connection=None) from piloto_ai_cli.payload_store to select a payload backend. With no payload_stage configured (including the ci-mock defaults), it uses payload_store_path. When a stage is configured, pass an open Snowflake connection; the factory does not open or close connections. Use that connection exclusively for the payload store while requests are running; the store serializes its own stage operations. The live payload test uses the same Settings configuration and requires database credentials and a payload stage.

HttpClient requires a session factory, payload store, and the ID of an already committed run_log. Pass the connector name as endpoint to write_request() (it defaults to the URL path). Each attempt, including a retry, commits its request and response payload in a separate transaction before the response is returned. The response's extensions["request_id"] identifies that attempt. Transport failures are logged before being raised. Check extensions["is_error_page"] before parsing a successful response. Automatic redirects and HTTPX authentication flows are rejected because they can send additional unlogged requests; follow redirects explicitly and send authentication through headers instead. Forms must not contain credentials; known token and credential fields are stripped from the log, and so are query parameters with those names. The logged URL is the one sent, including params=. Every response body is stored, whatever its status, error page or failure: raw sources are what the parsers and extraction are improved against. A complete body is stored after its Content-Encoding is undone; a partial or undecodable body is stored exactly as received, with ; content-encoding=<value> appended to its content type. Bodies may contain sensitive data, so protect the payload store accordingly.

Library API

The frontend agent imports the CLI as a Python package instead of running pc. The names in piloto_ai_cli.__all__ are the stable, typed library surface. They are versioned with the package under semantic versioning: a breaking change to any of them needs a major version bump. Read the installed version with importlib.metadata.version("perucompras-cli"). Other modules of the package are internal and may change in any release.

import piloto_ai_cli

settings = piloto_ai_cli.Settings()  # or omit settings: read from the environment
document = {
    "contract_version": 1,
    "scope": {"agreement": "EXT-CE-2024-18", "category": "AZÚCAR"},
    "predicates": [],
}
try:
    result = piloto_ai_cli.query(document, settings=settings)
except piloto_ai_cli.ContractError as refusal:
    print(refusal.to_dict())  # code, location and message, to repair and retry
else:
    print([match.ficha_id for match in result.matches])
Name What it is
query query(document, *, settings=None, max_items=None) -> QueryResult: what pc query <document> runs.
query_saved query_saved(query_id, *, settings=None, max_items=None) -> QueryResult: what pc query --saved <id> runs.
attributes attributes(scope, *, settings=None) -> AttributesListing: what pc attributes <scope> runs.
save save(document, *, settings=None) -> str: what pc save <document> runs; returns the saved query id.
QueryResult The result envelope: matches, non-match count, unknown, not_applicable, pending counts, facets, contract_version and department_as_of. A Pydantic model; model_dump(mode="json") gives the pc --json query output.
QueryMatch One matching ficha, with its latest card values and stamps.
UnknownCount One unknown count of the envelope, per predicate and reason.
NotApplicable An attribute absent from the scope's checked fichas, with checked and pending counts.
PendingCounts Pending cards, PDFs, extractions and proposals in the scope.
FacetSummary One requested facet: its values and the count of fichas whose value is unknown.
FacetValue One distinct facet value and its count.
AttributesListing The answer of attributes: a one-category scope's attributes, or a wider scope's categories.
ApplicableAttribute One attribute of a category, with kind, canonical unit and accepted values.
ScopeCategory One category of a scope, with its catalogue.
ContractError The typed refusal: code, location (a predicate index or a field such as scope.agreement or saved) and message.
ContractErrorCode The refusal codes: schema_violation, unknown_attribute, unit_not_convertible, bad_op_for_kind, department_unavailable.
Settings The configuration described above; every function reads Settings() from the environment when settings is omitted.
CONTRACT_SCHEMA_PATH The packaged JSON Schema of predicate documents (contract_version 1), as an importlib.resources resource: use read_text(), or importlib.resources.as_file() for a filesystem path.

Each call is one run_log run, exactly like the command: it validates its input, makes its requests through write_request() and records its run. Inputs are JSON values as json.loads returns them; a value JSON cannot hold (such as NaN or a Decimal) is refused with schema_violation, as pc refuses it. A refusal closes the run as refused and raises ContractError; any other error closes it as failed and propagates. max_items below 1 raises ValueError. The functions are synchronous and run their own event loop for their requests, so call them through asyncio.to_thread() from async code.

Database schema

Set the PILOTO_DATABASE_URL environment variable, then run this from the repository root to create or update the schema:

alembic upgrade head

Run alembic check to detect drift between the migration and the ORM models. SQLite uses the default database in place of the models' cli schema.

Snowflake migrations: pull-request check and deploy

Two workflows run the migrations against real Snowflake, each with its own identity from Mirkiux/snowflake-infra:

  • Check (ci.yml, job Snowflake migrations): on every same-repository pull request, push and manual run, it resets the scratch database PILOTO_AI_CLI_CI to base, runs alembic upgrade head and alembic check, then alembic downgrade base (also when the upgrade or check fails). It connects as PILOTO_AI_CLI_CI_MIGRATOR_SVC with role PILOTO_AI_CLI_CI_MIGRATOR, which has no access to PILOTO_AI, so a pull request can never drop deployed tables. Database, user and role are fixed in the workflow, not read from variables.
  • Deploy (migrations.yml): after CI passes on a push to main (or on manual dispatch), it runs alembic upgrade head on the commit CI checked against PILOTO_AI.CLI as PILOTO_AI_CLI_MIGRATOR_SVC with role PILOTO_AI_CLI_MIGRATOR, then fails unless alembic current reports head and alembic check finds no drift. It never downgrades. Deploys are serialized.

Maintainers must add:

  • Repository variable SNOWFLAKE_MIGRATIONS_ENABLED with value true (enables both).
  • Repository variables SNOWFLAKE_ACCOUNT and SNOWFLAKE_WAREHOUSE.
  • Repository secret SNOWFLAKE_CI_MIGRATOR_PAT: the role-restricted PAT of PILOTO_AI_CLI_CI_MIGRATOR_SVC (snowflake-infra bootstrap/15).
  • Environment snowflake-migrations with a deployment branch policy that allows only main, and in it the environment secret SNOWFLAKE_MIGRATOR_PAT: the PAT of PILOTO_AI_CLI_MIGRATOR_SVC (snowflake-infra bootstrap/13). Not a repository secret: this role owns the deployed tables, and pull requests can read repository secrets.

Both workflows build the SQLAlchemy URL with src/piloto_ai_cli/snowflake_url.py (standard library only), which URL-encodes the PAT, passes it as token with authenticator=programmatic_access_token, masks the encoded PAT and the URL, and fails naming any missing value. No LLM credentials are needed.

The check is skipped when SNOWFLAKE_MIGRATIONS_ENABLED is not true, its secret is absent, or the pull request comes from a fork. With the deploy enabled, a missing secret or variable fails the deploy at once. Snowflake DDL is not transactional: review migrations before merging, since a failed deploy may leave partial DDL in PILOTO_AI.CLI that needs a manual fix. Do not test deliberately destructive migrations against pilot data.

Scheduled health workflow

.github/workflows/health.yml runs pc --json health once a day (and on manual dispatch) against the live site and the pilot database. It never runs on pull requests, and it has a single daily schedule because live checks must not run more often than every 3 hours.

Live checks at most every 3 hours

The workflow enforces the 3-hour spacing itself. Before any live request, its spacing steps read this workflow's runs and their jobs through the Actions API (the job's token gets actions: read for this; the gh steps are the only run steps given it, and the project's Python decides with no token in its environment; the SHA-pinned actions/checkout, actions/setup-python and astral-sh/setup-uv also receive this read-only token through their default token inputs), and the "Enforce the 3-hour spacing" step fails with an error that names the earlier run and says when the next run is allowed if live checks started less than 3 hours ago. This covers manual dispatches (including force_failure tests), a run queued behind another in the pc-health concurrency group, and re-runs.

An earlier run counts when its "Run pc health" step started less than 3 hours before, measured from that step's start time. Every run of the workflow created in the last 31 days is considered (an older run can no longer be re-run), whatever its event, branch or result, and so is every earlier attempt of the current run; only the current attempt is left out. A run counts even if it failed or was cancelled after the live step started. A run does not count when its job or its live step was skipped (for example HEALTH_CHECK_ENABLED was off, the configuration check failed, or this spacing check stopped it), or when it was cancelled before the live step started, so a refused run never pushes the next allowed time back. If the runs or jobs cannot be read or are malformed, the spacing steps fail and the live checks do not run.

Every response the checks receive is stored by write_request() in the Snowflake payload stage, so the payload rows the run writes always point at durable storage. The run's health-report artifact holds the redacted report. Database credentials are redacted from the report, the issues and their comments.

Issues: one per failed check

When a check fails, or pc health cannot produce its report (reported as the workflow.pc_health check), the workflow handles each failed check on its own, keyed by the check's name (for example get_home.parse_home). The key is kept in a hidden <!-- pc-health-workflow check=<name> --> marker in the issue body, and only open issues the workflow itself opened (author github-actions[bot]) are considered:

  • No open issue for that check: the workflow opens a new issue with the failure, the full report and a link to the run, and assigns it to Copilot.
  • An open issue for that check: the failure is already with its owner, so no duplicate is opened. The workflow adds a comment to that issue with the run link and the reason, and assigns Copilot again only if nobody is assigned.
  • The check's issue was closed: closed issues are never reopened. If the check fails again, the workflow opens a new issue for it, assigned to Copilot.
  • Re-running the issues job (for example "Re-run failed jobs" after one Copilot assignment failed) records nothing twice. Every issue body and recurrence comment carries a hidden <!-- pc-health-workflow report=<run id>.<attempt> --> marker for the health job attempt that produced the report. The issues job reads every issue the workflow opened that changed since the report, open or closed, and its own comments there: a check whose report is already recorded anywhere gets no new issue or comment, even if that issue was closed since, and only Copilot is assigned again if the open issue that records it has nobody assigned. Issues and comments are stamped with the time the report was made, not the time the issues job ran.

A check that did not run (its reason starts with not run:) names the failed check that blocked it in the report's blocked_by field. It gets no issue of its own only when that check failed in the same report, which has the issue; the report still lists it. A check blocked by a precondition that is not a check (for example GET / listing no agreement with fichas, or an export with no PDF URL) has blocked_by: null and gets its own issue. Different checks never share an issue, so a new failure always reaches an owner even while an earlier issue is still open.

To test the issue path, dispatch the workflow with force_failure checked (at least 3 hours after the last run, like any run): it runs the real checks and adds a failed workflow.forced_failure check, which has its own key and so its own issue, titled "(forced test)". Real failures in the same run go to their own issues, and an open forced-test issue never absorbs a real failure. Close the forced-test issue once the workflow is verified.

Required configuration

Maintainers must add:

  • Two environments (Settings → Environments), each with a deployment branch policy that allows only main. The secrets below are environment secrets there (not repository secrets), so a workflow edited or dispatched on another branch cannot read them, and each secret is in the environment of only the jobs that use it:
    • pc-health, used only by the pc health job: holds PILOTO_HEALTH_DATABASE_URL.
    • pc-health-issues, used only by the Check the issue token and Health issues jobs, which run no project or third-party dependencies: holds COPILOT_ASSIGN_TOKEN.
  • Repository variable HEALTH_CHECK_ENABLED with value true. Without it the job is skipped.
  • Environment secret PILOTO_HEALTH_DATABASE_URL in pc-health: the SQLAlchemy URL of the pilot database that connects as the service user PILOTO_AI_CLI_HEALTH_SVC with role PILOTO_AI_CLI_HEALTH, database PILOTO_AI, schema CLI and warehouse PILOTO_AI_WH, for example snowflake://PILOTO_AI_CLI_HEALTH_SVC:<URL-encoded role-restricted PAT>@<account>/PILOTO_AI/CLI?warehouse=PILOTO_AI_WH&role=PILOTO_AI_CLI_HEALTH. The role and user are provisioned by Mirkiux/snowflake-infra; do not use the deploy or migrator role. The role is least-privilege and holds only what pc health uses:
    • USAGE on database PILOTO_AI, schema PILOTO_AI.CLI and warehouse PILOTO_AI_WH;
    • SELECT on every table in PILOTO_AI.CLI through a future grant, so each table the migrations create is readable (the foreign-key orphan checks);
    • INSERT and UPDATE on run_log (the run is opened, then closed) and INSERT on request_log and payload (append-only), granted per table. These exist only once the migrations are deployed and kept at head in PILOTO_AI.CLI and snowflake-infra applies with cli_tables_deployed = true (#165); until then the health job cannot write its run log;
    • READ and WRITE on stage PILOTO_AI.CLI.PAYLOADS (PUT of every response).
  • Repository variable PILOTO_PAYLOAD_STAGE with value @PILOTO_AI.CLI.PAYLOADS: the stage that keeps every raw response.
  • Environment secret COPILOT_ASSIGN_TOKEN in pc-health-issues: a user token (fine-grained PAT) of an account with access to the Copilot coding agent, with read and write access to this repository's actions, contents, issues and pull requests. The workflow's own token cannot assign Copilot. Two jobs reference it, each on its own fresh runner. Check the issue token runs first, with no permissions, no checkout and no install: it only tests whether the token is set and stops the run before any live check if it is not, since a failure could not reach an owner. Health issues runs after the pc health job, holds the only issues: write permission, installs no dependencies (it runs gh and the standard-library-only planner with plain python -I), and passes the token only to the gh calls over the issue plan. The pc health job, which installs runtime dependencies only (UV_NO_DEV=1), never references the token at all.

With HEALTH_CHECK_ENABLED set, a missing secret or variable, or a stage name that is not an unquoted Snowflake stage name, fails the run at once with an error naming it, before any check runs, and opens no issue. If the CLI cannot be installed (setup-uv or uv sync --locked fails, or hangs past its 5-minute step timeout), the run reports a failed workflow.install check and opens its issue like any other failure. pc health makes no LLM call, so the job passes a placeholder PILOTO_LLM_API_KEY rather than the real key.

Releasing

Releases are published by .github/workflows/publish.yml with PyPI trusted publishing (no API tokens). Each release tag is uploaded to TestPyPI first, through the testpypi environment, and to PyPI only after that succeeds, through the pypi environment. Each index needs a trusted publisher for owner Mirkiux, repository piloto-ai-cli, workflow publish.yml and the matching environment name.

  1. Open a release pull request that sets version in pyproject.toml (if it does not already have the target value, as 0.1.0 does) and moves the ## [Unreleased] entries of CHANGELOG.md under ## [<version>] - YYYY-MM-DD, with its release link, right before tagging.
  2. After it merges, create the GitHub release v<version> on main; every release needs one. Creating it pushes the tag, which runs the workflow; the workflow refuses a tag that does not match the project version. auto-tag.yml pushes the tag by itself only when a push to main changes the version; in that case create the release from the existing tag with gh release create v<version> --verify-tag. A release whose version is already on main, such as 0.1.0, is started by creating the release.
  3. When the run finishes, verify the release: in a clean virtualenv, pip install perucompras-cli==<version>, run pc --version and a replay pc query smoke, and check that the GitHub release v<version> exists. Record the result on the release issue.
  4. If the PyPI job fails after TestPyPI succeeded (for example, the PyPI trusted publisher is missing), fix the cause and use Re-run failed jobs on the same workflow run, within GitHub's 30-day re-run window. That keeps the successful TestPyPI job and the distributions it already uploaded. Do not use "Re-run all jobs" or delete and re-push the tag: either rebuilds the files, and TestPyPI rejects a same-named file with different contents, which stops the release before PyPI. Past that window, or if the code itself must change, release the next version instead.
  5. To stage a build on TestPyPI without releasing, run the workflow manually with target: testpypi: it uploads a unique <version>.devN build (N is the run number), so it never takes the release version. build-only, the default, only builds and checks the distributions. PyPI uploads only run for a v* tag push.

Checks

uv run ruff check
uv run ruff format --check
uv run mypy --strict src
uv run pytest

License

Copyright (c) 2026 Grupo Jaedmik. All rights reserved. Use of the CLI is subject to licensing by the copyright holder; see LICENSE.

Metadata

Release files for perucompras-cli 0.1.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 perucompras-cli 0.1.0
File Size Uploaded Provenance Actions
perucompras_cli-0.1.0.tar.gz 4.0 MB With provenance Details for perucompras_cli-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for perucompras-cli 0.1.0
File Interpreter ABI Platform Actions
perucompras_cli-0.1.0-py3-none-any.whl Python 3 none any Details for perucompras_cli-0.1.0-py3-none-any.whl

Total release size: 4.2 MB

Release files / perucompras_cli-0.1.0.tar.gz

Download URL perucompras_cli-0.1.0.tar.gz
Size 4.0 MB
Tags Source
SHA-256 checksum
How to use checksums
06872beb7dd07bdeb725040ee96993818846e2e70828cd70349a90301dd52bb3
BLAKE2b-256 checksum
How to use checksums
ba7b8ebeac482026c033baebfad646a5f060c1a7e7ff5e69331871aae0486b95
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Release files / perucompras_cli-0.1.0-py3-none-any.whl

Download URL perucompras_cli-0.1.0-py3-none-any.whl
Size 177.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cb257f566aefae34d24f9bcd6b6a1f08ae181a22c520a282487dc2d46be4bee9
BLAKE2b-256 checksum
How to use checksums
8091793cd747e0998def604bf54bc3b178c9ead5be755f22dbc61026cfd68cf4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

Security for perucompras-cli 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for perucompras_cli-0.1.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 27, 2026.

Transparency log

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.1.0 This release

2 release files Full 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