Saltar al contenido principal

Obtener Historial de Chat por Identificador

Recupera el historial de conversaciones de un usuario o identificador de sesión específico en todos los agentes de tu organización.

Endpoint

GET /api/v1/chat-history/identifier/{identifier}

Autenticación

Este endpoint requiere autenticación con API key. Incluye tu API key en el encabezado Authorization usando el esquema Bearer.

Formato del Encabezado:

Authorization: Bearer {PUBLIC_KEY}:{SECRET_KEY}

Solicitud

Parámetros de Ruta

ParámetroTipoRequeridoDescripción
identifierstringEl identificador único del usuario o sesión (por ejemplo, correo electrónico, ID de usuario, número de teléfono)

Encabezados

EncabezadoTipoRequeridoDescripción
AuthorizationstringTu API key en el formato Bearer pk_xxx:sk_xxx

Parámetros de Consulta

ParámetroTipoRequeridoPredeterminadoDescripción
pageintegerNo1Número de página para la paginación
limitintegerNo50Número de mensajes a devolver por página (máx: 100)
agent_idstring (UUID)No-Filtrar por agente específico
thread_idstringNo-Filtrar por ID de hilo/conversación específico
start_datestring (ISO 8601)No-Filtrar mensajes desde esta fecha en adelante
end_datestring (ISO 8601)No-Filtrar mensajes hasta esta fecha

Respuesta

Respuesta Exitosa

Código de Estado: 200 OK

Cuerpo de la Respuesta:

{
"success": true,
"data": {
"identifier": "user@example.com",
"messages": [
{
"id": "440e8400-e29b-41d4-a716-446655440099",
"agent_id": "550e8400-e29b-41d4-a716-446655440000",
"agent_name": "Customer Support Agent",
"thread_id": "thread_abc123xyz",
"input": "I need help with my account",
"output": "I'd be happy to help you with your account. What specific issue are you experiencing?",
"input_tokens": 8,
"output_tokens": 18,
"total_credits": 3,
"created_at": "2024-01-20T14:30:00Z",
"channel": "WEB"
},
{
"id": "550e8400-e29b-41d4-a716-446655440088",
"agent_id": "660e8400-e29b-41d4-a716-446655440001",
"agent_name": "Sales Assistant",
"thread_id": "thread_xyz789abc",
"input": "What pricing plans do you offer?",
"output": "We offer three pricing tiers: Basic ($29/month), Professional ($99/month), and Enterprise (custom pricing). Each plan includes different features and usage limits.",
"input_tokens": 7,
"output_tokens": 32,
"total_credits": 4,
"created_at": "2024-01-21T10:15:00Z",
"channel": "WHATSAPP"
}
],
"pagination": {
"page": 1,
"limit": 50,
"total": 2,
"has_more": false
}
}
}

Campos de la Respuesta

CampoTipoDescripción
successbooleanIndica si la solicitud fue exitosa
data.identifierstringEl identificador utilizado para filtrar el historial de conversaciones
data.messagesarrayArreglo de objetos de mensaje
data.messages[].idstring (UUID)Identificador único del mensaje
data.messages[].agent_idstring (UUID)ID del agente que procesó el mensaje
data.messages[].agent_namestringNombre del agente
data.messages[].thread_idstringIdentificador del hilo de conversación
data.messages[].inputstringMensaje de entrada del usuario
data.messages[].outputstringMensaje de respuesta del agente
data.messages[].input_tokensintegerNúmero de tokens en la entrada
data.messages[].output_tokensintegerNúmero de tokens en la salida
data.messages[].total_creditsintegerTotal de créditos consumidos para este mensaje
data.messages[].created_atstring (ISO 8601)Marca de tiempo de cuándo se creó el mensaje
data.messages[].channelstringCanal donde se originó el mensaje (API, WEB, WHATSAPP)
data.paginationobjectInformación de paginación
data.pagination.pageintegerNúmero de página actual
data.pagination.limitintegerNúmero de elementos por página
data.pagination.totalintegerNúmero total de mensajes
data.pagination.has_morebooleanSi hay más páginas disponibles

Respuestas de Error

401 Unauthorized

API Key Faltante o Inválida:

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

400 Bad Request

Parámetros Inválidos:

Status: 400 Bad Request
{
"success": false,
"error": "Invalid page or limit parameter"
}

Identificador Faltante:

Status: 400 Bad Request
{
"success": false,
"error": "Identifier parameter is required"
}

404 Not Found

No se Encontraron Mensajes:

Status: 404 Not Found
{
"success": false,
"error": "No conversation history found for this identifier"
}

500 Internal Server Error

Status: 500 Internal Server Error
{
"success": false,
"error": "Internal server error"
}

Ejemplos de Uso

cURL

# Get chat history for an identifier
curl -X GET "https://agentsgt.com/api/v1/chat-history/identifier/user@example.com" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

# With URL encoding for email identifier
curl -X GET "https://agentsgt.com/api/v1/chat-history/identifier/user%40example.com" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

# Filter by specific agent
curl -X GET "https://agentsgt.com/api/v1/chat-history/identifier/user@example.com?agent_id=550e8400-e29b-41d4-a716-446655440000" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

# With pagination
curl -X GET "https://agentsgt.com/api/v1/chat-history/identifier/user@example.com?page=2&limit=25" \
-H "Authorization: Bearer pk_1234567890abcdef:sk_abcdef1234567890"

# Filter by date range
curl -X GET "https://agentsgt.com/api/v1/chat-history/identifier/user@example.com?start_date=2024-01-01T00:00:00Z&end_date=2024-01-31T23:59:59Z" \
-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);

// Basic request
fetch(`https://agentsgt.com/api/v1/chat-history/identifier/${encodedIdentifier}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log(`Chat history for: ${data.data.identifier}`);
console.log(`Total messages: ${data.data.pagination.total}`);

// Group messages by agent
const messagesByAgent = {};
data.data.messages.forEach(msg => {
if (!messagesByAgent[msg.agent_name]) {
messagesByAgent[msg.agent_name] = [];
}
messagesByAgent[msg.agent_name].push(msg);
});

// Display messages by agent
Object.keys(messagesByAgent).forEach(agentName => {
console.log(`\n--- ${agentName} ---`);
messagesByAgent[agentName].forEach(msg => {
console.log(`[${msg.created_at}] User: ${msg.input}`);
console.log(`[${msg.created_at}] Agent: ${msg.output}`);
});
});
})
.catch(error => {
console.error('Error:', error);
});

// With filters
const params = new URLSearchParams({
page: '1',
limit: '25',
agent_id: '550e8400-e29b-41d4-a716-446655440000',
start_date: '2024-01-01T00:00:00Z'
});

fetch(`https://agentsgt.com/api/v1/chat-history/identifier/${encodedIdentifier}?${params}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => {
console.log('Filtered chat history:', data.data.messages);
});

Python (Requests)

import requests
from urllib.parse import quote

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'
}

# Basic request
response = requests.get(
f'https://agentsgt.com/api/v1/chat-history/identifier/{encoded_identifier}',
headers=headers
)

if response.status_code == 200:
data = response.json()
print(f"Chat history for: {data['data']['identifier']}")
print(f"Total messages: {data['data']['pagination']['total']}")

for msg in data['data']['messages']:
print(f"\n[{msg['created_at']}] via {msg['channel']}")
print(f"Agent: {msg['agent_name']}")
print(f"User: {msg['input']}")
print(f"Agent: {msg['output']}")
print(f"Credits: {msg['total_credits']}")
else:
print(f"Error: {response.status_code} - {response.json()}")

# With filters
params = {
'page': 1,
'limit': 25,
'agent_id': '550e8400-e29b-41d4-a716-446655440000',
'thread_id': 'thread_abc123xyz'
}

response = requests.get(
f'https://agentsgt.com/api/v1/chat-history/identifier/{encoded_identifier}',
headers=headers,
params=params
)

# Paginate through all messages
def get_all_messages(identifier, agent_id=None):
all_messages = []
page = 1
has_more = True

while has_more:
params = {'page': page, 'limit': 100}
if agent_id:
params['agent_id'] = agent_id

response = requests.get(
f'https://agentsgt.com/api/v1/chat-history/identifier/{quote(identifier)}',
headers=headers,
params=params
)

if response.status_code == 200:
data = response.json()
all_messages.extend(data['data']['messages'])
has_more = data['data']['pagination']['has_more']
page += 1
else:
break

return all_messages

# Get all messages for the identifier
messages = get_all_messages('user@example.com')
print(f"Retrieved {len(messages)} total messages")

Node.js (Axios)

const axios = require('axios');

const publicKey = 'pk_1234567890abcdef';
const secretKey = 'sk_abcdef1234567890';
const identifier = 'user@example.com';

// URL encode the identifier
const encodedIdentifier = encodeURIComponent(identifier);

axios.get(`https://agentsgt.com/api/v1/chat-history/identifier/${encodedIdentifier}`, {
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`,
'Content-Type': 'application/json'
},
params: {
page: 1,
limit: 50
}
})
.then(response => {
const { identifier, messages, pagination } = response.data.data;

console.log(`\nChat History for: ${identifier}`);
console.log(`Total messages: ${pagination.total}`);
console.log(`Page ${pagination.page}`);

// Display messages chronologically
messages.forEach(msg => {
console.log(`\n[${ msg.created_at}] ${msg.channel}`);
console.log(`Agent: ${msg.agent_name}`);
console.log(`User: ${msg.input}`);
console.log(`Agent: ${msg.output}`);
});

if (pagination.has_more) {
console.log('\n--- More messages available ---');
}
})
.catch(error => {
console.error('Error:', error.response?.data || error.message);
});

// Function to get all pages
async function getAllChatHistory(identifier, agentId = null) {
const allMessages = [];
let page = 1;
let hasMore = true;

while (hasMore) {
try {
const response = await axios.get(
`https://agentsgt.com/api/v1/chat-history/identifier/${encodeURIComponent(identifier)}`,
{
headers: {
'Authorization': `Bearer ${publicKey}:${secretKey}`
},
params: {
page,
limit: 100,
...(agentId && { agent_id: agentId })
}
}
);

allMessages.push(...response.data.data.messages);
hasMore = response.data.data.pagination.has_more;
page++;
} catch (error) {
console.error('Error fetching page:', page, error.message);
break;
}
}

return allMessages;
}

// Usage
getAllChatHistory('user@example.com')
.then(messages => {
console.log(`Retrieved ${messages.length} total messages`);
});

Casos de Uso

Historial de Soporte al Cliente

Recupera todas las interacciones que un cliente ha tenido con diferentes agentes de soporte:

const customerEmail = 'customer@example.com';
// Get complete conversation history for customer support analysis

Seguimiento del Recorrido del Usuario

Rastrea cómo un usuario ha interactuado con diferentes agentes (ventas, soporte, onboarding):

// See which agents a user has engaged with and their conversation flow

Cumplimiento y Auditoría

Accede a registros completos de conversaciones con fines de cumplimiento:

# Export all conversations for a specific user with date filtering

Notas

  • El identificador es típicamente un correo electrónico, ID de usuario, número de teléfono o cualquier identificador único de usuario que proporcionas al enviar mensajes
  • Los mensajes se devuelven en orden ascendente por fecha de creación (los más antiguos primero)
  • El límite máximo es de 100 mensajes por página
  • Los resultados incluyen conversaciones de todos los agentes de tu organización
  • El campo agent_name se incluye para ayudar a identificar qué agente manejó cada conversación
  • Los identificadores deben codificarse para URL, especialmente si contienen caracteres especiales (por ejemplo, @ en direcciones de correo electrónico)
  • Los filtros de fecha usan el formato ISO 8601 con información de zona horaria
  • La marca de tiempo last_used_at de la API key se actualiza automáticamente cuando se llama a este endpoint

Endpoints Relacionados