@spondo/margin
v0.4.0
Published
The client for Spondo Margin: send usage events, trace what each customer's AI calls cost, and manage customers and products.
Readme
@spondo/margin
The Node client for Spondo Margin. Use it to send usage events, see what each customer's AI calls cost you, and manage customers and products. What they paid comes from your Stripe, which you connect in the dashboard.
npm install @spondo/marginIt runs anywhere fetch does: Node 20 or later, Bun, Deno and edge runtimes. Tracing needs Node.
Events
An event is one thing your product did for a customer. It gets a cost (the traces under it), and its event name and the numbers in its data are what value rules count.
import { Spondo } from "@spondo/margin";
const spondo = new Spondo(); // reads SPONDO_API_KEY
await spondo.events.send({
eventName: "document_uploaded",
customer: { externalCustomerId: account.id },
attribution: { externalProductId: "documind" },
data: { pages: doc.pages },
idempotencyKey: doc.id, // a retry with the same key is stored once
});send takes one event or an array of them.
Cost tracing
Tracing puts the cost of each customer's AI calls on them. It also gives you a cost for each event.
Install the OpenTelemetry packages it uses (the 3.x line):
npm install @opentelemetry/api @opentelemetry/sdk-trace @opentelemetry/context-async-hooks @opentelemetry/exporter-trace-otlp-httpThen wrap each unit of work in trace():
import { initTracing, trace, event } from "@spondo/margin/tracing";
initTracing(); // once, at startup
await trace({ externalCustomerId: account.id, externalProductId: "documind" }, async () => {
const summary = await anthropic.messages.create({ ... }); // priced from its tokens
await event("document_uploaded", { pages: doc.pages }); // carries this trace's cost
});LLM calls are priced from the gen_ai.* token counts on their spans. Register an OpenTelemetry instrumentation for your LLM client as you normally would: OpenLLMetry, OpenInference, and the Vercel AI SDK's @ai-sdk/otel all set those attributes. A span with no token counts can give its own cost in US dollars as meter.cost. In serverless functions, await flush() before returning.
The rest of the API
// stripeCustomerId: their customer in your Stripe, so their payments count as their revenue
const customer = await spondo.customers.create({ name: "Acme", externalId: "acme", stripeCustomerId: "cus_…" });
await spondo.customers.get({ externalId: "acme" }); // or by Spondo Margin's id: "cus_…"The client also covers:
customers,productsandevents- any other
/api/v1call, throughspondo.request(method, path, { query, body, headers });headersadds to the client's own
A failed call throws a SpondoError, which carries status, code and message. A rate-limited call (429) is retried twice, after the wait the server asks for.
Options
| Option | Default |
|---|---|
| apiKey | SPONDO_API_KEY |
| baseUrl | SPONDO_BASE_URL, then https://margin.getspondo.com |
| maxRetries | 2 |
| fetch | globalThis.fetch |
