Apache APISIX Plugin

Add cost-aware model routing to Apache APISIX with the Nadir custom plugin, loaded through extra_lua_path, under the same design contract as the Kong plugin.

Cost-aware model routing for Apache APISIX, installed as a custom plugin with no application code changes. Same design contract as the Kong plugin.

Your application changes one string. Everything else, auth, provider keys, streaming, rate limits, and logging, stays exactly as APISIX already does it. This plugin only supplies the routing decision.

The whole application change
resp = client.chat.completions.create(
-   model="claude-opus-4-6",
+   model="nadir-auto",
    messages=[...],
)

nadir-auto is a virtual model. Inside APISIX, the plugin reads the prompt, calls /v1/recommend to ask which real model fits, and rewrites the request body before it leaves the gateway. There is no Nadir service to run alongside it.

Install

APISIX's Plugin Hub lists only Apache-authored plugins, so third-party plugins are distributed through extra_lua_path. That is what this plugin is laid out for.

1. Put the plugin where APISIX can read it
git clone https://github.com/NadirRouter/apisix-plugin-nadir /opt/nadir
# resulting in: /opt/nadir/apisix/plugins/nadir.lua
2. conf/config.yaml
apisix:
  # Point at the directory CONTAINING apisix/plugins/, not at the file.
  # A ';'-separated list works if you already have custom plugins.
  extra_lua_path: "/opt/nadir/?.lua"

plugins:
  - nadir
  # ... plus every built-in you use, see the warning below
3. Restart, the plugin list is read at boot
apisix reload

# Confirm it loaded before writing any route against it.
curl -s http://127.0.0.1:9180/apisix/admin/plugins/list \
  -H "X-API-KEY: $ADMIN_KEY" | grep nadir

Warning

The plugins: list replaces the defaults wholesale. APISIX does not merge your list with the built-in one. Copy the default list out of apisix/cli/config.lua in your release and append nadir, or you will silently lose every built-in plugin you did not name. One non-obvious entry: if you enable ai-proxy, you must also enable prometheus, which ai-proxy requires transitively. Without it, every route referencing ai-proxy errors with unknown plugin [ai-proxy].

Configure a route

The standalone, DB-less form.

conf/apisix.yaml
routes:
  # Nadir in front of an OpenAI-compatible upstream. Nadir rewrites `model`
  # in the body and the provider honours it.
  - id: nadir-openai
    uri: /v1/chat/completions
    upstream:
      type: roundrobin
      scheme: https
      pass_host: node
      nodes:
        "api.openai.com:443": 1
    plugins:
      nadir:
        api_url: "https://api.getnadir.com"
        recommend_path: /v1/recommend
        api_key: "$ENV://NADIR_API_KEY"
        virtual_model: nadir-auto
        default_model: claude-sonnet-4-6
        timeout_ms: 250

  # Nadir + ai-proxy. Nadir supplies the decision, ai-proxy owns provider
  # auth and streaming. Leave options.model UNSET so ai-proxy takes the
  # model from the (Nadir-rewritten) body.
  - id: nadir-aiproxy
    uri: /ai/chat
    plugins:
      nadir:
        api_url: "https://api.getnadir.com"
        api_key: "$ENV://NADIR_API_KEY"
        default_model: claude-sonnet-4-6
      ai-proxy:
        provider: anthropic
        auth:
          header:
            x-api-key: "$ENV://ANTHROPIC_API_KEY"

Or through the Admin API, in etcd mode.

Shell
curl -sS "$ADMIN/apisix/admin/routes/nadir-chat" \
  -H "X-API-KEY: $ADMIN_KEY" -X PUT -d '{
  "uri": "/v1/chat/completions",
  "upstream": {
    "type": "roundrobin",
    "scheme": "https",
    "pass_host": "node",
    "nodes": { "api.openai.com:443": 1 }
  },
  "plugins": {
    "nadir": {
      "api_url": "https://api.getnadir.com",
      "recommend_path": "/v1/recommend",
      "api_key": "$ENV://NADIR_API_KEY",
      "virtual_model": "nadir-auto",
      "default_model": "claude-sonnet-4-6",
      "timeout_ms": 250
    }
  }
}'

Keeping the API key out of the config

api_key is in the schema's encrypt_fields, so APISIX encrypts it at rest in etcd. For the value itself, use a secret reference rather than plaintext.

YAML
api_key: "$ENV://NADIR_API_KEY"            # process environment
api_key: "$secret://vault/1/nadir/api-key" # a configured secret manager

Info

Calls with a key are billed: the first 50 requests a month are free, then $0.002 each from a prepaid balance. When the balance is empty, Nadir answers HTTP 402 balance_empty and the plugin sends the request to default_model, so top up or turn on auto-recharge in Billing before you rely on it.

Configuration

FieldDefaultMeaning
api_urlhttps://api.getnadir.comNadir decision API base
recommend_path/v1/recommendDecision endpoint, no LLM call
api_keyrequiredX-API-Key for the decision call
virtual_modelnadir-autoThe sentinel model that opts into routing
default_modelclaude-sonnet-4-6Fail-open target
timeout_ms250Per-request decision budget
modelsunsetOptional candidate set; defaults to the models on the API key
response_headerstrueStamp x-nadir-* headers on the response
max_request_body_size1048576Bodies above this are passed through untouched
keepalivetruePool the connection to the decision API
keepalive_timeout_ms60000Idle timeout for that pool
keepalive_pool10Pool size

Guarantees

  • Fail-open. Any decision error or timeout means the request proceeds on default_model. If the body is unreadable or not JSON, the plugin touches nothing. A router outage never takes down inference.
  • Opt-in. Only requests with model: nadir-auto are routed. A real model name is honored and passed through untouched, so you can adopt on 5 percent of traffic first.
  • Bounded. The plugin calls the decision-only endpoint, which never invokes an LLM, and the whole call is bounded by timeout_ms, 250ms by default. The budget is split across connect, send, and read rather than applied to each, so the worst case is the number you configured and not 3 times it.

Seeing the decision

The decision rides back on the response the client already gets, so there is no second place to look.

x-nadir-model: claude-haiku-4-5
x-nadir-tier: simple
x-nadir-confidence: 0.983
x-nadir-routed: true

Set response_headers to false to suppress them.

Plugin ordering

Nadir sits at priority 1045 in the access phase. Both halves matter, because in APISIX the phase dominates the priority: every rewrite-phase plugin runs before every access-phase plugin, whatever the numbers say.

  • Auth plugins such as key-auth, jwt-auth, and openid-connect live in the rewrite phase, so they run before Nadir by phase alone and an unauthenticated request never spends a decision call.
  • ai-request-rewrite at 1073, ai-prompt-guard at 1072, and ai-rag at 1060 all run first, so Nadir routes on the final messages and a blocked prompt costs no decision call.
  • ai-proxy at 1040 and ai-proxy-multi at 1041 run after Nadir and dispatch the chosen model. ai-rate-limiting at 1030 meters the model actually dispatched.

APISIX's plugin development guide suggests priority 1 to 99 for custom plugins. That range is deliberately not used here: it would put Nadir after ai-proxy, and ai-proxy would dispatch nadir-auto before the rewrite ever happened.

Streaming

stream: true works. The body rewrite lands, the x-nadir-* headers arrive with the response headers, content-type: text/event-stream is preserved, and frames reach the client incrementally. The plugin registers no body_filter, so it never buffers a response.

Measured across a 5-frame stream produced 0.25s apart: Nadir to a plain upstream spread 0.91s, ai-proxy alone spread 0.89s, and ai-proxy with Nadir spread 0.90s. The control leg is the point, it shows the plugin is neutral. This is also where APISIX beats Kong, whose ai-proxy buffers server-sent events by itself.

Info

Point api_url at a self-hosted NadirClaw or Nadir instance instead of api.getnadir.com to keep the decision entirely in-network. Both speak the same endpoint contract, so it is a drop-in swap. See Self-Host.

What has been validated

Verified against apache/apisix:3.17.0-debian, standalone and DB-less, on a hermetic harness that mocks both the decision API and the LLM upstream: the plugin loads under extra_lua_path, the schema is accepted, the body rewrite reaches the upstream with a recalculated content-length, fail-open and opt-in behave as documented, $ENV:// secret references resolve on the wire, key-auth rejects before a decision call is spent, the ai-proxy pairing dispatches the chosen model, and server-sent events stream incrementally with headers intact.

Not yet exercised against etcd-backed deployments, APISIX 3.15 or 3.16, or the APISIX Ingress Controller, and the harness mocks the decision call rather than hitting api.getnadir.com.

Pages on this site

Machine-readable summaries of this site: llms.txt and llms-full.txt.