Retrieve, delete, and download previously generated audio files. Track your text-to-speech usage history and manage generated audio content.
import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
const client = new ElevenLabsClient({ apiKey: "your-api-key" });
// Access this API via: client.historyGet list of generated audio items with filtering and pagination.
/**
* @param request - Filter and pagination options
* @param requestOptions - Optional request configuration
* @returns Paginated list of history items
* @throws UnprocessableEntityError if request fails
*/
client.history.list(
request?: HistoryListRequest,
requestOptions?: RequestOptions
): HttpResponsePromise<GetSpeechHistoryResponse>;
interface HistoryListRequest {
/** Number of items per page */
pageSize?: number;
/** Start after this history item ID (for pagination) */
startAfterHistoryItemId?: string;
/** Filter by voice ID */
voiceId?: string;
/** Filter by model ID */
modelId?: string;
/** Filter items created before this Unix timestamp */
dateBeforeUnix?: number;
/** Filter items created after this Unix timestamp */
dateAfterUnix?: number;
/** Sort direction */
sortDirection?: "asc" | "desc";
/** Search query string */
search?: string;
/** Filter by source */
source?: string;
}
interface GetSpeechHistoryResponse {
/** Array of history items */
history: SpeechHistoryItem[];
/** Whether more results are available */
has_more: boolean;
/** ID of last item (for pagination) */
last_history_item_id?: string;
}
interface SpeechHistoryItem {
/** Unique history item ID */
history_item_id: string;
/** Request ID */
request_id: string;
/** Voice ID used */
voice_id: string;
/** Voice name */
voice_name: string;
/** Model ID used */
model_id: string;
/** Input text */
text: string;
/** Unix timestamp of creation */
date_unix: number;
/** Character count */
character_count_change_from: number;
/** Character count change */
character_count_change_to: number;
/** Content type */
content_type: string;
/** Processing state */
state: "created" | "deleted" | "processing";
/** Voice settings used */
settings?: VoiceSettings;
/** Source of generation */
source?: string;
}Retrieve detailed information about a specific history item.
/**
* @param history_item_id - History item ID
* @param requestOptions - Optional request configuration
* @returns History item details
* @throws UnprocessableEntityError if request fails
*/
client.history.get(
history_item_id: string,
requestOptions?: RequestOptions
): HttpResponsePromise<SpeechHistoryItemResponse>;
interface SpeechHistoryItemResponse {
history_item_id: string;
request_id: string;
voice_id: string;
voice_name: string;
model_id: string;
text: string;
date_unix: number;
character_count_change_from: number;
character_count_change_to: number;
content_type: string;
state: string;
settings?: VoiceSettings;
feedback?: Feedback;
share_link_id?: string;
source?: string;
}
interface Feedback {
thumbs_up: boolean;
feedback_text?: string;
emotions?: string[];
inaccurate_clone?: boolean;
glitches?: boolean;
audio_quality?: boolean;
other?: boolean;
}Delete a specific history item.
/**
* @param history_item_id - History item ID to delete
* @param requestOptions - Optional request configuration
* @returns Deletion confirmation
* @throws UnprocessableEntityError if request fails
*/
client.history.delete(
history_item_id: string,
requestOptions?: RequestOptions
): HttpResponsePromise<DeleteHistoryItemResponse>;
interface DeleteHistoryItemResponse {
success: boolean;
}Download audio for a specific history item.
/**
* @param history_item_id - History item ID
* @param requestOptions - Optional request configuration
* @returns ReadableStream of audio data
* @throws UnprocessableEntityError if request fails
*/
client.history.getAudio(
history_item_id: string,
requestOptions?: RequestOptions
): HttpResponsePromise<ReadableStream<Uint8Array>>;Download one or more history items as audio or zip archive.
/**
* @param request - History item IDs to download
* @param requestOptions - Optional request configuration
* @returns ReadableStream of audio (single) or zip (multiple)
* @throws UnprocessableEntityError if request fails
*/
client.history.download(
request: DownloadHistoryRequest,
requestOptions?: RequestOptions
): HttpResponsePromise<ReadableStream<Uint8Array>>;
interface DownloadHistoryRequest {
/** A list of history items to download, you can get IDs of history items and other metadata using the GET /v1/history endpoint. (REQUIRED) */
historyItemIds: string[];
/** Output format to transcode the audio file, can be wav or default. */
outputFormat?: string;
}import { ElevenLabsClient } from "@elevenlabs/elevenlabs-js";
const client = new ElevenLabsClient({ apiKey: "your-api-key" });
// Get recent history
const history = await client.history.list({
pageSize: 50,
sortDirection: "desc",
});
console.log(`Found ${history.history.length} items`);
for (const item of history.history) {
console.log(`${item.history_item_id}: ${item.text.substring(0, 50)}...`);
console.log(` Voice: ${item.voice_name}`);
console.log(` Model: ${item.model_id}`);
console.log(` Date: ${new Date(item.date_unix * 1000).toLocaleString()}`);
console.log(` Characters: ${item.character_count_change_to}`);
}// Get all history items with pagination
async function getAllHistory(): Promise<SpeechHistoryItem[]> {
const allItems: SpeechHistoryItem[] = [];
let lastItemId: string | undefined;
while (true) {
const page = await client.history.list({
pageSize: 100,
startAfterHistoryItemId: lastItemId,
});
allItems.push(...page.history);
if (!page.has_more) break;
lastItemId = page.last_history_item_id;
}
return allItems;
}
const allHistory = await getAllHistory();
console.log(`Total history items: ${allHistory.length}`);// Get history for specific voice
const voiceHistory = await client.history.list({
voiceId: "specific-voice-id",
pageSize: 100,
});
console.log(`Found ${voiceHistory.history.length} items for this voice`);// Get history from last 30 days
const thirtyDaysAgo = Math.floor(Date.now() / 1000) - (30 * 24 * 60 * 60);
const recentHistory = await client.history.list({
dateAfterUnix: thirtyDaysAgo,
sortDirection: "desc",
});
console.log(`Generated ${recentHistory.history.length} items in last 30 days`);// Search history by text content
const searchResults = await client.history.list({
search: "customer support",
pageSize: 50,
});
console.log(`Found ${searchResults.history.length} matching items`);// Get detailed information about a specific item
const item = await client.history.get("history-item-id");
console.log("Text:", item.text);
console.log("Voice:", item.voice_name);
console.log("Created:", new Date(item.date_unix * 1000).toLocaleString());
if (item.settings) {
console.log("Settings:", item.settings);
}
if (item.feedback) {
console.log("Feedback:", item.feedback);
}import { writeFile } from "fs/promises";
// Download audio for a history item
const audio = await client.history.getAudio("history-item-id");
const chunks: Uint8Array[] = [];
for await (const chunk of audio) {
chunks.push(chunk);
}
await writeFile("history_audio.mp3", Buffer.concat(chunks));// Download multiple history items as zip
const itemIds = ["item-id-1", "item-id-2", "item-id-3"];
const zipArchive = await client.history.download({
historyItemIds: itemIds,
});
const chunks: Uint8Array[] = [];
for await (const chunk of zipArchive) {
chunks.push(chunk);
}
await writeFile("history_download.zip", Buffer.concat(chunks));// Delete history items older than 90 days
const ninetyDaysAgo = Math.floor(Date.now() / 1000) - (90 * 24 * 60 * 60);
const oldHistory = await client.history.list({
dateBeforeUnix: ninetyDaysAgo,
pageSize: 100,
});
for (const item of oldHistory.history) {
await client.history.delete(item.history_item_id);
console.log(`Deleted: ${item.history_item_id}`);
}// Export history to JSON file
async function exportHistory(outputPath: string): Promise<void> {
const allHistory = await getAllHistory();
const exportData = allHistory.map(item => ({
id: item.history_item_id,
text: item.text,
voice: item.voice_name,
model: item.model_id,
date: new Date(item.date_unix * 1000).toISOString(),
characters: item.character_count_change_to,
}));
await writeFile(outputPath, JSON.stringify(exportData, null, 2));
}
await exportHistory("history_export.json");// Backup all history audio to files
async function backupHistoryAudio(outputDir: string): Promise<void> {
const history = await getAllHistory();
for (const item of history) {
try {
const audio = await client.history.getAudio(item.history_item_id);
const chunks: Uint8Array[] = [];
for await (const chunk of audio) {
chunks.push(chunk);
}
const filename = `${item.history_item_id}_${item.voice_name}.mp3`;
await writeFile(`${outputDir}/${filename}`, Buffer.concat(chunks));
console.log(`Backed up: ${filename}`);
} catch (error) {
console.error(`Failed to backup ${item.history_item_id}:`, error);
}
}
}
await backupHistoryAudio("./audio_backup");// Analyze history usage patterns
async function analyzeUsage(): Promise<void> {
const history = await getAllHistory();
// Count by voice
const voiceUsage = new Map<string, number>();
// Count by model
const modelUsage = new Map<string, number>();
// Total characters
let totalCharacters = 0;
for (const item of history) {
voiceUsage.set(
item.voice_name,
(voiceUsage.get(item.voice_name) || 0) + 1
);
modelUsage.set(
item.model_id,
(modelUsage.get(item.model_id) || 0) + 1
);
totalCharacters += item.character_count_change_to;
}
console.log("Usage Analytics:");
console.log(`Total items: ${history.length}`);
console.log(`Total characters: ${totalCharacters}`);
console.log("\nVoice usage:");
voiceUsage.forEach((count, voice) => {
console.log(` ${voice}: ${count}`);
});
console.log("\nModel usage:");
modelUsage.forEach((count, model) => {
console.log(` ${model}: ${count}`);
});
}
await analyzeUsage();// Find duplicate text entries in history
async function findDuplicates(): Promise<void> {
const history = await getAllHistory();
const textMap = new Map<string, SpeechHistoryItem[]>();
for (const item of history) {
const normalized = item.text.toLowerCase().trim();
if (!textMap.has(normalized)) {
textMap.set(normalized, []);
}
textMap.get(normalized)!.push(item);
}
console.log("Duplicate texts:");
textMap.forEach((items, text) => {
if (items.length > 1) {
console.log(`\nText: ${text.substring(0, 50)}...`);
console.log(`Generated ${items.length} times:`);
items.forEach(item => {
console.log(` - ${new Date(item.date_unix * 1000).toLocaleString()}`);
});
}
});
}
await findDuplicates();// Delete history items in failed state
async function cleanFailedItems(): Promise<void> {
const history = await getAllHistory();
const failedItems = history.filter(item => item.state === "deleted");
for (const item of failedItems) {
await client.history.delete(item.history_item_id);
console.log(`Deleted failed item: ${item.history_item_id}`);
}
console.log(`Cleaned up ${failedItems.length} failed items`);
}