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) |
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 | ✓ | Estimated completion token count |
end_user_id | str | — | Identifier for the end user. Used for per-user spend tracking and rate limiting |
cost_usd | float | — | Estimated cost in USD. If omitted, noburn calculates 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", "per_user_limit", "model_blocked") |
spend_usd | float | Current monthly spend at time of check |
budget_cap_usd | float | None | The active budget cap |
remaining_usd | float | None | Budget remaining. None if no cap |
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 |
tokens_out | int | ✓ | Actual completion token count |
cost_usd | float | ✓ | Actual cost in USD |
was_blocked | bool | ✓ | Whether the call was blocked |
end_user_id | str | — | Same 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) |
Per-user budgets
Pass end_user_id to track spend per user. You can set per-user caps in the dashboard under Alert Rules.
# 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
The SDK never raises exceptions for budget checks — it fails open. If the noburn API is unreachable, calls are allowed with blocked=False. Only network errors and invalid API keys raise exceptions.
try:
result = guard.check(model="gpt-4o", estimated_tokens_in=1000, estimated_tokens_out=300)
except NoburnAuthError:
# Invalid API key
pass
except NoburnTimeoutError:
# API unreachable — treat as allowed
result = CheckResult(blocked=False)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) |
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 | ✓ | Estimated completion tokens |
endUserId | string | — | Per-user tracking identifier |
costUsd | number | — | Estimated cost (auto-calculated if omitted) |
context | Record<string, unknown> | — | Arbitrary key-value pairs matched against server-side policy rules (e.g. { plan: 'free' }) |
Return: CheckResult
interface CheckResult {
blocked: boolean;
blockReason: string | null;
spendUsd: number;
budgetCapUsd: number | null;
remainingUsd: number | null;
}guard.record()
await guard.record({
model: 'gpt-4o',
tokensIn: response.usage.prompt_tokens,
tokensOut: response.usage.completion_tokens,
costUsd: 0.00848,
wasBlocked: false,
endUserId: 'user_abc123',
latencyMs: 1240,
});Framework integrations
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();
});