> ## Documentation Index
> Fetch the complete documentation index at: https://docs.macropay.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Cost Events

> Attach a _cost tag to any ingested event to track spend and margin next to revenue

Every dollar you bill a customer has a dollar (or a fraction of one) of cost behind it — an LLM call, a render farm, a transactional email. Macropay lets you record that cost on the same event stream you already use for usage-based billing, so spend and revenue live side by side instead of in two disconnected systems.

You do this by attaching a reserved `_cost` tag to an event's metadata when you ingest it. From there, costs roll up through the [Metrics API](/api-reference/metrics) right next to revenue — giving you margin, not just turnover.

<Tip>
  Because Macropay is your [Merchant of Record](/merchant-of-record/introduction), the *revenue* side of this picture is already net of sales tax and VAT — we remit those globally on your behalf. Pairing that with cost events means the margin you see is genuinely yours to keep.
</Tip>

## How it works

1. You ingest an event through the [Event Ingestion API](/api-reference/events) as usual.
2. You add a `_cost` object inside that event's `metadata`.
3. Macropay aggregates the cost and exposes it through the Metrics API alongside billed revenue.

The cost tag is purely additive. It never changes how the event is metered or billed — it simply records what the event *cost you* so you can reason about profitability.

## The `_cost` tag

Add `_cost` to any event's `metadata`. Here is the minimal shape:

<CodeGroup>
  ```typescript icon="square-js" TypeScript (SDK) theme={null}
  import { Macropay } from "@macropayments/sdk";

  const macropay = new Macropay({
    accessToken: process.env.MACROPAY_ACCESS_TOKEN,
  });

  await macropay.events.ingest({
    events: [
      {
        name: "llm.inference",
        externalCustomerId: "user_123",
        metadata: {
          _cost: {
            amount: 0.025, // cents → $0.00025
            currency: "usd",
          },
        },
      },
    ],
  });
  ```

  ```bash cURL theme={null}
  curl -X POST https://api.macropay.ai/v1/events/ingest \
    -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "events": [
        {
          "name": "llm.inference",
          "external_customer_id": "user_123",
          "metadata": {
            "_cost": {
              "amount": 0.025,
              "currency": "usd"
            }
          }
        }
      ]
    }'
  ```
</CodeGroup>

### Fields

| Field      | Required | Type   | Notes                                                                                 |
| ---------- | -------- | ------ | ------------------------------------------------------------------------------------- |
| `amount`   | yes      | number | Cost **in cents**, as a decimal. Up to 17 digits with 12 decimal places of precision. |
| `currency` | yes      | string | Currency code. `"usd"` is currently supported.                                        |

<Warning>
  **`amount` is in cents, not dollars.** A whole number is whole cents, and decimals go sub-cent. So `100` = $1.00, `0.5` = half a cent ($0.005), and `0.001` = one hundredth of a cent (\$0.00001). Mixing up cents and dollars is the most common Cost Insights mistake — double-check the magnitude.
</Warning>

## What to track

`_cost` is deliberately generic: anything that costs you money per unit of activity is fair game. Three common patterns:

<Tabs>
  <Tab title="AI & LLM calls">
    The headline use case. Record what each model call cost, attributed to the customer who triggered it. Stash token counts in metadata too, so you can later slice cost by model and prompt size.

    ```typescript icon="square-js" TypeScript theme={null}
    import { Macropay } from "@macropayments/sdk";
    import OpenAI from "openai";

    const macropay = new Macropay({
      accessToken: process.env.MACROPAY_ACCESS_TOKEN,
    });

    const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

    const completion = await openai.chat.completions.create({
      model: "gpt-4",
      messages: [{ role: "user", content: "Summarize Q3 churn drivers." }],
    });

    // Example rates: $0.03 / 1K input tokens, $0.06 / 1K output tokens.
    // Convert dollars → cents (×100) for the _cost amount.
    const inputCost = (completion.usage.prompt_tokens / 1000) * 0.03 * 100;
    const outputCost = (completion.usage.completion_tokens / 1000) * 0.06 * 100;
    const totalCost = inputCost + outputCost;

    await macropay.events.ingest({
      events: [
        {
          name: "gpt4.completion",
          externalCustomerId: "user_123",
          metadata: {
            _cost: {
              amount: totalCost,
              currency: "usd",
            },
            _llm: {
              vendor: "openai",
              model: "gpt-4",
              input_tokens: completion.usage.prompt_tokens,
              output_tokens: completion.usage.completion_tokens,
              total_tokens: completion.usage.total_tokens,
            },
          },
        },
      ],
    });
    ```

    <Note>
      Routing model traffic through the Macropay [AI proxy](/features/llm-inference) (`POST /ai/v1/chat/completions`) captures token cost for you automatically — no manual rate math, no `_cost` plumbing. Use manual `_cost` tagging when you call providers directly or need to fold in costs the proxy can't see.
    </Note>
  </Tab>

  <Tab title="Infrastructure">
    Compute, storage, bandwidth, transcoding — anything you provision per job. Keep the operational detail (duration, resolution) in metadata so spend stays explainable.

    ```json theme={null}
    {
      "events": [
        {
          "name": "video.transcode",
          "external_customer_id": "user_123",
          "metadata": {
            "_cost": {
              "amount": 45.5,
              "currency": "usd"
            },
            "duration_seconds": 120,
            "resolution": "1080p"
          }
        }
      ]
    }
    ```

    The `amount` of `45.5` cents is \$0.455 for this transcode job.
  </Tab>

  <Tab title="Third-party services">
    Pass-through costs from vendors you resell — email, SMS, geocoding, enrichment. Tag the provider so you can compare cost across them.

    ```json theme={null}
    {
      "events": [
        {
          "name": "email.sent",
          "external_customer_id": "user_123",
          "metadata": {
            "_cost": {
              "amount": 0.0001,
              "currency": "usd"
            },
            "provider": "sendgrid",
            "recipients": 1
          }
        }
      ]
    }
    ```

    Here `0.0001` cents is \$0.000001 per email — exactly the kind of micro-cost the 12-decimal precision exists for.
  </Tab>
</Tabs>

## Why margin matters for agents

If you bill autonomous agents, cost events are half of a profitability equation. The other half is what the agent earned: with the [Signals API](/features/usage-based-billing/credits) you certify the *value* an agent delivered, and Macropay computes **agentic margin** — billed revenue versus the AI cost (COGS) behind it, per agent.

Tag every model call, tool invocation, and downstream service with `_cost`, and that COGS figure becomes real instead of a guess. An agent that bills well but burns more in tokens than it earns shows up immediately, before it quietly erodes your margin.

## Practical tips

<AccordionGroup>
  <Accordion title="Ingest cost as it happens">
    Record the cost on the same code path that incurs it — right after the API call returns. Real-time ingestion keeps your margin metrics live and avoids batch reconciliation drift.

    ```typescript icon="square-js" TypeScript theme={null}
    const completion = await openai.chat.completions.create({
      model: "gpt-4",
      messages: [{ role: "user", content: "Draft a renewal email." }],
    });

    const cost = calculateCost(completion.usage); // returns cents

    await macropay.events.ingest({
      events: [
        {
          name: "llm.completion",
          externalCustomerId: "user_123",
          metadata: {
            _cost: { amount: cost, currency: "usd" },
          },
        },
      ],
    });
    ```
  </Accordion>

  <Accordion title="Don't round away sub-cent costs">
    The 12-decimal precision exists so a single token or a single API hit never rounds to zero. At scale, those fractions are your real cost.

    ```json theme={null}
    {
      "_cost": {
        "amount": 0.000125,
        "currency": "usd"
      }
    }
    ```

    `0.000125` cents is \$0.00000125 — preserved exactly.
  </Accordion>

  <Accordion title="Carry context next to the cost">
    A bare number tells you *how much*; surrounding metadata tells you *why*. Tag the model, feature, or workload so you can group spend by driver later.

    ```json theme={null}
    {
      "metadata": {
        "_cost": {
          "amount": 0.05,
          "currency": "usd"
        },
        "model": "gpt-4-turbo",
        "tokens": 1000,
        "feature": "support-copilot"
      }
    }
    ```
  </Accordion>
</AccordionGroup>
