Using promptfoo as a Node.js library with evaluate()

Running promptfoo evals from TypeScript or JavaScript with evaluate() lets your own code own the test run, its environment and its results. This page covers when to embed it, how to scope env overrides per call and how to handle results.

On this page

When teams call promptfoo's evaluate() from their own code

Teams that already run a service or test harness in Node.js may want LLM evals to run inside that code rather than through the CLI. promptfoo exposes an evaluate(testSuite, options) function for this purpose, and each call uses its own environment overrides without inheriting a previous evaluation. That isolation matters when one harness runs several suites against different models, keys or settings, because a value set for one run should not leak into the next. The supported route is the documented Node package, so start from the promptfoo Node package guide and build against its signatures rather than copying CLI behavior into your code.

promptfoo is released under the MIT license, so embedding it in an internal service or test harness does not by itself create a licensing obligation beyond the license terms. Confirm the license text and any third-party dependencies with your legal and procurement teams before you ship. The package requires Node.js 22.22.0 or newer, according to the current npm release, so check your runtime version against the version you pin. Because evals run on your machine and talk directly with the LLM, the harness needs network access to each model endpoint and the credentials for it. Plan where those keys live and who can read the environment that the harness passes to each call.

Embedding changes who owns the run. Your code now decides when evaluations start, how failures are reported and where results are stored, so decide those points before the first call. Ask the team that will maintain the harness to confirm how it handles errors thrown by a single evaluation, how it logs prompts and outputs, and whether test data with sensitive content will appear in those logs. Run a small suite from your harness against a non-production key first, and compare its results with the same suite run through the CLI to confirm that your wrapper is not changing the outcome.

What you need before embedding promptfoo in Node.js

Embedding promptfoo with evaluate() puts an npm package, a Node.js runtime, provider credentials and network access into one host that you control. Each card below is a prerequisite you can verify before the first call, and each one fails in a different way if it is missing.

Node.js runtime version

The npm release 0.124.1 requires Node.js 22.22.0 or newer. Older runtimes in a base image or CI container can install the package and then fail at import or at runtime, so the error can look unrelated to promptfoo. Check the version on the exact host that runs your code, including any container image and CI job image, not only on your laptop.

promptfoo on npm

The promptfoo npm package

Install the promptfoo package in the project that calls evaluate(), and pin the version in your lockfile so that a routine install does not change behavior between runs. Confirm the current release against the npm registry and the GitHub releases page before you pin it, because the version in your plan may be older than the one you install. Record the pinned version in your eval results so a later regression can be traced to an upgrade.

promptfoo releases

Model provider credentials

Every provider in your test suite needs its own credential, usually supplied as an environment variable that the process reads at call time. Decide where these live before writing code: a secrets manager injected into the job, not values committed to the repository or pasted into a config file. Use a separate, scoped key for evals so that test traffic can be budgeted and revoked without touching production keys.

Network paths to model endpoints

Because promptfoo runs locally and calls the model directly, the host running evaluate() must reach each provider endpoint and any application under test. Check outbound HTTPS rules, egress proxies, DNS and allowlists in both the runner and the target network. For private or self-hosted models, confirm that the host can reach the inference address and that TLS trust is configured, since a blocked call often surfaces as a generic request failure.

The host that runs the code

Decide whether the Node.js code runs on a CI runner, a scheduled job, a service in your cluster or a developer workstation. Each host has different answers for where secrets are stored, which logs are retained and who can read the results. Give the host a clear owner, enough memory and CPU for the suite size you plan, and a working directory for output files, and document how it is patched.

Version confirmation before pinning

Versions move, so confirm the current npm release and its Node.js requirement on the registry and the GitHub releases page before you pin anything in a plan or base image. Ask the vendor or your own engineers to confirm that the release you choose supports every provider and feature in your suite. Re-check at each upgrade, and treat a Node.js requirement change as a platform change that needs its own rollout.

Node package docs

How a service calls evaluate() and receives results

The flow starts in the host application, where a TypeScript or JavaScript caller builds a test suite and calls evaluate(testSuite, options). Each call carries its own env overrides, so one evaluation does not inherit settings from a previous one. Requests cross the trust boundary to the model provider endpoint, and the results object returns to the caller for assertions, storage or reporting. Check what leaves the host on each request and where the returned results are kept.

Each evaluate() call sends its own env overrides and returns a results object to the caller.

How to set up a first evaluate() call

This sequence takes a Node.js project from an empty dependency list to a working evaluate() call whose results your code can read and act on. Each step ends with a check you can run before moving on.

  1. Install the promptfoo package in the project

    A developer adds the promptfoo npm package to the existing TypeScript or JavaScript project, using the Node.js version the package requires (the current npm release needs Node.js 22.22.0 or newer). Run the install in the project directory, then confirm the package resolves by importing it in a scratch file and checking that the evaluate function is exported. If the import fails, check the Node.js version before anything else.

  2. Define the test suite as a code object

    Write the test suite in code: a provider entry for the model or application under test, a prompt, and an array of test cases with the variables and assertions each case needs. Keep the first suite to two or three cases so a failure is easy to trace. The check for this step is that the object loads without type or syntax errors and that the number of test cases in the array matches what you intended to write.

  3. Pass options for the call

    Build the options object that accompanies the test suite, such as output handling and any settings that should apply to this run only. Keep options in the same module as the call so a reviewer can see every setting in one place. Confirm the option names against the Node package documentation for your installed version, since the names are the part most likely to differ between releases.

  4. Set environment overrides for that call only

    Give the evaluate() call its own environment overrides, such as the API key for the provider under test. Each call uses its own overrides and does not inherit values from an earlier evaluation, so a key set for one run will not leak into the next. Load the key from your secrets store rather than hard-coding it. The check is a deliberately wrong key: the run should fail with an authentication error, which shows the override is being applied.

  5. Run evaluate() and capture the returned results

    Call evaluate with the test suite and options inside an async function, await the promise, and store the returned object. Run the script once with a valid key. The check is that the result contains one entry per test case you defined in the previous step, so a run that returns fewer results than expected signals a filtering or loading problem to fix before you build on it.

  6. Read the results programmatically

    Walk the returned results and count passes and failures per test case, then compare the failure count against the threshold your code enforces. Print a short summary and set the process exit code if your pipeline needs one. The check is a result you can predict: introduce one assertion you know will fail, confirm the failure appears in your summary with the right test case, then remove it.

How per-call env overrides isolate one evaluation from the next

The key point for a service owner is that each evaluate() call carries its own environment overrides and does not inherit the settings of a previous evaluation. That means one service can run a suite against one model key or configuration and a second suite against a different key or setting without the second call picking up the first call's values. The isolation is set per call, so the design question is which values you pass in each call and which values you leave to the process. Confirm this behavior in your own version before you rely on it, because the guarantee is documented for the call, not for the process around it.

The risk sits in the process environment. In a long-running service, anything written to process.env is shared by every request, worker and module in that Node.js process. If one code path sets a provider key or a base URL there and another path expects a different value, the outcome depends on timing and on what ran first. A per-call override reduces that exposure, but it does not remove it if the same variables are also read from process.env by code outside promptfoo. Keep secrets out of shared globals where you can, and decide which variables are passed explicitly and which are read from the environment.

Before a test harness runs suites in parallel, confirm three things: that each suite's overrides reach only that evaluation, that no suite writes to process.env directly, and that the results recorded for each suite match the model and settings it was meant to use. Then ask how overrides interact with variables already set in the process. Test whether an override replaces a value, merges with it, or is ignored when the same key already exists, and whether a missing override falls back to the process value. Record the answer in your harness documentation, because a silent fallback is the most likely source of a result that looks correct but ran against the wrong configuration.

Embedding in a service or test harness versus running the CLI

Embedding the library in a service fits cases where the application itself builds evaluation inputs at request time, for example from a customer's document set, a prompt template chosen by a feature flag, or a batch of records pulled from your own database. The service calls evaluate() with a test suite it assembled, and it receives results as objects it can store, aggregate or act on.

  • Your team owns: the test data, the per-call environment values such as provider keys, the decision about which prompts and providers are tested, and any pass or fail logic applied to the returned results.
  • promptfoo owns: running the eval against the configured providers, grading assertions, and returning results for each call.
  • Operational load: the service now carries provider credentials, outbound traffic and eval runtime, so timeouts, concurrency limits and error handling become your code's responsibility.
  • Isolation: each evaluate() call takes its own env overrides and does not inherit a previous evaluation, which lets concurrent requests use different settings without shared state.
  • Access control: the service should be the only path that can trigger evals, since anything that reaches evaluate() can spend provider budget.

Confirm with your security team where provider keys are stored and which network paths the service may use before you expose this pattern to other teams.

Mapping suite inputs, options and results between your code and promptfoo

This table maps each piece of data your application passes into evaluate() and gets back from it to the promptfoo field it fills, who sets it and where it lives. Read it before writing the wrapper so each value has one owner. The main takeaway is that per-call env overrides and result handling belong in your code, while the suite and provider definitions stay under version control.

Your datapromptfoo fieldWho sets itWhere it is stored
Prompt templates and variablestestSuite prompts and test varsYour service or test harness, per callSource files or a prompt store in your repository
Model and endpoint choicestestSuite providersYour team, from approved configurationConfig module checked into version control
Test cases and expected outputstestSuite tests with assertionsYour QA or product ownersDataset files such as CSV or JSON in your repository
API keys and endpoint secretsoptions env overrides for each callYour deployment pipeline or secret managerSecret store, never in the suite file
Output location and run flagsoptions settings such as output and cache optionsYour harness, per invocationHarness code; confirm option names in the Node package docs
Pass or fail decisionReturned results summary and per-test success flagsYour code applies the thresholdYour logs, CI job result or stored report
Failure details for triagePer-test outputs, assertion results and error fieldsYour code extracts what to logApplication logs or a findings store you control
Historical comparison dataReturned results written to your own storeYour code after each evaluate() callYour database or artifact storage, retained under your policy

Handling results programmatically in your own pipeline

Once evaluate() returns, the useful work is deciding what counts as a failure for your build or request and making that decision in your own code. Read the pass and fail counts from the returned results object, then compare them against a threshold your team has agreed on. The pass-rate gating logic belongs in your code, not in promptfoo, so the threshold, the handling of errors and the exit behavior of your pipeline are choices your team owns. Before writing any of this, confirm the exact result shape in the promptfoo Node package documentation for the version you pin, because field names for summary counts, per-test results and error states can change between releases. Pin the version in your lockfile and re-check the shape whenever you upgrade.

Decide early which outcomes block a change and which only report. A common split is to fail the build on a regression in a safety or authorization test while logging quality drops for review. Treat evaluation errors, such as a model timeout or a rejected API key, separately from assertion failures, so an infrastructure problem does not look like a regression in the model. For a request path, such as a service that calls evaluate() on demand, define what the caller receives when the run fails and whether the response should be blocked, retried or passed through with a warning. Document these rules next to the code so reviewers can see what each result means.

Route failures to where your team already works. Write a structured record for each failing test with the test description, the assertion that failed, the provider or model under test and the run identifier, then send it to your logging stack or open a ticket in your tracker. Keep raw prompts and outputs for each failing case, stored under the access controls and retention rules your data governance requires, because prompts and model responses can contain customer or internal data. Retaining the raw output lets a reviewer reproduce the failure, compare it with a later run and confirm a fix. Keep the stored evidence with the version of the prompt, configuration and promptfoo release that produced it.

Securing credentials, data and the host that runs evals

When evaluate() runs inside your service or test harness, the code, its provider keys, the prompts it sends and the host it runs on all become part of your security boundary. The cards below cover each of these in turn, starting with the secrets that the library needs to call models.

Keep provider keys out of source

Each provider reads its API key from the environment or from the options you pass in, so the key rarely needs to appear in code at all. Load it from your secret manager or CI secret store at runtime, and never commit it to a config file or a test fixture. Check that your repository scanner and pre-commit hooks cover the key formats your providers use. If a key ever reaches a commit, rotate it instead of only deleting the line.

Stop keys leaking into logs

An eval harness tends to print configs, error objects and request details while it runs, and any of these can carry a key or a bearer token. Review what your logger, test reporter and CI console capture from the evaluate() call, and redact authorization headers before output leaves the process. Ask whether results you save or upload include the resolved provider configuration, since that is where keys tend to end up.

Limit which services can call evaluate()

Any code path that can call evaluate() can spend provider budget and send your prompts to a model endpoint, so decide which services and jobs are allowed to run it. Give each caller its own credentials, scoped to the models it needs, and keep red team runs away from production traffic paths. If you wrap evaluate() in an internal HTTP endpoint, add authentication and rate limits to that endpoint, because the library itself has no access control.

Map what prompts and outputs get written

Eval results include test inputs, model outputs and grader reasoning, and promptfoo can persist these to a local database and to any output files you request. Decide where each result file lives, how long it stays, and who can read it, because test prompts often contain realistic customer or patient data. Confirm which options write to disk or send data to a shared service, and whether your own result handler forwards anything to a third party.

Confirm data residency by endpoint and host

promptfoo documentation states that evals run locally on your machine and talk directly with the LLM, so no promptfoo service sits in the data path. Where your data ends up therefore depends on the model endpoints you configure and the host where the code runs. Document each endpoint's location and terms with its provider, and confirm that the build host, CI runner and any container image are inside the boundary your compliance team approved.

promptfoo introduction

Pin and review dependencies

promptfoo is MIT licensed and published on npm, so every upgrade arrives as a package version that your own code and lockfile must accept. Pin the version in your lockfile, record the Node.js version it requires, and review release notes before upgrading, because provider and grader behavior can change between releases. Add npm audit or your software composition analysis tool to the pipeline, and confirm who approves a version bump before it reaches the harness.

promptfoo releases

Common failures when calling evaluate() from code

This table lists the failures teams most often hit when calling evaluate() from Node.js, with the likely cause and a fix for each. Read it when a run fails, returns unexpected results or behaves differently inside a service than it does on the command line.

FailureLikely causeFix
Node.js version too oldThe runtime is below the minimum required by the installed promptfoo release, so the package fails at import or startup.Check the minimum Node.js version in the release notes for the promptfoo version you pin, then upgrade the runtime in your image or host before debugging code.
Env overrides not applied to the callThe override was set on the process or in a different evaluate() call, or the option was placed outside the options object passed to that call.Pass env overrides in the options for the specific evaluate() call that needs them, then log the resolved values inside that call to confirm them.
Leftover process environment valuesA value set earlier in the same process, such as a shell export or a previous setup step, is still visible to code that expected a clean state.Keep overrides per call and avoid mutating process.env for eval settings. Start long-running services from a clean environment and run evals in separate processes when isolation matters.
Provider credentials rejectedThe API key is missing from the environment the service runs in, belongs to another account, or is injected under a different variable name than the provider config expects.Confirm the variable name the provider reads, supply it through your secret store to the service, and test the credential with a single small eval before running a full suite.
Results read with the wrong shape after an upgradeCode reads fields from the result object that were renamed or moved in a newer promptfoo release, so checks silently pass or throw on missing properties.Pin the promptfoo version, read the changelog for result structure changes before upgrading, and add a test that asserts the fields your code depends on.
Timeouts in a service request pathEvals call live model providers and can run far longer than a typical HTTP request, so the caller gives up while the evaluation continues.Do not run full evaluations inline with a user request. Run them as background jobs or scheduled tasks, store results, and return a job identifier to the caller.

Questions teams ask before embedding promptfoo in code

Is the promptfoo Node.js library free to use under the MIT license?

Yes. promptfoo is licensed under the MIT license, so the library and its evaluate() function can be used in code without a license fee. The MIT license covers the open-source package itself. Your costs come from the infrastructure you run it on, the model provider accounts your tests call, and any paid promptfoo edition you choose for team features. Confirm the license text in the package you install and check your own legal review requirements before you ship it inside a product or internal platform.

Does embedding promptfoo in code take more effort than using the CLI?

It usually takes more engineering effort, because you own the code that builds the test suite, calls evaluate(), and decides what happens to the results. The CLI runs a config file and writes output for you. The effort depends on four things: how complex your suite is, how many model providers you call, how much you do with the results (storing them, routing them to dashboards, failing builds), and how the run fits into your CI system. A thin wrapper around a fixed config is small work. A harness that generates tests from your application data and feeds results into other systems is a larger project.

How long does a first integration take?

No duration is fixed by the library, so treat any figure you hear as a guess until you scope your own work. A first integration depends on the number of test cases you already have, whether your application endpoints are ready to be called from a test harness, how many provider accounts need approval, and how many people must agree on pass criteria. Ask for a written plan that lists each step, the owner of each step, and the environment where the first run happens. Confirm the timeline against a working proof of concept in your own environment.

What must our team supply before the integration starts?

Plan to supply four things. First, a Node.js runtime that meets the version requirement for the release you pin, which is Node.js 22.22.0 or newer for release 0.124.1, published on 8 October 2026 (see the promptfoo package on npm). Second, accounts and API keys for each model provider your tests call, with rate limits and budgets set by your platform team. Third, representative test data, including inputs, expected behavior and any sensitive records that must be masked. Fourth, named owners who agree on pass criteria, since the library returns results but cannot decide what a regression means for your product.

Can one engineering team build this without outside help?

A team with working Node.js or TypeScript experience can build a basic harness alone, especially if it starts with a small suite and one provider. The harder parts are usually organizational: agreeing on pass criteria, keeping test data current, protecting API keys in CI, and handling results so failures reach the right people. Teams without a QA or security owner for LLM behavior often find those decisions take longer than the code. Before starting, check who will maintain the harness after the first release and whether that person has time in their plan.

When does a partner help with an evaluate() integration?

A partner is useful when the harness must run reliably across several pipelines, when results feed security reviews or audit evidence, or when your team lacks time to maintain it. DeployOpen plans, implements and documents self-hosted open-source platforms inside your own infrastructure, and runs security testing of AI systems. Most engagements are fixed-scope, with scope, deliverables and timelines agreed in writing before work starts, and a quote follows from that scope. Ask any provider for a written scope that names the test suites, providers, result handling and handover tasks. DeployOpen does not issue audit reports or certifications.

What operational risks should we check before shipping a harness?

Check how the harness stores and logs API keys, how it handles provider timeouts and rate limits, and whether each evaluate() call starts clean. The promptfoo documentation states that each evaluate() call uses its own environment overrides and does not inherit a previous evaluation, so you can pass different settings per call without leaking them between runs. Still, test that behavior in your own harness. Also confirm where results are written, who can read them, and how long they are kept, since eval output can contain prompts and model responses from your application.

Official promptfoo sources for the Node.js package

Start with the official Node.js package documentation before you write any code that calls evaluate(). The promptfoo docs: Using the Node.js package page is the reference for the evaluate(testSuite, options) signature and for how per-call environment overrides behave. The supplied documentation states that each evaluate() call uses its own env overrides and does not inherit settings from a previous evaluation, so your harness should not depend on leftover state between calls. Read that behavior against your own test runner's parallelism before you rely on it.

Next, check the runtime and version details on the npm package page for promptfoo, which lists the published release and the Node.js version it requires. The supplied facts list npm release 0.124.1, published on 8 October 2026, and a requirement of Node.js 22.22.0 or newer. Confirm these against the promptfoo package on npm and the GitHub releases before rollout, since newer releases may have changed the requirement or the API. Pin the exact version in your lockfile, and record the Node.js version your build images use so a mismatch fails in CI rather than in production.

Before rollout, confirm the pinned version against the npm registry and compare its release notes with the documentation you are following. Ask whether any evaluate() option you use is marked as changed or deprecated in that release, and rerun your harness after every upgrade. Assign one owner to track promptfoo releases, because the library is maintained as an open-source project and an unpinned dependency can change the behavior your evaluations depend on.

How DeployOpen scopes and delivers a promptfoo library integration

DeployOpen approaches a promptfoo library integration as a written, fixed-scope engagement. We first agree which evaluate() calls, test suites and result handling your service needs, then build and document the harness inside your own infrastructure and hand it over with a clear support path.

How we scope

  • We map which services or test harnesses will call evaluate() and what each call must check.
  • We agree in writing which environment overrides, providers and result outputs the integration covers.
  • We confirm the Node.js version your runtime uses, since the current npm release requires Node.js 22.22.0 or newer.

How we build

  • We write the TypeScript or JavaScript wrapper so each evaluate() call receives its own environment overrides.
  • We structure result handling so pass or fail outcomes feed your pipeline, logs and alerting in the form your teams use.
  • We run the integration against test providers in a non-production environment before connecting it to live model endpoints.

How we hand over

  • We document the wrapper, its configuration keys, required secrets and how each evaluate() call is isolated.
  • We deliver test cases that show a passing run, a failing run and an error path, so your team can verify behavior.
  • We walk your engineers through the code and the runbook so they can change assertions and providers without us.

How we support

  • Engagements are fixed-scope, so changes after handover are scoped and agreed in writing before work starts.
  • Ongoing support, upgrades when promptfoo releases change the library, and continuous testing are available as a retainer.
  • Ask us to confirm the upgrade cadence and the support terms in the written scope before you sign.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.