Get Metrics by Identifier
Retrieve usage metrics and consumption data for a specific user or session identifier.
Endpoint
GET /api/v1/consumption/identifier/{identifier}/dates
Authentication
This endpoint requires 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
| Parameter | Type | Required | Description |
|---|---|---|---|
identifier | string | Yes | The unique identifier for the user or session (e.g., email, user ID, phone number) |
Headers
| Header | Type | Required | Description |
|---|---|---|---|
Authorization | string | Yes | Your API key in the format Bearer pk_xxx:sk_xxx |
Query Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
from | string (ISO 8601) | No | Start date for the metrics period |
to | string (ISO 8601) | No | End date for the metrics period |
Response
Success Response
Status Code: 200 OK
Response Body:
{
"data": [
{
"date": "2024-01-15",
"total_credits": 12
},
{
"date": "2024-01-16",
"total_credits": 18
},
{
"date": "2024-01-17",
"total_credits": 9
},
{
"date": "2024-01-18",
"total_credits": 21
},
{
"date": "2024-01-19",
"total_credits": 15
}
]
}
Response Fields
| Field | Type | Description |
|---|---|---|
data | array | Array of daily consumption objects |
data[].date | string (YYYY-MM-DD) | Date in ISO format |
data[].total_credits | integer | Total credits consumed on this date for this identifier |
Error Responses
401 Unauthorized
Status: 401 Unauthorized
{
"error": "Invalid or missing API key"
}
400 Bad Request
Missing Identifier:
Status: 400 Bad Request
{
"error": "Identifier parameter is required"
}
404 Not Found
No Data Found:
Status: 404 Not Found
{
"error": "No consumption data found for this identifier"
}
500 Internal Server Error
Status: 500 Internal Server Error
{
"error": "Internal server error"
}
Example Usage
cURL
# Get consumption for an identifier
curl -X GET "https://agentsgt.com/api/v1/consumption/identifier/user@example.com/dates" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"
# With URL encoding for email identifier
curl -X GET "https://agentsgt.com/api/v1/consumption/identifier/user%40example.com/dates" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"
# Get consumption for date range
curl -X GET "https://agentsgt.com/api/v1/consumption/identifier/user@example.com/dates?from=2024-01-01T00:00:00Z&to=2024-01-31T23:59:59Z" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"
# Using phone number as identifier
curl -X GET "https://agentsgt.com/api/v1/consumption/identifier/%2B15551234567/dates" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"
JavaScript (Fetch API)
const publicKey = 'pk_1234567890abcdef';
const secretKey = 'sk_abcdef1234567890';
const identifier = 'user@example.com';
// URL encode the identifier
const encodedIdentifier = encodeURIComponent(identifier);
// Get daily consumption
fetch(`https://agentsgt.com/api/v1/consumption/identifier/${encodedIdentifier}/dates`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log(`Consumption for: ${identifier}`);
console.log('Daily breakdown:');
let totalCredits = 0;
data.data.forEach(day => {
console.log(` ${day.date}: ${day.total_credits} credits`);
totalCredits += day.total_credits;
});
console.log(`\nTotal: ${totalCredits} credits`);
console.log(`Average per day: ${(totalCredits / data.data.length).toFixed(2)} credits`);
})
.catch(error => {
console.error('Error:', error);
});
// Get consumption with date filter
const params = new URLSearchParams({
from: '2024-01-01T00:00:00Z',
to: '2024-01-31T23:59:59Z'
});
fetch(`https://agentsgt.com/api/v1/consumption/identifier/${encodedIdentifier}/dates?${params}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
// Find peak usage day
const peakDay = data.data.reduce((max, day) =>
day.total_credits > max.total_credits ? day : max,
data.data[0]
);
console.log(`Peak usage: ${peakDay.date} with ${peakDay.total_credits} credits`);
});
Python (Requests)
import requests
from urllib.parse import quote
from datetime import datetime, timedelta
public_key = 'pk_1234567890abcdef'
secret_key = 'sk_abcdef1234567890'
identifier = 'user@example.com'
# URL encode the identifier
encoded_identifier = quote(identifier)
headers = {
'Authorization': f'Bearer {public_key}:{secret_key}',
'Content-Type': 'application/json'
}
# Get 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/identifier/{encoded_identifier}/dates',
headers=headers,
params=params
)
if response.status_code == 200:
data = response.json()
print(f"Consumption for {identifier} (Last 30 days):\n")
total_credits = 0
daily_data = data['data']
for day in daily_data:
print(f" {day['date']}: {day['total_credits']} credits")
total_credits += day['total_credits']
if daily_data:
average = total_credits / len(daily_data)
print(f"\nSummary:")
print(f" Total credits: {total_credits}")
print(f" Average per day: {average:.2f}")
print(f" Days active: {len(daily_data)}")
# Find trends
peak_day = max(daily_data, key=lambda x: x['total_credits'])
print(f" Peak day: {peak_day['date']} ({peak_day['total_credits']} credits)")
elif response.status_code == 404:
print(f"No consumption data found for {identifier}")
else:
print(f"Error: {response.status_code} - {response.json()}")
# Track multiple users
def get_user_consumption_summary(identifiers, from_date=None, to_date=None):
"""Get consumption summary for multiple users."""
results = {}
for identifier in identifiers:
encoded = quote(identifier)
params = {}
if from_date:
params['from'] = from_date
if to_date:
params['to'] = to_date
response = requests.get(
f'https://agentsgt.com/api/v1/consumption/identifier/{encoded}/dates',
headers=headers,
params=params
)
if response.status_code == 200:
data = response.json()
total = sum(day['total_credits'] for day in data['data'])
results[identifier] = {
'total_credits': total,
'days_active': len(data['data']),
'daily_data': data['data']
}
else:
results[identifier] = {'error': response.status_code}
return results
# Usage
users = ['user1@example.com', 'user2@example.com', 'user3@example.com']
summary = get_user_consumption_summary(
users,
from_date='2024-01-01T00:00:00Z',
to_date='2024-01-31T23:59:59Z'
)
print("\nMulti-user Summary:")
for user, stats in summary.items():
if 'error' not in stats:
print(f" {user}: {stats['total_credits']} credits over {stats['days_active']} days")
else:
print(f" {user}: Error {stats['error']}")
Node.js (Axios)
const axios = require('axios');
const publicKey = 'pk_1234567890abcdef';
const secretKey = 'sk_abcdef1234567890';
const headers = {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
};
// Function to get user consumption metrics
async function getUserConsumption(identifier, from, to) {
const encodedIdentifier = encodeURIComponent(identifier);
const params = {};
if (from) params.from = from;
if (to) params.to = to;
try {
const response = await axios.get(
`https://agentsgt.com/api/v1/consumption/identifier/${encodedIdentifier}/dates`,
{ headers, params }
);
const daily = response.data.data;
const totalCredits = daily.reduce((sum, day) => sum + day.total_credits, 0);
const averagePerDay = totalCredits / daily.length;
return {
identifier,
daily,
statistics: {
totalCredits,
averagePerDay,
daysActive: daily.length,
peakDay: daily.reduce((max, day) =>
day.total_credits > max.total_credits ? day : max,
daily[0]
)
}
};
} catch (error) {
console.error(`Error fetching consumption for ${identifier}:`,
error.response?.data || error.message);
throw error;
}
}
// Get consumption for a user
getUserConsumption('user@example.com', '2024-01-01T00:00:00Z', '2024-01-31T23:59:59Z')
.then(metrics => {
console.log(`\nConsumption Metrics for ${metrics.identifier}`);
console.log('='.repeat(50));
console.log(`Total Credits: ${metrics.statistics.totalCredits}`);
console.log(`Days Active: ${metrics.statistics.daysActive}`);
console.log(`Average per Day: ${metrics.statistics.averagePerDay.toFixed(2)}`);
console.log(`Peak Day: ${metrics.statistics.peakDay.date} (${metrics.statistics.peakDay.total_credits} credits)`);
console.log('\nLast 7 Days:');
metrics.daily.slice(-7).forEach(day => {
const bar = '█'.repeat(Math.ceil(day.total_credits / 2));
console.log(` ${day.date}: ${bar} ${day.total_credits}`);
});
});
// Compare multiple users
async function compareUserConsumption(identifiers, from, to) {
const results = await Promise.all(
identifiers.map(id => getUserConsumption(id, from, to).catch(err => ({
identifier: id,
error: err.message
})))
);
console.log('\nUser Consumption Comparison');
console.log('='.repeat(50));
// Filter successful results
const successful = results.filter(r => !r.error);
// Sort by total consumption
successful.sort((a, b) => b.statistics.totalCredits - a.statistics.totalCredits);
successful.forEach((user, index) => {
console.log(`${index + 1}. ${user.identifier}`);
console.log(` Total: ${user.statistics.totalCredits} credits`);
console.log(` Avg/day: ${user.statistics.averagePerDay.toFixed(2)}`);
});
// Show errors
const errors = results.filter(r => r.error);
if (errors.length > 0) {
console.log('\nErrors:');
errors.forEach(err => {
console.log(` ${err.identifier}: ${err.error}`);
});
}
return results;
}
// Usage
const users = ['user1@example.com', 'user2@example.com', 'user3@example.com'];
compareUserConsumption(users, '2024-01-01T00:00:00Z', '2024-01-31T23:59:59Z');
Use Cases
User Activity Tracking
Monitor individual user engagement with your agents:
// Track which users are most active
Customer Success
Identify power users and those who might need assistance:
# Alert customer success team when user activity changes significantly
Billing Per User
Track consumption for user-based billing:
// Calculate credits consumed per user for invoicing
Churn Prevention
Detect decreasing engagement patterns:
# Identify users with declining usage
Notes
- The identifier is the same value you provide when sending messages to agents (e.g., email, user ID, phone number)
- Daily consumption data is sorted by date in ascending order
- If no date range is specified, all-time consumption is returned
- Days with zero consumption are not included in the response
- Identifiers should be URL-encoded, especially if they contain special characters (e.g., @ in emails, + in phone numbers)
- This endpoint returns consumption across all agents the user has interacted with
- Date parameters should be in ISO 8601 format with timezone (e.g.,
2024-01-01T00:00:00Z) - The identifier matches against the
external_user_idfield in the chat history
Related Endpoints
- Get Metrics by Agent - Get detailed metrics for a specific agent
- Get Metrics by Organization - Get organization-wide consumption metrics
- Get Chat History by Identifier - View conversation history for this identifier