Skip to main content

Overview

The Usage resource provides aggregated statistics for AI requests over a specified time period. Unlike the Requests resource (which shows individual requests), Usage gives you daily rollups with totals for:
  • Request counts
  • Token usage
  • Costs breakdown
  • Fees and service charges
Use this resource for billing, analytics dashboards, and quota management.

Method

retrieve()

Get aggregated usage statistics for a date range. Signature
retrieve(params: UsageParams): Promise<RestUsage>
Parameters
NameTypeRequiredDescription
startstringYesStart date (ISO 8601 format: YYYY-MM-DDTHH:mm:ssZ)
endstringNoEnd date (ISO 8601 format, defaults to now)
connection_idstringNoFilter by specific connection (customer)
product_idstringNoFilter by specific product configuration
metadata_filtersRecord<string, string>NoFilter by custom metadata key-value pairs
Returns
{
  items: Array<{
    date: string; // YYYY-MM-DD
    start: string; // ISO 8601 timestamp (start of day)
    end: string; // ISO 8601 timestamp (end of day)
    total_requests: number;
    total_usage_tokens: number;
    total_usage_cost: string; // USD as decimal string
    total_fee_amount: string;
    total_service_charge_amount: string;
    total_request_cost: string;
    total_wallet_cost: string; // What customers paid
    total_merchant_cost: string; // Your earnings
    total_gross_volume: string;
    total_net_volume: string;
  }>;
  totals: {
    total_requests: number;
    total_usage_tokens: number;
    total_usage_cost: string;
    total_fee_amount: string;
    total_service_charge_amount: string;
    total_request_cost: string;
    total_wallet_cost: string;
    total_merchant_cost: string;
    total_gross_volume: string;
    total_net_volume: string;
  };
}
Example: Monthly Usage
const usage = await lava.usage.retrieve({
  start: '2024-01-01T00:00:00Z',
  end: '2024-01-31T23:59:59Z'
});

console.log('Total requests:', usage.totals.total_requests);
console.log('Total tokens:', usage.totals.total_usage_tokens);
console.log('Total revenue:', usage.totals.total_merchant_cost);

// Daily breakdown
for (const day of usage.items) {
  console.log(`${day.date}: ${day.total_requests} requests, $${day.total_merchant_cost}`);
}
Example: Customer Usage Get usage for a specific customer:
const customerUsage = await lava.usage.retrieve({
  start: '2024-01-01T00:00:00Z',
  connection_id: 'conn_abc123'
});

const totalSpent = parseFloat(customerUsage.totals.total_wallet_cost);
console.log(`Customer spent $${totalSpent.toFixed(2)} this month`);
Example: Filter by Metadata Track usage by feature:
const chatUsage = await lava.usage.retrieve({
  start: '2024-01-01T00:00:00Z',
  end: '2024-01-31T23:59:59Z',
  metadata_filters: {
    feature: 'chat'
  }
});

console.log('Chat feature usage:');
console.log('Requests:', chatUsage.totals.total_requests);
console.log('Tokens:', chatUsage.totals.total_usage_tokens);
console.log('Cost:', chatUsage.totals.total_request_cost);

Understanding Usage Data

Daily Items

The items array contains one entry per day with statistics for that 24-hour period:
const usage = await lava.usage.retrieve({
  start: '2024-01-01T00:00:00Z',
  end: '2024-01-07T23:59:59Z'
});

// 7 days = 7 items
console.log('Days:', usage.items.length);

// Each day's stats
usage.items.forEach(day => {
  console.log(`${day.date}:`);
  console.log(`  Requests: ${day.total_requests}`);
  console.log(`  Tokens: ${day.total_usage_tokens}`);
  console.log(`  Cost: $${day.total_request_cost}`);
});

Totals

The totals object aggregates all daily items:
const usage = await lava.usage.retrieve({
  start: '2024-01-01T00:00:00Z',
  end: '2024-01-31T23:59:59Z'
});

// Month-wide totals
console.log('Total requests:', usage.totals.total_requests);
console.log('Total tokens:', usage.totals.total_usage_tokens);

// Financial totals
console.log('Gross volume:', usage.totals.total_gross_volume);
console.log('Your earnings:', usage.totals.total_merchant_cost);

Cost Breakdown

Each usage record includes multiple cost components:
const usage = await lava.usage.retrieve({
  start: '2024-01-01T00:00:00Z'
});

const totals = usage.totals;

// Base costs (what AI providers charged)
console.log('Provider costs:', totals.total_usage_cost);

// Your merchant fees
console.log('Merchant fees:', totals.total_fee_amount);

// Lava's service charge (1.9%)
console.log('Service charge:', totals.total_service_charge_amount);

// What customers paid
console.log('Customer total:', totals.total_wallet_cost);

// Your earnings (fees - service charge)
console.log('Your revenue:', totals.total_merchant_cost);

Common Use Cases

Analytics Dashboard

Display usage metrics to end users:
async function getCustomerDashboard(connectionId: string) {
  const thirtyDaysAgo = new Date();
  thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

  const usage = await lava.usage.retrieve({
    start: thirtyDaysAgo.toISOString(),
    connection_id: connectionId
  });

  return {
    totalRequests: usage.totals.total_requests,
    totalTokens: usage.totals.total_usage_tokens,
    totalSpent: parseFloat(usage.totals.total_wallet_cost),
    dailyData: usage.items.map(day => ({
      date: day.date,
      requests: day.total_requests,
      tokens: day.total_usage_tokens,
      cost: parseFloat(day.total_wallet_cost)
    }))
  };
}

// Usage in API route
app.get('/api/dashboard', async (req, res) => {
  const dashboard = await getCustomerDashboard(req.user.connectionId);
  res.json(dashboard);
});

Monthly Billing Report

Generate invoices or billing summaries:
async function generateMonthlyInvoice(connectionId: string, year: number, month: number) {
  const startDate = new Date(year, month - 1, 1);
  const endDate = new Date(year, month, 0, 23, 59, 59);

  const usage = await lava.usage.retrieve({
    start: startDate.toISOString(),
    end: endDate.toISOString(),
    connection_id: connectionId
  });

  const connection = await lava.connections.retrieve(connectionId);

  return {
    customer: {
      email: connection.wallet.email,
      name: `${connection.wallet.first_name} ${connection.wallet.last_name}`
    },
    period: {
      start: startDate.toISOString().split('T')[0],
      end: endDate.toISOString().split('T')[0]
    },
    usage: {
      requests: usage.totals.total_requests,
      tokens: usage.totals.total_usage_tokens
    },
    charges: {
      subtotal: parseFloat(usage.totals.total_usage_cost),
      fees: parseFloat(usage.totals.total_fee_amount),
      total: parseFloat(usage.totals.total_wallet_cost)
    },
    dailyBreakdown: usage.items.map(day => ({
      date: day.date,
      requests: day.total_requests,
      cost: parseFloat(day.total_wallet_cost)
    }))
  };
}

Quota Management

Implement usage limits and warnings:
async function checkQuotaExceeded(connectionId: string, monthlyLimit: number) {
  const startOfMonth = new Date();
  startOfMonth.setDate(1);
  startOfMonth.setHours(0, 0, 0, 0);

  const usage = await lava.usage.retrieve({
    start: startOfMonth.toISOString(),
    connection_id: connectionId
  });

  const currentUsage = usage.totals.total_requests;
  const percentUsed = (currentUsage / monthlyLimit) * 100;

  return {
    currentUsage,
    monthlyLimit,
    percentUsed,
    isExceeded: currentUsage >= monthlyLimit,
    isNearLimit: percentUsed >= 80,
    remaining: Math.max(0, monthlyLimit - currentUsage)
  };
}

// Usage in API route
app.post('/api/chat', async (req, res) => {
  const quota = await checkQuotaExceeded(req.user.connectionId, 10000);

  if (quota.isExceeded) {
    return res.status(429).json({
      error: 'quota_exceeded',
      message: 'Monthly request limit reached',
      quota
    });
  }

  if (quota.isNearLimit) {
    res.setHeader('X-Quota-Warning', 'true');
    res.setHeader('X-Quota-Remaining', quota.remaining.toString());
  }

  // Proceed with request
});

Revenue Analytics

Track merchant earnings over time:
async function getRevenueReport(days: number = 30) {
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - days);

  const usage = await lava.usage.retrieve({
    start: startDate.toISOString()
  });

  const dailyRevenue = usage.items.map(day => ({
    date: day.date,
    revenue: parseFloat(day.total_merchant_cost),
    requests: day.total_requests,
    avgRevenuePerRequest: parseFloat(day.total_merchant_cost) / day.total_requests
  }));

  const totalRevenue = parseFloat(usage.totals.total_merchant_cost);
  const avgDailyRevenue = totalRevenue / usage.items.length;

  return {
    totalRevenue,
    avgDailyRevenue,
    totalRequests: usage.totals.total_requests,
    avgRevenuePerRequest: totalRevenue / usage.totals.total_requests,
    dailyBreakdown: dailyRevenue
  };
}

Feature Usage Comparison

Compare usage across different features:
async function compareFeatureUsage(features: string[]) {
  const startDate = new Date();
  startDate.setDate(startDate.getDate() - 30);

  const featureData = await Promise.all(
    features.map(async feature => {
      const usage = await lava.usage.retrieve({
        start: startDate.toISOString(),
        metadata_filters: { feature }
      });

      return {
        feature,
        requests: usage.totals.total_requests,
        tokens: usage.totals.total_usage_tokens,
        cost: parseFloat(usage.totals.total_request_cost)
      };
    })
  );

  return featureData.sort((a, b) => b.requests - a.requests);
}

// Usage
const comparison = await compareFeatureUsage(['chat', 'search', 'code-gen']);
comparison.forEach(f => {
  console.log(`${f.feature}: ${f.requests} requests, $${f.cost.toFixed(2)}`);
});

Cost Forecasting

Predict monthly costs based on current usage:
async function forecastMonthlyCost(connectionId: string) {
  const startOfMonth = new Date();
  startOfMonth.setDate(1);
  startOfMonth.setHours(0, 0, 0, 0);

  const usage = await lava.usage.retrieve({
    start: startOfMonth.toISOString(),
    connection_id: connectionId
  });

  const daysElapsed = new Date().getDate();
  const daysInMonth = new Date(
    new Date().getFullYear(),
    new Date().getMonth() + 1,
    0
  ).getDate();

  const currentSpend = parseFloat(usage.totals.total_wallet_cost);
  const avgDailySpend = currentSpend / daysElapsed;
  const forecastedMonthlySpend = avgDailySpend * daysInMonth;

  return {
    currentSpend,
    daysElapsed,
    daysRemaining: daysInMonth - daysElapsed,
    avgDailySpend,
    forecastedMonthlySpend,
    projectedIncrease: forecastedMonthlySpend - currentSpend
  };
}

Date Range Tips

This Month

const startOfMonth = new Date();
startOfMonth.setDate(1);
startOfMonth.setHours(0, 0, 0, 0);

const usage = await lava.usage.retrieve({
  start: startOfMonth.toISOString()
});

Last 30 Days

const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

const usage = await lava.usage.retrieve({
  start: thirtyDaysAgo.toISOString()
});

Specific Month

const startDate = new Date(2024, 0, 1); // January 2024
const endDate = new Date(2024, 0, 31, 23, 59, 59);

const usage = await lava.usage.retrieve({
  start: startDate.toISOString(),
  end: endDate.toISOString()
});

Today Only

const startOfToday = new Date();
startOfToday.setHours(0, 0, 0, 0);

const usage = await lava.usage.retrieve({
  start: startOfToday.toISOString()
});

// Today's data will be in items[items.length - 1]
const today = usage.items[usage.items.length - 1];
console.log('Today\'s requests:', today?.total_requests || 0);
Always use ISO 8601 format for dates: YYYY-MM-DDTHH:mm:ssZ. Use new Date().toISOString() to generate properly formatted timestamps.