← All guides

Locus product guide · Updated

Meter and bill LLM and tool usage per customer in Node

To meter and bill LLM and tool usage per customer in a Node app, give each customer a prepaid balance and charge every model and API call to it as the call happens. With the @withlocus/credits SDK on Locus Pro Enterprise, pass the customer's ID as the user option on each call. Locus charges that customer's balance at the provider's price plus your markup, returns the exact charge, and records it in a ledger you can filter by customer. A customer with no credits left gets an insufficient-credits error, not a free call.

Setup, step by step

  1. Step 1

    Install the SDK and keep the secret key on your server

    The secret key (lcr_...) can move credits and charge any customer, so it belongs in server-side environment variables only. Customer balances and your own prices need an Enterprise plan or an Enterprise trial.

    npm install @withlocus/credits
    export LOCUS_SECRET_KEY="lcr_..."   # from your secret store
  2. Step 2

    Turn on the models and tools, and set your markup

    In the Locus Pro dashboard, open Agent tools and turn on the endpoints your app calls, such as anthropic/chat, openai/chat and tavily/search. Set your workspace default markup under Agent tools, then Pricing. Every customer call is charged at the base price plus that markup.

  3. Step 3

    Fund a customer's balance

    After your own billing confirms a payment, move credits from your workspace pool to the customer. To let the customer pay by card instead, create a Locus-hosted Stripe Checkout session for them with topup(). Amounts are exact decimal strings.

    import { LocusCredits } from "@withlocus/credits";
    
    const locus = new LocusCredits(process.env.LOCUS_SECRET_KEY);
    
    // You billed the customer yourself: move credits from your pool.
    await locus.allocate("cust_acme", { credits: "2000", idempotencyKey: "invoice-1042" });
    
    // Or let the customer buy credits through Locus checkout.
    const { url } = await locus.topup({
      usd: "20",
      externalUserId: "cust_acme",
      successUrl: "https://your-app.example/billing?paid=1",
      cancelUrl: "https://your-app.example/billing",
    });
  4. Step 4

    Charge an LLM call to the customer

    Send the provider's normal request body with the customer's ID as user. Locus holds credits sized from max_tokens, charges for the tokens the provider reports, and releases the rest. Tag the call with attribution so you can report usage by feature later.

    const chat = await locus.callJson(
      "anthropic/chat",
      {
        model: "claude-haiku-5-5",
        max_tokens: 300,
        messages: [{ role: "user", content: question }],
      },
      { user: "cust_acme", attribution: { feature: "support-bot" } },
    );
    
    console.log(chat.data.content[0].text);
    console.log(chat.cost.credits); // what this customer paid for the call
    console.log(chat.cost.balance); // the customer's remaining credits
  5. Step 5

    Charge a tool call the same way

    Paid APIs such as search or enrichment use the same call and the same user option, so model tokens and tool calls come out of one customer balance.

    const search = await locus.callJson(
      "tavily/search",
      { query: "usage-based billing for AI agents" },
      { user: "cust_acme", attribution: { feature: "research" } },
    );
    
    console.log(search.data.results.length, search.cost.credits);
  6. Step 6

    Stop calls when a customer runs out

    When the customer's balance can't cover a call, Locus refuses it before the provider runs and charges nothing. The SDK throws LocusInsufficientCreditsError with the credits required and available, so you can send the customer to top up.

    import { LocusInsufficientCreditsError } from "@withlocus/credits";
    
    try {
      await locus.callJson("tavily/search", { query }, { user: "cust_acme" });
    } catch (error) {
      if (error instanceof LocusInsufficientCreditsError) {
        return showTopUp(error.requiredCredits, error.availableCredits);
      }
      throw error;
    }
  7. Step 7

    Read each customer's usage

    balance() returns one customer's credits. ledger() lists charges with the customer, the base cost, your margin and the attribution tags, and filters by customer or by tag.

    const { credits } = await locus.balance("cust_acme");
    
    const usage = await locus.ledger({ user: "cust_acme", limit: 50 });
    const supportBot = await locus.ledger({ attribution: { feature: "support-bot" } });
    
    for (const entry of usage.entries) console.log(entry);

What should you meter for each customer?

Meter every call that costs you money, at the moment you make it, under the customer it was made for. For an AI feature that means the model calls and the paid APIs its agent uses.

Record the cost before the response reaches the customer. Usage you reconstruct later from provider invoices can't be split by customer, and it arrives after the customer has already spent it.

  • LLM calls: the input and output tokens the provider reports for each request
  • Tool and API calls: the price of each call, which for some endpoints depends on what it returns
  • Your price: the cost plus the markup you charge, so the customer's charge is known per call
  • Context: a customer ID and tags such as the feature or task, so you can explain a bill

Should customers prepay or pay after they use it?

Prepaid balances stop usage when the money runs out, so an agent loop can't run up a bill a customer never pays. Invoicing after use fits customers on contracts, but you carry unpaid usage until the invoice clears and need your own limits in the meantime.

This guide uses prepaid balances. If you already invoice through a billing engine, you can still meter calls this way and send the per-customer totals from the ledger to your invoices.

How does a call get charged to a customer?

The user option names the customer whose balance pays. Locus checks that balance before the provider runs, then charges the base price plus your markup. Without the user option, the call is charged to your own workspace balance at the base price.

When you fund customers with allocate(), your markup returns to your pool as they use the credits. When customers buy credits through Locus checkout, your markup accrues as payable earnings.

  • Every call returns cost.credits and cost.balance as exact decimal strings, so you never round money through a JavaScript number.
  • The SDK sends one idempotency key per call and reuses it on its retries, so a retry can't charge a customer twice. Pass your own idempotencyKey to keep that guarantee across a process restart.
  • Version 0.5.2 reports a streamed response's cost as 0 when the call returns; read the final charge from the stream's closing event or the call status.
How does a call get charged to a customer?
CallWhat the customer is charged forWhen the charge is final
LLM callTokens the provider reports, never more than the hold placed from the prompt and max_tokensWhen the response returns
Streamed LLM callTokens the provider reports at the end of the streamAfter the stream ends
Tool or API callThe endpoint's price, which for some endpoints depends on what the response returnsWhen the response returns

What if you call model providers with your own keys?

Locus meters only the calls that go through it. A model call made with your own OpenAI or Anthropic key never touches the customer's Locus balance, so you would meter its tokens yourself from the usage the provider returns with each response.

Sending the model calls through Locus as well keeps tokens and tool calls on one balance, one ledger and one set of limits per customer.

How do you cap what one customer can spend?

The customer's balance is the hard limit: a call that would take it below zero is refused before it runs. For agents that act on a customer's behalf, add limits per call and per loop.

  • Fund in small amounts and top up often, so one runaway loop can only spend what is on the balance
  • Create an agent key bound to one customer with agentConnections.create({ mode: "end_user", externalUserId }), limited to chosen tools
  • Set maxCreditsPerCall and maxCreditsPerLoop on that key so a single call or agent loop has a ceiling
  • Watch each customer's spend over time in the dashboard's Customers view

When is this the right setup?

It fits a Node backend whose customers use AI features that call models and paid APIs, where each customer should pay for their own usage and you don't want to keep provider accounts, a price table and a per-customer meter yourself.

It is the wrong tool when you only sell flat subscriptions with no usage component, or when every call goes to your own infrastructure and the only cost is your compute. A billing engine that meters your own events fits those better.

Frequently asked questions

Can LLM tokens and API tool calls come out of one customer balance?

Yes. Model endpoints such as anthropic/chat and openai/chat and tool endpoints such as tavily/search are called the same way with the same user option, so both are charged to that customer's prepaid credits and both appear in the same ledger.

Which Locus Pro plan do I need to bill my customers?

Customer balances, your own prices, the ledger API and customer analytics are part of Locus Pro Enterprise, which you can start yourself from Billing, then Plans, or through an Enterprise trial. Free and Plus are personal workspaces.

What happens when a customer's balance runs out?

Locus refuses the call with HTTP 402 before the provider runs and charges nothing. The SDK throws LocusInsufficientCreditsError with the required and available credits, so your app can ask the customer to top up.

Can a retried call charge a customer twice?

No. The SDK generates an idempotency key for each call and reuses it across its own retries. If your app retries after a restart, pass the original key as idempotencyKey and Locus returns the stored result instead of charging again.

Do I need the billing widget to bill customers?

No. You can bill customers your own way and move credits to them with allocate(), or create a Locus-hosted checkout link for a customer with topup(). The widget is an optional browser component that shows the balance and opens checkout.

Implementation references

Use these first-party references for current request contracts and account requirements. Tool availability, prices, and negotiated terms can change.

Sources

Third-party details were checked on December 1, 2026. Vendors change pricing and features often, so confirm on their site before you decide.

Related guides