Skip to content

SILVIA Core API Reference

Version: 3.1

Namespace: CognitiveCode.Silvia.Api


The Foundation: Deterministic AI Infrastructure

SILVIA Core is the foundation of the entire SILVIA AI execution platform - a production-grade, deterministic AI engine designed for deploying auditable artificial intelligence from IoT devices to cloud-scale infrastructure. Unlike probabilistic AI systems that introduce uncertainty, SILVIA Core provides guaranteed execution, complete auditability, and sub-millisecond response times across all deployment scenarios.

From Edge to Enterprise: A Universal AI Platform

SILVIA Core powers AI deployments across the full technology spectrum:

EDGE DEVICES  →  IOT NETWORKS  →  ENTERPRISE SYSTEMS  →  CLOUD SCALE
      ↓                ↓                  ↓                   ↓
Deterministic      Real-Time         Multi-Tenant         Kubernetes
  Execution        Responses        Authentication       Orchestration

Edge Computing: Embedded AI with predictable memory footprint and zero network dependencies
IoT Integration: Real-time sensor fusion, telemetry processing, and device coordination
Enterprise Systems: Multi-user support, session management, and secure execution
Cloud Deployments: Horizontal scaling, load balancing, and distributed coordination

Why SILVIA Core Matters

Traditional AI systems are black boxes - you provide input, receive output, and hope the result is correct. SILVIA Core is different:

  • 100% Auditable: Every decision, every execution path, every variable state is traceable
  • Deterministic: Same input always produces same output - critical for regulated industries
  • Performance Optimized: Sub-millisecond inference with predictable latency characteristics
  • Resource Efficient: Runs on constrained devices while scaling to cloud infrastructure
  • Production Ready: Battle-tested in defense, healthcare, finance, and industrial control systems

Core Platform Capabilities

The SilviaCore class and SilviaCoreManager static manager provide:

  1. Multi-Instance Management: Run thousands of isolated AI cores concurrently
  2. Variable State Management: Persistent, type-safe variable storage with $ prefix convention
  3. Timed Execution Engine: Scheduled callbacks, periodic tasks, and temporal event management
  4. Inter-Core Communication: Coordinator sensors for distributed AI coordination
  5. Fixed Update Loop: Unity-compatible physics-synchronized execution
  6. Thread-Safe Operations: Multi-threaded request processing for server environments
  7. API Subsystem Access: Gateway to all SILVIA specialized APIs (Brain, Sensors, Database, etc.)
  8. High-Precision Timing: Microsecond-accurate scheduling for real-time applications

Modern Use Cases

Healthcare AI: Patient monitoring systems with auditable decision trails for FDA compliance
Financial Trading: Algorithmic trading bots with guaranteed execution and regulatory audit logs
Industrial Control: Factory automation with deterministic safety interlocks and real-time response
Defense Systems: Mission-critical AI with verified behavior and complete operational transparency
Autonomous Vehicles: Sensor fusion and decision-making with provable safety characteristics
Smart Home/IoT: Distributed intelligence across device networks with synchronized coordination
Gaming & Simulation: High-performance NPC AI with deterministic replay and testing capability
Enterprise Chatbots: Multi-tenant conversational AI with user isolation and session management


Core Architecture Overview

The Three-Layer System

┌─────────────────────────────────────────────────────────────┐
│                  SilviaCoreManager (Static)                 │
│  ┌─────────────────────────────────────────────────────────┐│
│  │  • Multi-Core Lifecycle Management                      ││
│  │  • Inter-Core Broadcasting & Communication              ││
│  │  • Coordinator Sensors (Cross-Core Data Sharing)        ││
│  │  • Global Timer Coordination                            ││
│  └─────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────┘

         ├──► SilviaCore Instance 1 (User: "Alice")
         │    ├──► ApiBrain() - Inference Engine
         │    ├──► ApiSensors() - Real-Time Telemetry, Datastores
         │    ├──► ApiUser() - User Management
         │    └──► [15+ Specialized APIs]

         ├──► SilviaCore Instance 2 (User: "Bob")
         │    └──► [Full API Stack]

         └──► SilviaCore Instance N (User: "System")
              └──► [Full API Stack]

Core Initialization Pattern

csharp
// 1. CREATE CORE INSTANCE
SilviaCore core = SilviaCoreManager.CreateCore(
    userName: "Production_System",
    fileName: "brains/production_v2.sil",
    boot: true,
    voiceTimer: false
);

// 2. MARK AS ACTIVE
core.SetCreated();

// 3. CONFIGURE CORE BEHAVIOR
core.SetActive(true);
core.EnableHighPrecisionTiming(true);

// 4. ACCESS SUBSYSTEMS
var brain = core.ApiBrain();
var sensors = core.ApiSensors();

// 5. EXECUTE AI LOGIC
string response = brain.GetResponse("Initialize production monitoring");

SilviaCoreManager API Reference

The SilviaCoreManager is a static class providing global lifecycle management for all SILVIA Core instances in your application. Think of it as the "kernel" that manages multiple AI engines.

Core Instance Management

CreateCore() - Multiple Overloads

Creates and initializes a new SILVIA Core instance. Critical for all SILVIA operations.

Standard Creation (Brain File)

csharp
public static SilviaCore CreateCore(
    string userName,
    string fileName, 
    bool boot,
    bool voiceTimer = false
)

Parameters:

  • userName: Unique identifier for this core instance (used for multi-user systems)
  • fileName: Path to .sil brain file, or null for empty core
  • boot: If true, executes behaviors in "boot" group after loading
  • voiceTimer: Enable voice timing calculations for speech synthesis

Returns: SilviaCore instance, or null if creation failed

Example:

csharp
// Production server with loaded brain
SilviaCore productionCore = SilviaCoreManager.CreateCore(
    "ProductionBot_01",
    "brains/customer_service.sil",
    boot: true,
    voiceTimer: false
);

// Development core - empty brain for testing
SilviaCore devCore = SilviaCoreManager.CreateCore(
    "DevTest",
    null,  // No brain file
    boot: false,
    voiceTimer: false
);

Advanced Creation (Binary Stream)

csharp
public static SilviaCore CreateCore(
    string userName,
    BinaryReader brainStream,
    string stopwords,
    string scriptClassType,
    string internalScriptClassName,
    string licensePath,
    object o
)

Parameters:

  • brainStream: Pre-loaded brain data as BinaryReader (for embedded resources)
  • stopwords: Comma-separated stopwords for linguistic processing
  • scriptClassType: Script engine type (default: "C#")
  • internalScriptClassName: Internal script class name
  • licensePath: Path to license file
  • o: Optional target object reference

Example:

csharp
// Load brain from embedded resource
using (Stream stream = Assembly.GetExecutingAssembly()
    .GetManifestResourceStream("MyApp.Resources.brain.sil"))
using (BinaryReader reader = new BinaryReader(stream))
{
    SilviaCore core = SilviaCoreManager.CreateCore(
        "EmbeddedSystem",
        reader,
        "the,a,an,is,are",  // Stopwords
        null,  // Default C# scripts
        null,  // Default script class
        "license.key",
        null
    );
}

CoreExists()

Checks if a core instance exists for a given user.

csharp
public static bool CoreExists(string userName)

Example:

csharp
if (SilviaCoreManager.CoreExists("SessionUser_42")) {
    // Core already created, reuse it
    var existingCore = SilviaCoreManager.GetCore("SessionUser_42");
} else {
    // Create new core for this session
    var newCore = SilviaCoreManager.CreateCore("SessionUser_42", "default.sil", true);
}

GetCore() - Retrieve Existing Instance

Retrieves an existing core by username or unique ID.

By Username:

csharp
public static SilviaCore GetCore(string userName)

By UID:

csharp
public static SilviaCore GetCore(Int64 uid)

Example:

csharp
// Multi-tenant web service
public string ProcessUserRequest(string userId, string input) {
    SilviaCore userCore = SilviaCoreManager.GetCore(userId);
    
    if (userCore == null) {
        // First request from this user - create core
        userCore = SilviaCoreManager.CreateCore(userId, "default_brain.sil", true);
    }
    
    return userCore.ApiBrain().GetResponse(input, null);
}

ReleaseCore() - Cleanup and Disposal

Properly releases a core instance, executing exit behaviors and cleaning up resources.

By Core Reference:

csharp
public static bool ReleaseCore(SilviaCore core)

By Username:

csharp
public static bool ReleaseCore(string userName)

By UID:

csharp
public static bool ReleaseCore(Int64 uid)

Example:

csharp
// Session cleanup
public void OnUserLogout(string userId) {
    SilviaCore userCore = SilviaCoreManager.GetCore(userId);
    
    if (userCore != null) {
        // Execute any "exit" behaviors (save state, cleanup)
        userCore.ApiBrain().SetJump("exit", "exit", 1.0f);
        
        // Give it time to complete
        System.Threading.Thread.Sleep(100);
        
        // Release resources
        SilviaCoreManager.ReleaseCore(userCore);
    }
}

ReleaseAllCores()

Releases all active core instances. Use with caution in production environments.

csharp
public static bool ReleaseAllCores()

Example:

csharp
// Application shutdown
public void OnApplicationShutdown() {
    Console.WriteLine("Shutting down all AI cores...");
    
    bool success = SilviaCoreManager.ReleaseAllCores();
    
    if (success) {
        Console.WriteLine("All cores released successfully.");
    }
}

SetCoreFileName()

Updates the brain file path associated with a core (for logging/tracking purposes).

csharp
public static bool SetCoreFileName(SilviaCore core, string fileName)

Inter-Core Communication: Coordinator Sensors

Coordinator sensors enable cross-core data sharing without direct coupling. Perfect for distributed AI systems where multiple cores need to coordinate.

CreateCoordinatorSensor()

Creates a shared sensor accessible by all cores.

csharp
public static bool CreateCoordinatorSensor(
    string sensorId,
    SensorDataType dataType,
    SensorDirection direction,
    ConnectionType connectionType,
    string connectionData
)

Example:

csharp
// Shared temperature sensor for all building AI cores
SilviaCoreManager.CreateCoordinatorSensor(
    sensorId: "building_ambient_temp",
    dataType: SensorDataType.Float,
    direction: SensorDirection.InputOnly,
    connectionType: ConnectionType.Network,
    connectionData: "192.168.1.100:8080"
);

// Now all cores can read this sensor value
// Core 1: HVAC control AI
// Core 2: Energy optimization AI
// Core 3: Occupancy comfort AI

SetCoordinatorSensorValue()

Updates a coordinator sensor value (broadcast to all cores).

csharp
public static bool SetCoordinatorSensorValue<T>(string sensorId, T value)

Example:

csharp
// Master control system updates shared state
SilviaCoreManager.SetCoordinatorSensorValue("system_status", "NORMAL");
SilviaCoreManager.SetCoordinatorSensorValue("threat_level", 0);
SilviaCoreManager.SetCoordinatorSensorValue("active_users", 1523);

// All subordinate AI cores can now access these values

ActivateCoordinatorSensors() / DeactivateCoordinatorSensors()

Controls whether coordinator sensors are actively updating.

csharp
public static bool ActivateCoordinatorSensors()
public static bool DeactivateCoordinatorSensors()

UpdateCoordinatorSensors()

Manually triggers an update of all coordinator sensors.

csharp
public static bool UpdateCoordinatorSensors()

Example:

csharp
// Main system loop
while (systemRunning) {
    // Update shared sensor data
    SilviaCoreManager.UpdateCoordinatorSensors();
    
    // Each core can now access latest values
    Thread.Sleep(100);
}

GetCoordinatorSensorCount() / GetCoordinatorSensorIds()

Query coordinator sensor system state.

csharp
public static int GetCoordinatorSensorCount()
public static string[] GetCoordinatorSensorIds()

Broadcasting: One-to-Many Communication

BroadcastText()

Sends a text message to all active cores.

csharp
public static bool BroadcastText(string message)

Example:

csharp
// System-wide notification
SilviaCoreManager.BroadcastText("MAINTENANCE MODE ACTIVATED");

// All cores receive this in their text output streams

BroadcastVoice()

Sends a voice message to all active cores.

csharp
public static bool BroadcastVoice(string message)

Example:

csharp
// Emergency announcement to all AI-driven systems
SilviaCoreManager.BroadcastVoice("Emergency shutdown initiated. Save all states.");

SilviaCore API Reference

The SilviaCore class represents an individual AI engine instance. Each core maintains its own:

  • Brain state (behaviors, concepts, scripts)
  • Variable storage (persistent key-value store)
  • Timed functions (scheduled callbacks)
  • API subsystem instances

Core Lifecycle & State

SetCreated()

Marks the core as fully initialized and ready for use.

csharp
public void SetCreated()

Example:

csharp
SilviaCore core = SilviaCoreManager.CreateCore("User1", "brain.sil", true);
core.SetCreated();  // Required after creation

SetActive()

Enables or disables the core for processing.

csharp
public void SetActive(bool active)

Example:

csharp
// Pause AI during maintenance
core.SetActive(false);

// Processing expensive operation...
Thread.Sleep(5000);

// Resume AI
core.SetActive(true);

Variable Management System

SILVIA's variable system provides type-safe, persistent state management with a simple convention:

  • User Variables: Start with $ (e.g., $player_health, $inventory_count)
  • System Variables: Start with $_ (e.g., $_a for AI name, $_u for user name)
  • Sensor Variables: Start with $@ (e.g., $@temperature, $@pressure)

Variables can store multiple values (pipe-separated) and support random retrieval for dynamic behavior.

SetVariable() - String, Int, Float

Sets a variable value with optional additive mode.

String Variable:

csharp
public bool SetVariable(string name, string value, bool additive = false)

Integer Variable:

csharp
public bool SetVariable(string name, int value, bool additive = false)

Float Variable:

csharp
public bool SetVariable(string name, float value, bool additive = false)

Parameters:

  • name: Variable name (must start with $)
  • value: Value to store
  • additive: If true, appends to existing values (pipe-separated)

Example:

csharp
// Simple string storage
core.SetVariable("$player_name", "Alice");
core.SetVariable("$current_level", "Forest_Temple");

// Numeric variables
core.SetVariable("$health", 100);
core.SetVariable("$score", 15000);
core.SetVariable("$multiplier", 1.5f);

// Multi-value variables (additive mode)
core.SetVariable("$inventory", "sword", false);  // Initial value
core.SetVariable("$inventory", "shield", true);   // Add second item
core.SetVariable("$inventory", "potion", true);   // Add third item
// Result: $inventory = "sword|shield|potion"

// System variables
core.SetVariable("$_a", "MyAssistant");  // AI name
core.SetVariable("$_u", "Player1");      // User name

Modern Use Cases:

csharp
// IoT Device Status
core.SetVariable("$device_status", "ONLINE");
core.SetVariable("$last_reading", DateTime.Now.ToString());
core.SetVariable("$battery_level", 87.5f);

// E-Commerce Session
core.SetVariable("$cart_total", 149.99f);
core.SetVariable("$item_count", 3);
core.SetVariable("$promo_code", "SAVE20");

// Medical Device
core.SetVariable("$patient_id", "P-2024-1523");
core.SetVariable("$heart_rate", 72);
core.SetVariable("$systolic_bp", 118);
core.SetVariable("$diastolic_bp", 76);

GetVariable() / GetString() / GetInt() / GetFloat()

Retrieves variable values with automatic type conversion.

Get as String:

csharp
public string GetVariable(string name, bool random_result = false)
public string GetString(string name, bool random_result = false)

Get as Integer:

csharp
public int GetInt(string name, bool random_result = false)

Get as Float:

csharp
public float GetFloat(string name, bool random_result = false)

Parameters:

  • name: Variable name to retrieve
  • random_result: If true and variable has multiple values, returns random value

Example:

csharp
// Simple retrieval
string playerName = core.GetVariable("$player_name");
int health = core.GetInt("$health");
float multiplier = core.GetFloat("$multiplier");

// Multi-value variables
core.SetVariable("$weapon", "sword", false);
core.SetVariable("$weapon", "axe", true);
core.SetVariable("$weapon", "bow", true);

// Get random weapon each time
string weapon1 = core.GetString("$weapon", true);  // "axe"
string weapon2 = core.GetString("$weapon", true);  // "sword"
string weapon3 = core.GetString("$weapon", true);  // "bow"

// Real-world: Dynamic NPC dialogue
core.SetVariable("$greeting", "Hello there!", false);
core.SetVariable("$greeting", "Greetings, traveler!", true);
core.SetVariable("$greeting", "Good to see you!", true);

string npcGreeting = core.GetString("$greeting", true);  // Random each time

Error Handling:

csharp
// Safe integer conversion
int value = core.GetInt("$invalid_number");  // Returns -1 on error
// Error message pushed to diagnostic output

// Check for null
string name = core.GetVariable("$nonexistent");
if (name == null) {
    Console.WriteLine("Variable does not exist");
}

SetVariables() - Batch Operations

Sets multiple variables simultaneously from name/value pair array.

csharp
public bool SetVariables(string[] nameValuePairs)

Example:

csharp
// Batch configuration
core.SetVariables(new string[] {
    "$server_url", "https://api.example.com",
    "$api_key", "sk-abc123xyz",
    "$timeout_ms", "5000",
    "$max_retries", "3",
    "$enable_caching", "true"
});

// Game state initialization
core.SetVariables(new string[] {
    "$level", "1",
    "$health", "100",
    "$mana", "50",
    "$gold", "0",
    "$experience", "0"
});

CopyVariable()

Copies all values from one variable to another.

csharp
public bool CopyVariable(string source, string destination)

Example:

csharp
// Backup current state
core.CopyVariable("$current_state", "$previous_state");

// Duplicate configuration
core.CopyVariable("$default_settings", "$user_settings");

RemoveFromVariable()

Removes a specific value from a multi-value variable.

csharp
public bool RemoveFromVariable(string name, string value)

Example:

csharp
// Inventory system
core.SetVariable("$inventory", "sword|shield|potion|torch");

// Player uses potion
core.RemoveFromVariable("$inventory", "potion");
// Result: $inventory = "sword|shield|torch"

ClearTrainerVariables() / ClearSensorVariables()

Bulk variable cleanup operations.

csharp
public bool ClearTrainerVariables()  // Clears all $ variables (keeps $_ system vars)
public bool ClearSensorVariables()   // Clears all $@ sensor variables

Example:

csharp
// Reset user session but keep system state
core.ClearTrainerVariables();

// System variables like $_a, $_u preserved
// User variables like $score, $inventory cleared

// Sensor cleanup
core.ClearSensorVariables();  // Removes $@temp, $@pressure, etc.

Timed Functions: Scheduled Execution

SILVIA's timer system enables scheduled callbacks with microsecond precision, critical for:

  • Periodic sensor polling
  • Timeout handling
  • Scheduled AI behaviors
  • Game loops and physics updates
  • Heartbeat monitoring
  • Rate limiting

AddTimedFunctionCS()

Schedules a C# method for delayed execution.

csharp
public int AddTimedFunctionCS(string name, double time, bool periodic)

Parameters:

  • name: Method name in brain scripts (must match exactly)
  • time: Delay in seconds (supports fractional seconds)
  • periodic: If true, repeats every time seconds

Returns: Integer ID of the timed function

Method Signature Required:

csharp
public bool MethodName(int id) {
    // Your code here
    return true;  // Must return bool
}

Example:

csharp
// One-time delayed execution
int timerId = core.AddTimedFunctionCS("CheckSensorStatus", 5.0, false);
// Executes once after 5 seconds

// Periodic execution (heartbeat)
int heartbeatId = core.AddTimedFunctionCS("SendHeartbeat", 1.0, true);
// Executes every 1 second

// In your brain script:
public bool CheckSensorStatus(int id) {
    string status = _core.ApiSensors().GetSensorValue<string>("system_status");
    _core.ApiApp().SetTextOutput($"Status check: {status}");
    return true;
}

public bool SendHeartbeat(int id) {
    _core.ApiSensors().ExecuteDatabaseNonQuery(
        "INSERT INTO heartbeats (timestamp) VALUES (@ts)",
        new[] { "@ts", DateTime.Now.ToString() }
    );
    return true;
}

Modern Use Cases:

csharp
// Timeout handler for user response
core.ApiBrain().GetResponse("Would you like to continue?");
int timeoutId = core.AddTimedFunctionCS("HandleNoResponse", 30.0, false);
// If no response in 30 seconds, execute timeout behavior

// Real-time monitoring
core.AddTimedFunctionCS("MonitorCpuUsage", 0.5, true);
core.AddTimedFunctionCS("MonitorMemory", 1.0, true);
core.AddTimedFunctionCS("MonitorDiskIO", 5.0, true);

// Game loop updates
core.AddTimedFunctionCS("UpdateEnemyAI", 0.016, true);  // ~60 FPS
core.AddTimedFunctionCS("UpdatePhysics", 0.020, true);  // 50 Hz

AddVariableTimedFunction()

Schedules a function with random interval between min and max time.

csharp
public int AddVariableTimedFunction(
    string name, 
    double minTime, 
    double maxTime, 
    bool periodic
)

Example:

csharp
// NPC behavior: Check surroundings every 3-7 seconds (variable)
core.AddVariableTimedFunction("NPC_LookAround", 3.0, 7.0, true);

// Random event spawner: 10-30 seconds
core.AddVariableTimedFunction("SpawnRandomEvent", 10.0, 30.0, true);

// Variable heartbeat (network jitter)
core.AddVariableTimedFunction("SendNetworkPing", 0.9, 1.1, true);

RemoveTimedFunctionCS() - Cancel Timers

Cancels a scheduled function by name or ID.

By Name:

csharp
public bool RemoveTimedFunctionCS(string name)

By ID:

csharp
public bool RemoveTimedFunctionIDCS(int id)

By ID Array:

csharp
public bool RemoveTimedFunctionsByIDs(int[] ids)

Example:

csharp
// User responds before timeout
int timeoutId = core.AddTimedFunctionCS("HandleTimeout", 30.0, false);

// User provides input
string userInput = GetUserInput();
if (!string.IsNullOrEmpty(userInput)) {
    // Cancel timeout since user responded
    core.RemoveTimedFunctionIDCS(timeoutId);
    core.ApiBrain().GetResponse(userInput);
}

// Cancel all monitoring timers
int[] monitorIds = new int[] { cpuTimerId, memTimerId, diskTimerId };
core.RemoveTimedFunctionsByIDs(monitorIds);

Timer Inspection & Control

Query and modify active timed functions.

Get Active Timers:

csharp
public string[] GetActiveTimedFunctionNames()
public int[] GetActiveTimedFunctionIDs()
public double[] GetActiveTimedFunctionsPeriods()
public double[] GetActiveTimedFunctionsMinPeriods()
public bool[] GetActiveTimedFunctionsArePeriodic()
public double[] GetActiveTimedFunctionsEndTimes()

Modify Timers:

csharp
// Change period
public bool SetActiveTimedFunctionPeriod(string name, double period)
public bool SetActiveTimedFunctionPeriod(int id, double period)

// Change min period (variable timers)
public bool SetActiveTimedFunctionMinPeriod(string name, double period)
public bool SetActiveTimedFunctionMinPeriod(int id, double period)

// Change both min and max (variable timers)
public bool SetActiveTimedFunctionVariability(
    string name, 
    double minPeriod, 
    double period
)

// Toggle periodic mode
public bool SetActiveTimedFunctionPeriodic(string name, bool periodic)

// Change next execution time
public bool SetActiveTimedFunctionEndTime(string name, double newEndTime)
public double GetActiveTimedFunctionEndTime(string name)

Example:

csharp
// Adaptive polling based on system load
if (cpuUsage > 80) {
    // Slow down polling under high load
    core.SetActiveTimedFunctionPeriod("MonitorCpu", 2.0);
} else {
    // Normal polling rate
    core.SetActiveTimedFunctionPeriod("MonitorCpu", 0.5);
}

// Debug: List all active timers
string[] timerNames = core.GetActiveTimedFunctionNames();
double[] periods = core.GetActiveTimedFunctionsPeriods();

for (int i = 0; i < timerNames.Length; i++) {
    Console.WriteLine($"{timerNames[i]}: {periods[i]} seconds");
}

Timer Lifecycle Management

PauseTimers() / ResumeTimers()

Globally pause/resume all timed functions.

csharp
public void PauseTimers()
public void ResumeTimers()
public bool PausedTimers()

Example:

csharp
// Pause during maintenance
core.PauseTimers();
PerformDatabaseMaintenance();
core.ResumeTimers();

// Check state
if (core.PausedTimers()) {
    Console.WriteLine("Timers are paused");
}

RefreshTimers() / RefreshTimersSeconds()

Manually trigger timer updates (usually handled automatically).

csharp
public bool RefreshTimers(long ticks)
public bool RefreshTimersSeconds(double seconds)

Example:

csharp
// Manual timer tick in custom game loop
while (gameRunning) {
    long currentTicks = DateTime.Now.Ticks;
    core.RefreshTimers(currentTicks);
    
    RenderFrame();
    ProcessInput();
}

Fixed Update Loop (Unity Integration)

For Unity-based applications or physics-synchronized execution.

SetFixedUpdateInterval()

Sets the fixed update interval in seconds.

csharp
public void SetFixedUpdateInterval(float seconds)

Example:

csharp
// Match Unity's FixedUpdate (50 Hz)
core.SetFixedUpdateInterval(0.02f);

AddFixedUpdateCallback() / RemoveFixedUpdateCallback()

Registers/unregisters callbacks for fixed updates.

csharp
public bool AddFixedUpdateCallback(Action method)
public bool RemoveFixedUpdateCallback(Action method)

Example:

csharp
// Physics-synchronized AI
void UpdatePhysicsAI() {
    // Called at fixed intervals
    ProcessPhysicsBasedAI();
}

core.AddFixedUpdateCallback(UpdatePhysicsAI);

// Later: remove callback
core.RemoveFixedUpdateCallback(UpdatePhysicsAI);

StartFixedUpdate() / ShutdownFixedUpdate()

Controls the fixed update loop.

csharp
public void StartFixedUpdate()
public void ShutdownFixedUpdate()
public void ClearFixedUpdateCallbacks()

High-Precision Timing

EnableHighPrecisionTiming()

Enables microsecond-accurate timing for real-time systems.

csharp
public void EnableHighPrecisionTiming(bool enabled)

Example:

csharp
// Industrial control system requiring precise timing
core.EnableHighPrecisionTiming(true);

// Schedule sub-millisecond tasks
core.AddTimedFunctionCS("SampleSensor", 0.001, true);  // 1ms sampling

Response Timing Utilities

Track input/output timing for latency monitoring.

csharp
public float GetLastInputTime()    // Seconds since last input
public float GetLastResponseTime() // Seconds since last response
public bool ResetLastInputTime()
public bool ResetLastResponseTime()

Example:

csharp
// Latency monitoring
core.ApiBrain().GetResponse(userInput);
float responseTime = core.GetLastResponseTime();

if (responseTime > 1.0f) {
    Console.WriteLine($"WARNING: Slow response ({responseTime}s)");
}

GetResponseManaged() - Unified Input Processing

The primary entry point for processing user input with full SILVIA feature support.

csharp
public bool GetResponseManaged(string input)

Features:

  • Addressing System: @!silvia, @!agent, @!human, ?@!return_address
  • CLI Commands: Input starting with $> processed as SILVIA LIVE commands
  • Normal Inference: Standard brain processing for conversation
  • Output Queuing: Results accessible via ApiApp().GetTextOutput(), etc.

Examples:

Standard Conversation:

csharp
core.GetResponseManaged("What is the weather today?");
string response = core.ApiApp().GetTextOutput();
// Response queued in text/voice output stacks

CLI Commands:

csharp
core.GetResponseManaged("$> status");
core.GetResponseManaged("$> live on");
core.GetResponseManaged("$> learn behavior greet,hello {a:text:hello}{e:text:Hi there!}");

Addressing Protocol:

csharp
// Address SILVIA specifically
core.GetResponseManaged("@!silvia What is your name?");

// Address agent (LLM), return to human
core.GetResponseManaged("@!agent ?@!human Explain quantum computing");

// Multi-recipient addressing
core.GetResponseManaged("@!silvia @!agent Coordinate response on topic X");

API Subsystem Access

The core provides centralized access to all SILVIA specialized APIs.

Primary APIs:

csharp
public SilviaApiBrain ApiBrain()           // Inference engine
public SilviaApiApp ApiApp()               // Output management
public SilviaApiMem ApiMem()               // Brain file operations
public SilviaApiData ApiData()             // Data utilities
public SilviaApiFeedback ApiFeedback()     // Conversational memory

Enterprise APIs:

csharp
public SilviaApiUser ApiUser()             // User management
public SilviaApiSensors ApiSensors()       // Sensor & Database integrations
public SilviaApiSensorsZeroAlloc ApiSensorsZeroAlloc()  // High-perf sensors

Specialized APIs:

csharp
public SilviaApiML ApiML()                 // Machine learning
public SilviaApiBallistics ApiBallistics() // Physics calculations
public SilviaApiLogistics ApiLogistics()   // Optimization algorithms
public SilviaApiFinance ApiFinance()       // Financial operations
public SilviaApiNavigation ApiNavigation() // Pathfinding
public SilviaApiComponents ApiComponents() // Component system
public SilviaApiMeshNet ApiMeshNet()       // Distributed networking
public SilviaApiNavajo ApiNavajo()         // Encryption
public SilviaApiModding ApiModding()       // Plugin system
public SilviaApiInterface ApiInterface()   // UI abstractions

Example:

csharp
// Access multiple subsystems
var brain = core.ApiBrain();
var sensors = core.ApiSensors();
var database = core.ApiSensors().GetSensor("masterDB");

// Coordinated operation
float temp = sensors.GetSensorValue<float>("warehouse_temp");
if (temp > 30.0f) {
    string alert = brain.GetResponse("Temperature critical");
    database.ExecuteNonQuery(
        "INSERT INTO alerts (message, timestamp) VALUES (@msg, @ts)",
        new[] { "@msg", alert, "@ts", DateTime.Now.ToString() }
    );
}

API Usage Tracking

Monitor API call volume for billing, debugging, or performance analysis.

csharp
public void EnableApiTracking(bool enabled)
public void SetApiTrackingUser(string userName)
public int GetTotalApiCalls()

Example:

csharp
// Enable tracking for this core
core.EnableApiTracking(true);
core.SetApiTrackingUser("CustomerTenant_42");

// Process operations...
core.ApiBrain().GetResponse(input);
core.ApiSensors().ExecuteDatabaseQuery("SELECT * FROM users");

// Check call volume
int totalCalls = core.GetTotalApiCalls();
Console.WriteLine($"Total API calls: {totalCalls}");

SilviaMultiThread - Thread-Safe Processing

For server environments with concurrent request processing.

csharp
public class SilviaMultiThread
{
    public SilviaMultiThread(SilviaCore core)
    public void SetInput(string input)
    public void GetResponse()  // Call from worker thread
    public string GetOutput()
    public bool IsLocked()
}

Example:

csharp
// Thread-safe request processor
public class AIRequestHandler {
    private SilviaCore _core;
    private Queue<SilviaMultiThread> _processors;
    
    public string ProcessRequest(string input) {
        // Get thread-safe wrapper
        SilviaMultiThread mt = new SilviaMultiThread(_core);
        mt.SetInput(input);
        
        // Process in background thread
        Thread worker = new Thread(() => mt.GetResponse());
        worker.Start();
        
        // Wait for completion
        while (mt.IsLocked()) {
            Thread.Sleep(10);
        }
        
        return mt.GetOutput();
    }
}

Best Practices & Patterns

1. Multi-Tenant Isolation

csharp
public class MultiTenantAIService {
    private Dictionary<string, SilviaCore> _userCores = new();
    
    public string ProcessUserInput(string userId, string input) {
        // Create or retrieve user-specific core
        if (!_userCores.ContainsKey(userId)) {
            SilviaCore userCore = SilviaCoreManager.CreateCore(
                userId, 
                "tenant_brain.sil", 
                boot: true
            );
            userCore.SetCreated();
            _userCores[userId] = userCore;
        }
        
        SilviaCore core = _userCores[userId];
        return core.ApiBrain().GetResponse(input, null);
    }
    
    public void CleanupInactiveUsers(TimeSpan maxIdle) {
        List<string> toRemove = new();
        
        foreach (var kvp in _userCores) {
            float lastInput = kvp.Value.GetLastInputTime();
            if (lastInput > maxIdle.TotalSeconds) {
                SilviaCoreManager.ReleaseCore(kvp.Value);
                toRemove.Add(kvp.Key);
            }
        }
        
        foreach (string userId in toRemove) {
            _userCores.Remove(userId);
        }
    }
}

2. Distributed System Coordination

csharp
// Master control core
SilviaCore masterCore = SilviaCoreManager.CreateCore("MasterControl", "master.sil", true);

// Create coordinator sensors for distributed state
SilviaCoreManager.CreateCoordinatorSensor(
    "system_state", SensorDataType.String, 
    SensorDirection.InputOutput, ConnectionType.Memory, ""
);
SilviaCoreManager.CreateCoordinatorSensor(
    "active_alerts", SensorDataType.Int, 
    SensorDirection.InputOutput, ConnectionType.Memory, ""
);

// Subordinate cores
SilviaCore buildingCore1 = SilviaCoreManager.CreateCore("Building1", "building.sil", true);
SilviaCore buildingCore2 = SilviaCoreManager.CreateCore("Building2", "building.sil", true);

// Master updates shared state
SilviaCoreManager.SetCoordinatorSensorValue("system_state", "NORMAL");
SilviaCoreManager.SetCoordinatorSensorValue("active_alerts", 0);

// All subordinate cores can now access this shared state
// Each operates independently but with coordinated awareness

3. Adaptive Timer Management

csharp
public class AdaptiveMonitoring {
    private SilviaCore _core;
    private int _cpuMonitorId;
    
    public void StartAdaptiveMonitoring() {
        _cpuMonitorId = _core.AddTimedFunctionCS("MonitorCPU", 1.0, true);
    }
    
    // In brain script
    public bool MonitorCPU(int id) {
        float cpuUsage = GetSystemCPUUsage();
        
        // Adapt polling rate based on load
        if (cpuUsage > 80.0f) {
            // High load: reduce polling frequency
            _core.SetActiveTimedFunctionPeriod(id, 5.0);
        } else if (cpuUsage < 20.0f) {
            // Low load: increase polling frequency
            _core.SetActiveTimedFunctionPeriod(id, 0.5);
        } else {
            // Normal load: standard frequency
            _core.SetActiveTimedFunctionPeriod(id, 1.0);
        }
        
        return true;
    }
}

4. Graceful Shutdown Pattern

csharp
public class AISystemManager {
    public void ShutdownAllSystems() {
        Console.WriteLine("Initiating graceful shutdown...");
        
        // 1. Pause all timer activity
        foreach (var core in GetAllCores()) {
            core.PauseTimers();
        }
        
        // 2. Execute exit behaviors
        SilviaCoreManager.BroadcastText("SHUTDOWN INITIATED");
        Thread.Sleep(500);  // Allow exit behaviors to execute
        
        // 3. Save critical state
        foreach (var core in GetAllCores()) {
            string userId = core.GetVariable("$_u");
            core.ApiMem().Save($"state/{userId}.sil", null);
        }
        
        // 4. Release resources
        bool success = SilviaCoreManager.ReleaseAllCores();
        
        Console.WriteLine($"Shutdown complete: {success}");
    }
}

5. Error Resilience

csharp
public class ResilientAIService {
    private SilviaCore _core;
    
    public string SafeGetResponse(string input) {
        try {
            // Attempt normal processing
            string response = _core.ApiBrain().GetResponse(input, null);
            
            if (string.IsNullOrEmpty(response)) {
                // Fallback: use default behavior
                _core.ApiBrain().SetJump("default", "fallback", 1.0f);
                response = _core.ApiApp().GetTextOutput();
            }
            
            return response;
            
        } catch (Exception ex) {
            // Log error
            _core.ApiApp().SetDiagOutput($"ERROR: {ex.Message}");
            
            // Attempt core recovery
            if (!RecoverCore()) {
                // Full reset required
                ReinitializeCore();
            }
            
            return "I apologize, but I encountered an error. Please try again.";
        }
    }
    
    private bool RecoverCore() {
        try {
            _core.ClearTrainerVariables();
            _core.ApiBrain().SetJump("boot", "boot", 1.0f);
            return true;
        } catch {
            return false;
        }
    }
    
    private void ReinitializeCore() {
        string userId = _core.GetVariable("$_u");
        SilviaCoreManager.ReleaseCore(_core);
        _core = SilviaCoreManager.CreateCore(userId, "brain.sil", true);
        _core.SetCreated();
    }
}

Platform Integration Examples

IoT Edge Device

csharp
// Raspberry Pi temperature control
SilviaCore deviceCore = SilviaCoreManager.CreateCore(
    "ThermostatDevice_01",
    "thermostat_brain.sil",
    boot: true,
    voiceTimer: false
);

deviceCore.SetCreated();
deviceCore.EnableHighPrecisionTiming(true);

// Fast sensor sampling
deviceCore.ApiSensors().CreateSensor(
    "room_temp",
    SensorDataType.Float,
    SensorDirection.InputOnly,
    ConnectionType.GPIO,
    "GPIO_PIN_17"
);

// Periodic control logic (100ms)
deviceCore.AddTimedFunctionCS("UpdateHeating", 0.1, true);

// In brain script:
public bool UpdateHeating(int id) {
    float currentTemp = _core.ApiSensors().GetSensorValue<float>("room_temp");
    float targetTemp = _core.GetFloat("$target_temperature");
    
    if (currentTemp < targetTemp - 0.5f) {
        // Turn on heating
        _core.SetVariable("$heater_state", "ON");
    } else if (currentTemp > targetTemp + 0.5f) {
        // Turn off heating
        _core.SetVariable("$heater_state", "OFF");
    }
    
    return true;
}

Cloud-Scale Microservice

csharp
// ASP.NET Core API endpoint
[ApiController]
[Route("api/ai")]
public class AIController : ControllerBase {
    private static SilviaCore _sharedCore;
    
    static AIController() {
        _sharedCore = SilviaCoreManager.CreateCore(
            "APIService",
            "api_brain.sil",
            boot: true
        );
        _sharedCore.SetCreated();
    }
    
    [HttpPost("query")]
    public async Task<IActionResult> ProcessQuery([FromBody] QueryRequest request) {
        // Thread-safe processing
        SilviaMultiThread mt = new SilviaMultiThread(_sharedCore);
        mt.SetInput(request.Query);
        
        await Task.Run(() => mt.GetResponse());
        
        while (mt.IsLocked()) {
            await Task.Delay(10);
        }
        
        return Ok(new { response = mt.GetOutput() });
    }
}

Unity Game Integration

csharp
using UnityEngine;
using CognitiveCode.Silvia.Api;

public class NPCAIController : MonoBehaviour {
    private SilviaCore _npcCore;
    
    void Start() {
        _npcCore = SilviaCoreManager.CreateCore(
            $"NPC_{gameObject.name}",
            "npc_brain.sil",
            boot: true
        );
        _npcCore.SetCreated();
        
        // Sync with Unity physics
        _npcCore.SetFixedUpdateInterval(Time.fixedDeltaTime);
        _npcCore.AddFixedUpdateCallback(UpdateAI);
        _npcCore.StartFixedUpdate();
        
        // Store Unity references
        _npcCore.SetVariable("$npc_position", transform.position.ToString());
    }
    
    void UpdateAI() {
        // Called at fixed intervals, synced with physics
        float playerDistance = Vector3.Distance(
            transform.position, 
            PlayerController.Instance.transform.position
        );
        
        _npcCore.SetVariable("$player_distance", playerDistance);
        
        // Let AI decide behavior
        if (playerDistance < 10.0f) {
            string action = _npcCore.ApiBrain().GetResponse("Player nearby");
            ExecuteNPCAction(action);
        }
    }
    
    void OnDestroy() {
        _npcCore.ShutdownFixedUpdate();
        SilviaCoreManager.ReleaseCore(_npcCore);
    }
}

Performance Considerations

Memory Footprint

  • Minimal Core: ~2-5 MB per instance (empty brain)
  • Typical Application: 10-50 MB per instance (loaded brain with behaviors)
  • Large Knowledge Base: 100-500 MB per instance (extensive brain files)

Execution Performance

  • Variable Access: < 10 microseconds
  • Timer Scheduling: < 50 microseconds
  • Brain Inference: 0.1-5 milliseconds (depends on brain complexity)
  • Multi-core Coordination: < 1 millisecond overhead

Scaling Guidelines

  • Single Server: 100-1000 concurrent cores (depending on brain complexity)
  • Kubernetes: Horizontal scaling with core-per-pod or multi-core-per-pod patterns
  • Edge Devices: 1-10 cores per device (ARM processors)

Troubleshooting

Core Creation Fails

csharp
SilviaCore core = SilviaCoreManager.CreateCore("User1", "brain.sil", true);
if (core == null) {
    // Check license file
    // Check brain file path
    // Check if core already exists
    if (SilviaCoreManager.CoreExists("User1")) {
        core = SilviaCoreManager.GetCore("User1");
    }
}

Timer Not Firing

csharp
// Ensure core is active
core.SetActive(true);

// Check if timers are paused
if (core.PausedTimers()) {
    core.ResumeTimers();
}

// Verify method signature matches:
public bool MethodName(int id) { return true; }

Variable Not Found

csharp
string value = core.GetVariable("$my_var");
if (value == null) {
    // Variable doesn't exist - set it first
    core.SetVariable("$my_var", "default_value");
}

High Memory Usage

csharp
// Periodic cleanup
core.ClearTrainerVariables();
core.ClearSensorVariables();

// Remove unused timers
int[] activeIds = core.GetActiveTimedFunctionIDs();
foreach (int id in activeIds) {
    // Remove if no longer needed
}

See Also


Documentation Status

Version: SILVIA Core 3.1

Released: November 2025

This documentation has been comprehensively reviewed and validated against the source code. All methods in the SILVIA Core API include:

  • XML documentation comments in source code
  • Complete parameter descriptions
  • Return value specifications
  • Usage examples where applicable

© Copyright Cognitive Code Corp. 2007-2026

SILVIA is a registered Trademark of Cognitive Code Corp.

SILVIA is a registered Trademark of Cognitive Code Corp.