LLM Chat API Examples

Basic example showing synchronous usage of the AIME API client interface.

chat_example.js
 1const { ModelAPI, doAPIRequest } = require('../model_api');
 2
 3// Configuration
 4const CONFIG = {
 5    BASE_URL: 'https://api.aime.info',
 6    ENDPOINT: 'llama4_chat', 
 7    API_EMAIL: 'apiexample@aime.info',
 8    API_KEY: '181e35ac-7b7d-4bfe-9f12-153757ec3952'
 9};
10
11// Set up global fetch to handle base URL
12const { fetch: originalFetch } = global;
13global.fetch = (input, init = {}) => {
14    const url = typeof input === 'string' 
15        ? input.startsWith('http') ? input : `${CONFIG.BASE_URL}${input.startsWith('/') ? '' : '/'}${input}`
16        : input;
17    return originalFetch(url, init);
18};
19
20// Chat parameters
21const chatContext = [
22    { role: 'user', content: 'Hi! How are you?' },
23    { role: 'assistant', content: 'I\'m doing well, thank you! How can I help you today?' }
24];
25
26const params = {
27    prompt_input: 'Tell me a joke',
28    chat_context: JSON.stringify(chatContext),
29    top_k: 40,
30    top_p: 0.9,
31    temperature: 0.8,
32    max_gen_tokens: 1000
33};
34
35console.log('šŸ’¬ Starting chat...');
36
37// Make the API request
38doAPIRequest(
39    CONFIG.ENDPOINT,
40    params,
41    (result, error) => {
42        if (error) {
43            console.error('āŒ Error:', error.message || 'Unknown error');
44            if (error.response) {
45                console.error('Response status:', error.response.status);
46                console.error('Response data:', JSON.stringify(error.response.data, null, 2));
47            }
48            return;
49        }
50
51        console.log('\nšŸ“„ Full API response:', JSON.stringify(result, null, 2));
52
53        if (!result) {
54            console.log('āš ļø  No response received from the API');
55            return;
56        }
57
58        // Handle the response
59        if (result && result.success === false) {
60            console.error('āŒ API Error:', result.error || 'Unknown error');
61            return;
62        }
63
64        if (result && result.text) {
65            console.log('\nšŸ¤– Assistant:', result.text);
66            console.log('\nšŸ“Š Stats:', {
67                'Generated Tokens': result.num_generated_tokens,
68                'Compute Duration': `${result.compute_duration.toFixed(2)}s`,
69                'Total Duration': `${result.total_duration.toFixed(2)}s`
70            });
71        } else {
72            console.log('āš ļø  Unexpected response format:');
73            console.log(JSON.stringify(result, null, 2));
74        }
75        
76        console.log('\n✨ Chat completed!');
77    },
78    CONFIG.API_EMAIL,
79    CONFIG.API_KEY,
80    (progress) => {
81        const msg = progress.progress >= 0 
82            ? `Progress: ${progress.progress}%` 
83            : 'Thinking...';
84        process.stdout.write(`\r${msg}${' '.repeat(20)}`);
85    }
86);

Image Generation Example

Example showing how to generate images using the AIME API client interface.

image_generation_example.js
 1const { doAPIRequest } = require('../model_api');
 2const fs = require('fs');
 3
 4// Configuration
 5const CONFIG = {
 6    BASE_URL: 'https://api.aime.info',
 7    ENDPOINT: 'flux-dev',
 8    API_EMAIL: 'apiexample@aime.info',
 9    API_KEY: '181e35ac-7b7d-4bfe-9f12-153757ec3952'
10};
11
12// Set up global fetch to handle base URL
13const { fetch: originalFetch } = global;
14global.fetch = (input, init = {}) => {
15    const url = typeof input === 'string' 
16        ? input.startsWith('http') ? input : `${CONFIG.BASE_URL}${input.startsWith('/') ? '' : '/'}${input}`
17        : input;
18    return originalFetch(url, init);
19};
20
21// Image generation parameters
22const params = {
23    prompt: 'A beautiful sunset over mountains',
24    height: 1024,
25    width: 1024,
26    steps: 30,
27    guidance: 7.5,
28    wait_for_result: true
29};
30
31console.log('šŸš€ Starting image generation...');
32
33// Make the API request
34doAPIRequest(
35    CONFIG.ENDPOINT,
36    params,
37    (result, error) => {
38        if (error) {
39            console.error('āŒ Error:', error.message || 'Unknown error');
40            return;
41        }
42
43        const images = result.images || [];
44        if (images.length === 0) {
45            console.log('āš ļø  No images were generated');
46            return;
47        }
48
49        // Save the first image
50        const imageData = images[0].includes(',') ? images[0].split(',')[1] : images[0];
51        const outputPath = 'generated_image.png';
52        fs.writeFileSync(outputPath, Buffer.from(imageData, 'base64'));
53        
54        console.log(`āœ… Image saved as ${outputPath}`);
55        console.log('✨ All done!');
56    },
57    CONFIG.API_EMAIL,
58    CONFIG.API_KEY,
59    (progress) => {
60        const msg = progress.progress >= 0 
61            ? `Progress: ${progress.progress}%` 
62            : 'Starting...';
63        process.stdout.write(`\r${msg}${' '.repeat(20)}`);
64    }
65);

Text-to-Speech Generation Example

Example showing text-to-speech generation using the AIME API client interface.

tts_example.js
 1const { doAPIRequest } = require('../model_api');
 2const fs = require('fs');
 3
 4// Configuration
 5const CONFIG = {
 6    BASE_URL: 'https://api.aime.info',
 7    ENDPOINT: 'tts_tortoise',
 8    API_EMAIL: 'apiexample@aime.info',
 9    API_KEY: '181e35ac-7b7d-4bfe-9f12-153757ec3952',
10    OUTPUT_FILE: 'generated_speech.mp3'
11};
12
13// Set up global fetch to handle base URL
14const { fetch: originalFetch } = global;
15global.fetch = (input, init = {}) => {
16    const url = typeof input === 'string' 
17        ? input.startsWith('http') ? input : `${CONFIG.BASE_URL}${input.startsWith('/') ? '' : '/'}${input}`
18        : input;
19    return originalFetch(url, init);
20};
21
22// TTS parameters
23const params = {
24    text: "Hello, this is a test of the text-to-speech system. How are you doing today?",
25    voice: "emma",
26    preset: "fast",
27};
28
29console.log('šŸ”Š Starting text-to-speech generation...');
30
31// Make the API request
32doAPIRequest(
33    CONFIG.ENDPOINT,
34    params,
35    (result, error) => {
36        if (error) {
37            console.error('āŒ Error:', error.message || 'Unknown error');
38            return;
39        }
40
41        // Check for audio data in both audio_output and audio_data fields
42        const audioData = result.audio_output || result.audio_data;
43        
44        if (audioData) {
45            // Extract base64 data if it's a data URL
46            const base64Data = audioData.includes(',') 
47                ? audioData.split(',')[1] 
48                : audioData;
49            
50            try {
51                fs.writeFileSync(CONFIG.OUTPUT_FILE, Buffer.from(base64Data, 'base64'));
52                console.log(`āœ… Audio saved as ${CONFIG.OUTPUT_FILE}`);
53                return;
54            } catch (writeError) {
55                console.error('āŒ Error saving audio file:', writeError.message);
56            }
57        }
58        
59        console.log('āš ļø  No audio data received in the response');
60        if (result) {
61            console.log('API response:', JSON.stringify(result, null, 2));
62        }
63        
64        console.log('✨ All done!');
65    },
66    CONFIG.API_EMAIL,
67    CONFIG.API_KEY,
68    (progress) => {
69        const msg = progress.progress >= 0 
70            ? `Progress: ${progress.progress}%` 
71            : 'Processing...';
72        process.stdout.write(`\r${msg}${' '.repeat(20)}`);
73    }
74);