API Reference¶
Auto-generated API documentation via mkdocstrings. The pages below pull
docstrings directly from source, so they stay in sync automatically as
the codebase evolves.
Core¶
promptcanary.core.suite.CanarySuite(name, prompts, probes, *, description='', tags=None, default_system_prompt=None)
¶
Holds a collection of prompts and probes, and drives the canary run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Human-readable name for this suite. |
required |
prompts
|
list[CanaryPrompt]
|
List of :class: |
required |
probes
|
list[BaseProbe]
|
List of :class: |
required |
description
|
str
|
Optional description shown in reports. |
''
|
tags
|
list[str] | None
|
Optional tags for categorisation. |
None
|
Example::
from promptcanary import CanarySuite, LiteLLMProvider
from promptcanary.core.probes import JsonValidityProbe, StepByStepProbe
suite = CanarySuite(
name="production-agent",
prompts=[CanaryPrompt(text="Return JSON: {name: 'Alice', age: 30}")],
probes=[JsonValidityProbe(), StepByStepProbe(expect_steps=False)],
)
provider = LiteLLMProvider("openai/gpt-4o-mini")
result = suite.run(provider)
print(result.overall_score)
Source code in promptcanary/core/suite.py
from_yaml(path)
classmethod
¶
Load a CanarySuite from a YAML configuration file.
Expected YAML structure::
name: my-suite
description: Tests production agent behaviour.
probes:
- type: json_validity
- type: step_by_step
expect_steps: false
- type: keyword_presence
required_keywords: ["Paris"]
prompts:
- text: "What is the capital of France?"
expected_keywords: ["Paris"]
description: "Basic geography canary"
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Path to the |
required |
Returns:
| Type | Description |
|---|---|
CanarySuite
|
A fully configured :class: |
Source code in promptcanary/core/suite.py
run(provider, *, temperature=None, max_tokens=None, seed=None, show_progress=True)
¶
Run all prompts against the provider, apply all probes, return results.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
provider
|
BaseLLMProvider
|
The LLM provider to query. |
required |
temperature
|
float | None
|
Override default temperature (0.0 recommended). |
None
|
max_tokens
|
int | None
|
Override max_tokens. |
None
|
seed
|
int | None
|
Override seed for reproducibility. |
None
|
show_progress
|
bool
|
Whether to show a Rich progress bar. |
True
|
Returns:
| Type | Description |
|---|---|
CanaryRunResult
|
A fully-populated :class: |
Source code in promptcanary/core/suite.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 | |
to_yaml_template()
¶
Render this suite back to a YAML config string (useful for init).
Source code in promptcanary/core/suite.py
promptcanary.core.comparator.compare(baseline, current, *, regression_threshold=0.05, improvement_threshold=0.05)
¶
Compare a current run against a saved baseline snapshot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
baseline
|
BaselineSnapshot
|
Saved :class: |
required |
current
|
CanaryRunResult
|
Fresh :class: |
required |
regression_threshold
|
float
|
Minimum score drop (Δ) to declare a regression. |
0.05
|
improvement_threshold
|
float
|
Minimum score gain (Δ) to declare an improvement. |
0.05
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
DriftReport
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If suite names do not match (guards against comparing incompatible suites). |
Source code in promptcanary/core/comparator.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
promptcanary.core.models.CanaryPrompt
¶
Bases: BaseModel
A single prompt entry in a CanarySuite, with optional metadata.
promptcanary.core.models.CanaryRunResult
¶
Bases: BaseModel
Aggregated results for one full run of a CanarySuite against one provider.
by_category
property
¶
Group probe results by category.
duration_ms
property
¶
Total wall-clock duration of the run in milliseconds.
failed_probes
property
¶
Convenience: all probe results that did not pass.
overall_score
property
¶
Mean score across all probe results. Returns 1.0 if no probes ran.
pass_rate
property
¶
Fraction of probes that passed. Returns 1.0 if no probes ran.
promptcanary.core.models.BaselineSnapshot
¶
Bases: BaseModel
A saved baseline — the "known-good" state a future run is compared against.
promptcanary.core.models.DriftReport
¶
promptcanary.core.models.ProbeComparison
¶
Bases: BaseModel
Side-by-side comparison of a single probe between baseline and current run.
promptcanary.core.models.ProbeResult
¶
Bases: BaseModel
Result of running a single Probe against a single LLMResponse.
promptcanary.core.models.ProviderConfig
¶
Bases: BaseModel
Identifies and configures an LLM provider + model endpoint.
Probes¶
promptcanary.core.probes.base.BaseProbe
¶
Bases: ABC
Abstract base class for all PromptCanary probes.
Subclasses must implement :meth:evaluate.
Attributes:
| Name | Type | Description |
|---|---|---|
probe_id |
str
|
Stable machine-readable identifier (snake_case). |
name |
str
|
Human-readable display name. |
category |
ProbeCategory
|
High-level :class: |
description |
str
|
One-sentence description shown in reports. |
__call__(prompt, response)
¶
evaluate(prompt, response)
abstractmethod
¶
Run this probe and return a structured result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
CanaryPrompt
|
The :class: |
required |
response
|
LLMResponse
|
The :class: |
required |
Returns:
| Name | Type | Description |
|---|---|---|
A |
ProbeResult
|
class: |
Source code in promptcanary/core/probes/base.py
promptcanary.core.probes.base.probe(probe_id, *, name='', category=ProbeCategory.CUSTOM, description='')
¶
Decorator that turns a plain function into a registered BaseProbe.
Usage::
@probe("my_probe", name="My Custom Probe", category=ProbeCategory.CUSTOM)
def evaluate(prompt: CanaryPrompt, response: LLMResponse) -> ProbeResult:
passed = "hello" in response.content.lower()
return ProbeResult(
probe_id="my_probe",
probe_name="My Custom Probe",
category=ProbeCategory.CUSTOM,
prompt_id=prompt.id,
passed=passed,
score=1.0 if passed else 0.0,
details="Checked for greeting.",
)
Source code in promptcanary/core/probes/base.py
Providers¶
promptcanary.providers.base.BaseLLMProvider(config)
¶
Bases: ABC
Abstract base class for LLM provider adapters.
Subclasses must implement :meth:complete.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ProviderConfig
|
A :class: |
required |
Source code in promptcanary/providers/base.py
complete(prompt, *, system_prompt=None)
abstractmethod
¶
Send a prompt to the provider and return a structured response.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
CanaryPrompt
|
The :class: |
required |
system_prompt
|
str | None
|
Optional system-level instruction override. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
LLMResponse
|
class: |
Raises:
| Type | Description |
|---|---|
ProviderError
|
On any API or network error. |
Source code in promptcanary/providers/base.py
promptcanary.providers.litellm.LiteLLMProvider(model_id_or_config, *, temperature=0.0, max_tokens=1024, seed=42, **extra_params)
¶
Bases: BaseLLMProvider
LLM provider backed by the LiteLLM library.
This is the recommended provider for PromptCanary. It supports all major cloud providers and local models via a single unified interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id_or_config
|
str | ProviderConfig
|
Either a LiteLLM model string (e.g. |
required |
temperature
|
float
|
Sampling temperature (default: 0.0 for reproducibility). |
0.0
|
max_tokens
|
int
|
Max tokens in the response (default: 1024). |
1024
|
seed
|
int | None
|
Determinism seed (default: 42). |
42
|
**extra_params
|
object
|
Additional kwargs forwarded to |
{}
|
Examples::
# Quickstart
provider = LiteLLMProvider("openai/gpt-4o-mini")
# Anthropic
provider = LiteLLMProvider("anthropic/claude-3-5-sonnet-20241022")
# Local Ollama
provider = LiteLLMProvider("ollama/llama3", temperature=0.0)
# Full config
provider = LiteLLMProvider(
"openai/gpt-4o",
temperature=0.0,
max_tokens=2048,
extra_params={"response_format": {"type": "json_object"}},
)
Source code in promptcanary/providers/litellm.py
complete(prompt, *, system_prompt=None)
¶
Call the LLM via LiteLLM and return a structured :class:LLMResponse.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prompt
|
CanaryPrompt
|
The :class: |
required |
system_prompt
|
str | None
|
Optional system instruction. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
LLMResponse
|
class: |
Raises:
| Type | Description |
|---|---|
ProviderError
|
On API errors, auth failures, or network issues. |
Source code in promptcanary/providers/litellm.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | |
from_config(config)
classmethod
¶
Storage¶
promptcanary.storage.file.FileBaselineStore(directory='baselines')
¶
Stores and retrieves :class:BaselineSnapshot objects as JSON files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
|
str | Path
|
Directory where baseline JSON files are stored. Created automatically if it doesn't exist. |
'baselines'
|
File naming: {suite_name}__{model_slug}__{timestamp}.json
(URL-safe, avoiding characters that cause shell issues)
Example::
store = FileBaselineStore("baselines/")
snapshot = store.save(run_result)
loaded = store.load(snapshot.snapshot_id)
latest = store.load_latest("my-suite", "openai/gpt-4o")
Source code in promptcanary/storage/file.py
delete(snapshot_id)
¶
Delete a baseline by snapshot ID. Returns True if deleted.
Source code in promptcanary/storage/file.py
list_baselines(suite_name=None, model_id=None)
¶
List stored baselines with lightweight metadata (no full deserialization).
Returns a list of dicts with keys: path, snapshot_id, suite_name, model_id, created_at.
Source code in promptcanary/storage/file.py
load(snapshot_id)
¶
Load a snapshot by its ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
snapshot_id
|
str
|
The UUID of the snapshot to load. |
required |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If no snapshot with that ID exists. |
Source code in promptcanary/storage/file.py
load_from_path(path)
¶
load_latest(suite_name, model_id=None)
¶
Load the most recently saved baseline for a given suite and provider.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
suite_name
|
str
|
Name of the canary suite. |
required |
model_id
|
str | None
|
Optional model ID filter (e.g. |
None
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If no matching baseline exists. |
Source code in promptcanary/storage/file.py
save(run_result, *, note='', snapshot_id=None)
¶
Save a :class:CanaryRunResult as a baseline snapshot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
run_result
|
CanaryRunResult
|
The run to persist. |
required |
note
|
str
|
Optional human note (stored in the JSON). |
''
|
snapshot_id
|
str | None
|
Override the auto-generated ID (useful for testing). |
None
|
Returns:
| Type | Description |
|---|---|
BaselineSnapshot
|
The saved :class: |
Source code in promptcanary/storage/file.py
Reporting¶
promptcanary.core.reporter.Reporter(result)
¶
Generates reports for a single :class:CanaryRunResult.
Source code in promptcanary/core/reporter.py
print_terminal(console=None)
¶
Print a rich terminal report to stdout (or provided console).
Source code in promptcanary/core/reporter.py
to_html(path=None)
¶
Generate a self-contained HTML report. Optionally save to file.
to_json(path=None)
¶
Serialise the run result to JSON. Optionally save to file.
Source code in promptcanary/core/reporter.py
to_markdown(path=None)
¶
Generate a Markdown report string. Optionally save to file.
Source code in promptcanary/core/reporter.py
promptcanary.core.reporter.DriftReporter(report)
¶
Generates reports for a :class:DriftReport.
Source code in promptcanary/core/reporter.py
print_terminal(console=None)
¶
Print a rich terminal drift report.
Source code in promptcanary/core/reporter.py
to_markdown(path=None)
¶
Generate GitHub-flavoured Markdown drift report.
Source code in promptcanary/core/reporter.py
Visualization¶
promptcanary.utils.visualization.plot_score_history(snapshots, *, title='PromptCanary — Score History', output_path=None, mode='auto')
¶
Plot overall score over time from a list of baseline snapshots.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
snapshots
|
list[BaselineSnapshot]
|
Ordered list of :class: |
required |
title
|
str
|
Chart title. |
'PromptCanary — Score History'
|
output_path
|
str | Path | None
|
If set, save HTML to this path. |
None
|
mode
|
str
|
|
'auto'
|
Returns:
| Type | Description |
|---|---|
str | None
|
For plotly mode: the HTML string. |
str | None
|
For ascii mode: the printed sparkline (also printed to stdout). |
str | None
|
None if display-only (notebook mode). |
Example::
from promptcanary.storage.file import FileBaselineStore
from promptcanary.utils.visualization import plot_score_history
store = FileBaselineStore("baselines/")
snaps = [store.load_from_path(p) for p in sorted(Path("baselines").glob("*.json"))]
html = plot_score_history(snaps, output_path="trend.html")
Source code in promptcanary/utils/visualization.py
promptcanary.utils.visualization.plot_probe_heatmap(snapshots, *, title='PromptCanary — Probe Score Heatmap', output_path=None, mode='auto')
¶
Plot a probe x time heatmap showing score drift at probe granularity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
snapshots
|
list[BaselineSnapshot]
|
Ordered list of :class: |
required |
title
|
str
|
Chart title. |
'PromptCanary — Probe Score Heatmap'
|
output_path
|
str | Path | None
|
If set, save HTML to this path. |
None
|
mode
|
str
|
|
'auto'
|
Returns:
| Type | Description |
|---|---|
str | None
|
HTML string or ASCII table. |
Source code in promptcanary/utils/visualization.py
promptcanary.utils.visualization.plot_drift_timeline(drift_reports, *, title='PromptCanary — Drift Timeline', output_path=None, mode='auto')
¶
Plot a regression-count timeline from a series of DriftReport objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
drift_reports
|
list[DriftReport]
|
Ordered list of :class: |
required |
title
|
str
|
Chart title. |
'PromptCanary — Drift Timeline'
|
output_path
|
str | Path | None
|
If set, save HTML to this path. |
None
|
mode
|
str
|
|
'auto'
|