New
Apps 6,329Makers 6,308This week 13
Promote your app−30%
Conifer SDK screenshot 1
10views in
the last 30 days

Conifer SDK

One API key in front of every major model, with the exact cost of every call

Built with Claude/Claude Code

by coniferkit · Unclaimed · added Oct 29, 2026
no ratings0 comments
Conifer

The Conifer SDK

One API key in front of every major model — and the exact cost of every call.

Docs

Docs · Migrating · Issues · Contributing

What this is, in plain terms

Conifer is an API gateway. You get one API key and one base URL, and behind it are models from OpenAI, Anthropic, Google, DeepSeek, Moonshot and others. You do not sign up with each vendor and you do not juggle five keys.

It works with the tools you already use, because it speaks the OpenAI and Anthropic APIs. If an app lets you set a custom base URL and API key (Cursor, Cline, SillyTavern, LibreChat, Codex, Claude Code, anything using the openai package), point it here and it works:

Base URL:  https://api.conifer.build/v1
API key:   sk-conifer-…      (get one at https://conifer.build/console#/keys)
Model:     claude-fable-5, gpt-5.5, deepseek-v4, …

That is the whole product. This repo is the optional SDK for people who want more than a drop-in: a TypeScript and Python client, plus an MCP server.

Two things you get here that other gateways do not:

  1. The exact cost of every call, returned with the answer, itemized, as an integer number of nanodollars. Not an estimate from token counts.
  2. A hard spending cap per request. Set maxCostNanoUsd and the gateway refuses the call before it happens if it could cost more.

Pricing: you are charged the model's own list price, no markup. If you'd rather use your own OpenAI/Anthropic keys, Conifer will proxy them for free.

See the router pick a model

Conifer can also pick the model for you based on how hard the question is. In the recording below, an easy question ("what port?") goes to a cheap fast model and answers in 3 seconds. A hard one, with the dial set to best, goes to Claude Opus 5 and takes a minute. Same session, real screen recording, not sped up.

Claude Code running through Conifer's router. The router panel shows the turn routed to kimi-k3 with the cost dial on cheap; the answer, 5432, came back in 3 seconds. Click to watch the full recording on conifer.build.
▶ Watch the router choose (50s, no audio) — a real screen recording, playing on conifer.build

Let the router pick

Send model: "auto" and the gateway chooses the model for that turn, serves it, and tells you which one in the receipt:

const answer = await conifer.chat({
  model: "auto",                                  // or "balanced" | "best"
  messages: [{ role: "user", content: "What is 17 * 23?" }],
  maxTokens: 200,
});
console.log(answer.receipt.effectiveModel);       // "deepseek-v4-flash"
console.log(answer.receipt.reason);               // "routed"

When the router could not pick in time and the default model served instead, receipt.pinFallback (pin_fallback in Python) says why: timeout, unavailable, breaker_open or saturated, with more values possible later. receipt.reason reads as_requested on such a turn, so this field is what tells a skipped routing apart from a model you named.

auto is the balanced policy: the router scores the question against every model you can call, keeps the ones predicted to answer it, and takes the best value among them. best ranks that same shortlist on ability alone and costs what the strongest model costs. The router has two more names, cost-effective and fast, muted on the gateway until their value floor is measured: they are not listed, and asking for one gets the default model, not a quiet substitute. This README will change when that does.

Measured on held-out task families the router had never seen (n = 4,171): balanced matched the best single frontier model within the noise on accuracy at two thirds of its cost. It does not beat that model on accuracy, and it is not meant to; it is meant to keep landing near it as the catalog changes, without anyone re-picking.

If you would rather make the call yourself, the same decision is one request away, free, with no completion attached:

const pick = await conifer.route({ query: text, policy: "balanced" });
pick.model;        // "deepseek-v4-flash" — always a model your key can call
pick.fallbacks;    // ["gemini-3.6-flash", "claude-haiku-4-5"] — next picks, in order
pick = conifer.route(RouteRequest(query=text, policy="balanced"))

It returns a model id and up to three fallbacks. It does not return scores, and it never will: the pick is the product, the scoring is not.

Install the SDK

npm i conifer-sdk                 # TypeScript
pip install "conifer-sdk[tls]"    # Python — keep the [tls] extra

export CONIFER_API_KEY='sk-conifer-…'   # get one at https://conifer.build/console#/keys

The npm package name is unscoped: conifer-sdk. (@conifer/sdk is not ours.) On macOS keep the [tls] extra, or a fresh python.org venv fails its first call with CERTIFICATE_VERIFY_FAILED — why.

Then:

import { Conifer, textOf } from "conifer-sdk";

const conifer = new Conifer();
const answer = await conifer.chat({
  model: "claude-haiku-4-5",
  messages: [{ role: "user", content: "three names for a build cache" }],
  maxTokens: 200,
  maxCostNanoUsd: 5_000_000,      // refuse this turn if it could cost over $0.005
});

console.log(textOf(answer));
console.log(answer.receipt.costUsd);            // "0.001250000" — this exact call
console.log(answer.receipt.costComponentsNanoUsd); // itemized across four token classes
console.log(answer.receipt.pricingIdentity);       // "sha256:…" — the rate card that itemization used
from conifer_sdk import Conifer, ChatRequest

conifer = Conifer()
answer = conifer.chat(ChatRequest(
    model="claude-haiku-4-5",
    messages=[{"role": "user", "content": "three names for a build cache"}],
    max_tokens=200,
    max_cost_nano_usd=5_000_000,
))
print(answer.text, answer.receipt.cost_usd)

# Streaming, with the same semantics as the TypeScript twin.
for chunk in conifer.stream(ChatRequest(model="claude-haiku-4-5", messages=[...])):
    ...
print(conifer.stream_receipt.effective_model)   # routing arrives with the head

The cost is on the body too, not only the headers:

answer.usage.cost;          // 0.00178  — decimal USD, the field OpenRouter uses
answer.usage.cost_nanousd;  // 1780000  — the exact integer the gateway billed
answer.receipt.costNanoUsd; // the same number; the receipt stays the authority

That duplication is deliberate. Conifer discloses cost on a response header, and OpenRouter puts it in usage.cost — so every logging pipeline, request recorder, LangChain/LiteLLM callback and JSON dump keeps the body and throws the headers away. A team migrating would lose their cost column and never see why. It matters more here than elsewhere: a normal caller cannot read their usage history back, so the receipt on the turn is their only record of what they spent.

It is additive only — a cost the gateway sends itself always wins — and it is absent where the cost is unknown, because a 0 would read as "free".

On a streamed turn the cost headers are absent in both languages, and that is the wire being honest rather than a gap: the response head is sent before the first token and the money settles after the last. Reconcile a stream from its terminal usage chunk, which the SDK always requests.

When the answer comes back empty

The most confusing thing this API can return is "", and the reason is never in the content. A reasoning model spends maxTokens on its thinking block first — so a budget that looks generous for a one-word answer can be consumed entirely before the visible answer starts. You get empty content, finish_reason: "length", and a bill for every one of those output tokens. Measured on both the OpenAI and Anthropic wires: claude-fable-5 at maxTokens: 16 does exactly this; at 200 the same prompt answers fine.

That empty string looks identical to a refusal, a content filter, or a broken SDK. So the SDK reads the one distinguishing field for you:

const answer = await conifer.chat({ model, messages, maxTokens: 16 });
textOf(answer);        // ""
emptyReason(answer);   // "the model hit maxTokens before emitting visible text.
                       //  On a reasoning model the thinking block is spent FIRST…"
answer.text          # ""
answer.empty_reason  # the same sentence, or None when there is nothing to explain

It returns undefined/None whenever there is text — and also for a tool call, because empty text beside a tool call is the correct answer, not an absence.

Embeddings

Same key, same receipts, same cost ceiling — and the vectors arrive as plain numbers whatever the wire did.

const result = await conifer.embeddings.create({
  model: "text-embedding-3-small",
  input: ["alpha", "beta"],       // one vector per input, in order
});

console.log(result.data[0].embedding.length); // 1536
console.log(result.receipt.costUsd);          // "0.000000040" — settled, in band
from conifer_sdk import EmbeddingsRequest, vector_of

result = conifer.embed(EmbeddingsRequest(
    model="text-embedding-3-small",
    input="hello world",
))
print(len(vector_of(result)), result.receipt.cost_nano_usd)

Three things worth knowing, because they are decisions rather than defaults:

  • base64 on the wire, numbers in your hands. The SDK requests encoding_format: "base64" and decodes it for you. A JSON float array spends ~20 bytes per dimension against base64 float32's 5.33, so this is roughly 3x less network on the one payload that is actually large. It is applied silently only because it is exactly lossless — verified live, text-embedding-3-small returns identical values both ways, max absolute difference 0.0. Pass encodingFormat: "float" for JSON floats; raw always holds the provider's own body either way.
  • Embeddings bill on input only. There is no completion, so there is no output term, no max_tokens, no sampling knobs and no stream. Unlike a streamed chat turn, the cost is on this very response.
  • Refusals are legible. A chat model sent here is a 400 naming the chat door, not an opaque upstream 404 charged to you; token-id input is refused client-side before any spend, because the gateway cannot price token ids it did not tokenize.
  • Some models are not deterministic, and that is upstream of us. Measured 2026-08-27: six identical bge-m3 calls returned four distinct vectors, differing by up to 2.2e-4, while text-embedding-3-small returned the same bytes every time. Batched GPU inference reorders float accumulation depending on what else shares the batch. It is far below anything that changes a ranking, but if you are diffing stored vectors or asserting on exact values in a test, compare with a tolerance rather than ==.

conifer.cheapestFor(["embeddings"]) picks the cheapest embedding seat the catalog actually declares, and each catalog row carries embeddingDimensions (embedding_dimensions in Python) so you can size a vector(1536) column before spending a token — getting that wrong means a migration on a populated table.

conifer.models() also exposes minOutputTokens and outputTokenLimitSupported (min_output_tokens and output_token_limit_supported in Python) when the gateway declares them. The minimum includes reasoning tokens. A support value of false means the gateway refuses that seat's completions before spending; cheapestFor() and pickCheapest() skip it. Missing fields remain undeclared. On older gateways, these fields may be absent, and request admission remains authoritative.

Deferred jobs

For work that is not interactive — an overnight re-index, a bulk classification, an eval sweep — submit the turn as a job and collect it later.

const job = await conifer.defer({
  model: "claude-fable-5",
  messages: [{ role: "user", content: "classify these 400 tickets…" }],
});
console.log(job.jobId, job.status);          // "job-gw-…", "queued"

const answer = await conifer.jobs.wait(job.jobId);
console.log(textOf(answer), answer.receipt.costUsd);
job = conifer.defer(ChatRequest(model="claude-fable-5", messages=[...]))
answer = conifer.jobs_wait(job.job_id)       # or job_status / job_result
  • chat({ defer: true }) throws, on purpose. A deferred turn is answered with 202 and a job envelope, not a completion — so chat() has nothing to return. The previous behavior was worse than an error: the turn was accepted and debited, and came back as choices: [], indistinguishable at the call site from a model that answered with nothing.
  • The window floor is the gateway's, not ours. Deferred work rides a provider batch, so the gateway requires a completion window of at least 24h and refuses anything narrower rather than quietly serving it synchronously at a different price. defer() defaults to that floor so the common call works.
  • wait() stops on terminal states. cancelled, failed and expired never change; a poll loop keyed only on "is it ended yet" spins until the process dies. It also backs off exponentially, and on timeout it raises without cancelling — killing work you already paid for because a client-side clock ran out is not a decision an SDK should make for you.

Keep your client. Get the receipts anyway.

The exact per-turn cost is the thing Conifer has that other gateways do not, and it arrives on the response headers — which openai, @anthropic-ai/sdk, LangChain, LiteLLM and the Vercel AI SDK all throw away. So pointing an existing client at Conifer works perfectly and makes the whole differentiator invisible.

You do not have to rewrite anything to fix that. Every one of those clients takes an injected fetch (or an http_client), so hand it one that reads the receipt on the way past:

import OpenAI from "openai";
import { ReceiptCollector } from "conifer-sdk";

const receipts = new ReceiptCollector();
const openai = new OpenAI({
  baseURL: "https://api.conifer.build/v1",
  apiKey: process.env.CONIFER_API_KEY,
  fetch: receipts.fetch,          // the only line that changes
});

await openai.chat.completions.create({ model: "claude-fable-5", messages });

receipts.last.costNanoUsd;   // 580000 — that exact call
receipts.total.costUsd;      // "0.001170000" — the whole session
import httpx
from openai import OpenAI
from conifer_sdk import ReceiptCollector

receipts = ReceiptCollector()
openai = OpenAI(
    base_url="https://api.conifer.build/v1",
    api_key=os.environ["CONIFER_API_KEY"],
    http_client=httpx.Client(event_hooks={"response": [receipts.httpx_hook]}),
)

It never reads the response body. A body is a single-use stream that belongs to the caller: consuming it to find a cost would break streaming and double memory for everyone, and it would fail far from where it was caused. Headers are already materialized, so observing them costs nothing and changes nothing — the same response object is handed straight back.

SpendBudget answers the other question, the one no single request can:

const budget = new SpendBudget(5_000_000_000);   // $5 for this whole job
const openai = new OpenAI({ /* … */ fetch: budget.fetch });

It refuses the next call once the budget is gone. It cannot refund the one that crossed the line, because a turn's cost is only known after it settles — so the true worst case is budget + one turn. Pair it with a per-request maxCostNanoUsd and that overshoot is bounded rather than open-ended.

This works on all three wires

The gateway serves three request shapes, and the receipt headers are identical on every one. Verified against the real vendor SDKs, unmodified:

wire client verified
POST /v1/chat/completions openai → .chat.completions ✅ receipts, streaming
POST /v1/responses openai → .responses (the only wire Codex ≥ 0.145 speaks) ✅ receipts
POST /v1/messages anthropic → .messages ✅ receipts, streaming
import anthropic
client = anthropic.Anthropic(
    base_url="https://api.conifer.build",     # note: no /v1 on the Anthropic door
    api_key=os.environ["CONIFER_API_KEY"],
    http_client=httpx.Client(event_hooks={"response": [receipts.httpx_hook]}),
)

This SDK deliberately does not reimplement the Responses or Messages wires. Your vendor SDK already speaks them correctly, the gateway relays them faithfully, and a third implementation of someone else's wire is a liability, not a feature. ReceiptCollector is the piece that was missing, and it is wire-agnostic because it reads headers.

Why this exists when the OpenAI SDK already works

It still does, and it remains the right choice for a plain drop-in. This package exists for the four things the OpenAI client structurally cannot give you:

The receipt Every response carries the exact integer nanodollar cost of that call, itemized across fresh input, cache write, cache read, and output. No second stats request, no float dollars, no estimating from token counts and a price table.
Named refusals A 402 is three different problems: the account is out of credit, your own per-request ceiling refused this turn, or this key's lifetime cap is spent. The remedies are unrelated — top up, raise the ceiling, or rotate the key — so they are ConiferPaymentError, ConiferCostCeilingError and ConiferKeySpendCapError, not one status number. A 409 splits the same way: two of them mean "retry shortly" and are retried for you; the third never will be.
The spend ceiling maxCostNanoUsd is a hard, server-enforced bound checked before any upstream call. The gateway refuses rather than serves.
Portability Migration shims that refuse what Conifer cannot honor instead of dropping it silently.

Migrating from another gateway

Conifer speaks the OpenAI wire, so the base URL and key are most of the work:

// Vercel AI Gateway  ->  Conifer
- baseURL: "https://ai-gateway.vercel.sh/v1", apiKey: process.env.AI_GATEWAY_API_KEY
+ baseURL: "https://api.conifer.build/v1",    apiKey: process.env.CONIFER_API_KEY

// OpenRouter  ->  Conifer   (vendor/model ids resolve unchanged)
- baseURL: "https://openrouter.ai/api/v1",    apiKey: process.env.OPENROUTER_API_KEY
+ baseURL: "https://api.conifer.build/v1",    apiKey: process.env.CONIFER_API_KEY

The rest is the part that usually goes wrong quietly. The shims refuse what Conifer cannot honor, and name the replacement:

import { fromOpenRouter } from "conifer-sdk";

fromOpenRouter({ model: "anthropic/claude-opus-5", messages, provider: { order: ["anthropic"] } });
// ConiferPortabilityError: OpenRouter's `provider` preferences pin a serving host.
// Conifer picks the host for the admitted model itself, by price and health, and no
// client can override it. Remove the block, or use `maxCostNanoUsd` if the goal was
// cost control.

That is deliberate. Dropping a prov

Description taken from the repository README.

Ratings

–
0 ratings
5 0
4 0
3 0
2 0
1 0

Rate this app

Sign in to rate

Comments 0

Sign in to comment

No comments yet.

Related apps

#llm · #api · #cost