AI › AI Tools

Evaluating backend AI HTTP APIs with Promptfoo providers

Compare Promptfoo 0.126.0 built-in http and custom JS providers against a backend AI HTTP API, and prevent stale cache passes with --no-cache.

Evaluating backend AI HTTP APIs with Promptfoo providers

Calling an LLM directly misses regressions in your retrieval, prompt assembly, and post-processing layers. This note compares Promptfoo’s built-in http provider and a custom JavaScript provider against a backend JSON API, and shows how --no-cache prevents stale passes when server logic changes.

All outputs and numbers below come from running promptfoo@0.126.0 on Node.js v22.23.3 against a local Node.js HTTP server (http://127.0.0.1:4101/api/ask). Every run isolated PROMPTFOO_CONFIG_DIR and PROMPTFOO_CACHE_PATH inside a temporary directory.

Why evaluate the backend HTTP boundary

Production AI endpoints rarely return raw model text. A backend service authenticates the request, retrieves tenant-scoped documents, builds the final prompt, and serializes a JSON payload containing the answer, citations, policy version, and token usage. If your evaluation only hits the upstream model, it won’t catch broken retrieval filters, missing headers, or response-mapping bugs in your own API.

Promptfoo gives you two ways to target an HTTP endpoint directly: the built-in http provider configured in YAML, and a custom JavaScript provider that maps the request and response in code.

flowchart TD
    A["Promptfoo Eval"] --> B["Built-in http provider"]
    A --> C["Custom JS provider"]
    B --> D["Disk cache (fetchWithCache)"]
    D --> E["Backend POST /api/ask"]
    C --> E

The difference isn’t just syntax. Each provider exposes different fields to your assertions and behaves differently with Promptfoo’s disk cache.

CriterionBuilt-in http providerCustom JS provider (file://*.cjs)
ConfigurationYAML (url, method, headers, body)CommonJS/ESM class (id(), callApi())
Answer extractiontransformResponse: "json.answer"return { output: data.answer }
Domain metadataOnly HTTP status/headers (metadata.http) by defaultArbitrary fields (metadata: { citations, policyVersion })
Token accountingReports 0 by defaultPopulates tokenUsage: { prompt, completion, total }
Promptfoo disk cacheEnabled by default (fetchWithCache)Bypassed when calling Node’s fetch() directly
Best fitQuick text assertions on simple JSON responsesVerifying citations, token budgets, or custom auth/retries

Local Q&A API contract and test cases

To compare both providers deterministically without external model drift, I ran a local Node.js HTTP server (docs-api-server.cjs) simulating an internal docs Q&A endpoint. POST /api/ask checks the X-Internal-Token header and returns { answer, citations, policyVersion, usage }. The server also exposes GET /__stats to inspect the live request counter and POST /__mode to inject a backend regression on demand.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// docs-api-server.cjs (core response branching excerpt)
const http = require('node:http');

const PORT = Number(process.env.PORT || 4101);
const EXPECTED_TOKEN = process.env.DOCS_API_TOKEN || 'dev-docs-token';

let mode = process.env.API_MODE || 'v1';
let requestCount = 0;

function buildAnswer(question, tenant) {
  const q = String(question || '').toLowerCase();

  if (q.includes('rollback')) {
    if (mode === 'v2-bug') {
      return {
        answer: 'Restart the container manually and clear the Redis cache.',
        citations: [],
        policyVersion: '2026.11-buggy',
        usage: { promptTokens: 118, completionTokens: 14, totalTokens: 132 },
      };
    }
    return {
      answer: 'Run `kubectl rollout undo deployment/api` and verify `/healthz` returns HTTP 200 before reopening traffic.',
      citations: ['runbook-deploy.md#rollback'],
      policyVersion: '2026.11',
      usage: { promptTokens: 120, completionTokens: 45, totalTokens: 165 },
    };
  }

  if (q.includes('migration') || q.includes('lock')) {
    return {
      answer: 'Set `lock_timeout = 3s` and create indexes with `CREATE INDEX CONCURRENTLY` to avoid blocking writes.',
      citations: ['runbook-db.md#zero-downtime-migration'],
      policyVersion: '2026.11',
      usage: { promptTokens: 115, completionTokens: 38, totalTokens: 153 },
    };
  }

  return {
    answer: `For tenant ${tenant || 'default'}, temporary admin access is usually approved in Slack within 24 hours.`,
    citations: [],
    policyVersion: '2026.11',
    usage: { promptTokens: 110, completionTokens: 29, totalTokens: 139 },
  };
}

The test suite covers three scenarios:

  1. Deploy rollback procedure: returns kubectl rollout undo and cites runbook-deploy.md#rollback.
  2. Zero-downtime DB migration: returns CREATE INDEX CONCURRENTLY and cites runbook-db.md#zero-downtime-migration.
  3. Undocumented admin policy: returns a plausible answer string with an empty citations: [] array so we can verify whether our metadata assertion catches unsupported claims.

Extracting answer text with the built-in http provider

When you point the built-in http provider at a Content-Type: application/json endpoint without transformResponse, Promptfoo parses the response and passes the entire JSON object ({ answer, citations, ... }) as output. Any JavaScript assertion that assumes a string and calls string methods such as output.trim() fails with a TypeError.

The config below runs both variants side by side against the same POST /api/ask endpoint.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
# config-http-raw-vs-transform.yaml
description: "Built-in http provider: raw JSON vs transformResponse"

prompts:
  - "{{question}}"

providers:
  - id: http
    label: "http (raw response)"
    config:
      url: "http://127.0.0.1:4101/api/ask"
      method: POST
      headers:
        Content-Type: application/json
        X-Internal-Token: "{{env.DOCS_API_TOKEN}}"
      body:
        question: "{{prompt}}"
        tenant: "{{tenant}}"
  - id: http
    label: "http (transformResponse)"
    config:
      url: "http://127.0.0.1:4101/api/ask"
      method: POST
      headers:
        Content-Type: application/json
        X-Internal-Token: "{{env.DOCS_API_TOKEN}}"
      body:
        question: "{{prompt}}"
        tenant: "{{tenant}}"
      transformResponse: "json.answer"

tests:
  - description: "Deploy rollback procedure"
    vars:
      question: "How do I rollback a broken API deployment?"
      tenant: "platform"
    assert:
      - type: icontains
        value: "kubectl rollout undo"
        metric: Answer keyword
      - type: javascript
        value: "!output.trim().startsWith('{')"
        metric: Plain text answer
  - description: "Zero-downtime DB migration"
    vars:
      question: "How can we avoid table locks during a DB migration?"
      tenant: "platform"
    assert:
      - type: icontains
        value: "CREATE INDEX CONCURRENTLY"
        metric: Answer keyword
      - type: javascript
        value: "!output.trim().startsWith('{')"
        metric: Plain text answer

Running the comparison with DOCS_API_TOKEN=dev-docs-token and --no-cache shows the exact split:

1
2
DOCS_API_TOKEN=dev-docs-token npx promptfoo eval \
  -c config-http-raw-vs-transform.yaml --no-cache -o results-c4.json
Provider configurationoutput received by assertionsAnswer keywordPlain text answerOverall
http (raw response)Parsed JSON object ({ answer, citations, ... })2/20/2 (TypeError: output.trim is not a function)0/2
http (transformResponse)Plain string (Run \kubectl rollout undo …`)2/22/22/2

Without transformResponse, the parsed JSON object hits TypeError: output.trim is not a function in Plain text answer and fails 0/2. Adding transformResponse: "json.answer" extracts the plain answer string and brings the pass count to 2/2. However, extracting only json.answer drops the sibling fields (citations, policyVersion, and usage) from the assertion context.

Returning metadata and token usage from a custom JS provider

With the built-in http provider, context.providerResponse.metadata only contains transport details (metadata.http.{status, statusText, headers}), and tokenUsage stays at 0. If your backend returns grounding citations or token counts that you want to assert on, switch to a custom JavaScript provider.

A custom provider implements id() and async callApi(prompt, context), returning { output, tokenUsage, metadata }.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// docs-api-provider.cjs
class DocsApiProvider {
  constructor(options = {}) {
    this.providerId = options.id || 'custom-docs-api';
    this.config = options.config || {};
  }

  id() {
    return this.providerId;
  }

  async callApi(prompt, context) {
    const endpoint = this.config.url || 'http://127.0.0.1:4101/api/ask';
    const token = process.env.DOCS_API_TOKEN || 'dev-docs-token';
    const tenant = (context && context.vars && context.vars.tenant) || 'platform';

    const res = await fetch(endpoint, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Internal-Token': token,
      },
      body: JSON.stringify({ question: prompt, tenant }),
    });

    if (!res.ok) {
      return { error: `HTTP ${res.status}: ${await res.text()}` };
    }

    const data = await res.json();
    return {
      output: data.answer,
      tokenUsage: {
        prompt: data.usage?.promptTokens ?? 0,
        completion: data.usage?.completionTokens ?? 0,
        total: data.usage?.totalTokens ?? 0,
      },
      metadata: {
        citations: data.citations || [],
        policyVersion: data.policyVersion || 'unknown',
      },
    };
  }
}

module.exports = DocsApiProvider;

Next, write a JavaScript assertion (check-citations.cjs) that reads context.providerResponse.metadata.citations and checks both presence and the expected document prefix (expectedCitationPrefix).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// check-citations.cjs
module.exports = (output, context) => {
  const metadata = context?.providerResponse?.metadata;
  if (!metadata) {
    return {
      pass: false,
      score: 0,
      reason: 'No providerResponse.metadata available (http provider returns text only)',
    };
  }

  const citations = Array.isArray(metadata.citations) ? metadata.citations : [];
  if (citations.length === 0) {
    return {
      pass: false,
      score: 0,
      reason: `Missing citations in metadata (policyVersion=${metadata.policyVersion})`,
    };
  }

  const expectedPrefix = context?.vars?.expectedCitationPrefix;
  if (expectedPrefix && !citations.some((c) => c.startsWith(expectedPrefix))) {
    return {
      pass: false,
      score: 0,
      reason: `Citations ${JSON.stringify(citations)} do not match prefix "${expectedPrefix}"`,
    };
  }

  return {
    pass: true,
    score: 1,
    reason: `Verified ${citations.length} citation(s): ${citations.join(', ')}`,
  };
};

In config-providers-compare.yaml, both http (transformResponse) and file://docs-api-provider.cjs run against the same three test cases.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# config-providers-compare.yaml (providers and first test case excerpt)
providers:
  - id: http
    label: "http (transformResponse)"
    config:
      url: "http://127.0.0.1:4101/api/ask"
      method: POST
      headers:
        Content-Type: application/json
        X-Internal-Token: "{{env.DOCS_API_TOKEN}}"
      body:
        question: "{{prompt}}"
        tenant: "{{tenant}}"
      transformResponse: "json.answer"
  - id: file://docs-api-provider.cjs
    label: "custom JS provider (metadata)"
    config:
      url: "http://127.0.0.1:4101/api/ask"

tests:
  - description: "Deploy rollback procedure"
    vars:
      question: "How do I rollback a broken API deployment?"
      tenant: "platform"
      expectedCitationPrefix: "runbook-deploy.md"
    assert:
      - type: icontains
        value: "kubectl rollout undo"
        metric: Answer keyword
      - type: javascript
        value: file://check-citations.cjs
        metric: Citations metadata

Opening the output in promptfoo view makes the visibility gap obvious.

Promptfoo web UI comparing built-in http provider and custom JS provider results against a local backend API Figure 1. promptfoo view comparing both providers against the local Q&A API (127.0.0.1:4101). The built-in http provider fails all 3 citation checks (policyVersion=undefined) and reports no token counts, while the custom JS provider passes the 2 documented cases and records 457 total tokens.

ProviderAnswer keywordCitations metadataTotal TokensUndocumented policy case
http (transformResponse)3/30/3 (policyVersion=undefined)0Fails on all cases due to missing metadata
custom JS provider (metadata)3/32/3457 (165+153+139)Fails only on empty citations: []

With the custom JS provider, both documented cases pass, the undocumented policy case fails specifically on Citations metadata, and Promptfoo aggregates all 457 tokens (165 + 153 + 139) across the run.

Catching stale disk cache passes with –no-cache

The sharpest operational trap with the built-in http provider is Promptfoo’s default disk cache. Internally, the http provider calls fetchWithCache, keying cached responses on the request URL, method, headers, and body under PROMPTFOO_CACHE_PATH.

When you change your backend code or retrieval index without changing the prompt or test variables, the outgoing HTTP request looks identical. Promptfoo skips the network call, replays the cached response (cached: true), and reports a green pass even though your server is now broken.

Here is the three-step reproduction against the local server:

  1. Run 1 (mode=v1, cache enabled): The server returns the valid rollback answer. Promptfoo finishes with 2 passed (100%), exit=0, and GET /__stats reports requestCount: 2.
  2. Inject regression and Run 2 (mode=v2-bug, cache enabled): After switching the server to v2-bug (which returns "Restart the container manually and clear the Redis cache."), re-running the same eval command still prints 2 passed (100%), 2 cache hits (100%), and exit=0. GET /__stats stays at requestCount: 2 (zero new requests), and the JSON output marks each result as cached: true.
  3. Run 3 (mode=v2-bug, --no-cache): Passing --no-cache bypasses the disk cache and sends two fresh requests (requestCount: 4). Promptfoo immediately catches the regression with 1 passed (50.00%), 1 failed (50.00%), and exit=100.

Terminal output contrasting a stale cache pass against --no-cache catching a local HTTP API regression Figure 2. Terminal summary from the local HTTP API (127.0.0.1:4101) cache test: Run 2 returns a stale pass (requestCount: 2, cached: true) after switching to v2-bug, while Run 3 with --no-cache hits the updated server (requestCount: 4) and exits with 100.

Always pass --no-cache (or set PROMPTFOO_CACHE_ENABLED=false) when evaluating a local or staging backend API with the built-in http provider. By contrast, a custom JS provider calling Node’s built-in fetch() directly does not go through fetchWithCache, so every run hits your server unless you add caching yourself.

When not to use Promptfoo and production checklist

Promptfoo fits semantic and grounding checks on AI responses, but it shouldn’t replace your standard backend test suite. Keep these checks in JUnit, Vitest, or Supertest instead:

  • HTTP contract and auth checks: 401/403 authorization failures, 400 validation errors, rate limiting (429), and timeout handling are faster and clearer in standard integration tests.
  • Database and side-effect assertions: Verifying rows written, events published, or idempotency keys requires direct state inspection outside Promptfoo’s request-response model.
  • Load and latency benchmarking: latencyMs in Promptfoo is useful for spotting gross slowdowns, not for measuring p95/p99 throughput under concurrency (use a load generator like k6 for that).

Before wiring backend API evals into your team repo or CI, check four things:

  1. Inject auth tokens through environment variables: Reference secrets via "{{env.DOCS_API_TOKEN}}" instead of hardcoding them in YAML, and verify that exported -o results.json artifacts don’t leak sensitive request headers.
  2. Disable cache for moving backends: Pass --no-cache or PROMPTFOO_CACHE_ENABLED=false whenever backend code, prompts, or retrieval indexes change between runs.
  3. Pick the provider by assertion needs: Use built-in http + transformResponse for text-only checks; switch to a custom JS provider as soon as you need metadata fields (citations, policyVersion) or tokenUsage tracking.
  4. Isolate config and cache paths in CI: Set PROMPTFOO_CONFIG_DIR and PROMPTFOO_CACHE_PATH to a per-job temporary directory so stale local state never bleeds across runs.

References

Configure HTTP/HTTPS endpoints for custom LLM integrations with dynamic request transforms, variable substitution, and multi-provider API compatibility
Configure custom JavaScript providers to integrate any API or service with promptfoo's testing framework using TypeScript, CommonJS, or ESM modules
Configure caching for faster LLM evaluations. Learn cache strategies, storage options, and performance optimization for prompt testing workflows.
Write JavaScript assertions to validate LLM outputs, return custom scores, and run asynchronous checks. Use inline expressions or scripts in your eval config.
This post is licensed under CC BY 4.0 by the author.