Skip to main content

Getting Started

Ready to build with RunAnythingAI? This guide will have you making API calls and creating AI-powered characters in under 10 minutes. We'll walk through everything from authentication to your first character interaction, with working code you can copy and run immediately.

What You'll Build

By the end of this guide, you'll have:

  • Made your first text generation API call
  • Created a character with personality
  • Added voice to your character
  • Learned best practices for error handling

What You'll Need

Before we start building, gather these essentials:

  • RunAnythingAI Account - Sign up here if you haven't already
  • API Key - Find yours in your account dashboard after signing in
  • HTTP Client - We'll use JavaScript/fetch, but any language works
  • 5 minutes - That's all it takes to get your first AI response
Keep Your API Key Secure

Your API key is like a password—never expose it in client-side code or public repositories. Always use environment variables in production.

Step 1: Authentication Setup

Every API request needs your API key in the Authorization header. Here's the format:

Authorization: Bearer YOUR_API_KEY

Replace YOUR_API_KEY with your actual key from the RunAnythingAI dashboard.

Environment Variables

Set up your API key as an environment variable:

export RUNANYTHING_API_KEY="your-api-key-here"

Then use process.env.RUNANYTHING_API_KEY in your code.

Step 2: Your First API Call

Let's generate some text! This basic example shows the core pattern you'll use for all RunAnythingAI requests:

async function generateText() {
try {
// Step 1: Send generation request
const response = await fetch('https://api.runanythingai.com/api/text/default', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
"messages": [
{
"role": "You",
"content": "Write a creative short story about a robot learning to paint.",
"index": 0
}
],
"botName": "Assistant",
"samplingParams": {
"max_tokens": 150
}
})
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const data = await response.json();
console.log('✅ Request submitted! ID:', data.id);

// Step 2: Check status until complete
const result = await pollForResult(data.id);
console.log('🎉 Generated story:', result);

} catch (error) {
console.error('❌ Error:', error.message);
}
}

async function pollForResult(requestId) {
while (true) {
const statusResponse = await fetch(`https://api.runanythingai.com/api/v2/status/${requestId}`, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});

const data = await statusResponse.json();

if (data.status === 'completed') {
return data.reply;
} else if (data.status === 'error') {
throw new Error(`Generation failed: ${data.error}`);
}

// Wait 1 second before checking again
await new Promise(resolve => setTimeout(resolve, 1000));
}
}

// Run it!
generateText();
How It Works
  1. Send Request - POST your prompt to the generation endpoint
  2. Get Task ID - RunAnythingAI returns an ID to track your request
  3. Poll Status - Check the status endpoint until processing completes
  4. Get Result - Retrieve your generated content

Step 3: Creating Your First Character

Now let's create something more interesting—an AI character with personality! RunAnythingAI offers four specialized character endpoints, each with unique strengths:

CharacterBest ForPersonality
WitchFantasy, magic, mystical interactionsWise, mysterious, magical
MageKnowledge, strategy, analysisScholarly, intelligent, methodical
SuccubusPersuasion, charm, social interactionsCharismatic, alluring, confident
LightningEnergy, action, dynamic responsesFast-paced, energetic, spontaneous

Here's how to create a character interaction:

async function createCharacterInteraction() {
// Define your character's personality
const librarian = `Emma's Persona: Emma is a 28-year-old head librarian at a prestigious university.
She has a PhD in Literature and speaks with gentle authority. Emma loves recommending books
that perfectly match someone's mood and personality. She has an uncanny ability to sense what
people need to read, whether it's for escapism, learning, or personal growth. Emma often
includes little-known facts about authors and books in her recommendations.`;

try {
// Use the Mage endpoint for this scholarly character
const response = await fetch('https://api.runanythingai.com/api/text/Mage', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
"messages": [
{
"id": "msg_001",
"messageIndex": 0,
"chatId": "library_chat",
"userId": "visitor_001",
"content": "Hi Emma! I've been working long hours lately and feeling burned out. I love sci-fi but want something uplifting that won't require too much mental energy. Any suggestions?",
"createdAt": new Date().toISOString(),
"upvote": 0,
"role": "You",
"image": null,
"index": 0
}
],
"persona": librarian,
"botName": "Emma",
"samplingParams": {
"max_tokens": 200
}
})
});

const { id } = await response.json();
console.log('🎭 Character request submitted:', id);

const result = await pollForResult(id);
console.log('📚 Emma says:', result);

} catch (error) {
console.error('❌ Character interaction failed:', error.message);
}
}

createCharacterInteraction();
Character Selection Guide
  • Witch: Fantasy settings, mystical advice, magical worldbuilding
  • Mage: Educational content, analysis, strategic thinking
  • Succubus: Social dynamics, persuasive content, relationship advice
  • Lightning: Action scenes, energetic interactions, quick responses

Step 4: Adding Voice to Your Character

Let's bring Emma to life with text-to-speech! This complete example shows how to chain character generation with voice synthesis:

async function characterWithVoice() {
try {
// 1. Generate character response
console.log('🎭 Generating character response...');

const genResponse = await fetch('https://api.runanythingai.com/api/text/Mage', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
"messages": [
{
"id": "msg_002",
"messageIndex": 0,
"chatId": "library_chat",
"userId": "visitor_001",
"content": "That sounds perfect! Could you tell me a bit more about why you chose that particular book?",
"createdAt": new Date().toISOString(),
"upvote": 0,
"role": "You",
"image": null,
"index": 0
}
],
"persona": `Emma's Persona: Emma is a 28-year-old head librarian with a PhD in Literature.
She speaks with gentle authority and has an uncanny ability to recommend the perfect book.`,
"botName": "Emma",
"samplingParams": {
"max_tokens": 200
}
})
});

const { id } = await genResponse.json();

// 2. Wait for generation to complete
const characterResponse = await pollForResult(id);
console.log('✅ Emma responds:', characterResponse);

// 3. Convert to speech
console.log('🎙️ Converting to speech...');

const ttsResponse = await fetch('https://api.runanythingai.com/api/audio/full', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
"text": characterResponse,
"voice": "af_nicole", // Warm, professional voice for a librarian
"speed": 0.95 // Slightly slower for clarity
})
});

if (ttsResponse.ok) {
const audioBlob = await ttsResponse.blob();
const audioUrl = URL.createObjectURL(audioBlob);

// Play the audio (browser environment)
const audio = new Audio(audioUrl);
audio.play();

console.log('🔊 Playing Emma\'s voice response!');

return {
text: characterResponse,
audio: audioUrl
};
} else {
throw new Error(`TTS failed: ${ttsResponse.status}`);
}

} catch (error) {
console.error('❌ Character with voice failed:', error.message);
}
}

characterWithVoice();
Voice Selection

Choose voices that match your character's personality:

  • af_nicole: Professional, warm (great for educators, assistants)
  • af_james: Authoritative, storyteller (perfect for narrators, guides)
  • af_sarah: Friendly, approachable (ideal for customer service, companions)

Step 5: Standalone Text-to-Speech

Want to add voice to any text? Here's a simple TTS example:

async function textToSpeech(text, voice = "af_nicole") {
try {
const response = await fetch('https://api.runanythingai.com/api/audio/full', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
"text": text,
"voice": voice,
"speed": 1.0
})
});

if (!response.ok) {
throw new Error(`TTS failed: ${response.status}`);
}

// Browser: Play immediately
const audioBlob = await response.blob();
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.play();

console.log('🔊 Playing:', text.substring(0, 50) + '...');

return audioUrl;

// Node.js: Save to file
// const fs = require('fs');
// const buffer = await response.buffer();
// fs.writeFileSync('output.mp3', buffer);
// console.log('💾 Saved audio to output.mp3');

} catch (error) {
console.error('❌ TTS failed:', error.message);
}
}

// Try it out!
textToSpeech("Welcome to RunAnythingAI! Let's build something amazing together.");

Essential Error Handling

Production apps need robust error handling. Here's a battle-tested pattern:

class RunAnythingAIClient {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://api.runanythingai.com';
}

async makeRequest(endpoint, method = 'GET', body = null) {
const url = `${this.baseUrl}${endpoint}`;
const options = {
method,
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json'
}
};

if (body) {
options.body = JSON.stringify(body);
}

try {
const response = await fetch(url, options);

if (!response.ok) {
// Handle different error types
switch (response.status) {
case 401:
throw new Error('Invalid API key. Check your authentication.');
case 429:
throw new Error('Rate limit exceeded. Please slow down your requests.');
case 500:
throw new Error('Server error. Please try again later.');
default:
const errorText = await response.text();
throw new Error(`API error (${response.status}): ${errorText}`);
}
}

return await response.json();

} catch (error) {
if (error.name === 'TypeError' && error.message.includes('fetch')) {
throw new Error('Network error. Check your internet connection.');
}
throw error; // Re-throw other errors
}
}

async generateText(messages, options = {}) {
const body = {
messages,
botName: options.botName || 'Assistant',
samplingParams: {
max_tokens: options.maxTokens || 150
}
};

if (options.persona) {
body.persona = options.persona;
}

const endpoint = options.character
? `/api/text/${options.character}`
: '/api/text/default';

return await this.makeRequest(endpoint, 'POST', body);
}

async pollForResult(requestId, maxAttempts = 30) {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const result = await this.makeRequest(`/api/v2/status/${requestId}`);

if (result.status === 'completed') {
return result.reply;
} else if (result.status === 'error') {
throw new Error(`Generation failed: ${result.error}`);
}

// Wait before retrying (exponential backoff)
const delay = Math.min(1000 * Math.pow(1.5, attempt), 5000);
await new Promise(resolve => setTimeout(resolve, delay));
}

throw new Error('Request timed out after maximum attempts');
}
}

// Usage example
const client = new RunAnythingAIClient(process.env.RUNANYTHING_API_KEY);

async function example() {
try {
const response = await client.generateText([
{ role: "You", content: "Hello!", index: 0 }
], {
character: "Mage",
persona: "Friendly assistant",
maxTokens: 100
});

const result = await client.pollForResult(response.id);
console.log('✅ Success:', result);

} catch (error) {
console.error('❌ Error:', error.message);
}
}
Production Tips
  • Use exponential backoff for retries
  • Set reasonable timeouts
  • Log errors for debugging
  • Handle rate limits gracefully
  • Validate inputs before sending requests

🎉 You're Ready to Build!

Congratulations! You now know how to:

  • ✅ Authenticate with the RunAnythingAI API
  • ✅ Generate text with the default endpoint
  • ✅ Create characters with personality using specialized endpoints
  • ✅ Add voice to your characters with text-to-speech
  • ✅ Handle errors like a pro

What's Next?

Your journey is just beginning! Here's where to go from here:

🎯 Ready for More Advanced Stuff?

Advanced Features Guide - Learn about persona crafting, conversation memory, and advanced techniques

🎭 Want to Master Character Creation?

Character Development Guide - Deep dive into creating compelling, consistent AI personalities

📚 Need More Code Examples?

Code Examples - Real-world examples in JavaScript, Python, and more

🔗 Building an App?

Integration Guide - Framework-specific guides for React, Vue, Express, and others

📖 Want All the Technical Details?

API Reference - Complete documentation for every endpoint and parameter

Community & Support

Join thousands of developers building with RunAnythingAI:

  • 💬 Discord Community - Get help, share projects, connect with other builders
  • 📧 Support Email - Direct help for technical issues
  • 🐙 GitHub Examples - Open-source examples and community contributions
  • 📝 Blog - Tutorials, case studies, and product updates
Pro Tip

Start small and iterate! Begin with a simple character interaction, then gradually add features like voice, memory, and advanced personalities. The best AI applications are built one conversation at a time.

Happy building! 🚀