noburn.devdocs

SDK Reference

Complete reference for the noburn Python and Node.js SDKs.

Python SDK

Installation

pip install noburn

Requires 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

ParameterTypeRequiredDescription
api_keystrYour project SDK key from the dashboard
project_idstrProject UUID from the dashboard
budget_cap_usdfloatMonthly spend cap in USD. Calls are blocked once exceeded
base_urlstrOverride API endpoint (default: https://noburn.dev)
timeoutfloatRequest 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

ParameterTypeRequiredDescription
modelstrModel name as it appears in your LLM provider's API
estimated_tokens_inintEstimated prompt token count
estimated_tokens_outintEstimated completion token count
end_user_idstrIdentifier for the end user. Used for per-user spend tracking and rate limiting
cost_usdfloatEstimated cost in USD. If omitted, noburn calculates from token counts
contextdictArbitrary key-value pairs matched against server-side policy rules (e.g. {"plan": "free"})

Return value: CheckResult

FieldTypeDescription
blockedboolTrue if the call should be blocked
block_reasonstr | NoneWhy the call was blocked ("budget_exceeded", "per_user_limit", "model_blocked")
spend_usdfloatCurrent monthly spend at time of check
budget_cap_usdfloat | NoneThe active budget cap
remaining_usdfloat | NoneBudget 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

ParameterTypeRequiredDescription
modelstrModel name
tokens_inintActual prompt token count
tokens_outintActual completion token count
cost_usdfloatActual cost in USD
was_blockedboolWhether the call was blocked
end_user_idstrSame identifier passed to check()
latency_msintEnd-to-end latency in milliseconds
block_reasonstrReason if was_blocked=True
timestampstrISO 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/sdk

Requires 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

OptionTypeRequiredDescription
apiKeystringYour project SDK key
projectIdstringProject UUID
budgetCapUsdnumberMonthly spend cap in USD
baseUrlstringOverride API endpoint
timeoutMsnumberRequest 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

OptionTypeRequiredDescription
modelstringModel name
estimatedTokensInnumberEstimated prompt tokens
estimatedTokensOutnumberEstimated completion tokens
endUserIdstringPer-user tracking identifier
costUsdnumberEstimated cost (auto-calculated if omitted)
contextRecord<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();
});

On this page