This guide walks you through integrating Metrx into your application, from initial setup to advanced features.
Table of Contents
- Quickstart
- Python SDK
- TypeScript SDK
- OpenTelemetry Integration
- Gateway Proxy Setup
- Custom Headers for Tracking
- Streaming Responses
- Webhook Setup
- Migration Guide
- IDE-Assisted Setup
- Budget Configuration
- Alert Setup
- Realtime Dashboard
Quickstart
1. Get Your API Key
Sign up at app.metrxbot.com:
- Create an organization
- Go to Settings → Security → API Keys
- Create a key and copy it (it starts with
sk_live_)
Put it in the environment. Every snippet in this guide reads METRX_API_KEY:
export METRX_API_KEY="sk_live_..."2. Connect
Use the SDK for your language, or OpenTelemetry if your app already has it. Both send telemetry from your process; your LLM calls still go straight to your provider. The gateway proxy is the alternative: it forwards each call and records it on the way.
| Value | |
|---|---|
| API key env var | METRX_API_KEY |
| API key prefix | sk_live_... |
| Python package | metrxbot (imports as metrx) |
| TypeScript package | @metrxbot/sdk |
| OTLP traces endpoint | https://gateway.metrxbot.com/v1/traces (OTLP/HTTP, JSON only) |
| Gateway base URL, OpenAI SDKs | https://gateway.metrxbot.com/v1 |
| Gateway base URL, Anthropic SDK | https://gateway.metrxbot.com |
3. View Your Dashboard
Log into app.metrxbot.com to see cost by model, call counts, latency and error rates, and usage against your plan limit.
Python SDK
pip install "metrxbot[openai]>=0.4.0"
export METRX_API_KEY=sk_live_... # Settings -> Security -> API Keysimport os
from metrx import Metrx
from openai import OpenAI
m = Metrx(api_key=os.environ["METRX_API_KEY"], agent_key="refund-triage")
m.instrument() # patches OpenAI/Anthropic CLASSES: clients you create before or after are tracked
client = OpenAI()
with m.task(task_id="ticket-4821") as t: # any string id; non-UUID ids map to a deterministic UUIDv5 client-side
reply = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Summarise ticket 4821"}],
)
t.set_outcome(success=True)
# short scripts flush at exit automatically; on serverless call m.flush()m.task(...) correlates the LLM calls made inside the block with one task, and t.set_outcome(...) records that task’s result. See Tasks, outcomes, contracts and scorecards.
TypeScript SDK
Install
npm install @metrxbot/sdk@0.7.0 @opentelemetry/api@1.9.1 @opentelemetry/sdk-trace-node@2.11.0 @opentelemetry/instrumentation@0.222.0 @opentelemetry/instrumentation-openai@0.20.0 openai@6.49.0Set up tracing (metrx.ts)
Import this file before anything imports openai:
// metrx.ts: import this first, before anything imports "openai".
// Compile to CommonJS (tsc "module": "commonjs"). openai 7.x is not instrumented yet.
import { NodeTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { OpenAIInstrumentation } from '@opentelemetry/instrumentation-openai';
import { MetrxbotClient, MetrxbotSpanExporter, MetrxbotSpanProcessor } from '@metrxbot/sdk';
export const exporter = new MetrxbotSpanExporter({
apiKey: process.env.METRX_API_KEY!,
agentId: 'refund-triage',
});
const provider = new NodeTracerProvider({
spanProcessors: [new MetrxbotSpanProcessor(), new SimpleSpanProcessor(exporter)],
});
provider.register();
registerInstrumentations({ instrumentations: [new OpenAIInstrumentation()] });
export const metrx = new MetrxbotClient({ apiKey: process.env.METRX_API_KEY! });Track a task and its outcome
task() gives each unit of work a task_id (a v4 UUID by default), and setOutcome() records its result. Flush the exporter before the outcome so the span arrives first:
import { exporter, metrx } from './metrx';
import { task } from '@metrxbot/sdk';
import OpenAI from 'openai';
const client = new OpenAI();
export async function handleTicket() {
return task(metrx, async (t) => {
const reply = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Draft a reply to ticket 4821' }],
});
await exporter.forceFlush(); // send the span before the outcome
t.setOutcome({ success: true });
return reply;
});
}The pinned versions above are tested together with CommonJS output. With openai 7.x, or with native ES modules, the OpenAI instrumentation records no span yet.
OpenTelemetry Integration
Metrx receives OTLP/HTTP traces at https://gateway.metrxbot.com/v1/traces, JSON encoding only. Node apps need only environment variables; Python and other protobuf-only exporters send through an OpenTelemetry Collector. Direct protobuf is not supported yet.
The full setup (Node env vars, the Collector config, Python via the Collector, batch limits) is on the OpenTelemetry page.
Gateway Proxy Setup
The gateway is an alternative to the SDKs: point an OpenAI-compatible client at it and each call is forwarded to your provider and recorded. Your Metrx key authenticates with the gateway (Authorization: Bearer); your provider key goes in X-Provider-Key and is forwarded.
Python with OpenAI SDK
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["METRX_API_KEY"], # Metrx key, sent as Authorization: Bearer
base_url="https://gateway.metrxbot.com/v1",
default_headers={
"X-Provider-Key": os.environ["OPENAI_API_KEY"],
"X-Agent-ID": "refund-triage",
},
)
reply = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Hello"}],
)Node.js with OpenAI SDK
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.METRX_API_KEY, // Metrx key, sent as Authorization: Bearer
baseURL: 'https://gateway.metrxbot.com/v1',
defaultHeaders: {
'X-Provider-Key': process.env.OPENAI_API_KEY!,
'X-Agent-ID': 'refund-triage',
},
});
const reply = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Hello' }],
});Direct HTTP
curl -X POST https://gateway.metrxbot.com/v1/chat/completions \
-H "Authorization: Bearer $METRX_API_KEY" \
-H "X-Provider-Key: $OPENAI_API_KEY" \
-H "X-Agent-ID: refund-triage" \
-H "Content-Type: application/json" \
-d '{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Hello"}]}'Anthropic SDK
The Anthropic SDK appends /v1/messages itself, so its base URL is the bare gateway host:
import os
from anthropic import Anthropic
client = Anthropic(
auth_token=os.environ["METRX_API_KEY"], # Metrx key, sent as Authorization: Bearer
base_url="https://gateway.metrxbot.com",
default_headers={
"X-Provider-Key": os.environ["ANTHROPIC_API_KEY"],
"X-Agent-ID": "refund-triage",
},
)
message = client.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
)Custom Headers for Tracking
Use these headers on gateway requests to track costs and outcomes across your organization:
X-Agent-ID
Custom identifier for your AI agent or system:
curl -H "X-Agent-ID: customer-support-bot-v2"Benefits:
- Track costs by agent
- Compare performance across versions
- Identify which agents are most cost-effective
X-Session-ID
Group related LLM calls together (conversation, workflow, user session):
curl -H "X-Session-ID: user-456-session-2024-02-20-001"Benefits:
- Track multi-turn conversations as a single session
- Aggregate cost and latency per session
- Correlate with business outcomes
- Identify long-running sessions for optimization
session_id is the run identity (v0): mark a long-running run by stamping the same session_id on all of its events — Python via session(), TypeScript via the X-Session-ID header / sessionId field passthrough today.
X-Task-Id
The task_id (a UUID) of the unit of work this call belongs to. The SDKs’ task() sets it for you; on raw gateway calls, send it yourself and post the task’s outcome to /api/v1/tasks/{task_id}/outcome.
X-Customer-ID
Track costs by end-customer (for multi-tenant SaaS apps):
curl -H "X-Customer-ID: cust_enterprise_xyz"Benefits:
- Chargeback costs to specific customers
- Per-customer usage dashboards
- Identify high-cost customers
config_version (event field)
config_version is a free-text label you stamp on events to attribute them to a configuration revision (prompt, model, pipeline). Metrx applies no validation, parsing, or ordering to it — any string is stored verbatim (an empty string is stored as null). Pick a scheme (git SHA, semver, date tag) and stamp it consistently: grouping is by exact string equality only.
Stamp it via the OTel span attribute metrx.config_version (or gen_ai.request.config_version), or as the config_version field on directly-ingested events:
// TypeScript SDK (OTel exporter): set the metrx.config_version attribute
span.setAttribute('metrx.config_version', 'prompt-v3-2026-08-01');Streaming Responses
The gateway forwards streaming responses. Set stream: true on a request made with the gateway clients above; the gateway reads the token usage from the provider’s stream to calculate the cost:
- Gateway captures all SSE (Server-Sent Event) chunks
- Final chunk includes token usage from the provider
- Cost is calculated and logged with the event
Webhook Setup
Webhooks deliver real-time events to your backend as they happen.
1. Create a Webhook Endpoint
On your backend, create an endpoint to receive events:
// pages/api/webhooks/metrx.ts
import { NextApiRequest, NextApiResponse } from 'next';
import crypto from 'crypto';
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
// Verify webhook signature
const signature = req.headers['x-webhook-signature'] as string;
const secret = process.env.METRX_WEBHOOK_SECRET;
const hash = crypto
.createHmac('sha256', secret)
.update(JSON.stringify(req.body))
.digest('hex');
if (hash !== signature) {
return res.status(401).json({ error: 'Invalid signature' });
}
// Handle event
const { event_type, data } = req.body;
switch (event_type) {
case 'event.created':
await handleEventCreated(data);
break;
case 'outcome.confirmed':
await handleOutcomeConfirmed(data);
break;
}
res.status(200).json({ success: true });
}
async function handleEventCreated(data: any) {
console.log(`LLM call: ${data.model} cost $${data.cost_microcents / 1e6}`);
// Log to your analytics system
// Trigger alerts if cost exceeds threshold
// Update customer billing
}
async function handleOutcomeConfirmed(data: any) {
console.log(`Outcome confirmed: ${data.name}`);
// Update your database
// Calculate ROI
// Generate reports
}2. Register the Webhook
Log into app.metrxbot.com:
- Go to Settings → Webhooks
- Click Add Webhook
- Enter your endpoint:
https://your-app.com/api/webhooks/metrx - Select events:
event.created,outcome.confirmed, etc. - Click Create
3. Verify Webhook Signature
Every webhook includes a signature for verification:
import crypto from 'crypto';
function verifyWebhookSignature(
payload: string,
signature: string,
secret: string
): boolean {
const expectedSignature = crypto
.createHmac('sha256', secret)
.update(payload)
.digest('hex');
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expectedSignature)
);
}4. Handle Events
event.created:
{
"event_type": "event.created",
"data": {
"id": "event_123",
"model": "gpt-4",
"input_tokens": 150,
"output_tokens": 75,
"cost_microcents": 2250,
"latency_ms": 1234,
"status": "success",
"agent_key": "my-agent",
"session_id": "session-123",
"customer_id": "cust-456"
}
}outcome.confirmed:
{
"event_type": "outcome.confirmed",
"data": {
"id": "outcome_xyz",
"name": "Successfully handled inquiry",
"session_id": "session-123",
"related_events": 3
}
}Migration Guide: From Direct API Calls
The least-change migration is the SDK for your language (Python, TypeScript) or OpenTelemetry: your LLM client keeps calling the provider directly. If you would rather route calls through the gateway, these are the steps.
Step 1: Create Metrx Account
Sign up at app.metrxbot.com and create an API key in Settings → Security → API Keys.
Step 2: Update Environment Variables
Keep your provider key (the gateway forwards it as X-Provider-Key) and add your Metrx key:
export METRX_API_KEY="sk_live_..."Step 3: Refactor LLM Client
Before:
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});After:
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.METRX_API_KEY, // Metrx key, sent as Authorization: Bearer
baseURL: 'https://gateway.metrxbot.com/v1',
defaultHeaders: {
'X-Provider-Key': process.env.OPENAI_API_KEY!,
'X-Agent-ID': 'refund-triage',
},
});
const reply = await client.chat.completions.create({
model: 'gpt-4o-mini',
messages: [{ role: 'user', content: 'Hello' }],
});Step 4: Test Staging
- Deploy to staging with the new environment variable
- Run your integration tests
- Verify costs are tracked in the Metrx dashboard
- Check that responses match expected behavior
Step 5: Gradually Roll Out
Metrx has no traffic-split setting: you choose, in your own code, which calls go through the gateway. For example, build the gateway client for a share of requests and the direct client for the rest, and raise the share as you gain confidence:
// Your own rollout flag, not a Metrx setting.
const useMetrx = Math.random() * 100 < Number(process.env.GATEWAY_ROLLOUT_PERCENT ?? 0);Step 6: Monitor & Optimize
Once migrated, use the Metrx dashboard to:
- Identify expensive calls
- Compare model performance
- Set up cost alerts
- Optimize prompts for cheaper models
Troubleshooting
Every gateway error body carries a code and a hint; Errors lists each code and what to do.
”Invalid API key”
Ensure your Metrx API key is in the Authorization header, not X-Provider-Key:
# Wrong
curl -H "X-Provider-Key: sk_live_xxx"
# Correct
curl -H "Authorization: Bearer sk_live_xxx"“Missing X-Provider-Key header”
Your LLM provider key (OpenAI, Anthropic, etc.) must be in the X-Provider-Key header:
# Correct
curl -H "X-Provider-Key: sk_openai_xxx"“Unsupported model”
Check supported models:
curl https://gateway.metrxbot.com/v1/models \
-H "Authorization: Bearer sk_live_xxx"Costs not appearing
- Check that requests complete with status 200
- Verify session_id is set (if grouping calls)
- Check the Events tab in the dashboard
- With OpenTelemetry, check the exporter protocol is
http/json: protobuf is refused with415 OTLP_PROTOBUF_UNSUPPORTED
IDE-Assisted Setup
Metrx offers an intelligent setup feature that generates context-aware installation prompts for popular AI IDEs.
How It Works
- Go to app.metrxbot.com and start the onboarding flow
- At Step 1, click “Set up with AI IDE”
- Select your IDE from the list:
- Claude Code
- Cursor
- Codex
- Windsurf
- Gemini
- Grok
- Choose your preferred programming language (Python, TypeScript, etc.)
- Copy the generated prompt
- Paste it into your IDE’s AI assistant
What the Generated Prompt Includes
The AI IDE will guide you through:
- Installing the Metrx SDK for your language
- Configuring the agent with your API key
- Making your first test request
- Verifying the connection works
This approach lets you use your IDE’s AI assistant to understand each step and ask questions as you go.
Budget Configuration
Control spending by setting budget limits and enforcement policies.
Setting Up Budgets
- Log in to app.metrxbot.com
- Go to Settings → Budgets
- Click Create Budget
- Configure:
- Period: Daily or Monthly
- Limit: Maximum spending for the period (in dollars)
- Warning Threshold: Optional percentage (e.g., alert at 80% of limit)
- Enforcement Mode: See options below
- Apply To: Specific agent or entire organization
Enforcement Modes
| Mode | Behavior |
|---|---|
| alert_only | Send alerts when limit is reached; requests still go through |
| soft_block | Allow requests but flag them; log warnings to console |
| hard_block | Reject requests with 429 error when limit is exceeded |
Tier Limits
Budget functionality varies by plan:
| Tier | Budgets Allowed |
|---|---|
| Starter | 1 budget |
| Lite | 3 budgets |
| Pro | 10 budgets |
| Enterprise | 100 budgets |
See metrxbot.com/pricing for current tier details.
How Budget Enforcement Works
- When you make a request through the gateway, the gateway checks the current spending
- If enforcement is alert_only or soft_block, the request proceeds
- If enforcement is hard_block and the limit is reached, the gateway returns
429with codeBUDGET_EXCEEDED, the budget id, the amount spent and the limit (see Errors) - Budget resets at the start of the next period (daily/monthly)
Alert Setup
Configure notifications for cost spikes, errors, and other important events.
Configuring Alerts
- Log in to app.metrxbot.com
- Go to Settings → Alerts
- Select notification channels (see Notification Channels below)
- Choose which alert types to enable
- Set thresholds for each alert type
Alert Types
| Alert Type | Trigger | Example |
|---|---|---|
| cost_spike | Daily spending exceeds threshold | Spending jumped 50% above average |
| error_rate | Error percentage exceeds threshold | >5% of requests failed |
| usage_spike | API call volume exceeds threshold | 2x normal call volume |
| idle_agent | Agent inactive for configured period | No calls in 7 days |
| budget_warning | Spending approaching budget limit | 80% of monthly budget used |
Notification Channels
Metrx can send alerts via:
- Email: Instant emails to configured address
- Slack: Messages to a Slack channel (webhook required)
- Telegram: Direct messages to a Telegram user (bot token required)
- Webhook: POST requests to your backend
Example: Slack Setup
- Create an Incoming Webhook in Slack (at api.slack.com/apps)
- Copy the webhook URL
- In Metrx Settings → Alerts, select Slack
- Paste your webhook URL
- Enable specific alert types
- Metrx will post alerts to your channel
Example Slack message:
🚨 Cost Spike Alert
Your costs jumped 50% today: $145 vs. average $95
Breakdown: GPT-4 calls increased 200%
Action: Review recent prompts or adjust temperatureRealtime Dashboard
The Metrx dashboard updates in real time as events occur.
How Real-Time Updates Work
Instead of polling the API repeatedly, the dashboard uses Supabase Realtime subscriptions:
- When you open the dashboard, it establishes a WebSocket connection
- New events are pushed to your browser instantly
- Dashboard components (charts, metrics, agent list) update automatically
- No page refresh needed
What Updates in Real-Time
- New Events: LLM calls appear immediately
- Cost Totals: Daily/monthly spending updates live
- Agent Status: Online/offline status changes
- Alert Triggers: New alerts appear in the notification panel
- Agent Topology: Network graphs update as agents interact
Benefits
- No Stale Data: Always see current costs and activity
- Low Latency: Updates appear in under 100ms
- Reduced Load: No polling requests hammering your servers
- Better UX: Watch your agents work in real-time
Next Steps: See the API Reference for complete endpoint documentation.