rynn-k / gists
character-ai.js javascript
class CharacterAI {
    constructor() {
        this.initPromise = null;
        this.cai = null;
    }
    
    async _ensureInit() {
        if (!this.initPromise) {
            this.initPromise = (async () => {
                const { CAINode } = await import('cainode');
                this.cai = new CAINode();
                await this.cai.login('55c00cd91b3521a73e4ca58087144891681063c6');
            })();
        }
        await this.initPromise;
    }
    
    async search(query) {
        await this._ensureInit();
        
        if (!query) throw new Error('Query is required.');
        
        const data = await this.cai.search.characters(query);
        return data.characters.map(char => ({
            id: char.external_id,
            name: char.participant__name,
            description: char.description,
            greeting: char.greeting,
            primary_language: char.primary_language,
            avatar: 'https://characterai.io/i/80/static/avatars/' + char.avatar_file_name,
            interactions: char.participant__num_interactions,
            created_at: char.created_at,
            updated_at: char.updated_at
        }));
    }
    
    async chat(text, { char_id, chat_id } = {}) {
        await this._ensureInit();
        
        if (!text) throw new Error('Text is required.');
        if (!char_id) throw new Error('Character ID is required.');
        
        const chatId = chat_id ? chat_id : (await this.cai.character.create_new_conversation(false, { char_id: char_id }))?.chat?.chat_id;
        if (!chatId) throw new Error('Chat ID not found.');
        
        const chat = await this.cai.character.send_message(text, false, '', {
            char_id: char_id,
            chat_id: chatId,
            timeout_ms: 60000
        });
        
        const result = chat?.turn;
        if (!result) throw new Error('No result found.');
        
        return {
            id: chatId,
            response: result?.candidates?.[0]?.raw_content || 'No response.',
            character: {
                name: result?.author?.name || 'Unknown',
                charId: char_id
            }
        };
    }
}

// Usage:
const cai = new CharacterAI();
cai.chat('Hi! How are you today?', { char_id: '4wBUfWUMSu_Yun3_jA0YVex4s1czVaRlg2kwwSTJQ3U' }).then(console.log);
2328 bytes ยท Updated Feb 27, 2026