Writing custom Python providers for promptfoo

A custom Python provider lets promptfoo call your own model, RAG pipeline or agent framework through the file:// prefix. This page covers the interface, return format, worker settings, retries and tracing.

On this page

How a Python provider puts your own code under promptfoo tests

Many teams do not test a raw model API. They test an application or agent written in Python: a retrieval pipeline that gathers context before it calls a model, or a LangChain, LangGraph or CrewAI workflow that makes several calls and tools along the way. In that case promptfoo needs to call your code directly, not a provider endpoint in front of a model. promptfoo itself is written in TypeScript and runs on Node.js, but it supports Python for providers, assertions, test generators and prompts through the file:// prefix. A Python provider is the piece that lets promptfoo send each test prompt into your function and read back what your application produced. The provider function is the boundary between promptfoo and your code, so the first design decision is what that function accepts and what it must return.

When promptfoo runs a test, it passes the function the prompt for that test along with context such as the test variables and configuration, and it expects a structured result back. Your function does the application work (retrieval, orchestration, tool calls, the model call itself) and returns the final output that assertions and red team graders will inspect. Anything the grader needs to judge, such as retrieved documents, tool calls or intermediate messages, has to be returned in the result or it cannot be tested. Confirm the exact argument names, the return keys and any error fields against the Python integration documentation for your promptfoo version, because these details are what most first integrations get wrong. Check them with a single test case before you run a full suite.

Execution stays on your side. promptfoo documentation states that the software runs completely locally, so evals run on the machine that executes promptfoo and talk directly with the models and services your code calls. The Python process runs in that same environment, which means your application's API keys, vector stores and tool endpoints must be reachable from that machine, and the test data and responses pass through it. Decide early which Python environment promptfoo will invoke, who maintains its dependencies, and where the credentials come from. Those choices determine whether the same provider works in a developer's shell and in a CI runner, and they belong in your review before the first red team run touches a production-like system.

What you need before writing a Python provider

A Python provider sits between promptfoo and code you already run, so the work depends on three things: a Node.js runtime for promptfoo itself, a Python environment that can import your application, and credentials and network paths the function can reach. Check each of these on the machine that will run the evals before writing any wrapper code.

Node.js runtime for promptfoo

promptfoo is distributed on npm and the current release requires Node.js 22.22.0 or newer, so the machine or CI runner that launches evals needs that version or later. Python providers are invoked through the file:// prefix from the promptfoo process, which means Node.js is the host and Python is the callee. Pin the Node.js version in your CI image and record it alongside your promptfoo version so eval results can be reproduced later.

promptfoo on npm

Python interpreter and virtual environment

The Python code the provider calls needs its own interpreter and a virtual environment that holds your application's dependencies. Confirm the exact Python version your promptfoo release expects in the official Python integration docs, because the supported range is not part of the facts this page relies on. Keep the environment that promptfoo calls separate from the one your application uses in production so that test dependencies do not drift into deployed code.

promptfoo Python docs

Model keys and provider credentials

A provider function often calls a model API, so it needs keys for that service. Decide whether the function reads keys from environment variables, a secrets manager or a local file, and make sure the account behind those keys is a test account with a spending limit. Avoid placing production keys in promptfoo configuration files that may be committed to source control or shared in reports.

Vector store and agent dependencies

A RAG pipeline or agent framework usually depends on a vector database, a document index, tool servers or a memory store. List each dependency the function touches, then confirm that the test run can reach a non-production copy with representative data. Without that copy, red team probes may write to live indexes or trigger real tool actions, so check write permissions before the first run.

Network path and reachability

Map the network route from the machine running promptfoo to every system the function calls, including model endpoints, the application's internal services, and any gateways or proxies between them. Firewall rules, VPN requirements and egress policies often block calls that work on a developer laptop. Confirm the route from the same runner your CI pipeline will use, not only from a workstation.

Secrets and configuration access

List every secret the Python code reads at runtime, such as API tokens, database passwords and signing keys, and decide how each reaches the process: environment variables injected by the runner, a vault client or a mounted file. Give the test identity only the permissions it needs, and document which secrets the eval suite requires so that operators can rotate them without guessing.

How a test case flows through a Python provider

The run starts in the promptfoo CLI on your machine, which reads the config and hands each test prompt to the Python file named by the file:// provider path. The function calls your RAG pipeline or agent, which may reach a model API or data store outside the promptfoo host, then returns its output to promptfoo. Assertions grade that output afterward. Check where the boundary falls, because anything your function sends across it carries test data and credentials.

Test prompts cross the trust boundary to your pipeline, and only the returned output comes back.

Configuring a Python provider step by step

This sequence takes a team from an empty directory to a working promptfoo Python provider that answers a test prompt, returns fields the assertions can read, and runs inside a small eval. Each step ends with a check so problems surface before the suite grows.

  1. Create the Python module with a call function

    Start with a single file, such as provider.py, that defines a call_api function taking the prompt, the provider options and the test context. The function calls your model, RAG pipeline or agent and returns a dictionary with an output key holding the text under test. Keep the first version minimal, with a hard-coded or stubbed response, so the wiring can be checked before any real dependencies are involved. Confirm the exact function name and argument order against the promptfoo Python integration documentation for the release you have installed, because the interface is the part most likely to differ between versions. Done means the file imports cleanly under the same Python interpreter promptfoo will use.

  2. Reference the module with file:// in the config

    In promptfooconfig.yaml, add a provider entry that points to the module with the file:// prefix, for example file://provider.py, and pass any settings your function needs under config. Do not put secrets in the YAML; read them from environment variables inside the Python code. Make sure the path resolves relative to the directory where you run the CLI. Done means the config loads and promptfoo reports the provider without an import or path error when you run a validation or list command.

  3. Make a single-prompt call from the command line

    Run one prompt directly against the provider from the CLI, using the provider reference from the config, so you test the function without the rest of the suite. Use a prompt that exercises a known answer, such as a fixed question with a stub response. Look at the raw output and the logged request to confirm the function ran once, received the prompt you expected and returned without exceptions. Done means one call completes and the printed output matches the shape your function was written to return.

  4. Check the returned fields

    Inspect the full response object promptfoo receives, not only the text. Confirm that output is present and that any token counts, cost, error or metadata fields follow the names and types in the documentation for your version, since assertions and reports read those fields. Trigger a deliberate failure, such as an exception or a missing key, and check that promptfoo records it as an error rather than a passing empty answer. Done means a normal call and a forced failure both produce results you can tell apart in the output.

  5. Add assertions to the test cases

    Add a small set of test cases under tests with assertions that read the returned output, such as a string contains check or a simple JavaScript or Python assertion over the text. Choose assertions that are deterministic for your stub so a failure points at the wiring rather than at model variation. Keep the number of cases small at this stage. Done means each assertion is evaluated against the provider output and at least one case fails on purpose to prove assertions are enforced.

  6. Run a small eval and read the results

    Run the full eval with the small test set, then open the results view or export and confirm that each row shows the prompt, the provider output, the assertion results and any errors. Once the stub path works, swap in the real model, RAG pipeline or agent call and repeat the same run on the same cases. Done means the eval completes end to end and the results match what you expected from the stubbed run, so the provider is ready to expand with more cases, retries and worker settings.

Function interface and return format by target type

A plain model provider is the simplest case. promptfoo sends the rendered prompt for each test case to your Python function, and the function calls the model and returns the answer. The function receives the prompt text along with context about the test, such as the variables for that case, so it can forward the prompt unchanged to the model client. For most assertions, returning the model's text as a string is enough, and promptfoo treats that string as the output to grade.

  • Input: the rendered prompt and the test variables for the current case, passed as arguments to your function.
  • String return: a plain string is the minimal valid output and is graded as the model response.
  • Structured return: an object lets you add fields such as token usage or an error message when the model call fails.
  • Error handling: decide whether a failed model call should return an error field or raise an exception, and confirm how promptfoo records each case.
  • Consistency: keep the same return shape across all test cases so assertions behave the same way for every row.

Confirm the exact function signature, the accepted return keys and how errors are reported against the Python integration documentation before you write the wrapper.

Worker settings, retries and timeouts to decide

A custom Python provider sits between promptfoo's parallel workers and your model or application, so every test run inherits its concurrency, retry, timeout and state choices. Decide these before writing the function, because they determine whether a failing run points to your code, the provider's limits or the test itself. Confirm exact option names and defaults in the promptfoo Python documentation before you set them.

Worker concurrency against rate limits

promptfoo runs tests in parallel, so a Python provider can receive many calls at once. Set the concurrency to the lowest rate limit in the chain: your model platform, your gateway and any judge model used for grading. Parallel calls that exceed a limit fail with throttling errors that look like application bugs. Check the concurrency option name and whether it applies per provider or globally in the docs, and run a small batch first to see where throttling begins.

Python provider docs

Retries for transient errors only

Retry network timeouts, 429 responses and 5xx errors, since they often succeed on a second attempt. Do not retry a response that arrived but failed a check, such as malformed JSON or a refusal your test expects. Retrying those hides the regression you are trying to measure and inflates cost on paid endpoints. Put the retry logic in one place, log each attempt, and confirm whether promptfoo's own retry behavior would stack on top of yours.

Per-call timeouts for slow agents

A single-shot model call and a multi-step agent run for very different lengths of time. Set the timeout inside your function for each call type, and make it longer than the slowest normal path but short enough that a hung tool call does not stall a worker for the whole run. Record timeouts as a distinct error type so they appear separately in results. Confirm whether promptfoo also enforces a timeout at the provider level, and which value wins when both exist.

Statefulness and session handling

Multi-turn red team tests need the provider to keep a conversation going, while single-turn evals need every call to start clean. Decide whether your function accepts a session identifier from promptfoo and maps it to your application's conversation ID, or creates a fresh session on each call. A provider that carries memory between unrelated tests contaminates results in ways that are hard to trace. Confirm how promptfoo passes session data to Python providers in the docs.

Avoiding shared global state

Parallel tests share one Python process, so module-level variables, cached clients, global conversation lists and mutable default arguments can leak data from one test into another. Keep request state in local variables or per-session objects, and initialize clients once only if they are thread-safe or async-safe. Test the provider with two tests run in parallel and compare outputs against serial runs. A leaked answer from one test is one of the hardest failures to spot in a pass-rate report.

Adding OpenTelemetry spans to the provider

Add OpenTelemetry spans to your Python provider so that a failed RAG or agent run can be traced to the step that broke. Create one span for each provider call, then child spans for each retrieval query and each tool call the pipeline makes inside that call. Set attributes on the parent span for the promptfoo test case ID, the test description or scenario name, the model or pipeline version, and the prompt hash, so a trace can be matched to the row in the eval results that produced it. Without these attributes, a trace shows that a slow or wrong answer happened but not which of the test cases caused it. Keep attribute values short and avoid writing full prompts, retrieved documents or personal data into spans unless your data handling rules allow it, because traces are usually retained longer and read by more people than eval output.

Export spans to the telemetry backend your organization already operates, such as an existing OpenTelemetry Collector pipeline, rather than standing up a separate tracing store for promptfoo runs. Confirm with your platform team which exporter, endpoint and sampling settings they expect, and whether test traffic should be tagged with a distinct service name or environment so it does not mix with production data. Before relying on spans, confirm how promptfoo passes trace context into Python code, including whether the provider receives a parent trace context from the eval run or whether your code must create a root span for each call. Check the current promptfoo Python documentation for the exact mechanism, then run one small eval and confirm that the spans appear in your backend with the expected parent and child relationships and attributes.

Mapping promptfoo test fields to your Python code

This table maps each promptfoo test field to the Python argument, config value or return key that carries it. Read it as a checklist for the provider function, then confirm each key name against the current integration docs before your first run. The main takeaway is that the returned output drives assertions, while token and cost fields only report what your code measures.

Promptfoo conceptPython sideConfirm before relying on it
PromptThe prompt argument of call_api, after promptfoo renders the prompt templateWhether chat-style prompts arrive as a rendered string or as structured messages
Test variablesValues from the test case, available by name in the context mappingThe exact key path for vars in your promptfoo version
Provider configValues from the provider block in YAML, passed in as the options mapping; environment variables for secretsThe config key path and whether secrets should be read from the environment instead
Returned outputThe output key in the dictionary your function returnsWhether structured objects are accepted or only strings reach assertions
Token usageA tokenUsage mapping with the counts your code measures from the model responseExact key names and whether totals appear in the run summary
CostA cost number that your code calculates from its own pricing dataWhether promptfoo derives cost for custom providers or only displays your value
ErrorsAn error string returned when the model or pipeline call failsThat a returned error marks the test failed without stopping the whole run

Security for Python code that promptfoo executes

A Python provider runs inside your CI job or workstation with whatever credentials and network access that host has. The controls below keep that code contained, keep secrets out of files and logs, and make the provider reviewable before it touches a model or a production-like application.

Keep credentials out of config files

Model API keys, cloud credentials and test account passwords belong in environment variables or a secrets store that your CI system injects at run time. Reference them from the Python provider with os.environ lookups instead of hard-coding them in promptfooconfig.yaml or the provider module. Check that the repository and CI logs contain no key material, and rotate any key that was ever committed. Ask your security team which secrets store your pipelines already use before you add a new one.

Run providers in a pinned virtual environment

Create a dedicated virtual environment for the provider and pin every dependency, including transitive ones, with a lock file. Your provider may import the same agent framework or RAG library as the application under test, so an unpinned upgrade can change both behavior and attack surface between runs. Install into an isolated environment on the CI runner or a disposable container, not into a shared system Python. Record the interpreter version in your run notes so results remain reproducible.

Restrict network egress from the test host

A provider that calls the wrong URL can send test prompts, or real data pulled from a retrieval store, to an unintended destination. Limit outbound traffic from the test runner to the model endpoints, the target application and the judge model you approved. Block general internet access where your pipeline allows it, and confirm that any package index access goes through an internal mirror. Test the allowlist once with a deliberately wrong endpoint so you know the failure mode is visible.

Avoid logging sensitive prompts and responses

Print statements and debug logging in a provider often capture full prompts, retrieved documents and model outputs, which may contain personal data or confidential material. Log only identifiers, status codes and timings, and turn off verbose framework logging for the provider process. Review the promptfoo output directory and any saved result files before you upload them as CI artifacts. Confirm with your compliance team how long eval artifacts may be kept and who may read them.

Test with safe accounts only

Red teaming sends adversarial prompts that may succeed in unexpected ways, so the provider should authenticate as a dedicated test identity with limited permissions. Use test tenants, synthetic customer records and sandboxed tools wherever the application allows it. Avoid giving the provider production administrator rights, write access to live data or the ability to send real messages. Ask the application owner to confirm which actions the test identity can trigger before the first scan.

Review the provider like production code

The Python file runs with the permissions of the CI job, so it deserves the same review as any code that handles credentials and data. Have a second engineer check imports, network calls, file writes and subprocess use before the file is merged. Keep the provider in version control with protected branches, and require review when its dependencies or endpoints change. Treat changes to the provider as changes to the test target, because they can alter every result that follows.

Common failures in custom Python providers

This table lists the failures teams most often hit when promptfoo calls a custom Python provider, with the cause of each and the fix to try first. Read it when a run fails before any model output is scored. The main takeaway is that most failures come from environment setup, output shape, or concurrency, and each can be isolated by running one test case before scaling up.

FailureLikely causeFix
Import errorspromptfoo starts a Python interpreter that is not the one where your packages are installedPoint promptfoo at the project's virtual environment interpreter and confirm the setting in the Python integration docs
Output shape mismatchThe provider returns a plain string or a different field name than the assertions readReturn the dictionary format the docs describe, then check one result to confirm the output field is populated
Timeouts under concurrencyMany test cases call slow model or retrieval steps at the same timeRun one case first, then lower the worker count and review the timeout settings in the docs
Rate limit errorsParallel workers send requests to the same provider account and exceed its quotaReduce concurrency, add retry with backoff inside your function, and confirm the account's limits with the provider
Missing environment variables in CIAPI keys exist in a local shell or .env file but not in the CI job, so os.environ is emptyStore secrets in the CI system, pass them into the job, and have the provider fail fast with a clear message when one is missing
Empty tracesThe tracer is not initialized in the process that runs the provider, or no exporter endpoint is setInitialize the OpenTelemetry SDK inside the provider module, flush spans before returning, and confirm exporter settings with your collector
Stale code after editsThe run uses a cached result or an older copy of the provider fileClear the cache for the run, confirm the file path in the config, and rerun a single case to verify the change

Questions teams ask before writing a Python provider

How much effort does a Python provider wrapper take to build?

The effort depends mainly on how much code sits between the test harness and the answer you want to grade. A thin wrapper around one function that takes a prompt and returns text is a small job. Effort rises with the number of pipeline stages you need to call, the number of input types (plain text, structured JSON, file uploads, images), and whether the pipeline keeps state between turns. Each of these adds parsing, error handling and test cases. Ask for a scope that lists the entry points, the input and output shapes, the state model and the failure modes you want covered. That list is what turns a vague estimate into a quote you can compare.

Can an in-house Python developer build a promptfoo provider alone?

Often yes, for a single well-understood pipeline. The provider contract is a Python function that receives a prompt and returns an output in the format promptfoo expects, and the Python integration documentation covers the file:// prefix that loads it. The harder parts are usually outside the function: knowing which pipeline behavior matters for grading, handling authentication to a staging system, and deciding how red team probes should reach the agent without exposing production data. A capable developer can cover the code. What tends to stall a solo build is the lack of a second reviewer and of time to test edge cases against the real application. Confirm that your developer has both before deciding.

What does the work need from our team?

Four things determine how smoothly the work runs. First, access to a test or staging environment that behaves like production but holds no real customer data. Second, test accounts with the roles the application uses, so authorization can be tested. Third, a set of representative sample inputs, including awkward ones such as long documents, malformed requests and multi-turn conversations. Fourth, a named owner on your side who answers questions about expected behavior and approves the final output format. Without the owner, decisions about grading and error handling stall. Without the sample inputs, the wrapper is tested only against what the builder imagined. Ask for this list in the written scope so that each dependency has a date and a person attached.

How long does a custom Python provider take to build?

Duration follows scope, and no fixed figure applies across pipelines. The main factors are the number of entry points, how many input and output shapes must be supported, how much authentication work sits in front of the application, and how many rounds of review your team needs. Access delays on the client side often add more time than the code itself. A written scope should split the work into phases: wrapper for the first pipeline, validation against sample inputs, worker and retry tuning, and a documented handover. Each phase should name its exit criteria. Ask for the timeline as a sequence of dated milestones tied to your dependencies, not as a single number.

Can a custom Python provider run in CI pipelines?

Yes, promptfoo can be used as a CLI in CI/CD pipelines, so a Python provider can run wherever the CLI runs, as long as the runner has the Python environment, the pipeline's dependencies and the credentials it needs. Several points need planning. The runner needs network access to the staging system, not to production. Secrets for test accounts should come from your CI secret store, not from the repository. Worker settings and retries affect run time and rate limits on the downstream service, so CI runs often need lower concurrency than local runs. Pin the Python and Node.js versions so results stay comparable between builds. The pipeline integration work is covered separately, but the provider itself must be deterministic enough to gate a build.

What should we ask for in a written scope before we start?

Ask for the scope to name the pipeline entry points to wrap, the input and output formats, the state and session behavior, the authentication method for staging, the error and retry rules, and the test cases that will prove the wrapper works. Ask who owns each dependency and what happens if an access request is delayed. Ask what is handed over: source code, tests, configuration, a runbook and a short note on how to add a new entry point. Ask how changes after delivery are handled. DeployOpen plans, implements and documents engagements in fixed scope, with scope, deliverables and timelines agreed in writing before work begins, and it provides a quote from that written scope. Cost questions should be answered from the scope, not from a per-hour guess.

How DeployOpen scopes and delivers a Python provider

DeployOpen starts every Python provider engagement with a written, fixed scope agreed before any code is written. For a custom provider, that scope names the target you are wrapping (a bare model call, a RAG pipeline, or an agent framework), the function signature and return format the provider must honor, the worker and retry settings, whether OpenTelemetry spans are required, and the environment where the provider will run. Deliverables and the delivery timeline are set out in the same document, so the client knows what is included before the work begins. Because most engagements are fixed-scope, changes to the target or the test goals are handled as a written scope change rather than as an open-ended extension.

Planning comes first and centers on the application under test. DeployOpen reviews how the Python code is packaged, which dependencies it needs, where secrets come from, and how the provider will be invoked from the promptfoo configuration. The team then builds and tests the provider inside the client's own infrastructure, using the client's Python environment, network access and credential stores, so that prompts, responses and any traces stay under the client's control. Verification covers normal calls, error paths, timeouts and the retry behavior the client has chosen, with the results recorded for review. Ask the delivery team which Python version, dependency pinning approach and test accounts they will use, and confirm them against your own environment before the scope is signed.

Handover includes documentation of the provider's interface, configuration keys, known limits and the steps to upgrade promptfoo or the wrapped framework without breaking the provider. Ongoing support and retainers are available for teams that want DeployOpen to keep the provider working as the application changes, to rerun tests after upgrades, or to extend coverage over time. Whether you buy a one-off delivery or a retainer, ask for the written scope, the acceptance criteria and the support terms in the quote, and confirm who on your side will own the provider after handover.

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.