MeterixDeveloper Documentation

Integration & API Reference

Connect your AI agents and LLM backend pipelines to Meterix. Real-time cost calculation, token metering, and telemetry aggregation in under 2 minutes.

1. Python SDK Integration Guide

Python 3.8+

Install the official Meterix Python package from PyPI:

pip install meterix

Initialize the client and send telemetry logs after calling OpenAI, Anthropic, or custom LLM endpoints:

from meterix import Meterix

# Initialize Meterix client with your secret API key
meter = Meterix(api_key="mx_live_your_api_key_here")

# 1. Multi-call Agent Session helper (aggregates multi-step workflows)
session = meter.session("sess_task_99214")
session.log_usage(
    model="gpt-4o",
    prompt_tokens=1250,
    completion_tokens=480,
    metadata={"agent_name": "ResearchAgent", "step": "planning"}
)
session.log_usage(
    model="claude-3-5-sonnet",
    prompt_tokens=2100,
    completion_tokens=850,
    metadata={"agent_name": "ResearchAgent", "step": "synthesis"}
)

# 2. Or log telemetry payload manually
response = meter.log_usage(
    model="gpt-4o",
    prompt_tokens=1250,
    completion_tokens=480,
    metadata={
        "environment": "production",
        "agent_name": "CustomerSupportAgent",
        "user_id": "usr_99182"
    }
)

# 3. Or use the trace context manager to automatically track latency
with meter.trace(model="claude-3-5-sonnet", metadata={"workflow": "code_review"}) as t:
    # Perform your LLM completion call here
    pass

2. Node.js / TypeScript SDK Integration Guide

Node.js 16+

Install the Node.js SDK via npm or yarn:

npm i meterix

Import and initialize the client in your backend application or Next.js API routes:

import { MeterixClient } from "@/lib/meterix";

// Singleton — initialize once at module level
const meter = new MeterixClient({
  apiKey: process.env.METERIX_API_KEY,  // mx_live_...
  flushIntervalMs: 3000,               // auto-flush every 3 seconds
  maxBufferSize: 50,                   // force flush when buffer hits 50
});

async function runMultiCallAgentTask() {
  // Create a scoped session instance for multi-call agent tasks
  // All logUsage events from this session automatically attach session_id
  const session = meter.session("sess_agent_task_881923");

  // Step 1: Initial query planning
  session.logUsage({
    model: "gpt-4o-mini",
    promptTokens: 800,
    completionTokens: 250,
    metadata: { agent_name: "PlannerAgent", environment: "production" },
  });

  // Step 2: Complex reasoning & code generation
  session.logUsage({
    model: "gpt-4o",
    promptTokens: 3200,
    completionTokens: 1100,
    metadata: { agent_name: "CoderAgent", environment: "production" },
  });

  // Optional: manually flush all buffered logs immediately
  await session.flush();
}

runMultiCallAgentTask();

2b. Vercel & Serverless Environments

waitUntil() pattern

In serverless environments (Vercel Functions, Next.js Route Handlers, Edge Runtime), the process may be frozen immediately after sending the HTTP response — before background flushes complete. Use @vercel/functions waitUntil() to keep the function alive until the telemetry batch is fully flushed.

Next.js Route Handler + waitUntil()

// app/api/route.ts — Next.js Route Handler (Vercel Edge / Serverless)
import { waitUntil } from "@vercel/functions";
import { MeterixClient, flushWithWaitUntil } from "@/lib/meterix";

const meter = new MeterixClient({ apiKey: process.env.METERIX_API_KEY });

export async function POST(req: Request) {
  // Your LLM call here
  const result = await callLLM(req);

  // Queue telemetry — fire-and-forget
  meter.logUsage({
    model: "gpt-4o",
    promptTokens: result.usage.prompt_tokens,
    completionTokens: result.usage.completion_tokens,
    metadata: { environment: "production" },
  });

  // waitUntil() ensures the flush completes AFTER the response is returned
  // This is critical for serverless — avoids cold-start truncation
  flushWithWaitUntil(meter, waitUntil);

  return Response.json({ answer: result.content });
}
logUsage()

Returns { queued: true } instantly. Never blocks your response.

flushWithWaitUntil()

Wraps meter.flush() in Vercel's waitUntil to guarantee delivery post-response.

Silent Failures

Network errors are caught internally — never propagated to your application.

Node.js Graceful Shutdown (SIGTERM / beforeExit)

For long-running Node.js servers, MeterixClient automatically registers beforeExit and SIGTERM listeners to flush any remaining buffered logs before process exit.

// Node.js Long-Running Server (Express, Fastify, etc.)
import { MeterixClient } from "@/lib/meterix";

// MeterixClient automatically registers these — shown here for reference:
const meter = new MeterixClient({
  apiKey: process.env.METERIX_API_KEY,
  registerShutdownHandlers: true, // default: true
});

// You can also register manually for full control:
process.once("SIGTERM", async () => {
  console.log("SIGTERM received — flushing telemetry...");
  await meter.flush();
  meter.destroy();  // stop the background flush interval
  process.exit(0);
});

process.once("beforeExit", async () => {
  await meter.flush();
});

3. REST API Reference: Ingestion Endpoint

POST /api/v1/telemetry

Required HTTP Headers

Authorization:Bearer <YOUR_API_KEY>
Content-Type:application/json

JSON Request Payload Fields

FieldTypeRequiredDescription
modelstringYesLLM model name (e.g. gpt-4o, gpt-4o-mini, claude-3-5-sonnet).
prompt_tokensintegerYes*Number of prompt / input tokens processed (*or alias input_tokens).
completion_tokensintegerYes*Number of completion / output tokens generated (*or alias output_tokens).
metadataobjectOptionalCustom metadata key-value tags (e.g. environment, agent_id).
latency_msnumberOptionalLLM request round-trip latency in milliseconds.

Example cURL Command

curl -X POST https://meterix.app/api/v1/telemetry \
  -H "Authorization: Bearer mx_live_your_api_key_here" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "prompt_tokens": 1500,
    "completion_tokens": 450,
    "metadata": {
      "environment": "production",
      "agent_name": "SupportAgent"
    }
  }'

Successful Response (200 OK)

{
  "success": true,
  "log_id": "c5cf61ee-6ff6-4f73-a1e7-e75ca9601324",
  "model": "gpt-4o",
  "prompt_tokens": 1500,
  "completion_tokens": 450,
  "total_tokens": 1950,
  "calculated_cost": 0.00825,
  "is_estimated": false,
  "currency": "USD",
  "timestamp": "2026-08-15T10:23:00.000Z"
}
200 Success

Payload validated, cost calculated, and log stored in Supabase.

401 Unauthorized

Invalid or revoked secret key provided in Authorization header.

429 Quota Exceeded

Monthly log quota limit reached for organization plan tier.

4. Active Models Endpoint

GET /api/models

Returns all active LLM model pricing configurations filtered strictly by is_active = true.

Example Request

curl -X GET https://meterix.app/api/models

Sample Response

{
  "models": [
    {
      "model_name": "gpt-4o",
      "provider": "openai",
      "input_price_per_million": 2.5,
      "output_price_per_million": 10.0,
      "is_active": true
    },
    {
      "model_name": "claude-3-5-sonnet",
      "provider": "anthropic",
      "input_price_per_million": 3.0,
      "output_price_per_million": 15.0,
      "is_active": true
    }
  ]
}

5. API Key Management Endpoints

GET /api/keysPOST /api/keys

Lists or generates secret API keys for authenticated dashboard users. Newly generated keys format as mx_live_<random_32_chars> and are stored using SHA-256 hashes (key_hash).

Example List Keys Request

curl -X GET https://meterix.app/api/keys \
  -H "Authorization: Bearer <YOUR_SESSION_TOKEN>"