docs / reference
SDK Reference
Complete reference for the noburn Python and Node.js SDKs.
Python SDK
Installation
pip install noburnRequires Python 3.9+.
NoburnGuard
The main class. Create one instance per project and reuse it across requests.
from noburn import NoburnGuard
guard = NoburnGuard(
api_key="sk-nb-xxxxxxxxxxxxxxxx",
project_id="your-project-id",
budget_cap_usd=10.00,
)Constructor options
| Parameter | Type | Required | Description |
|---|---|---|---|
api_key | str | ✓ | Your project SDK key from the dashboard |
project_id | str | ✓ | Project UUID from the dashboard |
budget_cap_usd | float | — | Monthly spend cap in USD. Calls are blocked once exceeded |
base_url | str | — | Override API endpoint (default: https://noburn.dev) |
timeout | float | — | Request timeout in seconds (default: 2.0) |
on_error | str | — | Behavior when the noburn API is unreachable: "allow" (default — fail open, never breaks your app) or "block" (fail closed — blocks with reason "noburn_unreachable") |
fast_path | bool | — | Decide most checks locally from a short server lease (default: True). See Fast path |
guard.check()
Checks whether a planned LLM call should be allowed. Call this before every LLM API call.
result = guard.check(
model="gpt-4o",
estimated_tokens_in=1500,
estimated_tokens_out=500,
end_user_id="user_abc123", # optional — for per-user tracking
context={"plan": "free"}, # optional — matched against policy rules
)Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
model | str | ✓ | Model name as it appears in your LLM provider's API |
estimated_tokens_in | int | ✓ | Estimated prompt token count |
estimated_tokens_out | int | — | Output tokens the call may write: pass max_tokens when you set it. Leave it out (or 0) when you don't know, and noburn reserves what this project's calls to this model have actually written (see Output estimates) |
end_user_id | str | — | Identifier for the end user. Enforces that user's per-user budget cap |
run_id | str | — | Run identifier from start_run(). Enforces that run's per-run budget cap |
cost_usd | float | — | Cost override for unrecognized models. For recognized models, noburn prices the call server-side from token counts |
context | dict | — | Arbitrary key-value pairs matched against server-side policy rules (e.g. {"plan": "free"}) |
Return value: CheckResult
| Field | Type | Description |
|---|---|---|
blocked | bool | True if the call should be blocked |
block_reason | str | None | Why the call was blocked: "budget_exceeded", "user_budget_exceeded", "quota_exceeded", "plan_budget_exceeded", "run_budget_exceeded", "policy_rule", "plan_limit_exceeded", or "noburn_unreachable" |
forced_model_tier | str | None | "small" or "big" when a policy rule forces a cheaper/stronger model; otherwise None |
spend_usd | float | Current monthly project spend at time of check |
budget_cap_usd | float | None | The active project budget cap |
remaining_usd | float | None | Project budget remaining. None if no cap |
user_spend_usd / user_cap_usd / user_remaining_usd | float | None | Per-user budget state (when end_user_id is passed) |
run_spend_usd / run_cap_usd / run_remaining_usd | float | None | Per-run budget state (when run_id is passed) |
quota | Quota | None | The end user's usage quota — see Usage quotas |
winding_down / wind_down_scope | bool / str | None | True when this call is allowed but the tightest cap ("project", "user", "run" or "plan") can't pay for another like it. See Wind-down |
estimated_tokens_out / output_estimate | int | None / str | None | Output tokens the server priced the call with, and where that came from: "caller", "history" or "fallback" |
guard.remaining()
q = guard.remaining(end_user_id="user_123", plan="free")
# Quota(limit_type="requests", limit=20.0, used=8.0, remaining=12.0, window="day",
# resets_at="...", plan="free", upgrade_suggested=False) — or NoneReturns None when no quota applies or on any network error. Raises only NoburnAuthError.
Pricing authority
The SDK includes a local pricing table for offline fallback estimates only. On every check() and record(), noburn recomputes cost server-side from token counts. Call guard.fetch_pricing() (Python) or guard.fetchPricing() (Node) to refresh the local table from GET /api/v1/pricing (global rates + your project overrides). For unrecognized models, pass cost_usd explicitly or rely on the server's conservative token floor.
guard.record()
Records the actual outcome of an LLM call. Always call this after a successful call.
guard.record(
model="gpt-4o",
tokens_in=1423,
tokens_out=487,
cost_usd=0.00848,
was_blocked=False,
end_user_id="user_abc123",
latency_ms=1240,
)Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
model | str | ✓ | Model name |
tokens_in | int | ✓ | Actual prompt token count, including cached tokens |
tokens_out | int | ✓ | Actual completion token count |
cost_usd | float | ✓ | Actual cost in USD |
cached_tokens_in | int | — | Of tokens_in, how many were read from the provider's prompt cache (OpenAI's prompt_tokens_details.cached_tokens, Anthropic's cache_read_input_tokens) |
cache_write_tokens_in | int | — | Of tokens_in, how many were written to the prompt cache (Anthropic's cache_creation_input_tokens) |
was_blocked | bool | ✓ | Whether the call was blocked |
end_user_id | str | — | Same identifier passed to check() |
run_id | str | — | Same run identifier passed to check() |
latency_ms | int | — | End-to-end latency in milliseconds |
block_reason | str | — | Reason if was_blocked=True |
timestamp | str | — | ISO 8601 timestamp (default: now) |
record() is fire-and-forget — it returns immediately and never raises. The event is delivered on a background worker with retry. Call guard.flush() before your process exits to drain any queued events.
Per-user budgets
Pass end_user_id to track spend per user. You can set per-user caps in the dashboard under End-User Budgets — once a user crosses their cap, their calls are blocked with reason "user_budget_exceeded", independently of the project budget.
# Each user has independent spend tracking
result = guard.check(
model="claude-3-5-sonnet-20241022",
estimated_tokens_in=800,
estimated_tokens_out=200,
end_user_id=f"user_{request.user.id}",
)Error handling
check() never raises for budget decisions. By default it fails open: if the noburn API is unreachable, the call is allowed (blocked=False). Set on_error="block" to fail closed instead — unreachable means blocked=True with reason "noburn_unreachable". The only exception check() can raise is NoburnAuthError (invalid SDK key).
from noburn import NoburnGuard, NoburnAuthError
guard = NoburnGuard(api_key="sk-nb-…", project_id="…", on_error="block")
try:
result = guard.check(model="gpt-4o", estimated_tokens_in=1000, estimated_tokens_out=300)
except NoburnAuthError:
# Invalid SDK key — fix your credentials
raise
if result.blocked:
handle_blocked(result.block_reason)start_run() is stricter: it raises on network/auth failure (NoburnTimeoutError on timeout, NoburnAuthError on a bad key), since a run must be registered before you proceed.
Agent runs
A run bounds a single agent invocation with its own budget cap, separate from the project and per-user caps. Start a run, thread its run_id through check()/record(), then end it.
run = guard.start_run(budget_cap_usd=0.50) # StartRunResult(run_id, budget_cap_usd, started_at)
result = guard.check(
model="gpt-4o",
estimated_tokens_in=1000,
estimated_tokens_out=300,
run_id=run.run_id,
)
# ... make the LLM call ...
guard.record(model="gpt-4o", tokens_in=980, tokens_out=290,
cost_usd=0.005, was_blocked=False, run_id=run.run_id)
summary = guard.end_run(run.run_id) # EndRunResult(status="completed" | "budget_exceeded", spend_usd, ...)| Method | Description |
|---|---|
start_run(budget_cap_usd=None, end_user_id=None, metadata=None) | Registers a run. Raises on network/auth error. |
end_run(run_id) | Finalizes a run; returns EndRunResult or None on a network error. |
stop_run(run_id, reason=None) | Stops a run from outside the agent; returns StopRunResult or None on a network error. See Stopping a run. |
guard.estimate_cost()
cost = guard.estimate_cost("gpt-4o-mini", tokens_in=980, tokens_out=290) # USD, floatThis estimates a call's cost from the local pricing table, which you can refresh with fetch_pricing(). Use it for the cost_usd you pass to record(). The server recomputes cost on ingest anyway. Token counts are cleaned the same way the Node SDK's estimateCost() cleans them: None, NaN, infinities, negatives and non-numbers count as 0, and fractional counts are kept. Unknown models are priced at the conservative unknown-model floor. Pass cached_tokens_in= and cache_write_tokens_in= to price cached prompt tokens at the model's cache rates.
Prompt caching. Anthropic's raw input_tokens leaves out cached tokens; add cache_read_input_tokens and cache_creation_input_tokens back when you compute tokens_in. OpenAI's prompt_tokens already includes them. The integrations do this for you.
NoburnBlockedError
from noburn import NoburnBlockedError
try:
llm.invoke("Hello") # any call guarded by a noburn integration
except NoburnBlockedError as e:
e.block_reason # "budget_exceeded" | "user_budget_exceeded" | "run_budget_exceeded" | "policy_rule" | ...
e.model # model id that was blocked
e.check_result # the CheckResult behind the decisionThe framework integrations raise it when noburn blocks a call, before the request reaches the provider. check() itself never raises it: it returns blocked=True.
Fast path
Since 0.4.0 most check() calls make no network call. When the server allows a call with room to spare, it also leases the SDK a small slice of what's left: a tenth of the remaining budget (at most $5 and 50 calls), for 10 seconds. Later calls with the same model, end user, run and context are decided locally against that slice, and the SDK renews the lease in the background before it runs out. A locally decided call returns decidedLocally: true (decided_locally in Python).
The caps stay hard:
- Leases are reservations. Every check counts all active leases in the project as already spent, so leases held by different servers can never add up to more than the real headroom.
- Near a cap there is no lease. Once a tenth of the headroom can't cover two more calls, every call goes to the server, so the last calls before a cap always get a server decision.
- Changes arrive within 10 seconds. A stopped run, a lowered cap or a new policy rule reaches a server holding a lease when the lease ends or is renewed. A run stopped with
stopRun()from the same process stops at once.
The only cost is that spend made under a lease is counted twice for up to 10 seconds (as recorded spend and as the reservation), which can block slightly early, never late.
Set fastPath: false (fast_path=False) to send every check to the server.
Output estimates
A check prices a call before the model has written anything, so it needs the output length. When you pass max_tokens (or your own estimate), that is used. When you don't, noburn reserves what this project's calls to that model have actually written: the 95th percentile of output tokens over the last 30 days, or 2,048 tokens until there are 20 calls to learn from. About 5% of calls can then run past the reservation, instead of most of them.
Before SDK 0.11.0 the integrations assumed 256 output tokens and a direct check() without an output estimate assumed 0. On real traffic most gpt-5 and gpt-5-mini calls write more than 256, so a check could admit a call that then pushed a user past their cap. max_tokens itself is never changed, so no response is cut off.
The integrations also count tool definitions (and earlier tool calls in the conversation) in the prompt estimate, since providers bill them as prompt tokens.
Wind-down
When a check allows a call but the tightest cap can't pay for another one like it, the result says so: winding_down / windingDown is true and the scope names the cap. That is the moment to ask the model to finish with an answer, instead of having its next call refused mid-task and the run ending with nothing.
- AI SDK:
noburnMiddlewareadds a note to that call asking the model to give its final answer without calling more tools. The note goes last, so a cached prompt prefix is kept.windDown: falseturns it off. - LangChain: a callback can't change the prompt, so pass
onWindDown(Node) oron_wind_down(Python) and finish from there, for example by not offering tools on the next step. - Direct
check(): readwindingDownand handle it in your agent loop.
const check = await guard.check({ model: 'gpt-5', estimatedTokensIn: 2400, runId });
if (check.windingDown) messages.push({ role: 'user', content: 'Budget is nearly used. Give your final answer now.' });Loop detection
The framework integrations (Vercel AI SDK middleware and LangChain, in both SDKs) stop an agent that is going in circles. Before each model call they rebuild the agent's steps from the tool calls and tool results already in the prompt. Since 0.6.0 they act at the first repeat:
- The model is told. As soon as the next identical step would be refused, the AI SDK middleware adds a note to that model call's prompt: which tool keeps returning the same thing, and that calling it the same way again stops the run. Models often change course when told; a run that does is never stopped.
- The repeated call is refused before it runs. If the model asks for that call anyway, its answer is replaced by
NoburnBlockedErrorand the tool never runs.
| Pattern | Refused when the model asks for | Default |
|---|---|---|
repeat | the same tool call after it returned the same result N times (the 3rd identical call) | 2 |
error | the same tool call after it failed the same way N times in a row (a success resets it) | 3 |
ping_pong | the step that would continue an alternation of N cycles | 3 |
The error has blockReason: 'loop_detected' and loop: { pattern, tool, count }. A blocked event shows in the dashboard as loop. When the call belongs to a run, the run is stopped so every process working on it stops too. The model call that asked for the refused tool was made, so its tokens are still metered.
LangChain callbacks can't change the prompt, so LangChain gets no note: onLoop / on_loop receives a warn event at the same moment instead, and loopNudge(event) / loop_nudge(event) returns the note text if you want to add it yourself.
Comparing results, not just calls, keeps progress apart from repetition: a status check going running → done, or a search with a new cursor, never counts. Steps are hashed in your process; no prompt or tool text is sent to noburn.
How well it works. We ran gpt-5-mini and gpt-4.1-mini on 9 small agent tasks (sdk/node/bench/loop-live.ts), 5 runs per task in each of 3 modes: detection off, stop only (no note), and the default note-then-stop. Four tasks can't succeed (a service that keeps saying "unavailable", a deploy missing an env var, tests no edit can fix, a search with no results), so the right answer is to stop and report. Five are healthy but look like loops: polling a job, waiting for a server to boot, a flaky API, paging.
| Loop tasks done right (off → stop only → note) | Healthy tasks done right (off → note) | Told → changed course | Spend on loop tasks (off → note) | |
|---|---|---|---|---|
| gpt-5-mini | 70% → 50% → 85% | 100% → 100% | 9 of 10 | $0.132 → $0.063 |
| gpt-4.1-mini | 90% → 60% → 100% | 80% → 80% | 10 of 10 | $0.011 → $0.009 |
Stopping without the note is worse than doing nothing: the model never gets to say what went wrong. The note is what makes early detection pay off. These are small samples (20 loop and 25 healthy runs per model and mode), so read them as direction, not precision. On baar-core's scripted loop eval (180 labeled traces) the defaults stop all 75 loops and none of the 105 healthy runs, with a median of 2 calls made after a loop starts. Refusing on the first repeat instead stopped 29% of healthy runs, which is why the first repeat gets a note and not a stop.
noburnMiddleware(guard, {
runId: run.runId,
loopDetection: { exemptTools: ['job_status'], ignoreArgs: ['request_id'] },
// loopDetection: false → off
// loopDetection: { nudge: false } → no note, still refuse the repeated call
// loopDetection: { maxRepeats: 4 } → the 0.5.0 limit
// loopDetection: { stopRun: false } → refuse the call but keep the run
});NoburnCallbackHandler(guard, run_id=run.run_id, loop_detection={"exempt_tools": ["job_status"]})- Waiting is not looping. Since 0.6.1 a short result that says the work isn't finished (
running,pending,queued,in progress,processing,booting,starting,initializing,waiting,not ready) never counts, so polling a job or a booting server is left alone. Change the pattern withinProgress/in_progress(a RegExp), or passfalseto count those results too. - Exempt other polls. A tool that legitimately returns the same thing many times in some other wording belongs in
exemptTools/exempt_tools. - What it can't see: a loop that rephrases its tool call every step never repeats exactly. Keep a run budget (
startRun({ budgetCapUsd })) for those. - Without a framework:
LoopDetectoris exported from both SDKs. Callbefore(tool, args)before each tool call (it throwsLoopDetectedError/ raisesLoopDetected) andafter(tool, args, { result })/after(tool, args, result=...)after it.
Node.js SDK
Installation
npm install @noburn/sdkRequires Node.js 18+. Works with TypeScript out of the box.
NoburnGuard
import { NoburnGuard } from '@noburn/sdk';
const guard = new NoburnGuard({
apiKey: process.env.NOBURN_API_KEY!,
projectId: process.env.NOBURN_PROJECT_ID!,
budgetCapUsd: 10.00,
});Constructor options
| Option | Type | Required | Description |
|---|---|---|---|
apiKey | string | ✓ | Your project SDK key |
projectId | string | ✓ | Project UUID |
budgetCapUsd | number | — | Monthly spend cap in USD |
baseUrl | string | — | Override API endpoint |
timeoutMs | number | — | Request timeout in ms (default: 2000) |
onError | 'allow' | 'block' | — | Behavior when the API is unreachable: 'allow' (default — fail open) or 'block' (fail closed — blockReason: 'noburn_unreachable') |
fastPath | boolean | — | Decide most checks locally from a short server lease (default: true). See Fast path |
guard.check()
const result = await guard.check({
model: 'gpt-4o',
estimatedTokensIn: 1500,
estimatedTokensOut: 500,
endUserId: 'user_abc123',
context: { plan: 'free' }, // optional — matched against policy rules
});
if (result.blocked) {
return new Response('Budget exceeded', { status: 402 });
}Options
| Option | Type | Required | Description |
|---|---|---|---|
model | string | ✓ | Model name |
estimatedTokensIn | number | ✓ | Estimated prompt tokens |
estimatedTokensOut | number | — | Output tokens the call may write: pass max_tokens when you set it. Leave it out (or 0) when you don't know (see Output estimates) |
endUserId | string | — | Identifier that enforces the user's per-user budget cap |
runId | string | — | Run id from startRun(); enforces that run's per-run budget cap |
costUsd | number | — | Cost override for unrecognized models (recognized models are priced server-side from token counts) |
context | Record<string, string> | — | Key-value pairs matched against server-side policy rules (e.g. { plan: 'free' }) |
Return: CheckResult
interface CheckResult {
blocked: boolean;
// 'budget_exceeded' | 'user_budget_exceeded' | 'quota_exceeded' | 'plan_budget_exceeded' | 'run_budget_exceeded'
// | 'policy_rule' | 'plan_limit_exceeded' | 'noburn_unreachable' | null
blockReason: string | null;
forcedModelTier: 'small' | 'big' | null; // set by a force_small/force_big rule
spendUsd: number;
budgetCapUsd: number | null;
remainingUsd: number | null;
// Present when endUserId / runId are supplied:
userSpendUsd?: number;
userCapUsd?: number | null;
userRemainingUsd?: number | null;
runSpendUsd?: number;
runCapUsd?: number | null;
runRemainingUsd?: number | null;
// The end user's usage quota, or null when none applies
quota?: Quota | null;
// This call is allowed, but the tightest cap can't pay for another like it
windingDown?: boolean;
windDownScope?: 'project' | 'user' | 'run' | 'plan' | null;
// Output tokens the server priced the call with, and where that came from
estimatedTokensOut?: number;
outputEstimate?: 'caller' | 'history' | 'fallback';
}
interface Quota {
limitType: 'usd' | 'requests';
limit: number;
used: number;
remaining: number; // max(0, limit - used)
window: 'day' | 'week' | 'month'; // UTC
resetsAt: string; // ISO timestamp
plan: string | null;
upgradeSuggested: boolean; // a plan quota is what blocks the user
}guard.remaining()
const q = await guard.remaining({ endUserId: 'user_123', plan: 'free' });
if (q) console.log(`${q.remaining} of ${q.limit} left`);Returns null when no quota applies or on any network error. Throws only NoburnAuthError. See Usage quotas.
guard.record()
await guard.record({
model: 'gpt-4o',
tokensIn: response.usage.prompt_tokens,
tokensOut: response.usage.completion_tokens,
// Optional: of tokensIn, how many came from the prompt cache (billed at a discount).
cachedTokensIn: response.usage.prompt_tokens_details?.cached_tokens,
costUsd: 0.00848,
wasBlocked: false,
endUserId: 'user_abc123',
latencyMs: 1240,
});Agent runs
Bound a single agent invocation with its own cap, threading runId through check()/record():
const run = await guard.startRun({ budgetCapUsd: 0.5 });
const check = await guard.check({
model: 'gpt-4o',
estimatedTokensIn: 1000,
estimatedTokensOut: 300,
runId: run.runId,
});
// ... make the LLM call ...
await guard.record({ model: 'gpt-4o', tokensIn: 980, tokensOut: 290, costUsd: 0.005, wasBlocked: false, runId: run.runId });
const summary = await guard.endRun(run.runId); // { status: 'completed' | 'budget_exceeded', spendUsd, ... }record() is fire-and-forget with background retry; call await guard.flush() before exit to drain queued events. startRun() throws on network/auth error (NoburnTimeoutError on timeout).
guard.estimateCost()
const costUsd = guard.estimateCost('gpt-4o-mini', 980, 290); // USD, numberThis estimates a call's cost from the local pricing table, which you can refresh with fetchPricing(). Use it for the costUsd you pass to record(). The server recomputes cost on ingest anyway. Token counts are cleaned the same way the Python SDK's estimate_cost() cleans them: null, undefined, NaN, ±Infinity, negatives and non-numbers count as 0, and fractional counts are kept. Pass { cachedTokensIn, cacheWriteTokensIn } as a fourth argument to price cached prompt tokens at the model's cache rates (tokensIn still counts every prompt token).
NoburnBlockedError
import { NoburnBlockedError } from '@noburn/sdk'; // also re-exported from /ai-sdk and /langchain
try {
await generateText({ model, prompt }); // any call guarded by a noburn integration
} catch (err) {
if (err instanceof NoburnBlockedError) {
err.blockReason; // 'budget_exceeded' | 'user_budget_exceeded' | 'run_budget_exceeded' | 'policy_rule' | ...
err.model; // model id that was blocked
err.checkResult; // the CheckResult behind the decision
}
}The framework integrations throw it when noburn blocks a call, before the request reaches the provider. With streamText, it goes to onError instead. check() itself never throws it: it returns blocked: true. It is the same class across all three entry points, so instanceof works whichever one you import it from.
Stopping a run
A runaway agent can be stopped from outside its own process: a supervisor, a cron job, a spend.spike webhook handler, or the Stop run button in the dashboard's Active Runs list. Once a run is stopped, every later check() carrying its run ID returns blocked: true with blockReason: 'run_stopped', so the agent halts at its next guarded LLM call. Stopping takes effect on the next check, not mid-call.
// Anywhere you hold an SDK key for the project, e.g. a webhook handler:
const stopped = await guard.stopRun(runId, { reason: 'spend spike' });
// { runId, status: 'stopped', stoppedNow: true, spendUsd, stoppedAt, stoppedReason, ... } | null
// Inside the agent loop:
const check = await guard.check({ model: 'gpt-4o', estimatedTokensIn: 1000, estimatedTokensOut: 300, runId });
if (check.blocked && check.blockReason === 'run_stopped') {
return; // exit the loop cleanly
}# Anywhere you hold an SDK key for the project, e.g. a webhook handler:
stopped = guard.stop_run(run_id, reason="spend spike")
# StopRunResult(run_id, status="stopped", stopped_now=True, spend_usd, stopped_at, stopped_reason, ...) | None
# Inside the agent loop:
result = guard.check(model="gpt-4o", estimated_tokens_in=1000, estimated_tokens_out=300, run_id=run_id)
if result.blocked and result.block_reason == "run_stopped":
return # exit the loop cleanly- Idempotent. Stopping an already-stopped run returns its existing state with
stoppedNow/stopped_nowset tofalse. Stopping a run that has already ended (completedorbudget_exceeded) is a no-op that reports its status. - Never throws except
NoburnAuthError; returnsnull/Noneon a network error or an unknown run. - Survives an outage. If this guard instance stopped the run, or has already seen
run_stoppedfor it,check()keeps blocking that run even while the noburn API is unreachable. - Over HTTP, this is
POST /api/v1/runs/{id}/stopwith{ "project_id": "...", "reason": "..." }. See the API reference.
Framework integrations
For the Vercel AI SDK (@noburn/sdk/ai-sdk), LangChain.js (@noburn/sdk/langchain), Python LangChain and CrewAI, use the drop-in integrations. See Framework integrations. The examples below gate whole routes by hand.
Next.js middleware
// middleware.ts
import { NoburnGuard } from '@noburn/sdk';
const guard = new NoburnGuard({
apiKey: process.env.NOBURN_API_KEY!,
projectId: process.env.NOBURN_PROJECT_ID!,
budgetCapUsd: 50,
});
export async function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/api/ai')) {
const userId = request.headers.get('x-user-id') ?? undefined;
const check = await guard.check({
model: 'gpt-4o',
estimatedTokensIn: 1000,
estimatedTokensOut: 500,
endUserId: userId,
});
if (check.blocked) {
return Response.json(
{ error: 'Budget exceeded', code: 'BUDGET_EXCEEDED' },
{ status: 402 }
);
}
}
}Express
import express from 'express';
import { NoburnGuard } from '@noburn/sdk';
const guard = new NoburnGuard({ apiKey: '...', projectId: '...' });
const app = express();
app.use('/api/ai', async (req, res, next) => {
const check = await guard.check({
model: req.body.model ?? 'gpt-4o',
estimatedTokensIn: 1000,
estimatedTokensOut: 500,
endUserId: req.user?.id,
});
if (check.blocked) {
return res.status(402).json({ error: check.blockReason });
}
next();
});