How promptfoo cost and latency assertions catch slower, pricier prompts
promptfoo supports cost and latency assertion types, and a threshold value makes an eval fail when a run crosses the limit you set. The situation this addresses is familiar: a team changes a prompt, swaps the model or adjusts a retrieval step, then learns about a higher bill or slower responses only after release. Cost and latency checks move that discovery to the pull request. They sit in the same assert list as your quality assertions, so a single run can flag an answer that is accurate but slow, or one that is fast but no longer correct.
Both checks run locally. promptfoo evals run on the machine that starts them and call your own provider directly, so the timing and cost figures come from requests made with your credentials. Before you set limits, confirm that your provider returns the usage data the cost check depends on, and read the assertions reference for the units each threshold expects. Set thresholds from a baseline run of the current prompt, so a failure shows that the change moved the numbers.
Treat these results as a regression signal and keep the billing record separate. The cost value is calculated during the eval, so it may differ from your provider invoice, and it does not account for spend from other applications that share the same API key. Use your provider's usage reporting for chargeback and budget decisions. Record the baseline and the threshold values the team agreed on in the same repository as the eval config, so a reviewer can tell later whether a limit was tightened on purpose. Ask the people who own the prompt to explain any threshold change in the pull request description.
Assertion types and threshold options for cost and latency checks
This table compares the cost and latency assertions, the threshold option and the custom code assertions that accept thresholds in promptfoo. Read each row for what the check measures, where it fits a pass or fail gate and what to confirm in the docs for your installed version. Set every limit from your own baseline runs before you enforce it.
| Assertion | What it measures | When it fits a gate | What to confirm |
|---|---|---|---|
| Cost | The spend attributed to one response from the provider, checked against the threshold. | Catches prompt or model changes that make each answer more expensive in a suite with a stable test set. | How cost is calculated for each provider and whether cached responses still report a cost. |
| Latency | How long the provider took to return the response, checked against the threshold. | Protects a feature with a response time expectation, such as an interactive chat flow. | Whether the time includes retries and how concurrent runs affect the measured value. |
| Threshold option | The limit a cost, latency or code assertion must meet to pass, set as a single value. | Any gate where one number decides pass or fail, kept in config so changes show in review. | Which assertion types accept a threshold in your version and how it combines with other checks in the same test. |
| javascript | A custom check written in JavaScript that inspects the output and can apply a threshold. | Per-feature budgets or cost rules that need logic beyond a single number. | The function signature, how the threshold reaches the function and the Node.js version it runs on. |
| python | A custom check written in Python that inspects the output and can apply a threshold. | Teams that already compute cost or timing in Python or read usage data from their own logs. | How the Python interpreter is provided in CI, the function signature and how the threshold is passed. |
| ruby | A custom check written in Ruby that inspects the output and can apply a threshold. | Teams with existing Ruby helpers for usage or timing data that they want to reuse. | Whether the Ruby runtime is in your runner image, plus the function signature and threshold handling. |
How a cost or latency gate moves through one eval run
The diagram starts on your machine, where the config and test cases feed the provider call. promptfoo runs locally and talks directly with the model, so the response, its token usage and its timing return to the same run. Those values go to the cost and latency assertions, which compare them with the thresholds you set and mark each test as pass or fail. Results then go to the report and to your CI pipeline, where your own rules decide whether a failed gate stops the build. Check that your thresholds match the units your provider reports, and that your pipeline treats assertion failures as failed builds.
Cost and latency gates run locally, and your pipeline decides on failure.
Setting up cost and latency gates in a promptfoo config
This sequence moves cost and latency from something a team notices after release to a check that runs on every change. You pin the promptfoo version, record a baseline, set thresholds from that baseline, prove the gate fails on a heavier prompt, and connect the result to your pipeline's exit code. The output is a config that blocks a merge when spend or response time crosses a limit your team chose.
Pin the promptfoo version
Install one exact promptfoo release, 0.124.1, on Node.js 22.22.0 or newer, and record both versions next to the config. Baseline numbers can shift after an upgrade, so the same binary must produce the baseline and every later gate. Upgrades should happen as a separate, reviewed change with a fresh baseline. Check that the CLI reports the pinned version and that the Node.js version meets the minimum before you run anything else.
Record a baseline eval
Run the eval on the prompt and model you ship today, with the response cache cleared so timings reflect live provider calls. Keep the rest of the config unchanged and write the results to a JSON file. The baseline is the reference for every threshold, so store the file in version control or your artifact store with the pinned version noted. Check that each test case shows a cost and a latency value, and note the slowest and most expensive cases for the next step.
Add cost and latency assertions
Add a cost assertion and a latency assertion to
defaultTestor to the individual tests that matter most, and set each threshold above the matching baseline value with headroom your team agrees on in writing. Confirm the units each assertion expects for your pinned version in the promptfoo assertions documentation before you write any numbers. Check that the config validates without errors and that the file is saved aspromptfooconfig.yamlin the project you will run from CI.Run the gated eval unchanged
Run the updated config against the same prompt and model used for the baseline. Every cost and latency gate should pass on this run. Live latency varies between calls, so if a gate fails here, widen that threshold with a written reason and run again before you go further. Check that all gates report as passed and that the command finishes with a zero exit status.
Trigger a slower or longer prompt
On a separate branch, make a deliberately heavier change. For example (illustrative), add a long block of instructions to the system prompt, or point the same test set at a larger model. Run the eval with the same config. The purpose is to confirm the gate catches regressions, so keep the change small and record exactly what you changed. Check that the run reports failed cost or latency assertions and does not pass silently.
Confirm failing tests and thresholds
Open the results and list the test names that failed, along with the observed cost or latency value and the threshold it crossed. Confirm that each failure comes from a cost or latency assertion. Separate out quality assertions and provider errors, since those need their own handling in long runs. Check that every failed row names one of your thresholds and the value that crossed it. If a failure cannot be traced this way, fix the assertion before connecting the gate to a pipeline.
Wire the exit code into CI
Run the eval as a required CI step so that a non-zero exit code from promptfoo fails the job and blocks the merge. Confirm the exit behavior for your pinned version in the promptfoo documentation before you rely on it. Use the same pinned version in the pipeline image that you used for the baseline. Check that the slower branch turns the job red, that the unchanged branch turns it green, and that the failing job log keeps the threshold that was crossed as evidence.
Which prompt and model changes these thresholds are built to catch
Cost and latency assertions catch changes that move spend or response time, and most of those changes come from a small set of edits. A longer system prompt adds input tokens to every call in the suite, so the cost assertion moves even when the answers look the same. Added few-shot examples do the same, and more retrieved context does it in retrieval-augmented features, where each query can pull in more passages. A larger model raises the price per token and often the time to first token. Extra tool calls add round trips, and a changed output length shifts the bill and the latency together, because generated tokens usually cost more and take longer than input. Check each suite against this list before a release, and confirm the exact pricing and assertion syntax in the promptfoo assertions documentation.
A threshold only means something when the baseline and the candidate run under the same conditions, so fix the inputs and record the run configuration. Keep the test file, variables and dataset version identical between runs, and store them in version control next to the prompt. Write down the model name and version, provider parameters such as temperature and maximum output tokens, the promptfoo version, the concurrency setting and whether the response cache was on. A cached answer returns almost instantly, which would make latency look better than it is. Compare a candidate only against a baseline captured with the same record. If any field differs, the numbers describe the configuration change as much as the prompt change, so re-run the baseline.
Latency is noisy, so a single run is not enough to gate on. Provider load, network conditions and queueing change response times between runs even when nothing in your configuration has changed. Before you set a latency threshold, run the unchanged baseline several times and measure how far the results spread. Then decide, in writing, how many runs each gate uses and which statistic it reads, such as the mean, the median or a high percentile like p90 or p95. Percentiles show the tail behavior users feel, but they need more samples to be stable. Token counts usually repeat more closely than timing, so set the cost threshold separately and confirm that pattern on your own runs.
Why raw cost and latency numbers can mislead a gate
A cost or latency threshold is only as honest as the number behind it. The figures a run records can include time and spend that never reached the provider, time spent waiting behind your own concurrency settings, and prices that differ from what the invoice shows. Check each source below before you set a gate or accept a failing one.
Cached responses skip the provider
When a cache hit is returned, the run records almost no latency and no provider spend, so the average can look faster and cheaper than the live model really is. A prompt change that alters output can still pass the gate if older cached answers are served. Before trusting the gate, confirm whether the run used cache hits, then measure a cold run with the cache cleared or disabled and compare it with a warm run. Configuring the promptfoo response cache covers how to avoid stale results after a prompt or provider change.
Concurrency inflates wall-clock time
Suite duration depends on how many test cases run at once. If concurrency queues requests, a case's measured time may include waiting for a free slot rather than model response time, so a duration threshold can fail even when the model answers quickly. Compare per-request latency with total suite duration, and record the concurrency value beside every baseline so the gate compares runs with identical settings.
Rate-limit waits and retries
A provider rate limit or transient error can hold a request for seconds before a retry succeeds. If that retry wait is folded into the case's latency, the gate measures quota handling and retry behavior alongside the model or prompt you changed. Check whether any case was retried, keep error results separate from failed assertions, and exclude throttled runs from the latency baseline. Handling provider rate limits in promptfoo and Retrying failed promptfoo eval results cover the settings involved.
Pricing and token counts differ from invoices
A cost figure is an estimate built from token counts and the prices the run knows about. Your invoice reflects billed tokens, cached input rates, any discounted tiers and any gateway markup, so the local figure can drift from what finance sees. Before setting a cost threshold, confirm which price table the run uses, whether token counts cover every type the provider bills for, and reconcile one sample run against a billed invoice period. The assertions documentation explains how threshold values apply to each assertion type.
Assertions and metricsReporting promptfoo spend per suite for each audience
Engineers reading a local run are usually checking a prompt or model change on their own machine before it reaches the pipeline. The terminal output and the output file from that run show which test cases exceeded a cost or latency limit, so the question to answer is which case got slower or more expensive after the change. The assertion behavior is described in the promptfoo assertions documentation.
- Output: the terminal table plus any file you write for the run, opened in the web viewer or a JSON reader. Confirm which formats your installed version writes before you build a habit around one.
- Suite naming: keep one config file per suite and name it for the suite, such as
checkout-summary.yaml, so the source file identifies the suite without extra work. - Grouping: one run per config means totals per suite come from the run itself, with no parsing of test names.
- Cache effects: cached responses may not call the provider, so a local run can show less spend than the same run on a cold cache. Confirm how your version counts cached results.
- Invoice gap: a local run shows only your own traffic and the figures promptfoo calculates, so it does not prove what the provider billed.
Before you trust the totals, check one test case by hand against the token counts the provider returned.
A CI pipeline produces the artifact that outlives the job logs, so the report has to stay readable after the run ends. The pipeline runs each suite on every build and saves a machine-readable file next to the build record. Its job is to answer which suite spent what on which build, for the people who review a release later. The artifact records what the pipeline requested and what promptfoo calculated, which may differ from what the provider invoiced for that build.
- Output: a file the pipeline writes and uploads as a build artifact, usually JSON or JUnit XML. Confirm that the installed version writes the cost and latency values in the format you pick before you write a parser for it.
- Suite naming: build the file name from the suite name plus the build identifier, such as
checkout-summary-<build-id>.json, so files sort by suite and by build. - Grouping: group by the suite prefix in the file name or by the config path recorded in the run, and do not rely on test description text, which people edit.
- Retention: artifacts expire under your CI retention setting, so decide how long spend history must survive and copy the summaries to durable storage if needed.
- Reruns: retries and reruns after provider errors add tokens to the same build. Decide whether the artifact keeps the first attempt, the last or both, and label it.
Check that each artifact names the config file and the installed promptfoo version, so a later reader can reproduce the figures.
Finance and product owners ask a different question: what did each suite cost in a billing period, and which feature does that suite belong to. They should not read raw eval files. They need a summary built from the pipeline artifacts, with suite names mapped to the product feature and cost center that pays for them. That summary supports planning and review, and the provider invoice remains the record of what was charged.
- Output: a summary table or sheet generated from the build artifacts, with one row per suite per period. Ask the engineering team to produce it on a schedule so the figures are not assembled by hand.
- Suite naming: keep a mapping file in the same repository as the configs that links each suite name to a feature and cost center. Changing a suite name mid-period splits its history, so agree renames in advance.
- Grouping: sum by suite and period, then by feature through the mapping. Keep unmapped suites in a visible line so totals still reconcile.
- Price basis: the cost figures depend on the prices promptfoo holds for each model or the prices you configure. Confirm how the installed version gets those prices, when they were last updated and whether you can override them for negotiated rates.
- Invoice gap: the report cannot show taxes, credits, committed-use discounts or the provider's billing-period cutoff, so totals may differ from the invoice. Request usage exports from the provider and reconcile them monthly.
Agree the reconciliation method with the engineering lead before the first report goes to finance, and record the promptfoo version used to produce each one.
Handling the data inside cost and latency reports
Decide who may read a cost and latency report before the first run, because the report is built from the same prompts, responses and test data as the eval itself. promptfoo is designed to run completely locally: evals run on the machine or CI runner where you start them and talk directly with the LLM provider you configure. During the run, prompts, outputs and provider keys stay under your control and go to that provider directly. Sharing results is a separate step that you choose to take. Confirm with your security team which runners and workstations may hold provider API keys, because the environment variables that authenticate each call live in the same process that writes the report. The promptfoo introduction describes the local model in more detail.
A shared report can carry more than scores. Depending on the output you produce, it may contain the rendered prompts, the model responses, the test variables that filled each prompt template, and the timing and token figures for each case. If test variables come from production records or contain personal data, the report inherits that data. Treat every report as a copy of the test data. Readers are whoever can open the file or the CI artifact, so check read access to the repository, pipeline logs and artifact storage in your CI system, and confirm how long artifacts are retained. The report is written to the output path in the runner workspace and persists only as long as the CI system keeps the artifact. Confirm the path, access list and retention for your platform before the first pipeline run that writes a report.
The output format sets how much leaves the run. Formats that keep full records, such as json and jsonl, expose everything described above, while summary formats carry fewer fields. Choose the smallest format that answers the reader's question, and check what each format includes in the version you run. The self-hosted promptfoo server is a separate exposure point. It is an Express app that stores data in a local SQLite database, which cannot be shared across replicas and has no RBAC, built-in authentication or SSO. The server is not recommended for production use. If a team uses it, restrict network access, keep it off public networks, and plan a different production design before reports from sensitive suites are stored there. The self-hosting documentation lists these limits.
Limits to confirm before relying on cost and latency gates
Cost and latency gates are only as trustworthy as the numbers behind them. Each item below is a check to run in your own environment before a threshold blocks a release or a spend report goes to finance. Confirm them once per promptfoo version and provider setup, and again after upgrades.
Assertion syntax and threshold behavior
Confirm the assertion syntax and threshold behavior for your pinned version. Cost and latency assertions take threshold values, and the exact keys and comparison rules should be read from the documentation for the release you run. The current npm release requires Node.js 22.22.0 or newer, so check that your runners meet it. Then run a deliberately failing case and confirm the gate exits non-zero.
Assertions docsToken prices against contracted rates
Cost figures are only as accurate as the price table behind them. Cost estimates multiply recorded token counts by per-token prices from a table that you or the tool maintains, so confirm each model's rate matches your contract. List prices can differ from negotiated rates, and cached-input or batch usage may be billed at different rates than the default. Reconcile one suite's estimate against a provider invoice before a budget gate depends on it.
Latency measured against network and queueing
Measured latency may include time you do not control. Confirm whether the number promptfoo records covers only the model call or also includes DNS, TLS, network hops, proxy or gateway time, and time a request waits in a provider's queue or your own concurrency limiter. Cold starts and shared-capacity contention can move the figure between runs. Compare the recorded values with timings from your own load tests before deciding a latency threshold reflects the model itself.
Usage reporting from custom providers
No token usage means no cost gate. Built-in providers generally return usage data, but a custom HTTP, Python or JavaScript provider only supplies token counts if your code returns them in the fields the documentation describes. Check that a test run populates token counts and cost for every case, and that cached responses do not report stale or zero usage. Treat a missing value as a gap to fix before the gate is trusted.
Shared history on self-hosted servers
Self-hosted storage limits shared trend data. The self-hosted app stores its data in a local SQLite database that cannot be shared across replicas, and it has no built-in authentication, RBAC or horizontal scaling. If your cost trends need one history visible to the whole team, confirm whether a single instance can hold it and how it will be backed up. The self-hosting documentation also says it is not recommended for production use.
Self-hosting docsQuestions teams ask before adding cost and latency gates
How much effort does it take to add cost and latency gates to promptfoo?
The effort is mostly configuration and agreement on limits, and it scales with scope. The main drivers are how many suites, prompts and models you need to gate, how many test cases already exist, and how many people must approve a threshold before it can block a merge. promptfoo supports cost and latency assertion types, and threshold values apply to them, so the core work is choosing which cases carry a limit and setting each limit from measured results. A stable suite with one owner moves quickly. Several applications with no shared test data take longer, because each one needs its own baseline. Ask any partner to split the estimate into configuration, baselining and CI wiring so you can see where the time goes.
How long do setup and baselining take for promptfoo cost gates?
No single duration applies to every team, so the honest answer is to tie the timeline to steps. Setup means wiring the cost and latency assertions into your existing suite. Baselining means running the suite several times on the current prompt and model to see normal spend and response time, then setting limits with room for expected variation. Run length depends on the number of cases, how long your target model takes per case, and how many repeat runs you need for stable numbers. Provider rate limits and retries can stretch a run, so schedule the baseline around quota windows. In the written scope, ask for the number of baseline runs and the acceptance criteria for a baseline, so the timeline follows from observable steps.
What does the team need to provide for cost and latency gates?
The work needs three things from your side: representative test data, working provider access, and a named baseline owner. Test data should reflect production-like traffic, including long inputs, edge cases and the prompts users actually send, because limits set on easy cases may not hold in production. Provider access means API keys or service accounts for every model under test, with enough quota and billing visibility to see spend per suite. The baseline owner decides which measurements become thresholds, signs off when a model or prompt change is expected to move cost or latency, and keeps the limits current. Without that person, gates tend to be loosened after the first noisy failure. Confirm these three items before scoping, and name the people who approve threshold changes in the written scope.
Can one internal engineer set up promptfoo cost and latency gates alone?
One engineer who already runs promptfoo evals can add the gates alone, as long as someone else owns the threshold decisions. The engineer needs protected time for assertions, baseline runs and CI wiring, plus access to the models and billing data that set the numbers. Where nobody has run evals before, or the suite spans several applications, one person often becomes the bottleneck for review and reruns. A simple test is whether the engineer can explain, for each limit, where the number came from and who approved it. If so, an internal build is a sound option. If not, a partner can fill the gap in the written scope.
What drives the cost of outside help with promptfoo evals?
Outside cost follows the written scope, and promptfoo itself is licensed under the MIT license, so the spend is for people's work. The main drivers are:
- The number of applications, suites and prompts that need gates
- The number of providers and models under test, each with its own access setup
- Whether test data already exists, needs cleaning, or must be created
- How deep the integration goes, from local runs to CI wiring and per-suite spend reports
- How many review rounds and approvers each threshold needs
Setup and baselining are one-time work. Threshold upkeep after model or prompt changes recurs, so ask whether the quote covers it or a separate retainer does.
How do I request a quote for a cost and latency gating engagement?
Send a written description of the scope and DeployOpen will prepare a quote from it, since DeployOpen does not publish a price list. Most engagements are fixed-scope, so agree the scope, deliverables and timeline in writing before work starts. Include:
- The applications, suites and prompts to gate
- The providers and models under test, and how access will be granted
- The test data source and who will supply it
- The CI system and where results should go
- Named owners for baselines and threshold approvals
Say whether you want one-time setup, ongoing upkeep through a retainer, or both, since each is scoped differently. A quote follows from the written scope, so specific requests get specific quotes.
What do cost and latency thresholds catch that pass-fail checks miss?
They catch regressions that quality checks pass. In an illustrative case, a longer system prompt raises token use on every call while answers stay correct, so the quality assertions pass and spend climbs. promptfoo supports cost and latency assertion types, and threshold values apply to them, so a run can fail when a case goes over its limit. Set limits from repeated runs and keep a margin for normal variation, or the gate will fire on noise. Keep provider errors separate from assertion failures, so an outage does not look like a regression. Review the per-suite spend report after each model change to see where the budget moved.
How DeployOpen scopes and supports promptfoo cost and latency gates
DeployOpen scopes cost and latency gates for promptfoo as a fixed-scope piece of work, agreed in writing before anything is built. The work covers the assertion thresholds, the eval suites they sit in, and the reporting that shows spend per suite, in infrastructure you control. Ongoing tuning and continuous testing can follow as a retainer.
How we scope
- Written scope lists which assertions gate cost and which gate latency, per suite and per model.
- Scope records the baseline run, the token and time measurements each threshold is set against, and who approves changes.
- Scope confirms which providers return token usage, since cost checks depend on the usage data each response reports.
How we build
- Assertions are added to existing eval suites so every prompt or model change runs against the same cases.
- Thresholds are set on cost and latency assertions and tuned against a recorded baseline before they fail a build.
- Spend per suite is reported from the same run, so finance and engineering read one set of numbers.
How we hand over
- Handover includes the eval config files, threshold values with their baseline data, and the commands used to run them.
- Your team receives a runbook for changing thresholds, including who reviews a change and how a baseline is re-recorded.
- Documentation states which model prices were used for spend figures and when those prices must be checked again.
How we support
- Ongoing support is available as a retainer for upgrades, threshold reviews and continuous testing of the gates.
- Upgrades of promptfoo are planned and tested against the baseline, so a version change does not silently shift results.
- Provider price and model changes are reviewed, so spend figures and cost thresholds stay current.

