> ## 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.

# Agentic Margin

> See revenue vs. AI cost (COGS) per agent so you know which agents make money — captured automatically from every proxied model call.

Agentic margin is what each AI agent earns after the cost of running it. Macropay joins the revenue you bill against the model and tool spend it took to deliver, so you can tell a profitable agent from one quietly burning cash — per agent or across your whole organization.

Both sides of the equation are captured for you. When you route model calls through the [AI proxy](/features/llm-inference) (`/ai/v1`), every request writes an `ai.completion` event carrying the billed amount (revenue) and the upstream provider cost (COGS). Macropay rolls those up into a `MarginSummary` — no metering code, no manual joins.

<Note>
  Revenue here is the amount you bill the end customer (the proxy's marked-up
  rate). Cost is what the upstream provider charged you. The difference is your
  margin, sliced by model and flagged when it drops below a floor.
</Note>

## Where the numbers come from

<CardGroup cols={2}>
  <Card title="Revenue & LLM cost" icon="route">
    Each proxied call records billed amount and upstream model cost on the same
    `ai.completion` event. Margin needs no extra reporting from you.
  </Card>

  <Card title="Non-LLM COGS" icon="screwdriver-wrench">
    Tool calls, third-party APIs, and human-in-the-loop time can be recorded as
    `agent.cost` events that reduce margin — see below.
  </Card>

  <Card title="Per-model breakdown" icon="layer-group">
    Every summary includes `by_model[]`, so you can see exactly which model is
    eating your spread.
  </Card>

  <Card title="Low-margin guardrail" icon="shield-halved">
    A `low_margin` flag trips the moment an agent's margin falls under your
    floor (default 20%), so thin or negative agents surface on their own.
  </Card>
</CardGroup>

## Read an agent's margin

Two endpoints, same `MarginSummary` shape. Both accept optional `since` and `until` ISO-8601 query params to scope a window.

| Endpoint                     | Returns                       |
| ---------------------------- | ----------------------------- |
| `GET /v1/agents/{id}/margin` | Margin for a single agent     |
| `GET /v1/agents/margin`      | Org rollup across every agent |

<CodeGroup>
  ```bash Single agent theme={null}
  curl https://api.macropay.ai/v1/agents/agt_42/margin \
    -H "Authorization: Bearer <token>"
  ```

  ```bash Org rollup theme={null}
  curl "https://api.macropay.ai/v1/agents/margin?since=2026-05-01T00:00:00Z" \
    -H "Authorization: Bearer <token>"
  ```
</CodeGroup>

### Response: `MarginSummary`

```json theme={null}
{
  "agent_id": "agt_42",
  "revenue_cents": 124050.0,
  "cost_cents": 38200.0,
  "margin_cents": 85850.0,
  "margin_pct": 69.21,
  "low_margin": false,
  "margin_floor_pct": 20.0,
  "by_model": [
    {
      "model": "claude-sonnet-4",
      "revenue_cents": 98000.0,
      "cost_cents": 28000.0,
      "margin_cents": 70000.0,
      "margin_pct": 71.43,
      "count": 1820
    },
    {
      "model": "gpt-4o-mini",
      "revenue_cents": 26050.0,
      "cost_cents": 10200.0,
      "margin_cents": 15850.0,
      "margin_pct": 60.84,
      "count": 940
    }
  ]
}
```

| Field              | Meaning                                                                       |
| ------------------ | ----------------------------------------------------------------------------- |
| `revenue_cents`    | Total billed to customers (your marked-up rate)                               |
| `cost_cents`       | Total COGS — upstream model spend plus any recorded `agent.cost`              |
| `margin_cents`     | `revenue_cents − cost_cents`                                                  |
| `margin_pct`       | Margin as a percent of revenue; `0` when there's no revenue                   |
| `low_margin`       | `true` when there is revenue **and** `margin_pct` is below `margin_floor_pct` |
| `margin_floor_pct` | The guardrail threshold (default `20`)                                        |
| `by_model[]`       | The same metrics broken out per model, sorted by revenue                      |

## The low-margin guardrail

`low_margin` is the single signal you alert on. It is `true` only when an agent has earned revenue *and* its `margin_pct` sits under `margin_floor_pct` — so an agent with no billed activity never trips it, and a profitable agent stays quiet. The floor defaults to **20%**.

Wire it into monitoring: poll the org rollup on a schedule, and if `low_margin` is `true` or any entry in `by_model[]` shows a thin spread, you've caught a pricing or model-choice problem before it shows up on a P\&L. A negative `margin_cents` means the agent is losing money on every run — usually a sign the upstream model costs more than you're charging.

<Warning>
  A negative margin doesn't stop requests. Margin is reporting, not a budget
  cap. To hard-stop spend, set a **budget limit** on the proxy key — see
  [LLM inference](/features/llm-inference) — which returns `403` once the ceiling
  is hit.
</Warning>

## Record non-LLM costs

LLM spend is captured automatically, but agents also cost money in ways the proxy never sees: a paid search API, a geocoding lookup, a human reviewer. Report those as COGS with `POST /v1/agents/{id}/costs` and they fold straight into the agent's margin as an `agent.cost` event — adding cost without adding revenue.

A `customer_id` or `external_customer_id` is required so the cost attributes to the right account. Pass `external_id` as an idempotency key — it dedupes on `(organization, external_id)`, so retries never double-count.

```bash theme={null}
curl https://api.macropay.ai/v1/agents/agt_42/costs \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "amount_cents": 250,
    "currency": "usd",
    "description": "serp_api",
    "external_customer_id": "acct_8842",
    "external_id": "run_91f3-serp"
  }'
```

```json theme={null}
{ "status": "recorded", "agent_id": "agt_42" }
```

| Field                                  | Required | Notes                                                                            |
| -------------------------------------- | -------- | -------------------------------------------------------------------------------- |
| `amount_cents`                         | Yes      | The cost incurred, in cents. Must be greater than 0.                             |
| `currency`                             | No       | ISO currency code; defaults to `usd`.                                            |
| `description`                          | No       | What the cost was for, e.g. `serp_api`. Surfaces as the "model" in `by_model[]`. |
| `customer_id` / `external_customer_id` | One of   | Attributes the cost to a customer.                                               |
| `external_id`                          | No       | Idempotency key — dedupes on `(org, external_id)`.                               |

<Tip>
  Using the Macropay SDK? `cost.record(...)` calls this endpoint for you, and
  the tool-cost helpers can capture vendor spend automatically as your agent
  runs — no manual POST per tool call.
</Tip>

## FAQ

**How is margin calculated?**
Margin is billed revenue minus AI cost (COGS). Revenue and upstream model cost both come from the `ai.completion` events the proxy records on every call; any `agent.cost` events you report add to the cost side. Macropay sums them into `revenue_cents`, `cost_cents`, and `margin_cents`, with `margin_pct` as margin over revenue. The breakdown per model lives in `by_model[]`.

**How do I record non-LLM costs?**
Call `POST /v1/agents/{id}/costs` with `amount_cents`, a `currency`, an optional `description`, a `customer_id` or `external_customer_id`, and an `external_id` for idempotency. It's stored as an `agent.cost` event that reduces margin without adding revenue. The SDK's `cost.record()` wraps this endpoint.

**What triggers the low-margin flag?**
`low_margin` is `true` when an agent has earned revenue and its `margin_pct` is below `margin_floor_pct` (default 20%). An agent with no billed revenue never trips the flag, even if it has recorded costs.

**Is margin a spending limit?**
No. Margin is reporting only — it never blocks a request. To cap spend, set a budget limit on the proxy key in [LLM inference](/features/llm-inference); the proxy returns `403` once the ceiling is reached.

**How does this relate to Cost Insights?**
Agentic margin is the agent-scoped view of the same revenue-vs-cost ledger. For per-customer profit, LTV, and cost-annotated events beyond agents, see [Cost Insights](/features/cost-insights/introduction).

## Next steps

<CardGroup cols={2}>
  <Card title="Route calls through the AI proxy" icon="route" href="/features/llm-inference">
    Send model traffic through `/ai/v1` so revenue and cost are captured for you.
  </Card>

  <Card title="Explore Cost Insights" icon="chart-line" href="/features/cost-insights/introduction">
    See true profit, margin, and LTV per customer across your whole business.
  </Card>
</CardGroup>
