Skip to main content

Get Metrics by Agent

Retrieve detailed usage metrics and consumption data for a specific agent.

Endpoints

Get Daily Consumption

Get credit consumption broken down by day for a specific agent.

GET /api/v1/consumption/agent/{agentId}/dates

Get Consumption by Model

Get credit consumption broken down by AI model for a specific agent.

GET /api/v1/consumption/agent/{agentId}/models

Authentication

These endpoints require API key authentication. Include your API key in the Authorization header using the Bearer scheme.

Header Format:

Authorization: Bearer {PUBLIC_KEY}:{SECRET_KEY}

Request

Path Parameters

ParameterTypeRequiredDescription
agentIdstring (UUID)YesThe unique identifier of the agent

Headers

HeaderTypeRequiredDescription
AuthorizationstringYesYour API key in the format Bearer pk_xxx:sk_xxx

Query Parameters

ParameterTypeRequiredDescription
fromstring (ISO 8601)NoStart date for the metrics period
tostring (ISO 8601)NoEnd date for the metrics period

Response

Daily Consumption Response

Status Code: 200 OK

Response Body:

{
"data": [
{
"date": "2024-01-15",
"total_credits": 245
},
{
"date": "2024-01-16",
"total_credits": 312
},
{
"date": "2024-01-17",
"total_credits": 189
},
{
"date": "2024-01-18",
"total_credits": 401
},
{
"date": "2024-01-19",
"total_credits": 278
}
]
}

Response Fields (Daily)

FieldTypeDescription
dataarrayArray of daily consumption objects
data[].datestring (YYYY-MM-DD)Date in ISO format
data[].total_creditsintegerTotal credits consumed on this date

Consumption by Model Response

Status Code: 200 OK

Response Body:

{
"data": [
{
"model_id": "880e8400-e29b-41d4-a716-446655440000",
"name": "GPT-4",
"total_credits": 8420
},
{
"model_id": "990e8400-e29b-41d4-a716-446655440001",
"name": "GPT-3.5 Turbo",
"total_credits": 2180
}
]
}

Response Fields (By Model)

FieldTypeDescription
dataarrayArray of model consumption objects
data[].model_idstring (UUID)Unique identifier of the model
data[].namestringDisplay name of the model
data[].total_creditsintegerTotal credits consumed by this model

Error Responses

401 Unauthorized

Status: 401 Unauthorized
{
"error": "Invalid or missing API key"
}

403 Forbidden

Status: 403 Forbidden
{
"error": "Agent does not belong to your organization"
}

404 Not Found

Status: 404 Not Found
{
"error": "Agent not found"
}

500 Internal Server Error

Status: 500 Internal Server Error
{
"error": "Internal server error"
}

Example Usage

cURL

# Get daily consumption
curl -X GET "https://agentsgt.com/api/v1/consumption/agent/550e8400-e29b-41d4-a716-446655440000/dates" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

# Get daily consumption for date range
curl -X GET "https://agentsgt.com/api/v1/consumption/agent/550e8400-e29b-41d4-a716-446655440000/dates?from=2024-01-01T00:00:00Z&to=2024-01-31T23:59:59Z" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

# Get consumption by model
curl -X GET "https://agentsgt.com/api/v1/consumption/agent/550e8400-e29b-41d4-a716-446655440000/models" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

JavaScript (Fetch API)

const publicKey = 'pk_1234567890abcdef';
const secretKey = 'sk_abcdef1234567890';
const agentId = '550e8400-e29b-41d4-a716-446655440000';

// Get daily consumption
fetch(`https://agentsgt.com/api/v1/consumption/agent/${agentId}/dates`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log('Daily consumption:');
data.data.forEach(day => {
console.log(`${day.date}: ${day.total_credits} credits`);
});

// Calculate total and average
const total = data.data.reduce((sum, day) => sum + day.total_credits, 0);
const average = total / data.data.length;
console.log(`\nTotal: ${total} credits`);
console.log(`Daily average: ${average.toFixed(2)} credits`);
});

// Get consumption by model
fetch(`https://agentsgt.com/api/v1/consumption/agent/${agentId}/models`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log('\nConsumption by model:');
data.data.forEach(model => {
console.log(`${model.name}: ${model.total_credits} credits`);
});
});

// Fetch both metrics together
async function getAgentMetrics(agentId, from, to) {
const params = new URLSearchParams();
if (from) params.append('from', from);
if (to) params.append('to', to);

const [dailyResponse, modelsResponse] = await Promise.all([
fetch(`https://agentsgt.com/api/v1/consumption/agent/${agentId}/dates?${params}`, {
headers: { 'Authorization': `Bearer ${publicKey}:${secretKey}` }
}),
fetch(`https://agentsgt.com/api/v1/consumption/agent/${agentId}/models?${params}`, {
headers: { 'Authorization': `Bearer ${publicKey}:${secretKey}` }
})
]);

const [daily, models] = await Promise.all([
dailyResponse.json(),
modelsResponse.json()
]);

return { daily: daily.data, models: models.data };
}

// Usage
getAgentMetrics(agentId, '2024-01-01T00:00:00Z', '2024-01-31T23:59:59Z')
.then(metrics => {
console.log('Agent Metrics:', metrics);
});

Python (Requests)

import requests
from datetime import datetime, timedelta
import matplotlib.pyplot as plt # For visualization

public_key = 'pk_1234567890abcdef'
secret_key = 'sk_abcdef1234567890'
agent_id = '550e8400-e29b-41d4-a716-446655440000'

headers = {
'Authorization': f'Bearer {public_key}:{secret_key}',
'Content-Type': 'application/json'
}

# Get daily consumption for last 30 days
end_date = datetime.now()
start_date = end_date - timedelta(days=30)

params = {
'from': start_date.isoformat() + 'Z',
'to': end_date.isoformat() + 'Z'
}

response = requests.get(
f'https://agentsgt.com/api/v1/consumption/agent/{agent_id}/dates',
headers=headers,
params=params
)

if response.status_code == 200:
data = response.json()
print("Daily Consumption (Last 30 days):")

total_credits = 0
for day in data['data']:
print(f" {day['date']}: {day['total_credits']} credits")
total_credits += day['total_credits']

average_per_day = total_credits / len(data['data']) if data['data'] else 0
print(f"\nTotal: {total_credits} credits")
print(f"Average per day: {average_per_day:.2f} credits")

# Visualize daily consumption (optional)
dates = [day['date'] for day in data['data']]
credits = [day['total_credits'] for day in data['data']]

# plt.figure(figsize=(12, 6))
# plt.plot(dates, credits, marker='o')
# plt.xlabel('Date')
# plt.ylabel('Credits')
# plt.title('Daily Credit Consumption')
# plt.xticks(rotation=45)
# plt.tight_layout()
# plt.show()

# Get consumption by model
response = requests.get(
f'https://agentsgt.com/api/v1/consumption/agent/{agent_id}/models',
headers=headers,
params=params
)

if response.status_code == 200:
data = response.json()
print("\nConsumption by Model:")

# Sort by consumption
sorted_models = sorted(
data['data'],
key=lambda x: x['total_credits'],
reverse=True
)

total = sum(model['total_credits'] for model in sorted_models)

for model in sorted_models:
percentage = (model['total_credits'] / total * 100) if total > 0 else 0
print(f" {model['name']}: {model['total_credits']} credits ({percentage:.1f}%)")

Node.js (Axios)

const axios = require('axios');

const publicKey = 'pk_1234567890abcdef';
const secretKey = 'sk_abcdef1234567890';
const agentId = '550e8400-e29b-41d4-a716-446655440000';

const headers = {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
};

// Function to get comprehensive agent metrics
async function getAgentAnalytics(agentId, from, to) {
try {
const params = { from, to };

// Fetch both endpoints in parallel
const [dailyResponse, modelsResponse] = await Promise.all([
axios.get(
`https://agentsgt.com/api/v1/consumption/agent/${agentId}/dates`,
{ headers, params }
),
axios.get(
`https://agentsgt.com/api/v1/consumption/agent/${agentId}/models`,
{ headers, params }
)
]);

const daily = dailyResponse.data.data;
const models = modelsResponse.data.data;

// Calculate statistics
const totalCredits = daily.reduce((sum, day) => sum + day.total_credits, 0);
const averagePerDay = totalCredits / daily.length;
const maxDay = daily.reduce((max, day) =>
day.total_credits > max.total_credits ? day : max, daily[0]);
const minDay = daily.reduce((min, day) =>
day.total_credits < min.total_credits ? day : min, daily[0]);

return {
period: { from, to },
daily,
models,
statistics: {
totalCredits,
averagePerDay,
peakDay: maxDay,
lowestDay: minDay,
totalDays: daily.length
}
};
} catch (error) {
console.error('Error fetching agent analytics:', error.response?.data || error.message);
throw error;
}
}

// Get analytics for current month
const now = new Date();
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1).toISOString();
const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59).toISOString();

getAgentAnalytics(agentId, startOfMonth, endOfMonth)
.then(analytics => {
console.log('Agent Analytics');
console.log('===============');
console.log(`Period: ${analytics.period.from} to ${analytics.period.to}`);
console.log(`\nStatistics:`);
console.log(` Total Credits: ${analytics.statistics.totalCredits}`);
console.log(` Average per Day: ${analytics.statistics.averagePerDay.toFixed(2)}`);
console.log(` Peak Day: ${analytics.statistics.peakDay.date} (${analytics.statistics.peakDay.total_credits} credits)`);
console.log(` Lowest Day: ${analytics.statistics.lowestDay.date} (${analytics.statistics.lowestDay.total_credits} credits)`);

console.log(`\nModel Usage:`);
analytics.models.forEach(model => {
const percentage = (model.total_credits / analytics.statistics.totalCredits * 100).toFixed(1);
console.log(` ${model.name}: ${model.total_credits} credits (${percentage}%)`);
});

console.log(`\nLast 7 Days:`);
analytics.daily.slice(-7).forEach(day => {
console.log(` ${day.date}: ${day.total_credits} credits`);
});
});

Use Cases

Performance Tracking

Monitor agent usage patterns over time:

// Track daily usage to identify trends

Cost Optimization

Identify which models consume the most credits:

# Switch to more cost-effective models if appropriate

Capacity Planning

Forecast future usage based on historical data:

// Calculate growth rate and predict future consumption

Anomaly Detection

Detect unusual spikes or drops in usage:

# Alert if consumption deviates significantly from average

Notes

  • Daily consumption data is sorted by date in ascending order
  • If no date range is specified, all-time consumption is returned
  • Dates in the response use YYYY-MM-DD format
  • Days with zero consumption are not included in the daily breakdown
  • Model consumption shows aggregate usage across all days in the period
  • If an agent's model was changed during the period, both models will appear in the breakdown
  • Date parameters should be in ISO 8601 format with timezone (e.g., 2024-01-01T00:00:00Z)