8000 GitHub - pf-c/PromptGuard · GitHub
[go: up one dir, main page]

Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

PromptGuard

PromptGuard is a deterministic regression testing framework for LLM powered applications. You define test suites in YAML, run them concurrently across OpenAI, Anthropic, and Google Gemini, evaluate responses with deterministic assertions only, persist run history in local SQLite, and compare against previous CI runs.

PromptGuard never uses LLM judges, semantic similarity embeddings, or probabilistic scoring. Identical inputs and configurations always produce identical scores.

Requirements and installation

You need Python 3.13 or newer and uv.

Clone the repository and install dependencies with uv:

uv sync

Or install the package into an existing environment:

pip install .

Set the API key environment variables for the providers your suites target:

export OPENAI_API_KEY="your-openai-key"
export ANTHROPIC_API_KEY="your-anthropic-key"
export GEMINI_API_KEY="your-gemini-key"

You can also override the environment variable name per provider with api_key_env in your suite YAML.

Quick start

Validate a suite without making any network calls:

uv run promptguard validate examples/smoke_valid.yaml

Run the suite, persist results to SQLite, and generate JSON, HTML, and JUnit XML reports:

uv run promptguard run examples/smoke_valid.yaml \
  --db .promptguard/promptguard.db \
  --report-dir .promptguard/reports

YAML test suites

A PromptGuard suite is a YAML file with version: "1", a name, one or more providers, and one or more tests:

version: "1"
name: "support-assistant-regression"
description: "Deterministic checks for customer support replies"

defaults:
  timeout: 30.0
  max_retries: 2
  concurrency: 4
  providers: ["openai-mini"]
  parameters:
    temperature: 0.0
    max_tokens: 300

providers:
  - id: "openai-mini"
    provider: "openai"
    model: "gpt-4o-mini"
    rate_limit:
      max_rate: 60
      time_period: 60.0

tests:
  - id: "refund-policy-json"
    description: "Ensure structured refund policy output"
    tags: ["json", "policy"]
    prompt:
      - role: "system"
        content: "Respond only with valid JSON matching the requested keys."
      - role: "user"
        content: "Summarize the 30 day refund window."
    assertions:
      - type: "valid_json"
        critical: true
      - type: "json_path_exists"
        path: "$.refund_days"
      - type: "json_schema"
        schema_def:
          type: "object"
          required: ["refund_days", "summary"]
          properties:
            refund_days:
              type: "integer"
            summary:
              type: "string"
      - type: "max_length"
        limit: 500
        weight: 0.5
        severity: "warning"

Providers and parameters

Each entry under providers supports:

Field Required Description
id Yes Unique identifier referenced by tests or defaults.providers.
provider Yes One of openai, anthropic, or gemini.
model Yes Model identifier passed to the provider SDK.
api_key_env No Custom environment variable name for the provider API key.
concurrency No Maximum concurrent requests for this provider.
rate_limit No Token bucket limit with max_rate and time_period (seconds, default 60.0).
parameters No Generation settings: temperature 8000 , max_tokens, seed, top_p.

Parameter precedence is test.parameters over provider.parameters over defaults.parameters. If you request seed on a provider that does not support deterministic seeds, validation emits a warning (or fails when --strict-capabilities is passed).

Prompts and flaky retries

A test prompt can be either a plain string or a list of {role, content} messages where role is system, user, or assistant.

PromptGuard separates transient API retries from flaky assertion retries:

  • API retries (defaults.max_retries and defaults.timeout) retry only transient transport or server failures (HTTP 429, 500, 502, 503, 504, timeouts, connection errors).
  • Flaky retries (flaky on defaults or a test) rerun a test after an assertion failure and mark the test FLAKY when it meets pass_threshold within max_attempts:
flaky:
  enabled: true
  max_attempts: 3
  pass_threshold: 2

Deterministic assertions

Every assertion supports weight (float, default 1.0), critical (bool, default false), and severity (error, warning, or info, default error). A failing critical: true assertion fails the test regardless of weighted score.

Type Fields Behavior
exact_match value, case_sensitive (default true) Response equals value.
contains value, case_sensitive (default true) Response contains substring value.
contains_all values Response contains every string in values.
contains_any values Response contains at least one string in values.
contains_none values Response contains none of the strings in values.
regex pattern Response matches the regular expression pattern.
regex_not pattern Response does not match pattern.
valid_json Response parses as valid JSON.
json_schema schema_def Parsed JSON validates against schema_def.
json_path_exists path JSONPath expression starting with $ resolves to at least one match.
min_length limit Response character length is at least limit.
max_length limit Response character length is at most limit.
numeric_range min_value, max_value Parsed number falls within inclusive bounds (at least one bound required).
numeric_equals value, tolerance (default 0.0) Parsed number equals value within tolerance.

CLI commands

Run uv run promptguard --help or uv run promptguard <command> --help to inspect all options.

promptguard validate

Validate a YAML test suite locally without making provider calls:

uv run promptguard validate path/to/suite.yaml

promptguard run

Validate, execute, persist to SQLite, compare against a baseline, and write reports:

uv run promptguard run path/to/suite.yaml [OPTIONS]

Common options:

  • --db PATH: SQLite database path (defaults to PROMPTGUARD_DB or .promptguard/promptguard.db).
  • --baseline MODE: Baseline selection: auto (latest compatible run), <run_id>, or none.
  • --force-baseline: Allow comparing against an incompatible baseline run.
  • --score-drop-threshold FLOAT: Maximum allowed average score drop before flagging a regression (default 0.05).
  • --store-responses: Persist raw model responses in SQLite and reports (redacted by default).
  • --fail-fast: Stop remaining tests on the first ERROR or FAIL.
  • --strict-flaky: Treat FLAKY outcomes as CI failures.
  • --strict-capabilities: Fail on unsupported provider parameters such as seed.
  • --report-dir PATH: Write report.json, report.html, and report.junit.xml to a directory.
  • --json PATH, --html PATH, --junit PATH: Write individual report files to explicit paths.
  • --ci MODE: CI integration mode: auto, github, gitlab, or none.
  • --no-ci: Disable CI annotations and summary output.
  • --ci-summary PATH: Write GitLab CI Markdown summary to a custom path.

promptguard history

List persisted runs from the local SQLite database:

uv run promptguard history --db .promptguard/promptguard.db --limit 20

Filter by suite with --suite <name> or paginate with --offset <n>.

promptguard compare

Compare two persisted runs for deterministic regressions:

uv run promptguard compare <current_run_id> <baseline_run_id> --db .promptguard/promptguard.db

promptguard report

Regenerate JSON, HTML, and JUnit XML reports from a persisted run:

uv run promptguard report <run_id> --db .promptguard/promptguard.db --report-dir .promptguard/reports

Exit codes

Code Meaning
0 No blocking failures
1 Assertion failure or configured regression
2 Configuration or validation error
3 Provider or infrastructure error
4 Internal framework error

CI usage

PromptGuard runs in CI without any hosted backend. Persist the SQLite database as a CI artifact between runs so each run can compare against the previous compatible baseline.

Ready to use starter workflows are included in the repository:

When --ci auto is active, PromptGuard automatically detects GitHub Actions and GitLab CI environments, emits failure annotations or Markdown job summaries, and writes JUnit XML reports compatible with CI test viewers.

Development and release checks

Run the full verification suite:

uv run ruff check
uv run pyrefly check
uv run pytest

Build source and wheel distributions:

uv build

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0