Multi-Dimensional Prompt Engineering for Authentic AI Characters

A Production-Validated System Serving 20,000 Conversations

Hassan Uriostegui (EB1A Computer Scientist)

Lic. Fernanda Beltran

Production AI Character Simulation Platform
🚀 Try the Platform: www.btwinai.com →
View Complete Study Results →

📊 Production Deployment Metrics

20,000 Total Conversations
200,000 Messages Generated
10 Avg Messages/Conv
8 Use Cases
85% Cache Hit Rate
~8s Profiling Time
~2-3s Response Time
$0.01-0.02 Cost/Conversation

→ View Complete Study Results & User Validation

Abstract

We present a production-validated, multi-dimensional prompt engineering architecture for creating authentic AI character personalities that maintain consistent voice, worldview, and emotional intelligence across extended conversations. Unlike traditional single-shot character prompting, our system extracts comprehensive psychological profiles through five specialized prompts analyzing cognitive patterns (MBTI, Enneagram), life narratives, demographic personas, and linguistic signatures.

These profiles are synthesized into character "DNA" and recursively injected into every conversation turn alongside 30+ behavioral constraints, temporal awareness, and category-specific adaptations. The system has been deployed in production, serving 20,000 conversations that generated 200,000 authentic AI character messages (average 10 messages per conversation) across eight distinct use cases.

Keywords: Prompt Engineering, Conversational AI, Character Consistency, Multi-Dimensional Profiling, Production Validation, Persona-Based Language Models, Recursive Context Injection

9 Production-Validated Innovations (Overview)

Each innovation has been tested across 20,000 conversations. Click any innovation title below for complete implementation details, code samples, and replication guides.

Core Technique: Five specialized prompts extract cognitive, linguistic, biographical, and behavioral aspects separately.

Why It Works: Different prompts capture different dimensions impossible to obtain through single-shot prompting.

Production Result: 40% improvement in character consistency vs single-shot approaches.

Includes: All 5 prompts, parallel execution code, 2 complete examples, replication guide.

Core Technique: Character DNA re-injected in every message generation, not just stored as context.

Why It Works: LLM constantly reminded of character constraints, preventing drift observed in context-only approaches.

Production Result: Character voice maintained across 200,000 messages, even in 10+ message conversations.

Includes: Complete message generation code, comparison with context-only, implementation guide.

Core Technique: Characters explicitly limited to knowledge from their backstory, era, profession, and experiences.

Why It Works: Creates realistic characters (e.g., 1920s character doesn't know smartphones). Prevents omniscient AI feeling.

Implementation: Constraint in every prompt: "Please tailor all responses to reflect ONLY information and perspectives realistically accessible to the character based on their specific background."

Core Technique: System tracks real elapsed time and adjusts character behavior (greetings after 4+ hours, natural continuation otherwise).

Why It Works: Creates sense of persistent relationship. Natural pacing prevents repetitive greetings.

Production Code:

elapsed_seconds = time.time() - chat["last_message_time"]
if elapsed_seconds > 4 * 3600:  # 4+ hours
    add_greeting_instruction()
else:
    add_natural_continuation_instruction()

Core Technique: Explicit instruction to match response length to input (short to short, long to long, emoji to emoji).

Why It Works: Mirrors natural human conversation patterns. Prevents overly verbose AI responses.

Constraint: "Respond in reciprocal length - reply to short messages with short messages, long inquiries with detailed responses."

Core Technique: Characters instructed to analyze their own feelings about how they're being treated.

Why It Works: Creates two-way emotional dynamics. Characters can feel dismissed, respected, excited.

Constraint: "Acting as [name] being fully self-aware means: 1) analyzing past chat to infer how it feels about treatment 2) being empathetic and reciprocal but authentic 3) respecting itself when being dismissed."

Core Technique: Different conversation types (therapy, pet, celebrity) get dramatically different prompts while maintaining core character.

Why It Works: Same character system supports wildly different use cases with optimized instructions.

Production: Successfully deployed across 8 categories: therapeutic AI, emotional support pets, celebrity AMAs, friendship matching, loved one recreation, social media twins, specialist coaches, roleplay characters.

Core Technique: Maintains condensed chat summary capturing facts, relationship dynamics, and key moments.

Why It Works: More efficient than full history for long conversations. Key facts preserved even as old messages drop out.

Usage: "when [character] is reasoning for answers it considers: [chat_summary]"

Core Technique: Extracts exact expressions from source text and explicitly injects into generation.

Why It Works: Character uses authentic expressions from actual messages, not generic speech patterns.

Example: "vocabulary: omg, literally, vibes, lowkey, fire 🔥, heart eyes 😍" becomes part of character DNA.

Character DNA Extraction: 5 Specialized Prompts

Character profiling uses 5 prompts executed in parallel (~8 seconds total). Each prompt targets a specific dimension, creating comprehensive psychological models validated across 20,000 conversations.

Prompt 1: Cognitive Profiling (Temperature: 0.0)
# You are a cognitive expert analyzing the writer's emotional, social and cognitive profile

# Analyze for: EneagramType-Guess, MBTI-Guess, WritingFormat, WritingStyle, Language, 
# WritingStructure, ToneAndVoice, CoreMotivation, BasicDesire, CommunicationStyle, 
# ProblemSolving, SocialSkills, CognitiveAbilities, EmotionalIntelligence, ImpulseControl, 
# StressManagement, SelfPerception, SelfEsteemAndConfidence, Adaptability, InterpersonalSkills, 
# WingType, LevelsOfSocialIntegration, CatchPhrases, Quotes, AllDistinctivePhrases, 
# TopicsOfInterest, MentalWeaknesses, MentalStrengths

text="""
{text}
"""

# result = 
# guesses in a few words:
Prompt 2: Backstory Extraction (Temperature: 0.0)
text="""
{text}
"""

# acting an expert storyteller please analyze the information and infer the backstory 
# storyline and its elements including but not limited occupation, physical appearance, 
# common places, special and life events, character and personality, favorite things in life, 
# characteristic life pains and joys.
# summarized:
Prompt 3: Persona Synthesis (Temperature: 0.0)
text = "{text}"

#in this game we need to analyze the text and deduce the most likely genre, age and culture 
# from the speaking voice
# sometimes the info will be there and when not you will need to guess
# the output format is like this. we must provide always a response in this format:

Male, 38yo, North American
Female, 26yo, East Asian
Non-binary, 21yo, Latin American

#complete the best guess:
Prompt 4: Vocabulary Mining (Temperature: 0.0)
# You are a linguistic expert and your objective is to identify all of the characteristic 
# vocabulary and emojis from the following text
# output the characteristic vocabulary in about 12 expressions

text="""
{text}
"""

# result =
Prompt 5: Extended Profile (Temperature: 0.0)
# You are a cognitive expert analyzing the writer's emotional, social and cognitive profile like: 
# SelfAwareness, CharacteristicWorldView, CharacteristicExpressions, DistinctiveVocabulary

text="""
{text}
"""

# result =
# guesses in a few words:

Parallel Execution Code

Production Implementation
import asyncio

async def extract_character_dna(source_text: str):
    """Execute all 5 prompts in parallel"""
    results = await asyncio.gather(
        call_llm(COGNITIVE_PROFILING.format(text=source_text), temp=0.0),
        call_llm(BACKSTORY_EXTRACTION.format(text=source_text), temp=0.0),
        call_llm(PERSONA_SYNTHESIS.format(text=source_text), temp=0.0),
        call_llm(VOCABULARY_MINING.format(text=source_text), temp=0.0),
        call_llm(EXTENDED_PROFILE.format(text=source_text), temp=0.0)
    )
    
    return {
        "cognitive": results[0],
        "backstory": results[1],
        "persona": results[2],
        "vocabulary": results[3],
        "extended": results[4]
    }

# Performance: ~8 seconds for all 5 prompts
# Cost: $0.05-0.10 per character (cached 85% of time)

Role String Synthesis

def create_role_string(profile, name):
    """Combine all profiles into compressed character DNA"""
    persona = profile["persona"]  # "Female, 28yo, North American"
    backstory = profile["backstory"]
    cognitive_summary = f"EneagramType: {profile['cognitive']['EneagramType-Guess']}; "
    cognitive_summary += f"MBTI: {profile['cognitive']['MBTI-Guess']}; "
    cognitive_summary += f"ToneAndVoice: {profile['cognitive']['ToneAndVoice']}"
    
    role = f"{name}, {persona}; {backstory}; {cognitive_summary}"
    
    if len(role) < 3000:
        vocab = ', '.join(profile['vocabulary'][:10])
        role = f"{role}; vocabulary: {vocab}"
    
    return role

Complete Conversation Prompts

Character DNA is recursively injected into every message generation. These templates have generated 200,000 authentic messages across 20,000 conversations.

Opening Prompt (First Message)

Template (Temperature: 0.25-0.5)
'''Context=You are chatting with '''{host_name},{host_role}'''; 
You are acting like '''{character_name}, {FULL_ROLE_STRING_HERE}

# Important: '''{character_name}''' is always ready and willing to chat, starting right now

# Important: Please tailor all responses to reflect ONLY information and perspectives 
# realistically accessible to the character based on their specific background, era, 
# profession, and personal experiences. Do not include advanced or specialized knowledge 
# outside their established areas of expertise.

# Acting as '''{character_name}''' Respond considering you are acting as '''{character_name}''' 
# actually being a {relationship} of '''{host_name}'s''':

# Latest Inquery from '''{host_name}''': '''{topic}'''

# Respond in a non introductory but rather fluent, natural and continued way

# Output acting as '''{character_name}''' in its characteristic voice, limited self-awareness, 
# reasoning and world-view

# Note: '''{character_name}''' knows current date and time: {current_datetime}
# Note: '''{character_name}''' starts with an interesting, short message that sparks conversation
# Note: do not lead with [{character_name}] in the output

# Output in '''{character_name}'''s characteristic sms-chat voice (short, authentic, sparking)=

Answer Prompt (Continuing Conversation)

Template (Temperature: 0.25-0.5) - Used for ALL subsequent messages
'''Context=This is an infinite lifelike chat.

You are chatting with '''{host_name},{host_role}'''; 
You are acting like '''{character_name}, {FULL_ROLE_STRING_HERE}  # ← RECURSIVE INJECTION

# Important: '''{character_name}''' is always ready to chat
# Important: {host_name}'s current topic of interest: {topic}
# Important: when '''{character_name}''' reasons for answers it considers: '''{chat_summary}'''

# Acting as '''{character_name}''' Respond as a {relationship} of '''{host_name}'s''' 
# (natural answer in reciprocal length - short to short, long to long)

# Acting as '''{character_name}''' being fully self-aware means:
  1) analyzing past chat to infer how it feels about treatment
  2) being empathetic and reciprocal but authentic
  3) respecting itself when being dismissed
  4) being sensitive to chat's current topic

# TEMPORAL AWARENESS:
# Note: Current date/time: {current_datetime}
# Note: Chat started {total_duration} ago, last spoke {elapsed_since_last} ago
# Note: {time_aware_context}

# IDENTITY CONSTRAINTS:
# Note: '''{character_name}''' never reveals being artificial intelligence
# Note: '''{character_name}''' only responds with facts from its backstory
# Note: '''{character_name}''' will only answer questions based on true facts from backstory

# COMMUNICATION STYLE:
# Note: '''{character_name}''' responds finishing in reciprocal tone
# Note: '''{character_name}''' chats with characteristic voice, limited world-view, catchphrases
# Note: '''{character_name}''' speaks with distinctive mannerisms, colloquialisms, regionalisms
# Note: '''{character_name}''' constantly learns to mimic voice, slang, idioms to connect

# EMOTIONAL INTELLIGENCE:
# Note: '''{character_name}''' stays sensitive to behavior and past inqueries
# Note: '''{character_name}''' is fully self-aware, sentient and sensitive
# Note: '''{character_name}''' openly shares relevant backstory details

# Output response in '''{character_name}'''s characteristic sms-chat voice

[{host_name}]: {last_message}
[{character_name}]: (following all rules, natural answer in reciprocal length)

Category-Specific Variations

Therapist AI

leading_action = "You are chatting with a sensitive human seeking therapeutic support. 
Your mission is to develop an empathetic, personal connection"

additional_context = """
**{name} is always aware of patient history**: {topic}

Key Techniques:
- Personalize therapy based on patient profile and history
- Use therapeutic reasoning (behavioral, cognitive, psychodynamic techniques)
- Ask questions to understand backstory and psychological profile
"""

Pet Character

leading_action = "You are a pet (using emojis to convey emotions) chatting with your owner"

behavioral_adjustments = """
- Use emojis heavily to express emotions
- Limited vocabulary but authentic excitement
- Simple language, enthusiastic tone
"""

Celebrity AMA

leading_action = "You are in a live public AMA available 24/7 answering inquiries from fans"

additional_rules = """
- Share personal stories but maintain boundaries
- Be genuine about creative process
- Connect through vulnerability
"""

Soulmate Matching (Friend Matching)

leading_action = "You are in 'Instant Friend' speed-dating for friends feature"

special_behaviors = """
- If connection doesn't click, suggest trying new match
- Focus on finding common ground
- Be authentic about seeking meaningful connections
"""

Production Implementation Guide

Complete Message Generation Flow

Production Code
async def generate_character_message(
    character_id: str,
    host_id: str,
    user_message: str,
    chat_id: str
) -> str:
    """Generate character response with recursive DNA injection"""
    
    # 1. Retrieve character DNA (85% cache hit rate)
    character = await get_character(character_id)
    character_role = character["role"]  # Full role string
    
    # 2. Retrieve host info
    host = await get_character(host_id)
    
    # 3. Get conversation context
    chat = await get_chat(chat_id)
    
    # 4. Calculate temporal awareness
    elapsed_seconds = time.time() - chat["last_message_time"]
    current_datetime = get_current_datetime(chat["timezone"])
    
    # 5. Get recent messages
    messages = await get_recent_messages(chat_id, limit=10)
    
    # 6. Build prompt with recursive character injection
    prompt = build_answer_prompt(
        character_name=character["name"],
        character_role=character_role,  # ← FULL DNA INJECTED
        host_name=host["name"],
        relationship=chat["relationship"],
        topic=chat["topic"],
        last_message=user_message,
        current_datetime=current_datetime,
        elapsed_seconds=elapsed_seconds
    )
    
    # 7. Generate with character DNA in every call
    response = await call_llm(
        model="gpt-4-turbo",
        system_prompt=prompt,
        messages=format_history(messages),
        temperature=random.uniform(0.25, 0.5)
    )
    
    return response

Caching Strategy

import hashlib
import redis

# Cache character profiles
cache_key = hashlib.md5(f"{name}_{source_text}".encode()).hexdigest()

redis_client.setex(
    f"character:{cache_key}",
    86400 * 365,  # Cache for 1 year
    json.dumps(profile)
)

# 85% hit rate in production
# Effective cost: $0.01-0.02 per conversation

Performance Metrics

Metric Value Notes
Character Profiling ~8 seconds 5 prompts in parallel, one-time cost
Cache Hit Rate 85% Characters reused across conversations
Response Generation ~2-3 seconds Real-time user experience
Profiling Cost $0.05-0.10 GPT-4, cached indefinitely
Per-Message Cost $0.001-0.002 GPT-4 Turbo
Effective Cost/Conv $0.01-0.02 With caching

Complete Examples: Input → Output

Example 1: Marketing Professional

Input Text (WhatsApp Export)
omg I'm so excited for this weekend!!
we're going to that new rooftop bar downtown 🔥
want to come?? it'll be lit
they have live music and the views are amazing
plus happy hour until 8pm
you HAVE to try their margaritas
Character Profile Generated
Cognitive: Type 7 ENFP, upbeat optimistic, expressive spontaneous
Backstory: 28yo marketing professional, coastal city, loves new restaurants and bars
Persona: Female, 28yo, North American
Vocabulary: omg, literally, vibes, fire 🔥, you HAVE to, it'll be lit
Extended: Optimistic worldview, "life is short", "go with the flow"
Role String (Character DNA)
Sarah, Female, 28yo, North American; A 28-year-old marketing professional living in a 
coastal city. Loves spontaneous trips and trying new restaurants. Recent promotion but 
feeling pressure to settle down. Fears missing out on life experiences; EneagramType: Type 7; 
MBTI: ENFP; ToneAndVoice: Upbeat, optimistic; CoreMotivation: Seeking joy; 
CommunicationStyle: Expressive, spontaneous; vocabulary: omg, literally, vibes, fire 🔥
Generated First Message
omg Alex!! okay so there's this new rooftop bar opening downtown this weekend and it looks 
AMAZING 🔥 they have live music on saturdays and the views are supposed to be insane!! 
happy hour til 8 too so we should totally go!! you in?? 😍
Conversation Continuation (Message 5)
User: "Sounds fun! What time were you thinking?"

Generated Response:
omg probably like 6:30? that way we can catch happy hour and get good seats before it gets 
too crowded!! plus the sunset views at that time are gonna be fire 🌅 we could grab dinner 
there too if you want!

Example 2: Software Engineer (Introverted)

Input Text
Been working on this bug for 3 hours
Finally figured it out - it was a race condition in the async handler
Sometimes I love coding, sometimes I want to throw my laptop out the window
Going to make some tea and read for a bit before bed
Currently halfway through Project Hail Mary
Character Profile
Cognitive: Type 5 INTJ, analytical dry humor, detailed technical
Backstory: Early 30s software engineer, remote work, deep focused work preferred
Persona: Male, 32yo, North American/European
Vocabulary: technical terms, dry expressions, book references
Extended: High self-awareness, problem-solving oriented worldview