Skip to content

SILVIA Core – ApiFeedback Reference

Version: 3.1

Namespace: CognitiveCode.Silvia.Api


The SILVIA Feedback Engine

The Innovation: Proactive AI with Train-of-Thought Generation

Most AI is purely reactive - it waits for input, processes, responds, waits again. SILVIA ApiFeedback breaks this paradigm by introducing spontaneous feedback generation - SILVIA can think, remember, and speak unprompted, creating natural, flowing conversations.

Traditional AI Conversation Model

User: "Hello"
AI:   "Hello! How can I help?"
[SILENCE - AI waits passively]
User: "What's the weather?"
AI:   "It's sunny today."
[SILENCE - AI waits passively]

Problem: No continuity, no memory, no spontaneity


Dual-System Feedback Architecture

ApiFeedback is actually TWO powerful systems working together:

System 1: Train-of-Thought Generator (Spontaneous AI)

Every 20-30 seconds (configurable):
    1. Sample concepts from conversational memory
    2. Generate novel utterance using Markov chains
    3. Check threshold (is it meaningful enough?)
    4. Check probability (should we speak now?)
    5. Check anti-repetition (did we say this before?)
    6. If all pass → SILVIA speaks unprompted

This is what makes SILVIA feel alive - she can interject with relevant thoughts, follow trains of thought, and continue conversations naturally without being prompted.

System 2: Conversational Memory Database

For every conversation:
    - Store user input as concept array
    - Store AI output as concept array
    - Tag with username + timestamp
    - Build searchable knowledge graph
    - Persist across sessions

This is SILVIA's episodic memory - she remembers every conversation, can search her memory, and uses it to generate contextually relevant spontaneous thoughts.


Generative Behavior Explained

How Feedback Generation Works

Average dev's observation: "very strange function to me... almost like a term bubbler or a relevancy detector"

You're exactly right! Here's what's happening under the hood:

Step 1: Feedback Stack (Conversational Memory)

csharp
Feedback Stack (FIFO queue):
┌─────────────────────────────────────┐
│ [User] "weather is nice today"      │ ← Most recent
│ [AI]   "yes it's very sunny"        │
│ [User] "should we go to the park"   │
│ [AI]   "the park sounds great"      │
│ [User] "what about tomorrow"        │
│ [AI]   "tomorrow might rain"        │
│         ...                         │
│ [1000 items total, oldest deleted]  │
└─────────────────────────────────────┘

Every conversation adds to this stack. When it reaches max size (default 1000), oldest items are removed (FIFO).

Step 2: Timer Fires (Every 20-30 Seconds)

csharp
Timer triggers FeedbackTimerEvent():
    1. Pull most recent thought from stack
    2. Convert to string: "tomorrow might rain"
    3. Call GetResponse() with ONLY reusable exuders
    4. This generates NEW utterance via Markov chains

Key: only_reusable = true means SILVIA only samples from exuders marked "reusable" - these are vetted for train-of-thought generation.

Step 3: Novel Thought Generation

csharp
Input from stack: "tomorrow might rain"

Markov chain sampling from reusable exuders

Generated utterance: "maybe we should check the forecast"

Add conversational prefix (random):
    - 75% chance: no prefix
    - 12.5% chance: "so " + utterance
    - 12.5% chance: "anyway, " + utterance

Final: "anyway, maybe we should check the forecast"

This is the "term bubbler" - it bubbles up concepts from memory and generates novel combinations!

Step 4: Threshold + Probability Filters

csharp
Threshold Check:
    - Count "meaningful" concepts (weight >= 0.25)
    - Needs minimum N concepts (default: 1)
    - If fails → discard, no output

Probability Check:
    - Random(0.0-1.0) <= probability?
    - Default probability = 1.0 (always speak if threshold met)
    - If fails → discard, no output

This prevents spam - only speaks when thought is meaningful AND probability dice roll succeeds.

Step 5: Anti-Repetition Check

csharp
Utterance Stack (tracks what SILVIA said):
┌──────────────────────────────────────────┐
│ "anyway, maybe we should check forecast" │
│ "the park sounds like a great idea"      │
│ "yes it's very sunny today"              │
│         ...                              │
└──────────────────────────────────────────┘

New utterance checked against ALL previous:
    - Same behavior + exuder ID? → REJECT
    - Same concept array? → REJECT
    - Otherwise → ACCEPT + add to stack

SILVIA never repeats herself (within stack limit)!

Step 6: Multi-Modal Output

csharp
If all checks pass:
    SetTextOutput("anyway, maybe we should check forecast")
    SetVoiceOutput("anyway, maybe we should check forecast")
    SetSocketOutput("anyway, maybe we should check forecast")

Result: SILVIA spontaneously speaks without being prompted!


Why This Is Powerful

1. Natural Conversation Flow

Without Feedback:

User: "The weather is nice"
AI:   "Yes, it's sunny!"
[DEAD SILENCE]
User: "..."

With Feedback:

User: "The weather is nice"
AI:   "Yes, it's sunny!"
[20 seconds pass]
AI:   "so, maybe we should go outside?"
User: "Great idea!"
AI:   "I'll grab my jacket"
[15 seconds pass]
AI:   "anyway, where should we go?"

The AI drives the conversation!


2. Contextual Memory Mining

ApiFeedback doesn't just generate random thoughts - it mines conversational context:

csharp
// When feedback matches existing thought, it generates NEW combinations
FeedbackStruct incoming = "should we go to the park";

// Check stack for match
if (AlreadyInStack(incoming)) {
    // Generate novel thought by combining concepts from:
    // - 1 concept from incoming thought
    // - N concepts from random positions in stack
    
    generated = [
        incoming[random],           // "park"
        stack[-3][random],          // "weather"
        stack[-7][random],          // "tomorrow"
        stack[-1][random]           // "sunny"
    ]
    
    // Result: "park weather tomorrow sunny"
    // GetResponse() → "the park will be nice if tomorrow is sunny"
}

This is the "relevancy detector" - it finds related concepts across the entire conversation history and synthesizes new thoughts!


3. Progressive Learning Mode (Clarify)

The Clarify(count) method creates intensive learning sessions:

csharp
feedback.Clarify(10);

// Auto-configures for learning:
SetInterval(1.5f, 2.5f);    // Fast feedback (1.5-2.5 sec)
SetThreshold(0.25f, 1);     // Low threshold (catch weak patterns)
SetProbability(1.0f);       // Always speak when threshold met
SetActive(true, false, 10); // Only for next 10 utterances

// After 10 utterances → auto-shutdown

Use Case:

  • Training sessions
  • Guided conversations
  • Topic exploration
  • Context building

API Methods

Core Control

SetActive(bool active, bool clear)

Master switch for the entire feedback system.

Purpose:

  • Activate spontaneous generation - SILVIA begins thinking and speaking unprompted
  • Deactivate for focused tasks - Stop spontaneous interruptions
  • Clear memory - Wipe conversational history

Parameters:

  • active (bool): Enable/disable spontaneous thought generation
  • clear (bool): Clear all feedback data when activating

Usage:

csharp
SilviaApiFeedback fb = Core.ApiFeedback();

// Start spontaneous AI with fresh memory
fb.SetActive(true, true);

// Stop spontaneous output, keep memory
fb.SetActive(false, false);

What Happens When Active:

  1. Timer starts (random interval between min/max)
  2. Every timer tick:
    • Pulls concepts from feedback stack
    • Generates novel utterance via Markov chains
    • Checks threshold/probability/anti-repetition
    • Outputs to text/voice/socket if all pass
  3. Feedback continues until deactivated

What Happens When Inactive:

  • Timer stops
  • No spontaneous generation
  • Memory still records conversations (if AddFeedback() called)
  • Can still search historical data

IsActive()

Checks if feedback system is currently active.

Usage:

csharp
if (fb.IsActive()) {
    Console.WriteLine("SILVIA is thinking spontaneously");
} else {
    Console.WriteLine("SILVIA is passive (reactive only)");
}

Returns: bool - True if active


Clarify(int count)

Intensive learning mode - provides rapid feedback for N utterances then auto-shutdown.

Purpose:

  • Guided learning sessions - SILVIA actively participates for set number of turns
  • Topic exploration - Rapidly build context around subject
  • Training mode - High-frequency feedback for authoring

Algorithm:

csharp
1. Pause()                          // Stop current feedback
2. SetInterval(1.5f, 2.5f)         // Fast timing (1.5-2.5 sec)
3. SetThreshold(0.25f, 1)          // Low bar (25% weight, 1 concept min)
4. SetProbability(1.0f)            // Always speak when threshold met
5. SetActive(true, false, count)   // Activate for N utterances

Usage:

csharp
// Learning session: 10 rapid-fire spontaneous responses
fb.Clarify(10);

// After 10th utterance → system auto-deactivates

// Training mode: 50 interactions
fb.Clarify(50);

Parameters:

  • count (int): Number of utterances before auto-shutdown

Clarify Count Behavior:

  • Each spontaneous utterance decrements counter
  • When counter reaches 0 → SetActive(false) automatically
  • Counter = -1 → infinite (normal mode)

Memory Management

SetStackSize(int stackSize)

Controls maximum size of feedback memory stack.

Purpose:

  • Memory optimization - Limit RAM usage for long-running systems
  • Conversation depth - More history = better context but slower
  • Repetition window - Smaller stack = can repeat thoughts sooner

Default: 1000 items

Usage:

csharp
// Large conversational memory (more context, more RAM)
fb.SetStackSize(5000);

// Small memory footprint (less context, less RAM)
fb.SetStackSize(100);

Parameters:

  • stackSize (int): Maximum feedback items (must be > 0)

Returns: bool - True if set successfully

Stack Behavior:

  • FIFO (First-In-First-Out)
  • When stack reaches max → oldest item deleted
  • Both feedback stack AND utterance stack use same limit

Clear()

Wipes all feedback memory while preserving settings.

Purpose:

  • Fresh sessions - Clean slate for new conversation context
  • Privacy - Clear user data
  • Testing - Reset between test cases

Usage:

csharp
// Clear all conversational memory
fb.Clear();

// Settings (interval, threshold, probability) unchanged
// Timer state unchanged

Returns: bool - True if cleared

What Gets Cleared:

  • Feedback stack (all conversational history)
  • Utterance stack (all spoken thoughts)

What Stays:

  • Active/inactive state
  • Interval settings
  • Threshold settings
  • Probability settings

Feedback Input

AddFeedback(string feedback)

Adds confirmed, validated feedback to conversational memory.

Purpose:

  • Build conversational history - Add user/AI utterances to memory
  • Pattern learning - System learns from validated inputs
  • Context building - Future spontaneous thoughts draw from this

Usage:

csharp
// Add user input to memory
fb.AddFeedback("The weather is beautiful today");

// Add AI response to memory
fb.AddFeedback("Yes, it's perfect for outdoor activities");

// Add observations
fb.AddFeedback("temperature is 72 degrees");

Parameters:

  • feedback (string): Text to add to memory

Returns: bool - True if added successfully

Under the Hood:

csharp
FeedbackStruct {
    _user = "feedback"              // Internal category
    _concepts = [weather, beautiful, today]  // Concept indices
    _punctuated = [weather, is, beautiful, today]  // With punctuation
    _dateTime = DateTime.Now        // Timestamp
}

Anti-Repetition:

  • Checks if same concept array already in stack
  • If exists → generates NOVEL thought from existing concepts
  • If new → adds to stack

This is the core memory - everything SILVIA knows comes from here!


SuggestFeedback(string feedback)

Adds suggested (unconfirmed) feedback for evaluation.

Purpose:

  • Hypothesis testing - Add tentative thoughts without confirming
  • Exploratory suggestions - System can evaluate quality over time
  • Training data - Mark suggestions for later validation

Difference from AddFeedback:

  • Sets suggestion = true flag
  • Bypasses anti-repetition check (always generates novel thought)
  • Used for guiding conversation without hard commit

Usage:

csharp
// Suggest potential response
fb.SuggestFeedback("maybe we should check the forecast");

// Suggest exploratory thought
fb.SuggestFeedback("I wonder if it will rain tomorrow");

Parameters:

  • feedback (string): Suggested text

Returns: bool - True if added

When to Use:

csharp
// User says something, suggest possible follow-ups
string userInput = "I'm going to the park";
fb.AddFeedback(userInput);           // Confirmed input
fb.SuggestFeedback("bring a jacket"); // Potential suggestion

// Later, SILVIA might spontaneously say:
// "so, maybe you should bring a jacket"

Timing & Probability

SetInterval(float rate_min, float rate_max)

Controls timing between spontaneous utterances.

Purpose:

  • Conversation pacing - Prevent spam or long silences
  • Natural timing - Mimic human thought patterns
  • Context-aware delays - Different intervals for different scenarios

Algorithm:

csharp
On each timer cycle:
    wait_time = Random(rate_min, rate_max) seconds
    sleep(wait_time)
    attempt_spontaneous_utterance()

Usage:

csharp
// Fast-paced conversation (0.5-1.5 sec)
fb.SetInterval(0.5f, 1.5f);

// Normal conversation (5-10 sec)
fb.SetInterval(5.0f, 10.0f);

// Slow, thoughtful (20-30 sec, default)
fb.SetInterval(20.0f, 30.0f);

// Very slow background thoughts (60-120 sec)
fb.SetInterval(60.0f, 120.0f);

Parameters:

  • rate_min (float): Minimum seconds between thoughts
  • rate_max (float): Maximum seconds between thoughts

Returns: bool - True if valid (min > 0, max > min)

Randomization:

  • Each cycle picks random value in range
  • Creates natural, unpredictable timing
  • Prevents robotic regularity

SetThreshold(float threshold, int concept_min)

Sets minimum quality bar for spontaneous thoughts.

Purpose:

  • Quality control - Only speak meaningful thoughts
  • Spam prevention - Filter out low-quality generations
  • Concept richness - Require minimum semantic content

Algorithm:

csharp
For each generated utterance:
    meaningful_concepts = 0
    for each concept in utterance:
        if (concept.weight >= threshold):
            meaningful_concepts++
    
    if (meaningful_concepts >= concept_min):
        pass_threshold = true

Usage:

csharp
// Low bar - accept weak thoughts (learning mode)
fb.SetThreshold(0.25f, 1);  // 25% weight, 1 concept minimum

// Medium bar - decent thoughts (normal conversation)
fb.SetThreshold(0.5f, 2);   // 50% weight, 2 concepts minimum

// High bar - only strong thoughts (expert mode)
fb.SetThreshold(0.8f, 3);   // 80% weight, 3 concepts minimum

Parameters:

  • threshold (float): Minimum concept weight (0.0-1.0)
  • concept_min (int): Minimum number of concepts

Returns: bool - True if valid

Concept Weights:

  • Set by ApiData().SetConceptWeight() or auto-tuned
  • Higher weight = more important/relevant concept
  • Stopwords have low weight (0.1-0.3)
  • Domain-specific terms have high weight (0.7-1.0)

SetProbability(float probability)

Controls chance of speaking when threshold is met.

Purpose:

  • Frequency control - Reduce spontaneous output without raising threshold
  • Natural variation - Sometimes hold back even when thought is good
  • Contextual tuning - Different probabilities for different scenarios

Algorithm:

csharp
If (utterance passes threshold):
    random_value = Random(0.0, 1.0)
    if (random_value <= probability):
        speak()
    else:
        stay_silent()

Usage:

csharp
// Always speak when threshold met (learning mode)
fb.SetProbability(1.0f);  // 100% chance

// Speak half the time (balanced)
fb.SetProbability(0.5f);  // 50% chance

// Rarely speak (background thoughts only)
fb.SetProbability(0.2f);  // 20% chance

// Very quiet (occasional interjections)
fb.SetProbability(0.1f);  // 10% chance

Parameters:

  • probability (float): Chance of speaking (0.0-1.0)

Returns: bool - True if valid

Combination with Threshold:

csharp
// High threshold + high probability = rare but quality thoughts
fb.SetThreshold(0.8f, 3);
fb.SetProbability(1.0f);

// Low threshold + low probability = frequent evaluation, rare output
fb.SetThreshold(0.25f, 1);
fb.SetProbability(0.2f);

State Control

Pause()

Temporarily suspends spontaneous generation while preserving state.

Purpose:

  • Critical conversations - Disable interruptions during important dialog
  • Focused tasks - Stop background thoughts
  • System coordination - Sync with SILVIA State system

Usage:

csharp
// Before critical interaction
fb.Pause();

// During critical task
ProcessImportantStuff();

// Resume normal behavior
fb.Resume();

What Happens:

  1. Timer stops immediately
  2. No spontaneous generation
  3. All settings preserved (interval, threshold, probability)
  4. Memory intact (feedback stack, utterance stack)
  5. SILVIA State system also pauses (_state.WaitToJump(true))

Note: Calling Pause() does NOT deactivate the system - it just suspends it temporarily


Resume()

Resumes spontaneous generation after pause.

Purpose:

  • Restart after critical task - Resume normal spontaneous behavior
  • Coordinated activation - Sync with other SILVIA systems

Usage:

csharp
fb.Resume();

What Happens:

  1. Timer restarts with new random interval
  2. Spontaneous generation resumes
  3. All settings active (interval, threshold, probability)
  4. SILVIA State system resumes (_state.WaitToJump(false))

Note: Only works if system was previously active - if inactive, does nothing


Persistence

Write(string username, string filename)

Saves conversational memory to binary file.

Purpose:

  • Long-term memory - Persist conversations across sessions
  • User profiles - Save per-user conversation history
  • Backup - Archive conversational data

File Format (Binary):

[username: string]
[concept_count: int]
[concept_dictionary: string[concept_count]]
[feedback_count: int]
for each feedback:
    [timestamp: long]
    [concept_indices: int[]]
    [punctuated_indices: int[]]

Usage:

csharp
// Save user's conversation history
fb.Write("john_doe", "users/john_doe_memory.dat");

// Save session data
fb.Write("session_2024", "sessions/oct_13.dat");

// Backup current state
fb.Write("backup", "backup_" + DateTime.Now.ToString("yyyyMMdd") + ".dat");

Parameters:

  • username (string): Username to associate with data
  • filename (string): File path (creates directories if needed)

Returns: bool - True if written successfully

Thread Safety:

  • Uses volatile _writingFeedback flag
  • Check with IsWriting() before shutdown
  • Transactional: writes to .tmp then copies to final file

Read(string filename)

Loads conversational memory from binary file.

Purpose:

  • Session restoration - Restore previous conversations
  • User profiles - Load per-user history
  • Training data - Import pre-built conversational patterns

Usage:

csharp
// Restore user's memory
fb.Read("users/john_doe_memory.dat");

// Load training data
fb.Read("training/customer_service.dat");

// Import conversations
fb.Read("import/previous_session.dat");

Parameters:

  • filename (string): File path to read from

Returns: bool - True if loaded successfully

Concept Mapping:

  • Reads concept dictionary from file
  • Maps to current brain concepts (creates if missing)
  • Handles concept ID mismatches across brain versions

Integration:

  • Merges with existing feedback stack
  • Preserves timestamps from file
  • Respects stack size limits (oldest deleted if overflow)

IsWriting()

Checks if system is currently saving data.

Purpose:

  • Safe shutdown - Don't terminate during write operation
  • Resource monitoring - Track I/O operations

Usage:

csharp
// Safe shutdown pattern
if (fb.IsWriting()) {
    Console.WriteLine("Waiting for feedback write to complete...");
    while (fb.IsWriting()) {
        Thread.Sleep(50);
    }
}
Core.Release();

Returns: bool - True if currently writing


Advanced search through conversational memory.

Purpose:

  • Memory recall - Find specific conversations
  • Pattern analysis - Identify recurring themes
  • Context retrieval - Pull relevant historical context

Algorithm:

csharp
1. Parse date/time range
2. Convert concepts/strip/exclude to indices
3. Filter by username + date range
4. For each feedback item:
   - Check exclusions (fail → skip)
   - Count matching concepts (with optional bindings)
   - If requireAll: need ALL concepts
   - If !requireAll: need ANY concept
   - If match → add to search results
5. Return true if results found

Usage:

csharp
// Find weather conversations from john_doe in last week
fb.Search("john_doe", "weather temperature", null, null,
         "10/6/2024 00:00:00", "10/13/2024 23:59:59",
         false, true);

// Find work discussions requiring ALL concepts
fb.Search("mary", "project deadline budget", null, null,
         null, null, true, false);

// Find conversations about coding, exclude debugging
fb.Search(null, "programming code", null, "debugging error",
         "1/1/2024 00:00:00", null, false, true);

Parameters:

  • username (string): Filter by user (null = all users)
  • concepts (string): Space-separated concepts to find
  • strip (string): Concepts to remove from search (e.g., stopwords)
  • exclude (string): Reject results containing these concepts
  • dateTimeStart (string): Start date/time ("M/d/yyyy H:mm:ss" format)
  • dateTimeEnd (string): End date/time (null = now)
  • requireAll (bool): True = AND logic, False = OR logic
  • related (bool): True = include bound concepts, False = exact only

Returns: bool - True if search found results

Date Format: "3/10/2010 12:15:12" (month/day/year hour:min:sec)

Related Concepts:

  • If related = true: uses SilviaBindingSet to find synonyms, related terms
  • Expands search to semantic network
  • More results but less precise

SearchNext()

Moves to next result in search results.

Purpose:

  • Iteration - Loop through all matching results
  • Sequential processing - Handle results one by one

Usage:

csharp
if (fb.Search("john", "weather", ...)) {
    do {
        string text = fb.SearchGetString(true);
        string time = fb.SearchGetTime();
        Console.WriteLine($"[{time}] {text}");
    } while (fb.SearchNext());
}

Returns: bool - True if more results available, False if end reached

Internal Behavior:

  • Removes current result from search stack
  • Next result becomes current
  • Returns false when search stack empty

SearchGetString(bool punctuated)

Returns text of current search result.

Purpose:

  • Retrieve content - Get feedback text
  • Format control - Original or normalized punctuation

Usage:

csharp
// Original text with punctuation
string original = fb.SearchGetString(true);
// "The weather is beautiful today!"

// Normalized text (concepts only)
string normalized = fb.SearchGetString(false);
// "weather beautiful today"

Parameters:

  • punctuated (bool): True = original with punctuation, False = normalized

Returns: string - Feedback text, or null if no results


SearchGetTime()

Returns timestamp of current search result.

Purpose:

  • Temporal analysis - When was this said?
  • Chronological ordering - Sort by time
  • Session tracking - Group by time periods

Usage:

csharp
string timestamp = fb.SearchGetTime();
// "10/13/2024 2:45:32 PM"

DateTime dt = DateTime.Parse(timestamp);
TimeSpan age = DateTime.Now - dt;
Console.WriteLine($"Said {age.TotalHours:F1} hours ago");

Returns: string - Formatted date/time, or null if no results

Format: Standard DateTime.ToString() format


SearchRemoveFromStack()

Permanently deletes current search result from memory.

Purpose:

  • Data cleanup - Remove outdated/incorrect feedback
  • Privacy compliance - Delete user data
  • Quality control - Remove low-quality items

Usage:

csharp
if (fb.Search("john", "inappropriate", ...)) {
    do {
        string text = fb.SearchGetString(true);
        if (ShouldDelete(text)) {
            fb.SearchRemoveFromStack();
        }
    } while (fb.SearchNext());
}

Returns: bool - True if removed successfully

Warning: This is permanent! Item deleted from feedback stack.


Usage Examples

Example 1: Spontaneous Conversational AI

Building a chatbot that thinks and speaks unprompted:

csharp
using CognitiveCode.Silvia.Api;

public class SpontaneousBot {
    private SilviaCore Core;
    private SilviaApiFeedback fb;
    
    public void Initialize() {
        Core = SilviaCoreManager.CreateCore("Bot");
        fb = Core.ApiFeedback();
        
        // Configure spontaneous behavior
        fb.SetInterval(10.0f, 20.0f);    // Think every 10-20 seconds
        fb.SetThreshold(0.5f, 2);         // Medium quality bar
        fb.SetProbability(0.7f);          // Speak 70% of the time
        fb.SetStackSize(2000);            // Large memory
        
        // Activate!
        fb.SetActive(true, true);
    }
    
    public void UserSays(string input) {
        // Add user input to memory
        fb.AddFeedback(input);
        
        // Get AI response
        string[] response = Core.ApiBrain().GetResponseManaged(input);
        
        // Add AI response to memory (for future spontaneous thoughts)
        if (response != null) {
            fb.AddFeedback(response[0]);
            
            // Output AI response
            Console.WriteLine("AI: " + response[0]);
        }
        
        // Now SILVIA will spontaneously speak every 10-20 seconds
        // using concepts from conversation history
    }
    
    public void CheckForSpontaneousThoughts() {
        // Called in main loop (every 100ms or so)
        
        // Check if SILVIA spoke spontaneously
        string thought = Core.ApiApp().GetTextOutput();
        if (thought != null) {
            Console.WriteLine("AI (spontaneous): " + thought);
            Core.ApiApp().ClearTextOutput();
        }
    }
}

// Usage:
bot.Initialize();
bot.UserSays("The weather is beautiful");
// AI: "Yes, it's a lovely day!"

// [15 seconds later, spontaneously]
// AI (spontaneous): "so, maybe we should go for a walk?"

bot.UserSays("Great idea!");
// AI: "I'll grab my jacket"

// [12 seconds later, spontaneously]
// AI (spontaneous): "anyway, where should we walk?"

Example 2: Intensive Learning Mode

Using Clarify for focused training:

csharp
public class TrainingSession {
    private SilviaApiFeedback fb;
    
    public void TeachNewTopic(string topic) {
        fb = Core.ApiFeedback();
        
        // Start intensive learning mode
        fb.Clarify(20);  // 20 rapid-fire feedback responses
        
        // Seed initial context
        fb.SuggestFeedback($"Let's learn about {topic}");
        fb.SuggestFeedback($"{topic} is interesting");
        fb.SuggestFeedback($"I want to understand {topic}");
        
        // Now SILVIA will rapidly generate 20 spontaneous utterances
        // about the topic using feedback stack + Markov chains
        
        // After 20 utterances → auto-shutdown
    }
    
    public void MonitorLearning() {
        int count = 0;
        while (fb.IsActive() && count < 30) {
            string thought = Core.ApiApp().GetTextOutput();
            if (thought != null) {
                Console.WriteLine($"[{count}] SILVIA: {thought}");
                Core.ApiApp().ClearTextOutput();
                count++;
            }
            Thread.Sleep(100);
        }
        
        Console.WriteLine("Learning session complete!");
    }
}

// Output:
// [0] SILVIA: so, artificial intelligence is fascinating
// [1] SILVIA: machine learning algorithms can learn patterns
// [2] SILVIA: neural networks process information like brains
// [3] SILVIA: anyway, deep learning is a subset of AI
// ... (20 total, then auto-stop)

Finding and analyzing past conversations:

csharp
public class ConversationAnalyzer {
    private SilviaApiFeedback fb;
    
    public void FindWeatherConversations(string username) {
        fb = Core.ApiFeedback();
        
        // Search for weather discussions in last 30 days
        string endDate = DateTime.Now.ToString("M/d/yyyy H:mm:ss");
        string startDate = DateTime.Now.AddDays(-30).ToString("M/d/yyyy H:mm:ss");
        
        bool found = fb.Search(
            username,                    // Specific user
            "weather temperature rain",  // Weather-related concepts
            "the a is",                  // Strip stopwords
            null,                        // No exclusions
            startDate,                   // 30 days ago
            endDate,                     // Now
            false,                       // ANY concept (OR logic)
            true                         // Include related concepts
        );
        
        if (found) {
            List<(DateTime time, string text)> results = new List<(DateTime, string)>();
            
            do {
                string text = fb.SearchGetString(true);
                string timeStr = fb.SearchGetTime();
                DateTime time = DateTime.Parse(timeStr);
                
                results.Add((time, text));
                
            } while (fb.SearchNext());
            
            // Analyze results
            Console.WriteLine($"Found {results.Count} weather conversations:");
            foreach (var (time, text) in results.OrderBy(r => r.time)) {
                Console.WriteLine($"[{time:yyyy-MM-dd HH:mm}] {text}");
            }
        }
    }
    
    public void FindAndCleanOldData(string username, int daysOld) {
        // Remove conversations older than N days
        string cutoffDate = DateTime.Now.AddDays(-daysOld).ToString("M/d/yyyy H:mm:ss");
        
        bool found = fb.Search(
            username,
            null,                        // All concepts
            null,                        // No strip
            null,                        // No exclude
            "1/1/2000 00:00:00",        // Very old start
            cutoffDate,                  // Up to cutoff
            false,
            false
        );
        
        if (found) {
            int deleted = 0;
            do {
                fb.SearchRemoveFromStack();
                deleted++;
            } while (fb.SearchNext());
            
            Console.WriteLine($"Deleted {deleted} old conversations");
        }
    }
}

Example 4: User Profile Persistence

Saving and loading per-user conversational memory:

csharp
public class UserMemoryManager {
    private SilviaApiFeedback fb;
    private string memoryPath = "user_memories/";
    
    public void SaveUserSession(string username) {
        fb = Core.ApiFeedback();
        
        // Ensure directory exists
        Directory.CreateDirectory(memoryPath);
        
        // Save user's conversational memory
        string filename = Path.Combine(memoryPath, $"{username}_memory.dat");
        bool saved = fb.Write(username, filename);
        
        if (saved) {
            Console.WriteLine($"Saved {username}'s memory to {filename}");
        }
    }
    
    public void LoadUserSession(string username) {
        fb = Core.ApiFeedback();
        
        // Clear current memory
        fb.Clear();
        
        // Load user's previous conversations
        string filename = Path.Combine(memoryPath, $"{username}_memory.dat");
        
        if (File.Exists(filename)) {
            bool loaded = fb.Read(filename);
            
            if (loaded) {
                Console.WriteLine($"Loaded {username}'s memory");
                
                // Activate spontaneous thoughts using loaded history
                fb.SetInterval(15.0f, 30.0f);
                fb.SetThreshold(0.5f, 2);
                fb.SetProbability(0.8f);
                fb.SetActive(true, false);  // Don't clear (already loaded)
                
                Console.WriteLine("SILVIA will now use previous conversation context");
            }
        } else {
            Console.WriteLine($"No previous memory for {username}, starting fresh");
            fb.SetActive(true, true);  // Clear and start fresh
        }
    }
    
    public void AutoSaveInterval() {
        // Call this periodically (e.g., every 5 minutes)
        while (true) {
            Thread.Sleep(5 * 60 * 1000);  // 5 minutes
            
            if (!fb.IsWriting()) {
                SaveUserSession("current_user");
            }
        }
    }
}

Example 5: Context-Aware Spontaneous Thoughts

Controlling spontaneous behavior based on conversation state:

csharp
public class ContextAwareFeedback {
    private SilviaApiFeedback fb;
    private ConversationState state;
    
    enum ConversationState {
        Casual,        // Frequent spontaneous thoughts
        Important,     // Rare spontaneous thoughts
        Critical       // No spontaneous thoughts
    }
    
    public void SetConversationState(ConversationState newState) {
        state = newState;
        fb = Core.ApiFeedback();
        
        switch (state) {
            case ConversationState.Casual:
                // Chatty AI
                fb.SetInterval(5.0f, 15.0f);   // Think every 5-15 sec
                fb.SetThreshold(0.25f, 1);     // Low bar
                fb.SetProbability(0.9f);        // Speak 90% of time
                fb.SetActive(true, false);
                Console.WriteLine("SILVIA is chatty now");
                break;
                
            case ConversationState.Important:
                // Thoughtful AI (less intrusive)
                fb.SetInterval(20.0f, 40.0f);  // Think every 20-40 sec
                fb.SetThreshold(0.6f, 2);      // Medium-high bar
                fb.SetProbability(0.5f);        // Speak 50% of time
                fb.SetActive(true, false);
                Console.WriteLine("SILVIA is thoughtful now");
                break;
                
            case ConversationState.Critical:
                // Silent AI (user needs focus)
                fb.Pause();
                Console.WriteLine("SILVIA is silent now");
                break;
        }
    }
    
    public void UserSays(string input) {
        fb.AddFeedback(input);
        
        // Auto-detect conversation state
        if (input.Contains("urgent") || input.Contains("important")) {
            SetConversationState(ConversationState.Important);
        } else if (input.Contains("quiet") || input.Contains("focus")) {
            SetConversationState(ConversationState.Critical);
        } else {
            SetConversationState(ConversationState.Casual);
        }
        
        // Get response
        string[] response = Core.ApiBrain().GetResponseManaged(input);
        if (response != null) {
            fb.AddFeedback(response[0]);
            Console.WriteLine("AI: " + response[0]);
        }
    }
    
    public void EndCriticalTask() {
        // Resume spontaneous thoughts after critical task
        SetConversationState(ConversationState.Casual);
        fb.Resume();
    }
}

// Usage:
var bot = new ContextAwareFeedback();

bot.UserSays("Hey, how are you?");
// SILVIA is chatty now
// AI: "I'm doing great, thanks!"
// [7 seconds later]
// AI (spontaneous): "so, what's new with you?"

bot.UserSays("I need to focus on something important");
// SILVIA is thoughtful now
// AI: "Of course, I'll be quieter"
// [35 seconds later, maybe]
// AI (spontaneous): "let me know if you need help"

bot.UserSays("I need quiet please");
// SILVIA is silent now
// AI: "I'll be silent"
// [No spontaneous thoughts]

Use Cases

1. Virtual Companions

csharp
// Chatbot that feels alive - thinks, remembers, continues conversations
fb.SetInterval(10.0f, 25.0f);
fb.SetThreshold(0.5f, 2);
fb.SetProbability(0.8f);
fb.SetActive(true, true);

// SILVIA will naturally continue conversations like a real person

Benefits:

  • Natural conversation flow
  • No awkward silences
  • Contextual topic continuation
  • Feels human-like

2. Customer Service Memory

csharp
// Load customer's previous interactions
fb.Read($"customers/{customerId}_history.dat");

// SILVIA remembers previous conversations!
// Can reference past issues, preferences, context

// Save updated history at end of session
fb.Write(customerId, $"customers/{customerId}_history.dat");

Benefits:

  • Personalized service
  • Context retention
  • Issue tracking
  • Relationship building

3. Educational Tutoring

csharp
// Intensive learning mode for studying
fb.Clarify(50);  // 50 rapid-fire follow-up questions/hints

// SILVIA actively guides learning with spontaneous hints:
// "so, what about the quadratic formula?"
// "anyway, remember to factor first"
// "maybe try a different approach"

Benefits:

  • Active learning engagement
  • Socratic questioning
  • Context-aware hints
  • Progressive difficulty

4. Meeting Assistant

csharp
// Record entire meeting
foreach (string utterance in meeting) {
    fb.AddFeedback(utterance);
}

// Later, search meeting memory
fb.Search(null, "action items deadline", null, null, meetingDate, null, true, true);

do {
    string item = fb.SearchGetString(true);
    Console.WriteLine($"Action Item: {item}");
} while (fb.SearchNext());

Benefits:

  • Meeting memory
  • Action item extraction
  • Topic tracking
  • Searchable transcripts

5. Research Assistant

csharp
// Feed research papers to feedback
foreach (string paragraph in research) {
    fb.SuggestFeedback(paragraph);
}

// SILVIA spontaneously suggests connections:
// "so, this relates to the previous paper about X"
// "anyway, Smith (2020) had similar findings"
// "maybe we should look at the methodology"

Benefits:

  • Cross-reference detection
  • Pattern identification
  • Literature connections
  • Novel insights

Best Practices

1. Feedback Tuning

csharp
// GOOD: Progressive tuning
// Start conservative
fb.SetInterval(30.0f, 60.0f);
fb.SetProbability(0.3f);

// Monitor user response
// If positive → increase frequency
fb.SetInterval(15.0f, 30.0f);
fb.SetProbability(0.6f);

// BAD: Aggressive from start
fb.SetInterval(1.0f, 2.0f);  // Way too frequent!
fb.SetProbability(1.0f);      // Always speaks!
// Result: Annoying spam

2. Memory Management

csharp
// GOOD: Reasonable stack size
fb.SetStackSize(1000);  // ~1000 utterances of history

// BAD: Too large (memory issues)
fb.SetStackSize(100000);  // 100K utterances = huge RAM

// BAD: Too small (poor context)
fb.SetStackSize(10);  // Only 10 utterances = no context

3. Learning Mode

csharp
// GOOD: Use Clarify for focused learning
fb.Clarify(20);  // 20 active responses then stop

// BAD: Always-on high-frequency
fb.SetInterval(1.0f, 2.0f);
fb.SetProbability(1.0f);
fb.SetActive(true, false);
// Result: Endless spam

4. Persistence

csharp
// GOOD: Check before shutdown
if (!fb.IsWriting()) {
    fb.Write(user, filename);
    Core.Release();
}

// BAD: Force shutdown during write
fb.Write(user, filename);
Core.Release();  // May corrupt file!

5. Search Optimization

csharp
// GOOD: Specific search
fb.Search("john", "weather rain", "the a", null, startDate, endDate, false, true);

// BAD: Overly broad search
fb.Search(null, null, null, null, "1/1/2000", null, false, true);
// Result: Returns entire feedback stack (slow!)

Performance Notes

Timer Resolution:

  • Minimum interval: 0.5 seconds (faster may cause issues)
  • Maximum interval: Unlimited (but > 300 sec = impractical)
  • Randomization: Uses Random() for natural variation

Memory Usage:

  • Each feedback item: ~100-200 bytes (depending on concept count)
  • Stack of 1000: ~100-200 KB RAM
  • Stack of 10000: ~1-2 MB RAM

Search Performance:

  • Linear search: O(n) where n = stack size
  • Concept matching: O(n*m) where m = concepts per item
  • Date filtering: O(n) (fast integer comparison)

Write Performance:

  • Binary format: Fast write/read
  • Transactional: Uses temp file + copy (safe but slower)
  • Concept dictionary: Written once per file (efficient)

Optimization Tips:

  • Keep stack size reasonable (1000-5000)
  • Use date ranges in searches (reduce n)
  • Strip stopwords before search (reduce m)
  • Save periodically, not on every utterance

CLI Quick Reference

All feedback parameters can be tuned at runtime via the SILVIA CLI with no code:

On/Off/Status

$> feedback on
$> feedback off
$> feedback status

Status shows all tuning values at a glance:

Feedback: on | Interval: 20.0-30.0s | Chance: 100% | Threshold: 0.25 (min 1) | Stack: 47/1000

Tuning Commands

CommandDefaultDescription
feedback interval [min] [max]20-30sTimer range between spontaneous utterances
feedback chance [0.0-1.0]1.0 (100%)Probability of speaking when timer fires
feedback threshold [wt] [cnt]0.25, 1Minimum concept weight + count for utterance
feedback stacksize [n]1000Maximum feedback memory entries
feedback clearWipe feedback + utterance stacks

All tuning commands show current values when called with no arguments:

$> feedback chance
Current chance: 100%. Usage: feedback chance [0.0-1.0]

Demo Preset (fast, responsive)

$> feedback interval 5 10
$> feedback chance 1.0
$> feedback threshold 0.1 1
$> feedback on

WordNet + Seed + Feedback Pipeline

ApiFeedback integrates with SILVIA's WordNet and Seed systems to enable zero-code emergent NLU. When all systems are active, a single conversation creates a self-reinforcing knowledge loop:

Architecture

User says "car"

WordNet Auto-Binding (wordnet on)
    → Creates bindings: car↔vehicle (parent), car↔sedan (child), car↔auto (synonym)

WordNet Learn (wordnet learn on)
    → Queues definition gloss into pending feedback

WordNet Deep (wordnet deep on)
    → Queues relation sentences: "car is a type of vehicle", etc.

FlushPendingWordNetFeedback
    → Calls SuggestFeedback() for each queued string

SuggestFeedback() [with seed on]
    → 1. Creates reusable behavior (absorber + exuder) in seed.knowledge group
    → 2. Adds to feedback stack with concept blending

Feedback Timer fires (every interval)
    → Picks concepts from stack
    → Matches against reusable exuders (including seeded knowledge behaviors)
    → Applies threshold + chance + anti-repetition
    → SILVIA speaks: "so, car is a type of vehicle"

The Five-Command Standup

$> wordnet on          ← Tier 1: auto-bind semantic relations
$> wordnet learn on    ← Tier 2: definitions → feedback
$> wordnet deep on     ← Tier 3: relation sentences → feedback
$> seed on             ← Auto-create reusable behaviors from injected knowledge
$> feedback on         ← Spontaneous generation from feedback stack

Then talk. Every new word triggers the full pipeline. For faster demo response times:

$> feedback interval 5 10
$> feedback threshold 0.1 1

File-Based Knowledge Import

Any knowledge base can be imported via the ingest CLI command, which calls SeedKnowledge() + SuggestFeedback() for each line:

$> ingest file "domain_glossary.txt"
Ingested 142 of 150 lines from domain_glossary.txt

$> feedback on
$> feedback interval 5 10

SILVIA now has 142 reusable knowledge behaviors and a seeded feedback stack.

Programmatic Equivalent

csharp
SilviaApiFeedback fb = Core.ApiFeedback();
SilviaBrain brain = /* internal access */;

// Enable seed mode (behaviors created from suggestions)
brain.SetSeedMode(true);

// Enable feedback
fb.SetInterval(5.0f, 10.0f);
fb.SetThreshold(0.1f, 1);
fb.SetProbability(1.0f);
fb.SetActive(true, false);

// Inject knowledge — each call creates behavior + seeds feedback stack
fb.SuggestFeedback("a dog is a type of mammal");
fb.SuggestFeedback("a cat is a type of mammal");
fb.SuggestFeedback("a mammal is a type of animal");

// SILVIA will spontaneously generate from this knowledge

See Also

  • ApiApp - Output stacks receive spontaneous utterances
  • ApiBrain - GetResponse() uses reusable exuders for spontaneous generation
  • ApiData - Concept weights affect threshold filtering
  • ApiMem - Brain merging affects reusable exuder pool
  • ApiUser - Per-user feedback stacks in multi-user systems
  • CLI - No-code feedback tuning, seed, ingest, and WordNet commands

© Copyright Cognitive Code Corp. 2007-2026

SILVIA is a registered Trademark of Cognitive Code Corp.

SILVIA is a registered Trademark of Cognitive Code Corp.