Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | /**
* Tavus API Client Service
* Handles all Tavus API interactions for backup operations
*/
export interface TavusAccount {
id: string;
name: string;
apiKey: string;
environment: 'production' | 'staging' | 'testing';
}
export interface TavusPersona {
persona_id: string;
persona_name: string;
persona_type?: 'draft' | 'personal' | 'stock';
system_prompt?: string;
context?: string;
greeting?: string;
voice_engine?: string;
voice_id?: string;
language?: string;
default_replica_id?: string;
created_at?: string;
updated_at?: string;
}
export interface TavusConversation {
conversation_id: string;
title?: string;
created_at?: string;
updated_at?: string;
}
export interface TavusReplica {
replica_id: string;
replica_name?: string;
status?: string;
created_at?: string;
}
export interface TavusBackupData {
account_info: TavusAccount;
backup_timestamp: string;
personas: TavusPersona[];
conversations: TavusConversation[];
replicas: TavusReplica[];
objectives: any[];
guardrails: any[];
api_status: 'active' | 'limited' | 'error';
error_message?: string;
}
export class TavusClient {
private readonly baseUrl: string = 'https://tavusapi.com';
// Stock personas to exclude from backups
private readonly EXCLUDED_STOCK_PERSONAS = [
'sara - friendly tutor',
'nathan roleplay coach',
'gigi - banter buddy',
'chatty cathy',
'mentor',
'personal assistant hudson',
'lucy',
'sales coach',
'history teacher',
'sales agent at tavus',
'corporate trainer',
'tavus\' personal ai',
'ai interviewer',
'healthcare intake assistant',
'tavus researcher',
'charlie',
'santa',
'demo persona',
'technical co pilot',
'college tutor'
];
constructor(private account: TavusAccount, baseUrl?: string) {
// For testing environments, allow override to use fake Tavus server
if (baseUrl) {
this.baseUrl = baseUrl;
} else if (account.environment === 'testing' && process.env.FAKE_TAVUS_URL) {
this.baseUrl = process.env.FAKE_TAVUS_URL;
} else {
this.baseUrl = 'https://tavusapi.com';
}
}
private async makeAPIRequest(endpoint: string): Promise<any> {
const url = `${this.baseUrl}${endpoint}`;
const response = await fetch(url, {
method: 'GET',
headers: {
'x-api-key': this.account.apiKey,
'Content-Type': 'application/json'
}
});
Iif (!response.ok) {
throw new Error(`API request failed: ${response.status} ${response.statusText}`);
}
return response.json();
}
private filterPersonas(personas: TavusPersona[]): TavusPersona[] {
console.log(`š Filtering ${personas.length} personas to exclude stock personas...`);
// Filter out stock personas by name (case-insensitive)
const filteredPersonas = personas.filter(persona => {
const name = (persona.persona_name || '').toLowerCase().trim();
// Check against specific stock persona names
const isStock = this.EXCLUDED_STOCK_PERSONAS.some(stockName =>
name === stockName.toLowerCase()
);
// Also check persona_type if available
const isStockByType = persona.persona_type === 'stock';
Iif (isStock || isStockByType) {
console.log(`š« Filtering out stock persona: ${persona.persona_name}`);
return false;
}
// Include custom/user-created personas
console.log(`ā
Including custom persona: ${persona.persona_name} (Type: ${persona.persona_type || 'undefined'})`);
return true;
});
console.log(`ā
Found ${personas.length} total personas, ${filteredPersonas.length} after filtering out stock personas`);
Iif (filteredPersonas.length !== personas.length) {
try {
const filteredOut = personas.filter((p: TavusPersona) => !filteredPersonas.some(fp => fp.persona_id === p.persona_id));
const filteredNames = filteredOut.map((p: TavusPersona) => p.persona_name || 'Unknown').filter(Boolean);
console.log(`š« Filtered out stock personas: ${filteredNames.join(', ')}`);
} catch (error) {
console.log(`š« Filtered out ${personas.length - filteredPersonas.length} stock personas (debug error)`);
}
}
return filteredPersonas;
}
async fetchPersonas(): Promise<TavusPersona[]> {
try {
console.log(`š Fetching personas from ${this.account.name}...`);
// Fetch with pagination to get ALL personas (not just first 10)
const response = await this.makeAPIRequest('/v2/personas?page=1&limit=50');
const allPersonas = response.data || response.personas || response || [];
console.log(`š Got ${allPersonas.length} personas from API (with pagination)`);
allPersonas.forEach((persona: TavusPersona, index: number) => {
console.log(`š ${index + 1}. ${persona.persona_name} (ID: ${persona.persona_id}, Type: ${persona.persona_type || 'null'})`);
});
return this.filterPersonas(allPersonas);
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
console.error(`ā Failed to fetch personas: ${message}`);
throw error;
}
}
async fetchConversations(): Promise<TavusConversation[]> {
try {
console.log(`š Fetching conversations from ${this.account.name}...`);
const response = await this.makeAPIRequest('/v2/conversations');
const conversations = response.data || response.conversations || response || [];
console.log(`ā
Found ${conversations.length} conversations`);
return conversations;
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
console.log(`ā ļø Could not fetch conversations: ${message}`);
return []; // Non-critical, return empty array
}
}
async fetchReplicas(filteredPersonas?: TavusPersona[]): Promise<TavusReplica[]> {
try {
console.log(`š Fetching replicas from ${this.account.name}...`);
const response = await this.makeAPIRequest('/v2/replicas');
const allReplicas = response.data || response.replicas || response || [];
// If we have filtered personas, only return replicas that belong to those personas
Iif (filteredPersonas && filteredPersonas.length > 0) {
const allowedReplicaIds = new Set(
filteredPersonas
.map(p => p.default_replica_id)
.filter(id => id) // Remove null/undefined values
);
const filteredReplicas = allReplicas.filter((replica: TavusReplica) =>
allowedReplicaIds.has(replica.replica_id)
);
console.log(`ā
Found ${allReplicas.length} total replicas, ${filteredReplicas.length} after filtering out stock replicas`);
return filteredReplicas;
}
console.log(`ā
Found ${allReplicas.length} replicas (no filtering applied)`);
return allReplicas;
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
console.log(`ā ļø Could not fetch replicas: ${message}`);
return []; // Non-critical, return empty array
}
}
async testConnectivity(): Promise<{ status: 'active' | 'limited' | 'error'; error?: string }> {
try {
console.log(`š Testing API connectivity for ${this.account.name}...`);
// Try personas endpoint first (usually the most reliable)
await this.makeAPIRequest('/v2/personas');
return { status: 'active' };
} catch (personasError) {
const personasMessage = personasError instanceof Error ? personasError.message : 'Unknown error';
console.log(`ā ļø Personas API error: ${personasMessage}`);
// Try conversations as fallback
try {
await this.makeAPIRequest('/v2/conversations');
return { status: 'limited' };
} catch (convError) {
const convMessage = convError instanceof Error ? convError.message : 'Unknown error';
console.log(`ā ļø Conversations API error: ${convMessage}`);
return {
status: 'error',
error: personasMessage
};
}
}
}
async createFullBackup(): Promise<TavusBackupData> {
console.log(`\nš Creating full backup for: ${this.account.name} (${this.account.id})`);
Iif (!this.account.apiKey) {
throw new Error(`No API key found for ${this.account.id}`);
}
const backupData: TavusBackupData = {
account_info: this.account,
backup_timestamp: new Date().toISOString(),
personas: [],
conversations: [],
replicas: [],
objectives: [], // TODO: Implement if needed
guardrails: [], // TODO: Implement if needed
api_status: 'error'
};
// Test connectivity first
const connectivity = await this.testConnectivity();
backupData.api_status = connectivity.status;
Iif (connectivity.error) {
backupData.error_message = connectivity.error;
}
// If API is working, fetch all data
if (backupData.api_status === 'active') {
try {
// Fetch personas (most important)
backupData.personas = await this.fetchPersonas();
// Fetch additional data
backupData.conversations = await this.fetchConversations();
// Pass filtered personas to fetchReplicas to filter out stock replicas
backupData.replicas = await this.fetchReplicas(backupData.personas);
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
console.error(`ā Failed to fetch all data: ${message}`);
backupData.api_status = 'error';
backupData.error_message = message;
}
} else Iif (backupData.api_status === 'limited') {
// Try to get at least conversations if personas failed
try {
backupData.conversations = await this.fetchConversations();
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
console.log(`ā ļø Limited backup failed: ${message}`);
}
}
console.log(`š Backup summary for ${this.account.name}:`);
console.log(` Status: ${backupData.api_status}`);
console.log(` Personas: ${backupData.personas.length}`);
console.log(` Conversations: ${backupData.conversations.length}`);
console.log(` Replicas: ${backupData.replicas.length}`);
return backupData;
}
// Static method to create client from environment and API key
static createFromEnvironment(environment: 'production' | 'staging' | 'testing', apiKey: string): TavusClient {
const account: TavusAccount = {
id: `customer-${environment}`,
name: `${environment.charAt(0).toUpperCase() + environment.slice(1)} Account`,
apiKey,
environment
};
return new TavusClient(account);
}
// Static method to get default accounts from environment variables
static getDefaultAccounts(): TavusAccount[] {
const accounts: TavusAccount[] = [];
// Check for environment variables following the pattern from the working script
Iif (process.env.prod1_TAVUS_API_KEY) {
accounts.push({
id: 'customer-prod1',
name: 'Production Account 1',
apiKey: process.env.prod1_TAVUS_API_KEY,
environment: 'production'
});
}
Iif (process.env.testing_larsbell_TAVUS_API_KEY) {
accounts.push({
id: 'customer-testing-larsbell',
name: 'Testing Account - LarsBell',
apiKey: process.env.testing_larsbell_TAVUS_API_KEY,
environment: 'testing'
});
}
Iif (process.env.staging_lars_at_TAVUS_API_KEY) {
accounts.push({
id: 'customer-staging-lars',
name: 'Staging Account - Lars',
apiKey: process.env.staging_lars_at_TAVUS_API_KEY,
environment: 'staging'
});
}
return accounts;
}
} |