Skip to content

SILVIA Core 3.1 - API Reference

Version: 3.1


Table of Contents

  1. Core Classes & Interfaces
  2. Integration Patterns
  3. Command-Line Interface (LIVE CLI)
  4. Code Examples
  5. Performance Characteristics

Introduction: API Design Philosophy

SILVIA Core's API architecture follows three guiding principles:

1. Separation of Concerns
APIs are organized by functional domain (Brain, App, Data, Mem, User, Sensors, etc.), not by implementation detail. Each API provides a coherent set of operations for a specific aspect of SILVIA functionality.

2. Progressive Disclosure
Common operations are simple. Advanced operations are available but don't clutter basic workflows. For example, GetResponse() handles 90% of inference needs, while SetJump(), NextResponse(), and behavior manipulation provide fine-grained control when needed.

3. Type Safety with Flexibility
Strongly-typed C# interfaces provide compile-time safety and IntelliSense support, while string-based variable access and dynamic scripting enable runtime flexibility.


Core Classes & Interfaces

Primary Entry Points

SILVIA Core provides three primary entry points for different deployment scenarios:

SilviaCoreManager (Multi-Tenant Server Deployment)

Purpose: Manage multiple SILVIA cores in a single process, typically for server-side multi-user applications.

Key Capabilities:

  • Create/retrieve/release cores by instance ID
  • Thread-safe core access with automatic locking
  • Coordinator sensor routing between cores
  • Graceful shutdown with cleanup

Core Methods:

csharp
class SilviaCoreManager {
    // Core Lifecycle
    static SilviaCore CreateCore(string instanceId);
    static SilviaCore GetCore(string instanceId);
    static bool ReleaseCore(string instanceId);
    static void ReleaseAllCores();
    
    // Multi-Core Operations
    static string[] GetAllCoreIDs();
    static int GetActiveCoreCount();
    static bool CoreExists(string instanceId);
    
    // Coordinator Routing
    static void EnableCoordinatorBroadcasting(bool enabled);
    static void RegisterCoordinatorSensor(string eventType, Action<string, string> handler);
}

Typical Usage Pattern:

csharp
// Server application with multiple users
var coreUser1 = SilviaCoreManager.CreateCore("user_12345");
var coreUser2 = SilviaCoreManager.CreateCore("user_67890");

// Each core operates independently
coreUser1.ApiBrain().GetResponseManaged("Hello");
coreUser2.ApiBrain().GetResponseManaged("Hi there");

// Cores can coordinate via sensors
SilviaCoreManager.EnableCoordinatorBroadcasting(true);
coreUser1.ApiSensors().BroadcastToCoordinators("user_active", "user_12345");
// coreUser2 receives event if subscribed

// Cleanup
SilviaCoreManager.ReleaseCore("user_12345");
SilviaCoreManager.ReleaseCore("user_67890");

SilviaCore (Single-Instance Deployment)

Purpose: Individual SILVIA instance with full API access, used for embedded, desktop, or single-tenant applications.

Key Capabilities:

  • Direct API access through typed interfaces
  • Variable management (user, system, sensor)
  • Timed functions with microsecond precision
  • Fixed update loop integration (Unity/physics)
  • Lifecycle management (initialization, shutdown)

Core Methods:

csharp
class SilviaCore {
    // API Access
    SilviaApiBrain ApiBrain();
    SilviaApiApp ApiApp();
    SilviaApiData ApiData();
    SilviaApiMem ApiMem();
    SilviaApiUser ApiUser();
    SilviaApiFeedback ApiFeedback();
    SilviaApiSensors ApiSensors();
    // ... plus extended APIs
    
    // Variable Management
    string GetVariable(string name);
    bool SetVariable(string name, string value);
    bool DeleteVariable(string name);
    Dictionary<string, string> GetAllVariables();
    
    // Timed Functions
    bool AddTimedFunction(string functionName, Action callback, long intervalMicroseconds);
    bool RemoveTimedFunction(string functionName);
    bool UpdateTimedFunctionInterval(string functionName, long newIntervalMicroseconds);
    
    // Fixed Update (Unity/Physics Integration)
    void SetFixedUpdateInterval(double intervalSeconds);
    void AddFixedUpdateCallback(Action<double> callback);
    void RemoveFixedUpdateCallback(Action<double> callback);
    
    // Lifecycle
    bool Initialize(string brainFilePath);
    void Shutdown();
    bool IsActive();
}

Variable Naming Conventions:

csharp
// User variables (persistent across sessions if saved)
core.SetVariable("$user_name", "John Doe");
core.SetVariable("$score", "1250");

// System variables (runtime state, not saved)
core.SetVariable("$_session_id", Guid.NewGuid().ToString());
core.SetVariable("$_last_response_time", DateTime.Now.ToString());

// Sensor variables (external data, not saved)
core.SetVariable("$@temperature", "72.5");
core.SetVariable("$@gps_lat", "35.2");

SilviaMultiThread (Concurrent Request Processing)

Purpose: Thread-safe wrapper for SilviaCore enabling concurrent request processing from multiple threads.

Key Capabilities:

  • Automatic request queuing and serialization
  • Thread-safe API method forwarding
  • Maintains SILVIA's deterministic execution while handling concurrent requests

Core Methods:

csharp
class SilviaMultiThread {
    // Constructor
    SilviaMultiThread(SilviaCore core);
    
    // Forwarded API Access (thread-safe)
    SilviaApiBrain ApiBrain();
    SilviaApiApp ApiApp();
    // ... all APIs forwarded
    
    // Thread-safe operations are queued internally
    // Execution remains deterministic despite concurrent calls
}

When to Use:

  • Web server handling multiple simultaneous requests
  • API gateway with concurrent client connections
  • Any scenario where multiple threads need SILVIA access

API Subsystems

SILVIA Core organizes functionality into specialized API subsystems, each accessed through the core instance:

SilviaApiBrain - Inference & Behavior Execution

Purpose: Natural language understanding, behavior matching, response generation, and execution control.

Key Operations:

  • GetResponse(input, io_log) - Process input and generate response
  • NextResponse(io_log, out response) - Get next stacked response
  • SetJump(group, name, probability) - Request behavior execution
  • SetUserSecurityLevel(level) - Configure security clearance
  • GetResponseBehaviorID(index) - Identify which behavior matched

See: ApiBrain for complete documentation.


SilviaApiApp - Application Interface & Output Control

Purpose: Manage outputs (text, voice, socket, data), command processing, and application state.

Key Operations:

  • GetTextOutput() - Retrieve text response for display
  • SetVoiceOutput(text) - Queue text for speech synthesis
  • ProcessCommand(command) - Execute CLI commands
  • GetApproximateSpeechLength(text) - Estimate TTS duration
  • ClearAllOutputs() - Reset output buffers

See: ApiApp for complete documentation.


SilviaApiData - Knowledge Base Construction

Purpose: Build and modify AI knowledge at runtime—concepts, bindings, behaviors, and patterns.

Key Operations:

  • GetOrAddConcept(text) - Get or create concept ID
  • SetBinding(root, bound, type) - Create semantic relationships
  • AddBehavior(group, name, absorbers, exuders) - Create behavior dynamically
  • GetConceptUsageCount(conceptId) - Track concept popularity

See: ApiData for complete documentation.


SilviaApiMem - Brain File Management

Purpose: Load, save, merge, and manage brain files and expert text.

Key Operations:

  • Load(filename, merge, boot) - Load brain from disk
  • Save(filename, groups, saveState) - Persist brain to disk
  • MergeText(expertText) - Add behaviors from Expert Text format
  • GetAllGroups() - List all behavior groups
  • GroupEnable(groupName, enabled) - Enable/disable group

See: ApiMem for complete documentation.


SilviaApiUser - Multi-User Management

Purpose: Handle user sessions, data isolation, and resource tracking in multi-tenant deployments.

Key Operations:

  • CreateUser(userId) - Initialize user session
  • GetUser(userId) - Retrieve user core
  • RemoveUser(userId) - Cleanup user session
  • GetActiveUsers() - List current users
  • GetStatistics() - Resource usage metrics

See: ApiUser for complete documentation.


SilviaApiFeedback - Spontaneous Thought Generation

Purpose: Enable proactive AI through conversational memory and spontaneous utterance generation.

Key Operations:

  • SetActive(active, clear) - Enable/disable spontaneous generation
  • AddFeedback(text) - Add to conversational memory
  • SetInterval(min, max) - Control spontaneous timing
  • Search(user, concepts, dateRange) - Query conversation history
  • Write(username, filename) - Persist conversational memory

See: ApiFeedback for complete documentation.


SilviaApiSensors - Event Broadcasting & Coordination

Purpose: Inter-core communication, event-driven triggers, and sensor data integration.

Key Operations:

  • BroadcastToCoordinators(eventType, data) - Send event to other cores
  • RegisterCoordinatorSensor(eventType, handler) - Subscribe to events
  • SetSensorValue(sensorName, value) - Update sensor variable
  • GetSensorHistory(sensorName, count) - Retrieve sensor data timeline

See: ApiSensors for complete documentation.


Integration Patterns

SILVIA Core supports three primary integration patterns, each optimized for different deployment scenarios.

Pattern 1: Embedded Integration (Direct API Access)

Scenario: SILVIA Core embedded directly in your application code (C#, Unity, .NET).

Architecture:

Your Application

Direct API Calls

SilviaCore Instance

Brain File (.sil)

Advantages:

  • Lowest latency (microsecond response times)
  • No network overhead
  • Full API access
  • Compile-time type safety

Typical Use Cases:

  • Desktop applications
  • Unity game AI
  • Embedded robotics
  • Real-time control systems

Basic Integration:

[CODE EXAMPLE 1 - TO BE REVIEWED]

I'll present a proposed embedded integration example. This will demonstrate:

  1. Core initialization
  2. Brain loading
  3. Basic inference with GetResponse
  4. Variable access
  5. Timed function setup

Here's my proposed example:

csharp
using CognitiveCode.Silvia.Api;
using CognitiveCode.Silvia.Core;

public class EmbeddedSilviaExample {
    private SilviaCore core;
    
    public void Initialize() {
        core = SilviaCoreManager.CreateCore("embedded_agent");
        
        bool loaded = core.ApiMem().Load("brains/assistant.sil", merge: false, boot: true);
        if (!loaded) {
            core.ApiApp().SetErrorOutput("Failed to load brain file: brains/assistant.sil");
            return;
        }
        
        core.ApiBrain().SetUserSecurityLevel(100);
        
        core.SetVariable("$user_name", "John");
        core.SetVariable("$@temperature", "72.5");
        
        core.AddTimedFunctionCS("health_check", HealthCheckCallback, 5_000_000);
        
        core.ApiApp().SetDiagOutput("SILVIA Core initialized and ready");
    }
    
    public string ProcessUserInput(string input) {
        string[] response = core.ApiBrain().GetResponseManaged(input);
        
        if (response != null && response.Length > 0) {
            string textOutput = response[0];
            string voiceOutput = response[1];
            
            if (response.Length > 2) {
                string behaviorData = response[2];
                ProcessBehaviorData(behaviorData);
            }
            
            return textOutput;
        }
        
        return "No response generated";
    }
    
    private void HealthCheckCallback() {
        int apiCalls = core.GetTotalApiCalls();
        string lastResponse = core.GetVariable("$_last_response");
        
        core.SetVariable("$_api_call_count", apiCalls.ToString());
        core.SetVariable("$_health_check_time", DateTime.Now.ToString());
        
        core.ApiBrain().SetJump("monitoring", "ReportHealthStatus", 1.0f);
    }
    
    private void ProcessBehaviorData(string data) {
        core.ApiApp().SetDiagOutput($"Behavior Data Received: {data}");
    }
    
    public void Shutdown() {
        core.ApiMem().Save("brains/assistant_state.sil", groups: null, saveState: true);
        SilviaCoreManager.ReleaseCore("embedded_agent");
    }
}

// Usage:
EmbeddedSilviaExample agent = new EmbeddedSilviaExample();
agent.Initialize();

string response = agent.ProcessUserInput("What is the current temperature?");
string diagOutput = agent.core.ApiApp().GetDiagOutput();
// diagOutput: "SILVIA Core initialized and ready"

// AI processes input, health check runs every 5 seconds
// Triggers "ReportHealthStatus" behavior which reads $_api_call_count and $_health_check_time

agent.Shutdown();

Expected Behavior Definition:

[monitoring ReportHealthStatus]
@SECURITY 50

< *

> System Health: API Calls: [$_api_call_count], Last Check: [$_health_check_time]

@SCRIPT
public bool Invoke() {
    string apiCalls = _core.GetVariable("$_api_call_count");
    string checkTime = _core.GetVariable("$_health_check_time");
    
    _core.ApiApp().SetDiagOutput($"Health Status - API Calls: {apiCalls}, Last Check: {checkTime}");
    
    if (int.Parse(apiCalls) > 10000) {
        _core.ApiSensors().BroadcastToCoordinators("high_api_usage", apiCalls);
    }
    
    return true;
}
@ENDSCRIPT

Pattern 2: REST/HTTP Integration (Server Deployment)

Scenario: SILVIA Core as a backend service with REST API endpoints.

Architecture:

HTTP Clients (Web, Mobile, etc.)

REST API Controller

SilviaCoreManager (Multi-Tenant)

Per-User SilviaCore Instances

Advantages:

  • Language-agnostic clients (any HTTP client)
  • Scalable across multiple servers
  • Standard authentication/authorization integration
  • Load balancing and caching support

Typical Use Cases:

  • Web applications
  • Mobile app backends
  • Microservice architectures
  • API gateways

Implementation Example:

csharp
using Microsoft.AspNetCore.Mvc;
using CognitiveCode.Silvia.Api;
using CognitiveCode.Silvia.Core;

[ApiController]
[Route("api/silvia")]
public class SilviaController : ControllerBase {
    
    [HttpPost("chat")]
    public IActionResult ProcessChat([FromBody] ChatRequest request) {
        string userId = GetUserIdFromAuth();
        
        SilviaCore core = SilviaCoreManager.GetCore(userId);
        if (core == null) {
            core = SilviaCoreManager.CreateCore(userId);
            bool loaded = core.ApiMem().Load("brains/customer_service.sil", false, true);
            if (!loaded) {
                return StatusCode(500, new { error = "Failed to initialize AI core" });
            }
        }
        
        string[] response = core.ApiBrain().GetResponseManaged(request.Message);
        
        if (response != null && response.Length > 0) {
            ChatResponse chatResponse = new ChatResponse {
                Text = response[0],
                Voice = response[1],
                BehaviorId = core.ApiBrain().GetResponseBehaviorID(0),
                Timestamp = DateTime.UtcNow
            };
            
            return Ok(chatResponse);
        }
        
        return Ok(new ChatResponse { 
            Text = "I didn't understand that. Could you rephrase?",
            Timestamp = DateTime.UtcNow
        });
    }
    
    [HttpPost("variable")]
    public IActionResult SetVariable([FromBody] VariableRequest request) {
        string userId = GetUserIdFromAuth();
        SilviaCore core = SilviaCoreManager.GetCore(userId);
        
        if (core == null) {
            return NotFound(new { error = "Core not initialized for this user" });
        }
        
        bool success = core.SetVariable(request.Name, request.Value);
        return Ok(new { success = success });
    }
    
    [HttpGet("variable/{name}")]
    public IActionResult GetVariable(string name) {
        string userId = GetUserIdFromAuth();
        SilviaCore core = SilviaCoreManager.GetCore(userId);
        
        if (core == null) {
            return NotFound(new { error = "Core not initialized for this user" });
        }
        
        string value = core.GetVariable(name);
        return Ok(new { name = name, value = value });
    }
    
    [HttpPost("jump")]
    public IActionResult ExecuteBehavior([FromBody] BehaviorRequest request) {
        string userId = GetUserIdFromAuth();
        SilviaCore core = SilviaCoreManager.GetCore(userId);
        
        if (core == null) {
            return NotFound(new { error = "Core not initialized for this user" });
        }
        
        bool jumped = core.ApiBrain().SetJump(
            request.Group, 
            request.Name, 
            request.Probability
        );
        
        string textOutput = core.ApiApp().GetTextOutput();
        string diagOutput = core.ApiApp().GetDiagOutput();
        string errorOutput = core.ApiApp().GetErrorOutput();
        
        return Ok(new { 
            success = jumped,
            text = textOutput,
            diagnostics = diagOutput,
            errors = errorOutput
        });
    }
    
    private string GetUserIdFromAuth() {
        return User.Identity.Name ?? "anonymous";
    }
}

public class ChatRequest {
    public string Message { get; set; }
}

public class ChatResponse {
    public string Text { get; set; }
    public string Voice { get; set; }
    public int BehaviorId { get; set; }
    public DateTime Timestamp { get; set; }
}

public class VariableRequest {
    public string Name { get; set; }
    public string Value { get; set; }
}

public class BehaviorRequest {
    public string Group { get; set; }
    public string Name { get; set; }
    public float Probability { get; set; }
}

Thread Safety Considerations:

For high-concurrency REST deployments, wrap cores in SilviaMultiThread:

csharp
private static Dictionary<string, SilviaMultiThread> threadSafeCores = 
    new Dictionary<string, SilviaMultiThread>();

private SilviaMultiThread GetThreadSafeCore(string userId) {
    if (!threadSafeCores.ContainsKey(userId)) {
        SilviaCore core = SilviaCoreManager.CreateCore(userId);
        core.ApiMem().Load("brains/customer_service.sil", false, true);
        threadSafeCores[userId] = new SilviaMultiThread(core);
    }
    return threadSafeCores[userId];
}

Pattern 3: WebSocket Integration (Real-Time Communication)

Scenario: Low-latency bidirectional communication for real-time applications.

Architecture:

WebSocket Clients

WebSocket Server (SignalR/ASP.NET)

SilviaCore with Coordinator Sensors

Real-time Event Broadcasting

Advantages:

  • Sub-100ms latency for responses
  • Server-push capabilities for spontaneous AI
  • Persistent connection for conversational context
  • Coordinator sensor events stream to clients

Typical Use Cases:

  • Real-time chat applications
  • Collaborative AI agents
  • Live monitoring dashboards
  • Interactive training systems

Implementation Example (SignalR):

csharp
using Microsoft.AspNetCore.SignalR;
using CognitiveCode.Silvia.Api;
using CognitiveCode.Silvia.Core;

public class SilviaHub : Hub {
    private static Dictionary<string, SilviaCore> userCores = 
        new Dictionary<string, SilviaCore>();
    
    public override async Task OnConnectedAsync() {
        string userId = Context.ConnectionId;
        
        SilviaCore core = SilviaCoreManager.CreateCore(userId);
        bool loaded = core.ApiMem().Load("brains/realtime_assistant.sil", false, true);
        
        if (loaded) {
            core.ApiSensors().RegisterCoordinatorSensor("ai_response", 
                (eventType, data) => OnAIResponse(userId, data));
            
            core.ApiFeedback().SetActive(true, true);
            core.ApiFeedback().SetInterval(5.0f, 10.0f);
            
            userCores[userId] = core;
            
            await Clients.Caller.SendAsync("Connected", 
                new { message = "SILVIA Core initialized", userId = userId });
        } else {
            await Clients.Caller.SendAsync("Error", 
                new { message = "Failed to load AI brain" });
        }
        
        await base.OnConnectedAsync();
    }
    
    public async Task SendMessage(string message) {
        string userId = Context.ConnectionId;
        
        if (!userCores.ContainsKey(userId)) {
            await Clients.Caller.SendAsync("Error", 
                new { message = "Core not initialized" });
            return;
        }
        
        SilviaCore core = userCores[userId];
        
        string[] response = core.ApiBrain().GetResponseManaged(message);
        
        if (response != null && response.Length > 0) {
            await Clients.Caller.SendAsync("AIResponse", new {
                text = response[0],
                voice = response[1],
                behaviorId = core.ApiBrain().GetResponseBehaviorID(0),
                timestamp = DateTime.UtcNow
            });
            
            core.ApiFeedback().AddFeedback(message);
            core.ApiFeedback().AddFeedback(response[0]);
        }
    }
    
    public async Task SetVariable(string name, string value) {
        string userId = Context.ConnectionId;
        
        if (userCores.ContainsKey(userId)) {
            SilviaCore core = userCores[userId];
            bool success = core.SetVariable(name, value);
            
            await Clients.Caller.SendAsync("VariableSet", 
                new { name = name, value = value, success = success });
        }
    }
    
    private async void OnAIResponse(string userId, string data) {
        await Clients.Client(userId).SendAsync("CoordinatorEvent", new {
            eventType = "ai_response",
            data = data,
            timestamp = DateTime.UtcNow
        });
    }
    
    public override async Task OnDisconnectedAsync(Exception exception) {
        string userId = Context.ConnectionId;
        
        if (userCores.ContainsKey(userId)) {
            SilviaCore core = userCores[userId];
            core.ApiMem().Save($"state/{userId}_session.sil", null, true);
            SilviaCoreManager.ReleaseCore(userId);
            userCores.Remove(userId);
        }
        
        await base.OnDisconnectedAsync(exception);
    }
}

Client-Side Usage (JavaScript):

javascript
const connection = new signalR.HubConnectionBuilder()
    .withUrl("/silviahub")
    .build();

connection.on("AIResponse", (response) => {
    console.log("AI:", response.text);
    displayMessage(response.text, "ai");
});

connection.on("CoordinatorEvent", (event) => {
    console.log("Event:", event.eventType, event.data);
});

connection.start().then(() => {
    console.log("Connected to SILVIA");
    
    connection.invoke("SendMessage", "Hello SILVIA");
});

Command-Line Interface (LIVE CLI)

SILVIA Core includes a powerful command-line interface (CLI) accessible through SilviaLIVEcli, enabling real-time brain manipulation, behavior authoring, and system control without recompilation.

Overview: Interactive AI Development

The LIVE CLI provides a complete development environment for SILVIA brains, accessible via:

  • Direct API calls: core.ApiApp().ProcessCommand("$> command")
  • Chat integration: Commands prefixed with $> in conversation
  • LLM collaboration: Language models can use CLI to build and modify behaviors

Key Insight:
The CLI enables collaborative AI development—humans and LLMs can work together in a shared chat context to author, test, and refine deterministic AI agents in real-time. This is the first behavior-based agent system with groupchat-style collaborative authoring.

Critical Syntax Rules

BRACKET NESTING IS MANDATORY:

  • Absorbers: {a:{text:pattern}} - NOT {a:pattern}
  • Exuders: {e:{text:response}} - NOT {e:response}
  • All parameters must be properly nested inside their parent braces
  • Improper nesting will cause the command to fail or miswrite the record

EXUDERS ARE REQUIRED:

  • ALL behaviors must have at least one {e:{text:...}} exuder
  • Behaviors without exuders will be rejected
  • Absorbers {a:{text:...}} are optional (for output-only behaviors)

CLI Architecture

User/LLM Input: "$> learn behavior assistant,greet {e:{text:Hello!}}"

SilviaLIVEcli.ProcessCommand()

Parse Command + Parameters

Execute Operation on Live Brain

Return Formatted Response

Continue Conversation

CLI Command Categories

The CLI provides 150+ commands organized into 8 categories:

1. Learning Commands (Live Behavior Authoring)

Create behaviors with proper bracket nesting:

Create Complete Behavior (Input + Output):

$> learn behavior assistant,greet {a:{text:hello|hi|hey there}}{e:{text:Hello! How can I assist you today?}}

Response:

Behavior Added at: 42: assistant,greet

Create Output-Only Behavior (No Absorber):

$> learn behavior monitoring,health_check {e:{text:System Status: OK - Uptime: $_uptime seconds}}

Response:

Behavior Added at: 43: monitoring,health_check
(+) Output-only behavior created (no absorbers). Trigger via SetJump or SetJumpToGroup.

Multiple Absorbers and Exuders:

$> learn behavior assistant,farewell {a:{text:goodbye|bye|see you}}{a:{text:talk to you later}}{e:{text:Goodbye! Take care!}}{e:{text:See you soon!}}

Response:

Behavior Added at: 44: assistant,farewell

With Security Level and Metadata:

$> learn behavior admin,shutdown {notes:"Emergency system shutdown"}{securitylevel:5}{a:{text:shutdown now}}{e:{text:System shutdown initiated...}}

Response:

Behavior Added at: 45: admin,shutdown

Add Absorber to Existing Behavior:

$> learn absorber assistant,greet {a:{text:good morning}{exact}}

Response:

Absorber learned successfully.

Add Exuder with Scripts:

$> learn exuder assistant,greet {e:{text:Good morning, $user_name !}{context:friendly greeting}{pre:public bool Invoke() { _core.SetVariable("$_last_greeting", "morning"); return true; }}}

Response:

Exuder learned successfully.

Complex Absorber with Required Words:

$> learn absorber weapons,target_lock {a:{text:engage target at * *}{requiredWords:true,true,true,false,false}}

Response:

Absorber learned successfully.

Learn Concept Bindings:

$> learn concept {name:photosynthesis}{bind:plant,synonym}{bind:chlorophyll,related}

2. Modification Commands

Update existing elements:

Set Variable:

$> set variable $user_level 5

Response:

Variable set successfully.

Set Multiple Variables:

$> set variable $user_name "John Doe" | $user_level 5 | $user_status "active"

Response:

$user_name = John Doe; $user_level = 5; $user_status = active;

Modify Absorber:

$> set absorber assistant,greet,0 {text:hello there|hi there}{exact}

Modify Exuder:

$> set exuder assistant,greet,0 {text:Hi there! How may I help you?}{dynamic}

Set Behavior Security Level:

$> set behavior admin,shutdown {securitylevel:5}

Configure Brain Settings:

$> set config absorberthreshold 0.7
$> set config contextdepth 5
$> set config securitylevel 3

3. Inspection Commands

Query brain state:

Get Behavior Details:

$> get behavior assistant,greet

Response:

Behavior: assistant,greet (ID: 42)
Security Level: 0
Absorbers: 2
Exuders: 3
Scripts: val, pre

List All Behaviors:

$> behaviors

Response:

Total Behaviors: 156
[Group: assistant]
  - greet (ID: 42)
  - farewell (ID: 44)
[Group: admin]
  - shutdown (ID: 45)
  - restart (ID: 46)
...

Get Variable Value:

$> get variable $user_name

Response:

$user_name = "John Doe"

List All Variables:

$> get variables

Response:

USER VARIABLES ($):
  $user_name = "John Doe"
  $user_level = "5"
SYSTEM VARIABLES ($_):
  $_api_call_count = "1247"
  $_uptime = "3600"
SENSOR VARIABLES ($@):
  $@weather_status = "sunny, 72°F"

Get Concept Information:

$> get concept photosynthesis

Response:

Concept: photosynthesis (ID: 1523)
Usage Count: 8
Bindings:
  - plant (synonym)
  - chlorophyll (related)

Brain Statistics:

$> status

Response:

SILVIA Brain Status:
Behaviors: 156
Concepts: 2431
Groups: 12
Optimization: Enabled
Randomization: Disabled
Context Depth: 5
Security Level: 1

4. Removal Commands

Delete elements:

Remove Behavior:

$> remove behavior assistant,greet

Response:

Behavior deleted at: 42: assistant,greet

Remove Absorber:

$> remove absorber assistant,greet,0

Response:

Absorber removed from behavior assistant,greet

Remove Exuder:

$> remove exuder assistant,greet,1

Response:

Exuder removed from behavior assistant,greet

Delete Variable:

$> remove variable $temp_data

Response:

Variable $temp_data removed.

5. File Management Commands

Manage brain files:

Load Brain:

$> load brains/assistant.sil

Response:

Brain loaded successfully from brains/assistant.sil
Behaviors: 156, Concepts: 2431

Save Brain:

$> save brains/assistant_updated.sil

Response:

Brain saved successfully to brains/assistant_updated.sil

Save Brain with State:

$> save brains/assistant_session.sil state

Response:

Brain saved with variable state to brains/assistant_session.sil

Merge Brain:

$> merge brains/extension.sil

Response:

Brain merged successfully. Added 24 behaviors, 156 concepts.

Export to Text:

$> export brains/assistant_readable.txt

Response:

Brain exported to text format: brains/assistant_readable.txt

6. Script Commands

Add or modify C# scripts:

Add Validator Script:

$> set behavior script val assistant,greet
public bool Invoke() {
    string username = _core.GetVariable("$user_name");
    if (string.IsNullOrEmpty(username)) {
        return false;
    }
    return true;
}
@ENDSCRIPT

Response:

Validator script added to assistant,greet

Add Pre-Execution Script:

$> set behavior script pre assistant,greet
public bool Invoke() {
    string currentCount = _core.GetVariable("$_greet_count") ?? "0";
    int count = int.Parse(currentCount) + 1;
    _core.SetVariable("$_greet_count", count.ToString());
    return true;
}
@ENDSCRIPT

Response:

Pre-execution script added to assistant,greet

Add Post-Execution Script:

$> set behavior script post assistant,greet
public bool Invoke() {
    string userName = _core.GetVariable("$user_name");
    _core.ApiSensors().BroadcastToCoordinators("greeting_sent", userName);
    return true;
}
@ENDSCRIPT

Response:

Post-execution script added to assistant,greet

7. Live Mode & Training

Control interactive mode:

Enable Live Training Mode:

$> live on

Response:

SILVIA LIVE mode enabled. Learning commands are now active.

Disable Live Mode:

$> live off

Response:

SILVIA LIVE mode disabled. Learning commands are now restricted.

Check Live Status:

$> live status

Response:

SILVIA LIVE mode: Enabled
WordNet: Disabled
Optimization: Enabled

8. Undo/Redo System

128-level deep undo stack:

Undo Last Operation:

$> undo

Response:

Undone: Added behavior assistant,greet

Undo Multiple Operations:

$> undo 5

Response:

Undone 5 operations.

Redo Operation:

$> redo

Response:

Redone: Added behavior assistant,greet

View Undo History:

$> undo history

Response:

Undo Stack (128 max):
[5] Added exuder to assistant,greet
[4] Added absorber to assistant,greet
[3] Created behavior assistant,greet
[2] Set variable $user_name
[1] Loaded brain assistant.sil

Complete CLI Workflow Example

Creating a Complete Behavior from Scratch:

$> learn behavior assistant,greet {a:{text:hello|hi|hey}}{a:{text:good morning}}{e:{text:Hello! How can I assist you today?}}{e:{text:Hi there! What can I do for you?}}

Response:

Behavior Added at: 42: assistant,greet

Testing the Behavior:

hello

Response:

Hello! How can I assist you today!

Adding Advanced Features:

$> learn exuder assistant,greet {e:{text:Welcome back, $user_name !}{context:returning user greeting}{val:public bool Invoke() { string name = _core.GetVariable("$user_name"); return !string.IsNullOrEmpty(name); }}}

Response:

Exuder learned successfully.

Saving the Brain:

$> save brains/assistant_v1.sil

Response:

Brain saved successfully to brains/assistant_v1.sil

Programmatic CLI Usage

C# Integration:

csharp
SilviaCore core = SilviaCoreManager.CreateCore("dev_instance");
core.ApiMem().Load("brains/assistant.sil", false, true);

// Create a complete behavior in one command
string cmd1 = "$> learn behavior assistant,farewell {a:{text:goodbye|bye|see you}}{e:{text:Goodbye! Have a great day!}}";
string result1 = core.ApiApp().ProcessCommand(cmd1);
core.ApiApp().SetDiagOutput(result1);
// result1: "Behavior Added at: 47: assistant,farewell"

// Set a variable
string cmd2 = "$> set variable $session_id abc123";
string result2 = core.ApiApp().ProcessCommand(cmd2);
// result2: "Variable set successfully."

// Test the behavior
string[] response = core.ApiBrain().GetResponseManaged("goodbye");
core.ApiApp().SetTextOutput(response[0]);
// response[0]: "Goodbye! Have a great day!"

// Save the brain
string cmd3 = "$> save brains/assistant_with_farewell.sil";
string result3 = core.ApiApp().ProcessCommand(cmd3);
core.ApiApp().SetDiagOutput(result3);
// result3: "Brain saved successfully to brains/assistant_with_farewell.sil"

##Performance Characteristics

SILVIA Core's architecture is optimized for production deployment with measurable performance guarantees.

Latency Benchmarks

Inference (GetResponse) Timing:

DeploymentAvg Latency95th Percentile99th Percentile
Embedded (ARM Cortex-A)250 μs500 μs1.2 ms
Desktop (x64, 3.5GHz)120 μs200 μs450 μs
Server (Xeon, multi-core)150 μs300 μs600 μs
Unity (Game thread)300 μs800 μs1.5 ms

Factors Affecting Latency:

  • Brain size (behaviors, concepts)
  • Script complexity (C# execution time)
  • Coordinator sensor subscriptions
  • Context depth (conversation history)

Optimization:

csharp
core.ApiBrain().SetOptimization(true);  // Enable fast-path optimizations
core.ApiBrain().SetContextDepth(3);     // Limit context history
core.ApiBrain().SetRandomizeResponses(false);  // Deterministic selection

Throughput Benchmarks

Concurrent Request Handling (SilviaMultiThread):

ConfigurationRequests/secNotes
Single-threaded8,000 req/sNo SilviaMultiThread wrapper
Multi-threaded (4 cores)28,000 req/sSilviaMultiThread with request queuing
Multi-core (8 instances)45,000 req/s8 separate SilviaCore instances

Factors Affecting Throughput:

  • Number of CPU cores
  • Brain complexity
  • Request concurrency
  • I/O operations in scripts

Memory Usage

Base Memory Footprint:

ComponentMemory Usage
SilviaCore (empty)2.5 MB
Brain (1000 behaviors)15 MB
Brain (10000 behaviors)120 MB
Context history (100 turns)500 KB
Feedback stack (1000 items)200 KB

Per-User Memory (Multi-Tenant):

Base Core: 2.5 MB
Loaded Brain: 15 MB (shared, not per-user)
User Variables: ~10 KB
Context History: ~500 KB
Total per user: ~3 MB + shared brain

Memory Optimization:

csharp
core.ApiBrain().SetContextDepth(3);  // Reduce context memory
core.ApiFeedback().SetStackSize(500);  // Reduce feedback memory
core.ApiData().ClearBindings("unused");  // Remove unused bindings

Resource Usage Monitoring

Built-in API Tracking:

csharp
core.EnableApiTracking(true);
core.SetApiTrackingUser("user_12345");

int totalCalls = core.GetTotalApiCalls();

string apiStats = core.ApiApp().GetDiagOutput();
// Output: "API Calls: 1247, Brain: 342, App: 201, Data: 104, Mem: 15..."

User Manager Statistics:

csharp
SilviaUserManager userManager = core.ApiUser();
Dictionary<string, object> stats = userManager.GetStatistics();

int totalUsers = (int)stats["total_users"];
int activeUsers = (int)stats["active_users"];
long totalMemoryBytes = (long)stats["total_memory_bytes"];
int totalApiCalls = (int)stats["total_api_calls"];

core.ApiApp().SetDiagOutput($"Users: {activeUsers}/{totalUsers}, Memory: {totalMemoryBytes / 1024 / 1024} MB, API Calls: {totalApiCalls}");

Performance Best Practices

1. Use SilviaMultiThread for Web Servers

csharp
// DON'T: Direct core access from multiple threads
SilviaCore core = SilviaCoreManager.GetCore("shared");
// Race conditions, undefined behavior

// DO: Wrap in SilviaMultiThread
SilviaMultiThread threadSafe = new SilviaMultiThread(core);
// Automatic request serialization, deterministic execution

2. Minimize Context Depth for High-Throughput

csharp
// High latency: Deep context evaluation
core.ApiBrain().SetContextDepth(10);

// Optimized: Shallow context
core.ApiBrain().SetContextDepth(3);

3. Preload Brains at Startup

csharp
// DON'T: Load on first request (adds latency)
if (core == null) {
    core = CreateAndLoadCore(userId);  // 50-200ms delay
}

// DO: Preload during initialization
void ApplicationStart() {
    SilviaCore templateCore = SilviaCoreManager.CreateCore("template");
    templateCore.ApiMem().Load("brains/customer_service.sil", false, true);
    // First request uses pre-loaded brain
}

4. Use Coordinator Sensors for Inter-Core Communication

csharp
// DON'T: Poll for state changes
while (true) {
    string status = otherCore.GetVariable("$_status");
    if (status == "ready") break;
    Thread.Sleep(100);  // Wastes CPU, adds latency
}

// DO: Event-driven coordination
core.ApiSensors().RegisterCoordinatorSensor("status_ready", 
    (eventType, data) => OnStatusReady(data));
// Zero polling, immediate response

5. Batch API Calls in Scripts

csharp
// DON'T: Multiple individual API calls
for (int i = 0; i < 100; i++) {
    core.SetVariable($"$item_{i}", values[i]);  // 100 calls
}

// DO: Use batch operations or single JSON variable
string jsonData = JsonSerialize(values);
core.SetVariable("$items_json", jsonData);  // 1 call

Summary: Production-Ready AI Integration

SILVIA Core's API provides three key guarantees for production deployment:

  1. Predictable Performance - Microsecond-precision timing, measurable latency, bounded memory usage
  2. Flexible Integration - Embedded, REST, WebSocket, CLI - choose the pattern that fits your architecture
  3. Runtime Adaptability - Live brain modification, behavior authoring, system control without recompilation

The combination of strongly-typed APIs, comprehensive CLI, and multi-pattern integration support enables SILVIA Core to serve as the orchestration layer for production AI systems across embedded devices, enterprise servers, and distributed architectures.


© Copyright Cognitive Code Corp. 2007-2026

SILVIA is a registered Trademark of Cognitive Code Corp.

SILVIA is a registered Trademark of Cognitive Code Corp.