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
Method
retrieve()
Get aggregated usage statistics for a date range. SignatureCopy
Ask AI
retrieve(params: UsageParams): Promise<RestUsage>
| Name | Type | Required | Description |
|---|---|---|---|
start | string | Yes | Start date (ISO 8601 format: YYYY-MM-DDTHH:mm:ssZ) |
end | string | No | End date (ISO 8601 format, defaults to now) |
connection_id | string | No | Filter by specific connection (customer) |
product_id | string | No | Filter by specific product configuration |
metadata_filters | Record<string, string> | No | Filter by custom metadata key-value pairs |
Copy
Ask AI
{
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;
};
}
Copy
Ask AI
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}`);
}
Copy
Ask AI
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`);
Copy
Ask AI
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
Theitems array contains one entry per day with statistics for that 24-hour period:
Copy
Ask AI
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
Thetotals object aggregates all daily items:
Copy
Ask AI
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:Copy
Ask AI
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:Copy
Ask AI
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:Copy
Ask AI
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:Copy
Ask AI
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:Copy
Ask AI
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:Copy
Ask AI
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:Copy
Ask AI
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
Copy
Ask AI
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
Copy
Ask AI
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const usage = await lava.usage.retrieve({
start: thirtyDaysAgo.toISOString()
});
Specific Month
Copy
Ask AI
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
Copy
Ask AI
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.