> This page is for version Preview (default).
> For other versions, use one of these documentation indexes:
> - Preview (default): https://docs.preview.paid.ai/preview/llms.txt
> - Current: https://docs.preview.paid.ai/current/llms.txt

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.preview.paid.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.preview.paid.ai/_mcp/server.

# Create a meter

POST https://api.paid.ai/v1/meters
Content-Type: application/json

**Draft scaffold — not implemented or available in the API.**

Creates a meter, which defines on the server what gets measured from events. `eventNames` or `eventNamePattern` and `filters` pick the events it reads, and `measure.type` sets the mode: `events` aggregates matching events over the billing period, `singleEvent` turns each event into its own measured quantity, and `workflows` groups related events into one outcome per workflow. Prices reference the meter by its `key`, which must be unique and cannot change.

Reference: https://docs.preview.paid.ai/api-reference/metering/meters/create

## Authentication

- `Authorization` header (bearer token, required) — API Key authentication using Bearer token

## Request

### Headers

- `Paid-Beta` (enum, required) — This endpoint is in the `meters=v1` beta. Send this header to use it.
  - Allowed values: `meters=v1`

### Body (application/json)

This endpoint expects a CreateMeterRequest.

- `key` (string, required) — Your stable identifier, 1 to 255 characters.
- `measure` (MeterMeasure, required) — The immutable billing definition.
- `description` (string, optional, nullable) — What the resource represents.
- `eventNamePattern` (string, optional) — Event-name regular expression.
- `eventNames` (list of string, optional) — Exact matching event names.
- `filters` (list of MeterFilter, optional) — Conditions every event must match.
- `metadata` (map from string to string, optional) — String key-value pairs of your own, up to 500 characters per value. Always updatable.
- `name` (string, optional) — The resource name.
- `validationMode` (enum, optional, default: lenient) — Acceptance behavior for invalid values.
  - Allowed values: `lenient`, `strict`

## Response

### 201

201

- `id` (string, required) — The Meter ID.
- `object` (enum, required) — The type of object. Always `meter`.
  - Allowed values: `meter`
- `createdAt` (datetime, required) — When the object was created.
- `archivedAt` (datetime, required, nullable) — When this resource was archived, or null.
- `description` (string, required, nullable) — What the resource represents.
- `eventNamePattern` (string, required, nullable) — Event-name regular expression.
- `eventNames` (list of string, required, nullable) — Exact matching event names.
- `filters` (list of MeterFilter, required) — Conditions every event must match.
- `health` (MeterHealth, required) — MeterHealth.
- `key` (string, required) — Your stable identifier, 1 to 255 characters.
- `livemode` (boolean, required) — `true` for an object on a live account, `false` on a test account.
- `measure` (MeterMeasure, required) — The immutable billing definition.
- `metadata` (map from string to string, required) — String key-value pairs of your own, up to 500 characters per value. Always updatable.
- `name` (string, required) — The resource name.
- `updatedAt` (datetime, required) — When the object was last changed.
- `validationMode` (enum, optional, default: lenient) — Acceptance behavior for invalid values.
  - Allowed values: `lenient`, `strict`

## Errors

### 400 Bad Request Error

400

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 401 Unauthorized Error

401

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 403 Forbidden Error

403

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 404 Not Found Error

404

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 409 Conflict Error

409

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 429 Too Many Requests Error

429

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 500 Internal Server Error

500

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

### 501 Not Implemented Error

501

- `error` (ApiErrorObject, required) — What went wrong, in the same shape for every /v1 error.

## Types

### MeterMeasure

The immutable billing definition.

- `type`: `events` (events)
  - `events` (EventsMeasure, required) — EventsMeasure.
- `type`: `workflows` (workflows)
  - `workflows` (WorkflowMeasure, required) — WorkflowMeasure.
- `type`: `singleEvent` (singleEvent)
  - `singleEvent` (SingleEventMeasure, required) — SingleEventMeasure.

### MeterFilter

MeterFilter.

- `op` (enum, required) — Matching operator.
  - Allowed values: `eq`, `ne`, `in`, `notIn`, `exists`
- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.
- `value` (MeterFilterValue, optional) — Comparison value; omitted for exists.

### MeterHealth

MeterHealth.

- `invalidValues24h` (integer, required) — Invalid values over 24 hours.
- `lastMatchedAt` (datetime, required, nullable) — Last matched event.
- `matchedEvents24h` (integer, required) — Matched events over 24 hours.
- `warnings` (list of string, required) — Measurement health warnings.
- `closedWorkflows24h` (integer, optional) — closedWorkflows24h measurement health count.
- `discardedEvents24h` (integer, optional) — discardedEvents24h measurement health count.
- `emittedEvents24h` (integer, optional) — emittedEvents24h measurement health count.
- `missingIdentifier24h` (integer, optional) — missingIdentifier24h measurement health count.
- `openWorkflows` (integer, optional) — openWorkflows measurement health count.
- `timedOut24h` (integer, optional) — timedOut24h measurement health count.
- `unpricedOutcomes` (list of string, optional) — Emitted outcomes without billing coverage.

### ApiErrorObject

What went wrong, in the same shape for every /v1 error.

- `code` (string, required) — A stable, machine-readable code for this error. New codes may be added at any time. See [Errors](https://docs.paid.ai/preview/developers/api/errors) for what each one means and how to fix it. - `unauthorized`: The API key is missing, malformed, revoked or expired. - `session_revoked`: The session behind this token has been signed out. - `forbidden`: The credentials are valid but cannot access this account. - `insufficient_scope`: The API key's scopes do not cover this endpoint. - `user_required`: Only a person signed in to Paid can do this, not an API key: it sends email for the account or acts on its behalf. - `customer_key_forbidden`: A customer-scoped API key called an endpoint it cannot use. - `organization_required`: The request did not say which account it is for. - `auth_context_error`: Paid could not load the account for these credentials. - `invalid_version`: The API version is malformed or not a released version. - `rollback_window_expired`: The account tried to move its pinned version back after the rollback window closed. - `unknown_beta`: `Paid-Beta` names a beta that does not exist, or is malformed. - `beta_not_enabled`: The account is not enrolled in this private beta. - `beta_header_required`: A beta endpoint or field was used without opting in. - `invalid_idempotency_key`: `Idempotency-Key` is empty, longer than 255 characters, or not printable ASCII. - `idempotency_key_reused`: The `Idempotency-Key` was already used with a different request. - `idempotency_request_in_progress`: A request with this `Idempotency-Key` is still running. - `validation_error`: The request body or parameters failed validation. - `invalid_json`: The request body is not valid JSON. - `payload_too_large`: The request body exceeds 10 MB. - `resource_missing`: No resource or path matches the request. - `type_mismatch`: A polymorphic field's `type` doesn't match the sub-object sent with it, or more than one sub-object was sent. `param` names the field. - `reference_not_found`: A reference in the body or query string doesn't name a resource on the account. `param` names the field, e.g. `customer` or `lines[0].price`. - `resource_archived`: A resource the request names is archived, so it can't be used for this. `param` names the field; it's empty when the archived resource is the one in the path. - `resource_not_active`: A resource the request names isn't active: it's still a draft, has ended or was deactivated. `param` names the field. - `status_conflict`: The action can't run on the object in the path from its current `status`, e.g. activating an active order or releasing a captured hold. `message` names the status and the statuses the action needs. - `resource_in_use`: The resource can't be archived or changed this way while other resources still use it. `param` names the field when there is one. - `resource_exists`: A resource with this identifier (an `externalId`, `key` or alias) already exists on the account, ignoring letter case. `param` names the field. - `customer_mismatch`: A resource the request names belongs to a different customer than the one the request is for. `param` names the field. - `internal_error`: Something went wrong on Paid's side. - `currency_not_supported`: `currency` is not enabled on the account. - `currency_locked`: The customer has an order, so its `currency` cannot change. - `customer_has_active_orders`: The customer cannot be archived while it has an activating, active or paused order. - `parent_livemode_mismatch`: `parent` names a customer in the other mode: live for a test key, or test for a live key. - `parent_has_parent`: Parents are one level deep: the named parent has a parent of its own, or the customer being given a parent has children. - `parent_cycle`: `parent` names the customer itself, or, for a customer unit, the unit itself or a unit under it. - `has_active_children`: The customer cannot be archived while it is the `parent` of a customer that is not archived, or the customer unit while it has units under it that are not archived. - `tax_provider_not_connected`: Tax cannot be enabled while no tax provider is connected. - `mixed_tax_codes`: A prepaid commit taxed at purchase is scoped to products with different tax codes, so its invoice has no single code. - `tax_provider_unavailable`: The tax provider could not be reached, so the tax code could not be checked against its catalog. - `immutable_field`: An update tried to change a field that can't change after creation, such as a rate, a key or a reference. - `currency_mismatch`: An amount or reference isn't in the currency the request needs, such as an order's currency. - `limit_exceeded`: The request has more items than the resource allows, such as rates, adjustments, filters or outcomes. - `forfeit_confirmation_required`: Ending this would forfeit a remaining balance, and `forfeitRemaining` wasn't `true`. - `external_id_scopes_meter`: The product's `externalId` can't change while a meter is scoped to it, because the meter matches on that ID. - `percent_of_base_missing`: A percent-of line names prices in `of.lines` that aren't on the order. - `outcome_not_allowed`: `usage.outcome` was sent for an events meter, which has no outcomes. - `meter_not_priceable`: The meter can't be priced on its own: it has `groupBy`, or uses a dashboard-only feature. - `price_in_active_plan`: The price can't be archived while an active plan lists it. - `ambiguous_match`: Two rates match the same dimension values with equal specificity, so rating couldn't choose between them. - `meter_already_priced`: One measure would be priced by both a price and a rate card on the same order. - `no_common_currency`: The plan's lines share no currency. - `default_requires_upgrade_path`: `default: true` was sent on a plan with no `upgradePath`. - `plan_legacy`: The plan was converted from v2 without v1 prices, so it can't be used on a v1 order. - `upgrade_path_position_taken`: Another plan already has this `position` in the upgrade-path `group`. - `quantity_not_allowed`: A line has a `quantity`, but its price has no `unit` (a usage price or flat fee). - `quantity_out_of_range`: A `quantity` is outside the price's or line's `quantityLimits`. - `quantity_limits_wider_than_price`: A line's `quantityLimits` are wider than its price's. - `interval_mismatch`: A recurring price's interval neither divides the order's billing cycle evenly nor is a whole multiple of it. - `line_not_on_order`: An amendment change names a line from another order. - `no_material_changes`: The amendment's changes leave the order as it is. - `usage_billing_behind`: Usage for a past period hasn't been billed yet, so the usage line can't be replaced now. - `seats_exceed_quantity`: The new quantity is below the line's active seats. - `order_ambiguous`: Several orders share this `externalId`, so it can't name one of them. - `order_version_mismatch`: The order changed since the `expectedVersion` sent. - `preview_stale`: The order changed after the amendment was previewed. - `billing_unavailable`: Billing couldn't be reached to preview or apply the change. Nothing changed. - `commit_conflict`: The invoiced minimum overlaps another on the order in both time and scope. - `duplicate_outcome_key`: Two outcomes, or an outcome and `catchAll`, share a key. - `single_event_field_not_allowed`: A single-event meter sent a field only workflows or event aggregation use, such as `identifier`, `close` or `aggregation`. - `alias_unit_conflict`: `customer` is an alias of one unit and `customerUnit` names a unit outside its subtree. - `workflow_unit_conflict`: The event names a different customer unit from the open workflow it joins. - `incompatible_unit`: A strict meter reads a Quantity whose unit can't be converted to the meter's unit. - `unknown_provider`: Paid's model catalog doesn't know the inference provider. - `unknown_model`: Paid's model catalog doesn't know the model. - `range_too_large`: The range is longer than `granularity` allows. - `misaligned_range`: `startsAt` or `endsAt` doesn't fall on a bucket boundary in `timezone`. - `depth_exceeded`: The unit, or a moved subtree, would go below 16 levels. - `root_unit_immovable`: An update tried to move the customer's root unit. - `root_unit_always_billable`: A create or update tried to make the root unit non-billable. - `has_active_cap`: The unit can't be archived while it has an active spend cap. - `has_active_seat`: The unit can't be archived while it holds an active seat, or the customer is billed per seat, so its units can't be created, changed or archived. - `alias_held_by_draft_customer`: The alias value is a draft customer's external ID: usage sent under it before the alias existed made that draft. - `alias_system_managed`: The alias was made by Paid, when a customer's `externalId` changed or from a SalesBricks buyer, so it can't be updated, archived, unarchived or deleted. It has `systemManaged: true`. - `draft_has_billing`: The draft customer to merge has credit grants, pending spends or other billing postings. - `price_not_on_order`: `price` isn't on the order. - `price_not_seat_based`: `price` isn't a recurring price with `seats`. - `customer_unit_not_billable`: The customer unit has `effectiveBillable: false`, so it can't hold a seat. - `seat_limit_reached`: The seat line is full: a purchased line has `quantity` active seats, or an assigned line reached `quantityLimits.maximum`. - `unit_already_has_seat`: The unit already holds an active seat for this product. - `refill_rollover_conflict`: The grant sets both `refill` and `rollover`. - `credit_currency_key_reserved`: The credit currency `key` is an ISO 4217 currency code. - `insufficient_credits`: The customer's spendable balance in the credit currency doesn't cover the hold. Nothing was reserved. - `price_not_one_time`: The auto top-up's `price` isn't a one-time price. - `price_grants_mismatch`: The auto top-up's `price` doesn't grant the rule's credit currency. - `payment_method_required`: `collection: "chargeAutomatically"` was set, but there is no card to charge: the customer has no payment method on file, or the one named (or the default) is a bank transfer account. - `auto_top_up_conflict`: The customer already has an enabled auto top-up for this credit currency. - `invalid_request`: The request was rejected. - `not_found`: The requested resource does not exist. - `conflict`: The request conflicts with the resource's current state. - `rate_limited`: Too many requests in too short a time. - `api_error`: An unexpected error.
- `docUrl` (string, required) — A link to this code's entry on the errors page, or to the page itself for an undocumented code.
- `message` (string, required) — A human-readable explanation of what went wrong.
- `requestId` (string, required) — The ID of the request, also returned in the `Request-Id` header. Include it when contacting support.
- `type` (enum, required) — The category of error.
  - Allowed values: `invalid_request_error`, `authentication_error`, `permission_error`, `idempotency_error`, `rate_limit_error`, `api_error`
- `param` (string, optional) — The request field or header the error relates to, when there is one.

### EventsMeasure

EventsMeasure.

- `aggregation` (EventAggregation, required) — Aggregation over events in a billing period.
- `groupBy` (list of string, optional) — Dimension paths.
- `unit` (string, optional, default: event) — What the quantity is counted in, such as `token`, `ticket` or `page`.

### WorkflowMeasure

WorkflowMeasure.

- `close` (WorkflowMeasureClose, required) — At least one close event or timeout is required.
- `identifier` (string, required) — The event field whose value groups events into one workflow, such as `payload.ticketId`.
- `catchAll` (WorkflowMeasureCatchAll, optional) — Unmatched outcome.
- `derivedEvent` (WorkflowMeasureDerivedEvent, optional) — Quantity and payload of the derived event.
- `outcomes` (list of WorkflowMeasureOutcomesItems, optional) — Ordered workflow classification rules.

### SingleEventMeasure

SingleEventMeasure.

- `derivedEvent` (SingleEventMeasureDerivedEvent, required) — The independent measurement output.
- `catchAll` (SingleEventMeasureCatchAll, optional) — Unmatched outcome.
- `outcomes` (list of SingleEventMeasureOutcomesItems, optional) — Ordered event classification rules.

### MeterFilterValue

Comparison value; omitted for exists.

- string
- integer
- boolean
- Quantity: Quantity
- list of MeterFilterValueOneOf4Items

### EventAggregation

Aggregation over events in a billing period.

- `type`: `count` (count)
- `type`: `sum` (sum)
  - `sum` (EventAggregationSumSum, required) — The field to aggregate.
- `type`: `max` (max)
  - `max` (EventAggregationMaxMax, required) — The field to aggregate.
- `type`: `min` (min)
  - `min` (EventAggregationMinMin, required) — The field to aggregate.
- `type`: `average` (average)
  - `average` (EventAggregationAverageAverage, required) — The field to aggregate.
- `type`: `latest` (latest)
  - `latest` (EventAggregationLatestLatest, required) — The field to aggregate.
- `type`: `uniqueCount` (uniqueCount)
  - `uniqueCount` (EventAggregationUniqueCountUniqueCount, required) — The field to aggregate.

### WorkflowMeasureClose

At least one close event or timeout is required.

- `eventName` (string, optional) — The event's name, such as `ticket.closed`.
- `onTimeout` (enum, optional) — Timeout behavior.
  - Allowed values: `close`, `discard`
- `timeout` (Quantity, optional) — An exact value with an explicit measurement unit.

### WorkflowMeasureCatchAll

Unmatched outcome.

- `action` (enum, optional, default: discard) — Unmatched workflow behavior.
  - Allowed values: `emit`, `discard`
- `key` (string, optional, default: everything_else) — An outcome's key, such as `resolved`.

### WorkflowMeasureDerivedEvent

Quantity and payload of the derived event.

- `payload` (map from string to WorkflowPayloadValue, optional) — Computed payload fields.
- `quantity` (WorkflowQuantity, optional) — The quantity emitted on workflow close.

### WorkflowMeasureOutcomesItems

- `conditions` (list of WorkflowCondition, required) — All predicates must hold.
- `key` (string, required) — An outcome's key, such as `resolved`.

### SingleEventMeasureDerivedEvent

The independent measurement output.

- `quantity` (SingleEventQuantity, required) — Independent source-event measurement.
- `payload` (map from string to SingleEventMeasureDerivedEventPayload, optional) — Fields copied from the source event.

### SingleEventMeasureCatchAll

Unmatched outcome.

- `action` (enum, optional, default: emit) — Unmatched event behavior.
  - Allowed values: `emit`, `discard`
- `key` (string, optional, default: measured) — An outcome's key, such as `resolved`.

### SingleEventMeasureOutcomesItems

- `conditions` (list of SingleEventMeasureOutcomesItemsConditionsItems, required) — All event predicates must hold.
- `key` (string, required) — An outcome's key, such as `resolved`.

### Quantity

An exact value with an explicit measurement unit.

- `unit` (string, required) — What `value` is measured in: a time unit such as `minute` or `month`, or what a meter counts, such as `token` or `ticket`.
- `value` (string, required) — A non-negative exact decimal string, up to 15 fractional places.

### MeterFilterValueOneOf4Items

- string
- integer
- boolean

### EventAggregationSumSum

The field to aggregate.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### EventAggregationMaxMax

The field to aggregate.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### EventAggregationMinMin

The field to aggregate.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### EventAggregationAverageAverage

The field to aggregate.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### EventAggregationLatestLatest

The field to aggregate.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### EventAggregationUniqueCountUniqueCount

The field to aggregate.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### WorkflowPayloadValue

A derived workflow payload value.

- WorkflowOperand: WorkflowOperand
- WorkflowPayloadValue1

### WorkflowQuantity

The quantity emitted on workflow close.

- `type`: `count` (count)
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`
  - `unit` (string, optional, default: workflow) — What the quantity is counted in, such as `token`, `ticket` or `page`.
- `type`: `sum` (sum)
  - `sum` (WorkflowQuantitySumSum, required) — Field to sum.
  - `unit` (string, required) — What the quantity is counted in, such as `token`, `ticket` or `page`.
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`
- `type`: `composite` (composite)
  - `composite` (WorkflowComposite, required) — WorkflowComposite.
  - `unit` (string, required) — What the quantity is counted in, such as `token`, `ticket` or `page`.
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`

### WorkflowCondition

A predicate over workflow events.

- `type`: `anyEvent` (anyEvent)
  - `anyEvent` (WorkflowEventSelector, required) — WorkflowEventSelector.
- `type`: `noEvent` (noEvent)
  - `noEvent` (WorkflowEventSelector, required) — WorkflowEventSelector.
- `type`: `eventCount` (eventCount)
  - `eventCount` (WorkflowEventCountCondition, required) — A workflow event count comparison.
- `type`: `lastValue` (lastValue)
  - `lastValue` (MeterFilter, required) — MeterFilter.
- `type`: `firstValue` (firstValue)
  - `firstValue` (MeterFilter, required) — MeterFilter.

### SingleEventQuantity

Independent source-event measurement.

- `type`: `count` (count)
  - `unit` (string, required) — What the quantity is counted in, such as `token`, `ticket` or `page`.
- `type`: `value` (value)
  - `unit` (string, required) — What the quantity is counted in, such as `token`, `ticket` or `page`.
  - `value` (SingleEventQuantityValueValue, required) — Numeric event field.
- `type`: `stringLength` (stringLength)
  - `stringLength` (SingleEventQuantityStringLengthStringLength, required) — String field and counting convention.
  - `unit` (string, required) — What the quantity is counted in, such as `token`, `ticket` or `page`.

### SingleEventMeasureDerivedEventPayload

- `type` (enum, required) — Copy a source value.
  - Allowed values: `value`
- `value` (SingleEventMeasureDerivedEventPayloadValue, required) — Source field.

### SingleEventMeasureOutcomesItemsConditionsItems

- `type` (enum, required) — Value condition.
  - Allowed values: `value`
- `value` (MeterFilter, required) — MeterFilter.

### WorkflowOperand

A value computed from workflow events.

- `type`: `eventCount` (eventCount)
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `eventCount` (WorkflowEventSelector, optional) — WorkflowEventSelector.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`
- `type`: `sum` (sum)
  - `sum` (WorkflowOperandSumSum, required) — The source event field.
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`
- `type`: `min` (min)
  - `min` (WorkflowOperandMinMin, required) — The source event field.
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`
- `type`: `max` (max)
  - `max` (WorkflowOperandMaxMax, required) — The source event field.
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`
- `type`: `average` (average)
  - `average` (WorkflowOperandAverageAverage, required) — The source event field.
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`
- `type`: `first` (first)
  - `first` (WorkflowOperandFirstFirst, required) — The source event field.
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`
- `type`: `last` (last)
  - `last` (WorkflowOperandLastLast, required) — The source event field.
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`
- `type`: `duration` (duration)
  - `duration` (WorkflowOperandDurationDuration, required) — Duration output unit.
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`
- `type`: `openedAt` (openedAt)
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`
- `type`: `closedAt` (closedAt)
  - `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
  - `filters` (list of MeterFilter, optional) — Events included in this computation.
  - `round` (enum, optional) — Quantity rounding after division.
    - Allowed values: `up`, `down`, `nearest`

### WorkflowPayloadValue1

- `composite` (WorkflowComposite, required) — WorkflowComposite.
- `type` (enum, required) — Combine values.
  - Allowed values: `composite`
- `divideBy` (string, optional) — A positive exact decimal string, up to 15 fractional places.
- `filters` (list of MeterFilter, optional) — Events included in this computation.
- `round` (enum, optional) — Quantity rounding after division.
  - Allowed values: `up`, `down`, `nearest`

### WorkflowQuantitySumSum

Field to sum.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### WorkflowComposite

WorkflowComposite.

- `op` (enum, required) — Combine computed operands.
  - Allowed values: `add`, `min`, `max`
- `values` (list of WorkflowOperand, required) — Workflow values to combine.

### WorkflowEventSelector

WorkflowEventSelector.

- `eventName` (string, required) — The event's name, such as `ticket.closed`.
- `filters` (list of MeterFilter, optional) — Event-selection conditions.

### WorkflowEventCountCondition

A workflow event count comparison.

- `eventName` (string, required) — The event's name, such as `ticket.closed`.
- `op` (enum, required) — Count comparison.
  - Allowed values: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`
- `value` (integer, required) — Count to compare.
- `filters` (list of MeterFilter, optional) — Event-selection conditions.

### SingleEventQuantityValueValue

Numeric event field.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### SingleEventQuantityStringLengthStringLength

String field and counting convention.

- `counting` (enum, required) — Count Unicode code points without normalization.
  - Allowed values: `unicodeCodePoints`
- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### SingleEventMeasureDerivedEventPayloadValue

Source field.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### WorkflowOperandSumSum

The source event field.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### WorkflowOperandMinMin

The source event field.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### WorkflowOperandMaxMax

The source event field.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### WorkflowOperandAverageAverage

The source event field.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### WorkflowOperandFirstFirst

The source event field.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### WorkflowOperandLastLast

The source event field.

- `path` (string, required) — A dot-separated path to a field in the event, such as `payload.ticketId` or `cost.inference.model`.

### WorkflowOperandDurationDuration

Duration output unit.

- `unit` (string, required) — The time unit to report the duration in, such as `minute`.

## Examples

**Request**

```json
{
  "key": "output_tokens",
  "measure": {
    "type": "events",
    "events": {
      "aggregation": {
        "type": "sum",
        "sum": {
          "path": "cost.inference.outputTokens"
        }
      },
      "groupBy": [
        "cost.inference.model"
      ],
      "unit": "token"
    }
  }
}
```

**Response**

```json
{
  "id": "mtr_6Hn2Qa",
  "object": "meter",
  "createdAt": "2024-01-15T09:30:00Z",
  "archivedAt": "2024-01-15T09:30:00Z",
  "description": "Output tokens on chat messages, by model.",
  "eventNamePattern": "string",
  "eventNames": [
    "chat_message"
  ],
  "filters": [
    {
      "op": "eq",
      "path": "payload.plan",
      "value": "pro"
    }
  ],
  "health": {
    "invalidValues24h": 1,
    "lastMatchedAt": "2024-01-15T09:30:00Z",
    "matchedEvents24h": 1,
    "warnings": [],
    "closedWorkflows24h": 1,
    "discardedEvents24h": 1,
    "emittedEvents24h": 1,
    "missingIdentifier24h": 1,
    "openWorkflows": 1,
    "timedOut24h": 1,
    "unpricedOutcomes": []
  },
  "key": "output_tokens",
  "livemode": true,
  "measure": {
    "type": "events",
    "events": {
      "aggregation": {
        "type": "sum",
        "sum": {
          "path": "cost.inference.outputTokens"
        }
      },
      "groupBy": [
        "cost.inference.model"
      ],
      "unit": "token"
    }
  },
  "metadata": {
    "crmId": "0015g00000XyZ"
  },
  "name": "Output tokens",
  "updatedAt": "2024-01-15T09:30:00Z",
  "validationMode": "lenient"
}
```

**SDK Code**

```python
import requests

url = "https://api.paid.ai/v1/meters"

payload = {
    "key": "output_tokens",
    "measure": {
        "type": "events",
        "events": {
            "aggregation": {
                "type": "sum",
                "sum": { "path": "cost.inference.outputTokens" }
            },
            "groupBy": ["cost.inference.model"],
            "unit": "token"
        }
    }
}
headers = {
    "Paid-Beta": "meters=v1",
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api.paid.ai/v1/meters';
const options = {
  method: 'POST',
  headers: {
    'Paid-Beta': 'meters=v1',
    Authorization: 'Bearer <token>',
    'Content-Type': 'application/json'
  },
  body: '{"key":"output_tokens","measure":{"type":"events","events":{"aggregation":{"type":"sum","sum":{"path":"cost.inference.outputTokens"}},"groupBy":["cost.inference.model"],"unit":"token"}}}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api.paid.ai/v1/meters"

	payload := strings.NewReader("{\n  \"key\": \"output_tokens\",\n  \"measure\": {\n    \"type\": \"events\",\n    \"events\": {\n      \"aggregation\": {\n        \"type\": \"sum\",\n        \"sum\": {\n          \"path\": \"cost.inference.outputTokens\"\n        }\n      },\n      \"groupBy\": [\n        \"cost.inference.model\"\n      ],\n      \"unit\": \"token\"\n    }\n  }\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Paid-Beta", "meters=v1")
	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api.paid.ai/v1/meters")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Paid-Beta"] = 'meters=v1'
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"key\": \"output_tokens\",\n  \"measure\": {\n    \"type\": \"events\",\n    \"events\": {\n      \"aggregation\": {\n        \"type\": \"sum\",\n        \"sum\": {\n          \"path\": \"cost.inference.outputTokens\"\n        }\n      },\n      \"groupBy\": [\n        \"cost.inference.model\"\n      ],\n      \"unit\": \"token\"\n    }\n  }\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api.paid.ai/v1/meters")
  .header("Paid-Beta", "meters=v1")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"key\": \"output_tokens\",\n  \"measure\": {\n    \"type\": \"events\",\n    \"events\": {\n      \"aggregation\": {\n        \"type\": \"sum\",\n        \"sum\": {\n          \"path\": \"cost.inference.outputTokens\"\n        }\n      },\n      \"groupBy\": [\n        \"cost.inference.model\"\n      ],\n      \"unit\": \"token\"\n    }\n  }\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api.paid.ai/v1/meters', [
  'body' => '{
  "key": "output_tokens",
  "measure": {
    "type": "events",
    "events": {
      "aggregation": {
        "type": "sum",
        "sum": {
          "path": "cost.inference.outputTokens"
        }
      },
      "groupBy": [
        "cost.inference.model"
      ],
      "unit": "token"
    }
  }
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
    'Paid-Beta' => 'meters=v1',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api.paid.ai/v1/meters");
var request = new RestRequest(Method.POST);
request.AddHeader("Paid-Beta", "meters=v1");
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"key\": \"output_tokens\",\n  \"measure\": {\n    \"type\": \"events\",\n    \"events\": {\n      \"aggregation\": {\n        \"type\": \"sum\",\n        \"sum\": {\n          \"path\": \"cost.inference.outputTokens\"\n        }\n      },\n      \"groupBy\": [\n        \"cost.inference.model\"\n      ],\n      \"unit\": \"token\"\n    }\n  }\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Paid-Beta": "meters=v1",
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "key": "output_tokens",
  "measure": [
    "type": "events",
    "events": [
      "aggregation": [
        "type": "sum",
        "sum": ["path": "cost.inference.outputTokens"]
      ],
      "groupBy": ["cost.inference.model"],
      "unit": "token"
    ]
  ]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api.paid.ai/v1/meters")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```