Advanced Features & Techniques
Take your AI applications to the next level with RunAnythingAI's advanced capabilities. This guide covers sophisticated techniques for creating immersive character experiences, optimizing performance, and building complex interactions that engage users on a deeper level.
This section is for developers ready to move beyond basic API calls. If you're just getting started, check out the Getting Started Guide first.
Character Creation with Character Endpoints
RunAnythingAI offers four specialized character endpoints (Witch, Mage, Succubus, and Lightning) for creating immersive character-driven interactions. Unlike general text generation, these character models excel at maintaining consistent character personas, speech patterns, and behavioral traits throughout conversations, each with their own unique characteristics.
Deep Persona Configuration
Create rich, multidimensional characters by defining detailed personas with physical characteristics, personality traits, speech patterns, and behavioral tendencies. Each character type (Witch, Mage, Succubus, and Lightning) offers unique capabilities that you can leverage for different scenarios.
// You can use any character model: Witch, Mage, Succubus, or Lightning
// This example uses the Mage model, which is ideal for scholarly characters
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": [
{
"role": "You",
"content": "Tell me about quantum computing",
"index": 0
}
],
"persona": "Dr. Eliza Chen's Persona: Dr. Chen is a 43-year-old quantum physicist with 15 years of experience in the field. She has a warm, patient demeanor and enjoys making complex concepts accessible through creative analogies. Dr. Chen speaks in a methodical way, often using hand gestures (which she references in conversation) to illustrate points. She has a slight Singaporean accent and occasionally uses Singlish phrases. Dr. Chen believes in the practical applications of quantum computing and gets excited when discussing potential breakthroughs in the field. She has a habit of asking questions to ensure her explanations are being understood.",
"botName": "Dr. Chen",
"samplingParams": {
"max_tokens": 200
}
})
});
Message Context Management
For chatbot applications, maintaining context is crucial. The message array allows you to include the full conversation history:
{
"messages": [
{
"role": "You",
"content": "What's the capital of France?",
"index": 0
},
{
"role": "Bot",
"content": "The capital of France is Paris.",
"index": 1
},
{
"role": "You",
"content": "What about Germany?",
"index": 2
}
]
}
By providing the full conversation history, the AI understands that "What about Germany?" is asking about Germany's capital.
Voice Customization in TTS
The Text-to-Speech API allows for detailed voice customization:
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": "Welcome to our platform!",
"voice": "af_nicole",
"speed": 0.9, // Slightly slower than normal
})
});
Handling Long-Running Requests
For complex generations that might take longer to process, implement a robust polling strategy:
async function pollUntilComplete(requestId, maxAttempts = 30, interval = 1000) {
let attempts = 0;
return new Promise((resolve, reject) => {
const check = async () => {
if (attempts >= maxAttempts) {
reject(new Error('Maximum polling attempts reached'));
return;
}
attempts++;
try {
const response = await fetch(`https://api.runanythingai.com/api/v2/status/${requestId}`, {
headers: {
'Authorization': 'Bearer YOUR_API_KEY'
}
});
const data = await response.json();
if (data.status === 'completed') {
resolve(data.reply);
} else if (data.status === 'error') {
reject(new Error(data.error || 'Unknown error occurred'));
} else {
// Still processing, check again after interval
setTimeout(check, interval);
}
} catch (error) {
reject(error);
}
};
// Start polling
check();
});
}
// Usage
try {
const text = await pollUntilComplete('08ab17b0-e0d0-4b4d-a0cd-ea0bbdef455a');
console.log('Generated text:', text);
} catch (error) {
console.error('Polling failed:', error);
}
Best Practices
Effective Text Generation
-
Provide Clear Instructions: The more specific your prompt, the better the results.
-
Use System Messages: System messages can set the context for the entire conversation.
-
Progressive Refinement: For complex tasks, break them down into steps with separate API calls.
Efficient TTS Usage
-
Chunk Long Text: For very long text, split it into logical segments and send separate requests.
-
Cache Common Audio: If your application frequently uses the same phrases, consider caching the audio files.
-
Optimize Text: Remove unnecessary characters, normalize formatting, and ensure proper punctuation for the best speech output.
Rate Limit Management
Implement a queue system for high-volume applications to avoid hitting rate limits:
class ApiQueue {
constructor(maxConcurrent = 5, interval = 1000) {
this.queue = [];
this.runningCount = 0;
this.maxConcurrent = maxConcurrent;
this.interval = interval;
}
async add(apiCallFn) {
return new Promise((resolve, reject) => {
this.queue.push({ apiCallFn, resolve, reject });
this.processQueue();
});
}
async processQueue() {
if (this.runningCount >= this.maxConcurrent || this.queue.length === 0) {
return;
}
const { apiCallFn, resolve, reject } = this.queue.shift();
this.runningCount++;
try {
const result = await apiCallFn();
resolve(result);
} catch (error) {
reject(error);
} finally {
this.runningCount--;
// Add a small delay before processing the next item
setTimeout(() => this.processQueue(), this.interval);
}
}
}
// Usage example
const apiQueue = new ApiQueue(3, 1000); // 3 concurrent requests, 1s interval
// Add API calls to the queue
apiQueue.add(() => textGenerationApiCall("Prompt 1"))
.then(result => console.log(result))
.catch(error => console.error(error));
This ensures that your API requests are spaced out appropriately to avoid rate limit errors.
Multicharacter Scenes and Interactions
The character endpoints excel at handling scenes with multiple characters interacting with each other, perfect for developing immersive storytelling experiences.
Character Relationships and Group Dynamics
You can define relationships between characters in your persona descriptions to create realistic interactions:
const response = await fetch('https://api.runanythingai.com/api/text/Witch', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
"messages": [
{
"role": "You",
"content": "How's the café doing today?",
"index": 0
}
],
"persona": "Café Scene Persona: Maria is the 35-year-old owner of Sunrise Café. She's energetic, business-minded, and speaks quickly when excited. Jake is Maria's 28-year-old barista who has a relaxed demeanor and dry sense of humor. Jake and Maria have a friendly relationship with occasional good-natured banter. Elena is a regular customer in her 40s who writes novels at the café and has philosophical conversations with the staff.",
"botName": "Café Scene",
"samplingParams": {
"max_tokens": 250
}
})
});
Scene Setting and Environmental Details
Include environmental details in your messages to create rich, immersive scenes:
{
"messages": [
{
"role": "You",
"content": "*The café is bustling with morning customers. The espresso machine hisses loudly as rain taps against the windows.* Good morning everyone, busy day today?",
"index": 0
}
]
}
Advanced Storytelling Techniques
The character endpoints include specialized capabilities for creating compelling narratives and storytelling experiences.
Narrative Progression
Create evolving storylines by updating the persona description as the story progresses:
// Initial setup
let storyPersona = `Adventure Story: The protagonist Alex is an optimistic
explorer setting out on their first major expedition. They are excited but
nervous about the journey ahead.`;
// After a significant event
storyPersona = `Adventure Story: After discovering ancient ruins, Alex has
become more confident but also more cautious. The weight of their discovery
has made them contemplative about history and their place in it.`;
Character Development Arcs
Track character growth and transformation by maintaining state between API calls:
class Character {
constructor(name, initialTraits) {
this.name = name;
this.traits = initialTraits;
this.experiences = [];
this.relationships = {};
}
addExperience(event) {
this.experiences.push(event);
}
updateTrait(trait, newValue) {
this.traits[trait] = newValue;
}
generateCurrentPersona() {
let persona = `${this.name}'s Persona: ${this.name} is `;
// Add traits
Object.entries(this.traits).forEach(([trait, value]) => {
persona += `${trait} (${value}), `;
});
// Add significant experiences
if (this.experiences.length > 0) {
persona += `They have experienced ${this.experiences.slice(-3).join(', ')}. `;
}
// Add relationships
Object.entries(this.relationships).forEach(([person, relationship]) => {
persona += `Their relationship with ${person} is ${relationship}. `;
});
return persona;
}
}
// Usage example
const protagonist = new Character('Alex', {
'courage': 'growing',
'wisdom': 'developing',
'optimism': 'high'
});
// After story events
protagonist.addExperience('surviving a dangerous storm');
protagonist.updateTrait('courage', 'strong');
protagonist.relationships['Maya'] = 'trusting but cautious';
// Use the updated persona in the next API call
const currentPersona = protagonist.generateCurrentPersona();
Emotional Intelligence in Characters
Create emotionally intelligent characters that respond appropriately to user emotions:
const response = await fetch('https://api.runanythingai.com/api/text/Witch', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOUR_API_KEY'
},
body: JSON.stringify({
"messages": [
{
"role": "You",
"content": "I'm feeling really overwhelmed with work lately and I don't know how to handle it all.",
"index": 0
}
],
"persona": "Therapist Persona: Dr. Sophia is an empathetic therapist with 15 years of experience. She prioritizes validating emotions before offering practical advice. She speaks in a calm, measured tone and uses reflective listening techniques. Dr. Sophia asks thoughtful questions to help people explore their feelings deeper.",
"botName": "Dr. Sophia",
"samplingParams": {
"max_tokens": 200
}
})
});