Skip to content

SILVIA Core – ApiData Reference

Version: 3.1

Namespace: CognitiveCode.Silvia.Api


The Brain Authoring API

The Foundation: Dynamic Knowledge Base Construction

SILVIA ApiData is the central API for building and modifying AI brains at runtime. This is not a static configuration file—this is live brain authoring where you can add behaviors, teach concepts, create semantic relationships, attach scripts, and tune the knowledge base while the AI is running.

Traditional AI Knowledge Management (What Everyone Else Does)

AI Training → Static Model File → Deploy → Pray

                              No runtime changes
                              No behavior addition
                              No knowledge updates

Problems:

  • Static Knowledge: Can't add new behaviors after deployment
  • Retraining Required: Every change requires full model retraining
  • No Runtime Authoring: Can't teach AI new patterns on the fly
  • No Semantic Network: Vocabulary has no relationships or meaning
  • Version Hell: Multiple model versions for different knowledge sets

The ApiData Architecture

Dynamic Brain Construction Model

                 Runtime Brain Authoring

        ┌───────────────────┴────────────────────┐
        │         SILVIA BRAIN COMPONENTS        │
        └───────────────────┬────────────────────┘

    ┌────────┬────────┬──────────┬────────┬────────┐
    ▼        ▼        ▼          ▼        ▼        ▼
 CONCEPTS BINDINGS BEHAVIORS  ABSORBERS EXUDERS SCRIPTS
    │        │        │          │        │        │
    │        │        │          │        │        │
  Words  Relations  Groups     Inputs  Outputs    Code
    │        │        │          │        │        │
    ↓        ↓        ↓          ↓        ↓        ↓
Vocabulary Context Categories Patterns Responses Logic

The Innovation: Live Brain Programming

Six-Layer Knowledge Architecture:

  1. Concepts Layer: Vocabulary atoms with weights and stopword flags
  2. Bindings Layer: Semantic relationships (synonyms, locations, properties, etc.)
  3. Behaviors Layer: Organized response groups (greeting, help, error, custom domains)
  4. Absorbers Layer: Input pattern recognition (wildcards, exact match, rejection filters)
  5. Exuders Layer: Multi-modal outputs (text, voice, PAGER tags, data, dynamic generation)
  6. Scripts Layer: C# execution hooks (pre/post behavior, per-exuder logic)

This is what separates SILVIA from static chatbots—you can author the AI like code, not train it like a model.


Core Api Classes

SilviaApiData

Primary interface for brain authoring, knowledge base manipulation, and runtime behavior construction.

Key Features:

  • Concept Management: Add/remove/tune vocabulary with semantic weights
  • Semantic Binding: Create meaning networks (WordNet-style relationships)
  • Behavior Authoring: Create/modify/delete behaviors, absorbers, exuders
  • Script Integration: Attach C# or Lua scripts to behaviors for custom logic
  • Metadata Storage: Arbitrary data fields, PAGER tags, security levels
  • Usage Tracking (3.1 NEW): API call metrics, rate limiting, audit logging

Access:

csharp
SilviaApiData api = Core.ApiData();

API Methods

Concept Management

Concepts are atomic vocabulary units - the fundamental building blocks of SILVIA's language understanding.

GetOrAddConcept(string concept)

Gets existing concept ID or creates new concept if it doesn't exist.

Purpose:

  • Vocabulary Growth: Automatically add new words as they're encountered
  • Concept Reuse: Ensure same word always maps to same concept ID
  • WordNet Integration: Optionally use WordNet for semantic enrichment

Usage:

csharp
// Add or retrieve concept ID
int conceptID = api.GetOrAddConcept("hello");
// conceptID = 42 (unique identifier for "hello")

// Concepts are case-normalized and trimmed
int same = api.GetOrAddConcept("HELLO"); // Returns 42 (same concept)

Parameters:

  • concept (string): Word or phrase to add/retrieve

Returns: int - Concept ID (>= 0), or -1 if failed

Automatic Behavior:

  • Auto-Creation: Creates concept if it doesn't exist
  • Sets Modified Flag: Marks brain as modified for save prompts
  • WordNet Lookup: If enabled, enriches concept with semantic data

Best Practice:

csharp
// Always use GetOrAddConcept instead of manual concept creation
int userID = api.GetOrAddConcept(userName);
int actionID = api.GetOrAddConcept(userAction);
int targetID = api.GetOrAddConcept(targetObject);

// Now you can create bindings between these concepts
api.SetBinding(userName, userAction, "performs");
api.SetBinding(userAction, targetObject, "affects");

GetConceptCount()

Returns total number of concepts in the brain.

Usage:

csharp
int totalConcepts = api.GetConceptCount();
Console.WriteLine($"Brain has {totalConcepts} concepts");

Returns: int - Total concept count


GetConcept(int conceptID)

Gets the text/word of a concept by its ID.

Usage:

csharp
int id = api.GetOrAddConcept("hello");
string word = api.GetConcept(id); // Returns "hello"

Parameters:

  • conceptID (int): Concept identifier

Returns: string - Concept text, or null if not found


GetConceptID(string word)

Gets the concept ID for a given word (does NOT create if missing).

Usage:

csharp
int id = api.GetConceptID("hello");
if (id == -1) {
    Console.WriteLine("Concept doesn't exist");
}

Parameters:

  • word (string): Word to look up

Returns: int - Concept ID, or -1 if not found


ConceptInUse(int conceptID)

Checks if a concept is currently used in any behaviors.

Purpose:

  • Safe Deletion: Verify concept can be removed without breaking behaviors
  • Cleanup Validation: Identify unused concepts for pruning

Usage:

csharp
int id = api.GetConceptID("obsolete");
if (!api.ConceptInUse(id)) {
    api.RemoveConcept(id); // Safe to remove
}

Parameters:

  • conceptID (int): Concept identifier

Returns: bool - True if concept is referenced in behaviors


RemoveConcept(int conceptID)

Removes a concept if it's not currently in use.

Usage:

csharp
bool removed = api.RemoveConcept(conceptID);
if (!removed) {
    Console.WriteLine("Concept is in use, cannot remove");
}

Parameters:

  • conceptID (int): Concept to remove

Returns: bool - True if removed, false if in use or failed

Safety: Will NOT remove concepts used in behaviors


RemoveUnusedConcepts()

Removes all concepts that are not referenced in any behaviors.

Purpose:

  • Memory Optimization: Clean up vocabulary bloat
  • Performance: Smaller concept dictionary = faster lookups
  • Maintenance: Remove test/temporary concepts

Usage:

csharp
string report = api.RemoveUnusedConcepts();
Console.WriteLine(report);
// Output: "Removed 347 unused concepts"

Returns: string - Report of removed concepts

Best Practice:

csharp
// After major brain editing session
api.RemoveUnusedConcepts();
api.CleanConcepts(); // Alphabetize remaining concepts
Core.SaveBrain("cleaned_brain.txt");

GetConceptWeight(int conceptID) / SetConceptWeight(int conceptID, float weight)

Gets or sets the importance/weight of a concept in pattern matching.

Purpose:

  • Relevance Tuning: Boost important domain-specific words
  • Stopword Handling: Reduce weight of common words (the, a, is)
  • Custom Weighting: Emphasize technical terms, brand names, etc.

Usage:

csharp
// Get current weight
float weight = api.GetConceptWeight(conceptID);

// Boost important concept
api.SetConceptWeight(conceptID, 2.5f); // 2.5x more important

// Reduce noise word
api.SetConceptWeight(noiseID, 0.1f); // 90% less important

Parameters:

  • conceptID (int): Concept identifier
  • weight (float): Weight multiplier (1.0 = normal, higher = more important)

Returns: float for Get, bool for Set

Default Weight: 1.0 (neutral)


GetConceptStopword(int conceptID) / SetConceptStopword(int conceptID, bool isStopword)

Gets or sets whether a concept is marked as a stopword (low semantic value).

Purpose:

  • Natural Language Processing: Mark words like "the", "a", "is" as stopwords
  • Pattern Matching: Stopwords have lower influence on absorber matching
  • Dynamic Generation: Stopwords treated differently in Markov chains

Usage:

csharp
// Mark common words as stopwords
api.SetConceptStopword(api.GetOrAddConcept("the"), true);
api.SetConceptStopword(api.GetOrAddConcept("a"), true);
api.SetConceptStopword(api.GetOrAddConcept("is"), true);

// Check if word is stopword
bool isStopword = api.GetConceptStopword(conceptID);

Parameters:

  • conceptID (int): Concept identifier
  • isStopword (bool): True to mark as stopword

Returns: bool


TuneConcepts(bool useAbsorbers, bool absorberAsDocument, bool useExuders)

Automatically tunes concept weights based on usage patterns in behaviors.

Purpose:

  • Statistical Optimization: Recalculate concept weights from behavior corpus
  • TF-IDF Weighting: Emphasize rare but important concepts
  • Performance Tuning: Improve pattern matching accuracy

Algorithm:

  • Absorbers: Analyze input patterns for concept frequency
  • Exuders: Analyze output patterns for concept importance
  • Document Mode: Treat each absorber as a separate document for TF-IDF

Usage:

csharp
// Full auto-tune using all data
bool success = api.TuneConcepts(true, false, true);

// Only tune from absorbers (input patterns)
api.TuneConcepts(true, false, false);

// Document-level TF-IDF (best for diverse topic domains)
api.TuneConcepts(true, true, true);

Parameters:

  • useAbsorbers (bool): Include absorber patterns in tuning
  • absorberAsDocument (bool): Treat each absorber as separate document for TF-IDF
  • useExuders (bool): Include exuder patterns in tuning

Returns: bool - True if tuning succeeded

When to Use:

csharp
// After major behavior additions
Core.ApiMem().MergeBrainFile("new_domain_knowledge.txt");
api.TuneConcepts(true, true, true); // Recalculate weights

// After editing absorbers
api.TuneConcepts(true, false, false); // Focus on input patterns

CleanConcepts()

Removes unused concepts and alphabetizes the concept dictionary.

Purpose:

  • Cleanup: Remove orphaned concepts
  • Optimization: Alphabetize for faster binary search
  • Maintenance: Clean state before saving brain

Usage:

csharp
bool success = api.CleanConcepts();
// Removes unused concepts + alphabetizes remaining

Returns: bool - True if successful

Equivalent to:

csharp
api.RemoveUnusedConcepts();
brain.Alphabetize(); // Internal alphabetization

Concept Bindings (Semantic Relationships)

Bindings create semantic networks - relationships between concepts that give vocabulary meaning and context.

SetBinding(string root, string bound, string type)

Creates or updates a binding relationship between two concepts.

Purpose:

  • Semantic Network: Build WordNet-style knowledge graphs
  • Intent Inference: Help AI understand word relationships
  • Context Understanding: Connect related concepts

Binding Types (Examples):

  • "synonym" - words with same meaning
  • "antonym" - opposite meanings
  • "location" - spatial relationships
  • "partof" - component relationships
  • "isa" - hierarchical relationships
  • "property" - attribute relationships
  • "causes" - causal relationships
  • Custom types - you define your own!

Usage:

csharp
// Location bindings
api.SetBinding("tokyo", "japan", "location");
api.SetBinding("paris", "france", "location");

// Synonym bindings
api.SetBinding("happy", "joyful", "synonym");
api.SetBinding("sad", "unhappy", "synonym");

// Hierarchical (is-a) bindings
api.SetBinding("dog", "animal", "isa");
api.SetBinding("cat", "animal", "isa");

// Property bindings
api.SetBinding("sky", "blue", "property");
api.SetBinding("grass", "green", "property");

// Causal bindings
api.SetBinding("rain", "wet", "causes");

// Custom domain bindings
api.SetBinding("voltage", "electricity", "measures");
api.SetBinding("temperature", "thermometer", "measured_by");

Parameters:

  • root (string): Root concept in binding
  • bound (string): Bound concept in binding
  • type (string): Binding type (relationship name)

Returns: bool - True if binding created successfully

Auto-Creation: Concepts are created if they don't exist


GetBindingTypeNames()

Gets all available binding type names.

Usage:

csharp
string[] types = api.GetBindingTypeNames();
// Returns: ["synonym", "antonym", "location", "partof", "isa", ...]

Returns: string[] - Array of binding type names


ClearBindings() / ClearBindingsOfType(string type)

Removes all bindings or all bindings of a specific type.

Usage:

csharp
// Clear all bindings
api.ClearBindings();

// Clear only location bindings
api.ClearBindingsOfType("location");

Returns: bool - True if cleared


UnbindConcept(string concept)

Removes all bindings for a specific concept.

Usage:

csharp
api.UnbindConcept("obsolete_term");

Parameters:

  • concept (string): Concept to unbind

Returns: bool - True if unbound


SetBindingTypeModifier(string name, float modifier) / GetBindingTypeModifier(string name)

Sets or gets the weight multiplier for a binding type.

Purpose:

  • Binding Importance: Control how much different binding types influence intent matching
  • Domain Tuning: Boost important relationship types for your domain

Usage:

csharp
// Boost location bindings (geography app)
api.SetBindingTypeModifier("location", 2.0f);

// Reduce synonym weight (prefer exact matches)
api.SetBindingTypeModifier("synonym", 0.5f);

// Check current modifier
float modifier = api.GetBindingTypeModifier("location"); // 2.0

Parameters:

  • name (string): Binding type name (or variable reference: $varname)
  • modifier (float): Weight multiplier

Returns: float for Get, bool for Set


TestBinding(string concept, string bound, string type)

Tests if a binding relationship exists between concepts.

Usage:

csharp
string direction = api.TestBinding("tokyo", "japan", "location");
// Returns: "forward" (tokyo → japan)

direction = api.TestBinding("japan", "tokyo", "location");
// Returns: "reverse" (japan ← tokyo)

direction = api.TestBinding("tokyo", "france", "location");
// Returns: null (no binding)

Parameters:

  • concept (string): Root concept
  • bound (string): Bound concept
  • type (string): Binding type

Returns: string - "forward", "reverse", or null


GetBoundConcept(string root, string type)

Gets a randomly selected bound concept of specified type.

Usage:

csharp
// Get a random location for "tokyo"
string location = api.GetBoundConcept("tokyo", "location");
// Returns: "japan"

Parameters:

  • root (string): Root concept
  • type (string): Binding type

Returns: string - Bound concept name, or null if none found


GetBoundConcepts(string root, string type)

Gets ALL bound concepts of specified type.

Usage:

csharp
// Get all locations for "japan"
string[] cities = api.GetBoundConcepts("japan", "location");
// Returns: ["tokyo", "osaka", "kyoto", ...]

Parameters:

  • root (string): Root concept
  • type (string): Binding type

Returns: string[] - Array of bound concept names


GetAllBoundConcepts(string root)

Gets all bound concepts and their binding types.

Usage:

csharp
string[] allBindings = api.GetAllBoundConcepts("tokyo");
// Returns: ["japan", "location", "asia", "continent", "megacity", "property", ...]
// Format: [concept1, type1, concept2, type2, ...]

Parameters:

  • root (string): Root concept

Returns: string[] - Interleaved array of [concept, type, concept, type, ...]


GetAllForwardBoundConcepts(string root) / GetAllInverseBoundConcepts(string root)

Gets only forward or inverse bindings.

Usage:

csharp
// Forward bindings only (root → bound)
string[] forward = api.GetAllForwardBoundConcepts("tokyo");

// Inverse bindings only (root ← bound)
string[] inverse = api.GetAllInverseBoundConcepts("tokyo");

Use Case: Useful for duplicating bindings for different languages


GetUtteranceTrunk(string input, bool conceptualize)

Converts utterance to trunk concepts using bindings.

Purpose:

  • Concept Normalization: Replace synonyms with canonical forms
  • Intent Simplification: Reduce variations to common trunks

Usage:

csharp
// "joyful" → "happy" (if trunk binding exists)
string trunk = api.GetUtteranceTrunk("I'm joyful", true);
// Returns: "I'm happy"

Parameters:

  • input (string): Input utterance
  • conceptualize (bool): Whether to conceptualize input first

Returns: string - Processed utterance with trunk concepts


Behavior Management

Behaviors are the fundamental organizational units of SILVIA's knowledge - containers for input patterns (absorbers) and output patterns (exuders).

GetBehaviorID(string group, string name, string subgroup = "")

Gets or creates a behavior ID by group, name, and optional subgroup.

Purpose:

  • Behavior Organization: Group related behaviors hierarchically
  • Auto-Creation: Creates behavior if it doesn't exist
  • Unique Identification: Each behavior has a unique ID (UID)

Usage:

csharp
// Create or get greeting behavior
int behaviorID = api.GetBehaviorID("conversation", "greeting");

// With subgroup for finer organization
int helpID = api.GetBehaviorID("support", "help", "technical");

// Check if it was created or retrieved
bool exists = api.VerifyBehaviorExists(behaviorID);

Parameters:

  • group (string): Behavior group name
  • name (string): Behavior name
  • subgroup (string): Optional subgroup name

Returns: int - Behavior ID (UID), or -1 if creation failed

Hierarchy Example:

Group: conversation
  Subgroup: formal
    - greeting
    - goodbye
  Subgroup: casual
    - greeting
    - goodbye
    
Group: support
  Subgroup: technical
    - help
    - troubleshoot
  Subgroup: billing
    - payment_info
    - refund_request

VerifyBehaviorExists(string group, string name) / VerifyBehaviorExists(int behaviorID)

Checks if a behavior exists.

Usage:

csharp
// By group and name
bool exists = api.VerifyBehaviorExists("conversation", "greeting");

// By ID
bool existsID = api.VerifyBehaviorExists(behaviorID);

Returns: bool - True if behavior exists


GetBehaviorCount()

Returns total number of behaviors in the brain.

Usage:

csharp
int count = api.GetBehaviorCount();
Console.WriteLine($"Brain has {count} behaviors");

Returns: int - Total behavior count


GetAllGroups() / GetAllGroupsSubgroups() / GetAllGroupsSubgroupsNames()

Gets hierarchical lists of behaviors.

Usage:

csharp
// All groups
string[] groups = api.GetAllGroups();
// Returns: ["conversation", "support", "errors", ...]

// All groups + subgroups
Tuple<int, string, string, string>[] groupsSubs = api.GetAllGroupsSubgroups();
// Returns: [(id, group, subgroup, ""), ...]

// Full hierarchy
Tuple<string, string, string>[] full = api.GetAllGroupsSubgroupsNames();
// Returns: [(group, subgroup, name), ...]

Returns: Sorted arrays of behavior hierarchy


GetAllBehaviorsInfos()

Gets complete list of all behaviors with full metadata.

Usage:

csharp
Tuple<int, string, string, string>[] all = api.GetAllBehaviorsInfos();
// Returns: [(behaviorID, group, subgroup, name), ...]
// Sorted alphabetically by group → subgroup → name

Returns: Tuple<int, string, string, string>[] - Full behavior list

Use Case: Populate UI dropdowns, generate behavior reports, index behaviors


GetBehaviorGroup(int id) / GetBehaviorSubGroup(int id) / GetBehaviorName(int id)

Gets individual behavior metadata fields.

Usage:

csharp
string group = api.GetBehaviorGroup(behaviorID);    // "conversation"
string subgroup = api.GetBehaviorSubGroup(behaviorID); // "formal"
string name = api.GetBehaviorName(behaviorID);      // "greeting"

Parameters:

  • id (int): Behavior ID

Returns: string - Field value, or null if not found


SetBehaviorGroup(int id, string group) / SetBehaviorSubGroup(int id, string subgroup) / SetBehaviorName(int id, string name)

Sets individual behavior metadata fields.

Usage:

csharp
api.SetBehaviorGroup(behaviorID, "new_group");
api.SetBehaviorSubGroup(behaviorID, "new_subgroup");
api.SetBehaviorName(behaviorID, "new_name");

Parameters:

  • id (int): Behavior ID
  • group/subgroup/name (string): New value

Returns: bool - True if set successfully


SetBehaviorSecurityLevel(int id, int securityLevel) / GetBehaviorSecurityLevel(int id)

Sets or gets the security clearance required to access a behavior.

Purpose:

  • Access Control: Restrict sensitive behaviors to authorized users
  • Multi-Tenant Security: Different users see different behaviors

Usage:

csharp
// Public behavior (anyone can access)
api.SetBehaviorSecurityLevel(greetingID, 0);

// Admin-only behavior
api.SetBehaviorSecurityLevel(systemConfigID, 10);

// Check security level
int level = api.GetBehaviorSecurityLevel(behaviorID);

Parameters:

  • id (int): Behavior ID
  • securityLevel (int): Security level (0 = public, higher = more restricted)

Returns: int for Get, bool for Set

Integration: Works with ApiBrain().SetUserSecurityLevel() for access control


SetBehaviorContentState(int id, string state) / GetBehaviorContentState(int id)

Sets or gets arbitrary content state string for a behavior.

Purpose:

  • Workflow States: "draft", "review", "published"
  • Custom Tagging: "deprecated", "experimental", "stable"
  • Application Logic: Custom state machine

Usage:

csharp
api.SetBehaviorContentState(behaviorID, "published");
string state = api.GetBehaviorContentState(behaviorID);

Parameters:

  • id (int): Behavior ID
  • state (string): State string

Returns: string for Get, bool for Set


GetBehaviorCreated(int id) / GetBehaviorLastModified(int id)

Gets creation or last modified timestamp (binary format).

Usage:

csharp
long created = api.GetBehaviorCreated(behaviorID);
long modified = api.GetBehaviorLastModified(behaviorID);

DateTime createdDate = DateTime.FromBinary(created);
DateTime modifiedDate = DateTime.FromBinary(modified);

Returns: long - Binary DateTime value


GetBehaviorCreatedString(int id) / GetBehaviorLastModifiedString(int id)

Gets formatted creation or modified date/time string.

Usage:

csharp
string created = api.GetBehaviorCreatedString(behaviorID);
// Returns: "2025:10:13/14:32"

string modified = api.GetBehaviorLastModifiedString(behaviorID);

Returns: string - Formatted date string "YYYY:MM:DD/HH:MM"


GetBehaviorCreatedYear/Month/Day/Hour/Minute(int id)

GetBehaviorLastModifiedYear/Month/Day/Hour/Minute(int id)

Gets individual date/time components.

Usage:

csharp
int year = api.GetBehaviorCreatedYear(behaviorID);     // 2025
int month = api.GetBehaviorCreatedMonth(behaviorID);   // 10
int day = api.GetBehaviorCreatedDay(behaviorID);       // 13
int hour = api.GetBehaviorCreatedHour(behaviorID);     // 14
int minute = api.GetBehaviorCreatedMinute(behaviorID); // 32

Returns: int - Date/time component value


RemoveBehavior(int id)

Deletes a behavior and all its absorbers and exuders.

Usage:

csharp
bool removed = api.RemoveBehavior(behaviorID);

Parameters:

  • id (int): Behavior ID to remove

Returns: bool - True if removed successfully

Warning: This is permanent - behavior and all its contents are deleted


Absorber Management (Input Patterns)

Absorbers are input pattern matchers - they define what user input will trigger a behavior.

AddAbsorber(int id, string absorberText)

Adds a new absorber to a behavior.

Purpose:

  • Input Pattern: Define what user input triggers this behavior
  • Wildcard Matching: Use * for flexible pattern matching
  • Multiple Patterns: Add multiple absorbers for variations

Usage:

csharp
int behaviorID = api.GetBehaviorID("conversation", "greeting");

// Simple exact match
int absorberID = api.AddAbsorber(behaviorID, "hello");

// Wildcard pattern
int absorberID2 = api.AddAbsorber(behaviorID, "hello *");
// Matches: "hello there", "hello world", "hello everyone"

// Multiple wildcards
int absorberID3 = api.AddAbsorber(behaviorID, "* hello *");
// Matches: "well hello there", "oh hello world"

Parameters:

  • id (int): Behavior ID
  • absorberText (string): Input pattern text (supports * wildcards)

Returns: int - New absorber ID, or -1 if failed

Pattern Syntax:

  • "hello" - Exact match (after normalization)
  • "hello *" - hello + any words after
  • "* hello" - any words + hello
  • "* hello *" - hello anywhere in input
  • "show * status" - show [anything] status

SetAbsorberText(int id, int absorberID, string absorberText) / GetAbsorberText(int id, int absorberID)

Sets or gets the text pattern of an absorber.

Usage:

csharp
// Modify absorber pattern
api.SetAbsorberText(behaviorID, absorberID, "hi *");

// Get current pattern
string pattern = api.GetAbsorberText(behaviorID, absorberID);

Parameters:

  • id (int): Behavior ID
  • absorberID (int): Absorber ID within behavior
  • absorberText (string): New pattern text (for Set)

Returns: string for Get, bool for Set


RemoveAbsorber(int id, int absorberID)

Deletes an absorber from a behavior.

Usage:

csharp
bool removed = api.RemoveAbsorber(behaviorID, absorberID);

Returns: bool - True if removed


GetAbsorberCount(int id)

Returns number of absorbers in a behavior.

Usage:

csharp
int count = api.GetAbsorberCount(behaviorID);

Returns: int - Absorber count, or -1 if behavior not found


GetAbsorberRequired(int id, int absorberID) / SetAbsorberRequired(int id, int absorberID, bool[] required)

Gets or sets which concepts in an absorber are required for matching.

Purpose:

  • Flexible Matching: Mark some concepts as optional
  • Advanced Patterns: Fine-tune pattern matching logic

Usage:

csharp
// Get required flags for "show * status"
bool[] required = api.GetAbsorberRequired(behaviorID, absorberID);
// Returns: [true, false, true] (show=required, *=optional, status=required)

// Set required flags
bool[] newRequired = new bool[] { true, false, true };
api.SetAbsorberRequired(behaviorID, absorberID, newRequired);

Returns: bool[] for Get, bool for Set


SetAbsorberExact(int id, int absorberID, bool exact) / GetAbsorberExact(int id, int absorberID)

Sets or gets whether absorber requires exact conceptual match.

Purpose:

  • Strict Matching: Require exact input, no fuzzy matching
  • Precision Control: Disable semantic matching for critical commands

Usage:

csharp
// Require exact match (no wildcards, no fuzzy)
api.SetAbsorberExact(behaviorID, absorberID, true);

bool exact = api.GetAbsorberExact(behaviorID, absorberID);

Parameters:

  • exact (bool): True for exact match requirement

Returns: bool


SetAbsorberReject(int id, int absorberID, bool reject) / GetAbsorberReject(int id, int absorberID)

Sets or gets whether absorber is a rejection filter.

Purpose:

  • Blacklist Patterns: If matched, reject this behavior (weight = 0)
  • Negative Matching: Explicitly exclude certain inputs
  • Safety Filters: Block inappropriate inputs from triggering behavior

Usage:

csharp
// Reject behavior if input contains profanity
int rejectID = api.AddAbsorber(greetingID, "* profanity *");
api.SetAbsorberReject(greetingID, rejectID, true);

// Now "hello profanity world" will NOT trigger greeting behavior

Parameters:

  • reject (bool): True to mark as rejection filter

Returns: bool

How It Works: If reject absorber matches, behavior weight = 0 (behavior excluded from response)


SetAbsorberIsPrompt(int id, int absorberID, bool isPrompt) / GetAbsorberIsPrompt(int id, int absorberID)

Sets or gets whether absorber is an LLM prompt template.

Purpose:

  • LLM Integration: Mark absorber as prompt for language model
  • Hybrid AI: Combine symbolic matching with LLM generation

Usage:

csharp
api.SetAbsorberIsPrompt(behaviorID, absorberID, true);
bool isPrompt = api.GetAbsorberIsPrompt(behaviorID, absorberID);

Returns: bool


SetAbsorberData(int id, int absorberID, string data) / GetAbsorberData(int id, int absorberID)

Sets or gets arbitrary application-specific data for an absorber.

Purpose:

  • Metadata Storage: Store JSON, XML, or any custom data
  • Application Logic: Attach config, hints, or context to absorber
  • UI Integration: Store editor metadata, comments, etc.

Usage:

csharp
// Store JSON metadata
api.SetAbsorberData(behaviorID, absorberID, "{\"priority\":5,\"category\":\"greetings\"}");

// Retrieve metadata
string data = api.GetAbsorberData(behaviorID, absorberID);

Parameters:

  • data (string): Arbitrary string data

Returns: string for Get, bool for Set


Exuder Management (Output Patterns)

Exuders are multi-modal output generators - they define what the AI says/does when a behavior triggers.

AddExuder(int id, string exuderText)

Adds a new exuder to a behavior.

Purpose:

  • Output Pattern: Define AI response text
  • Multiple Variations: Add multiple exuders for response variety
  • Multi-Modal Output: Embed voice tags, PAGER tags, variables

Usage:

csharp
int behaviorID = api.GetBehaviorID("conversation", "greeting");

// Simple text response
int exuderID = api.AddExuder(behaviorID, "Hello there!");

// Response with variable
int exuderID2 = api.AddExuder(behaviorID, "Hello $_u!");

// Response with PAGER tags (animation)
int exuderID3 = api.AddExuder(behaviorID, "Hello! <Gesture-Wave/>");

// Response with SSML (voice prosody)
int exuderID4 = api.AddExuder(behaviorID, "<prosody rate='fast'>Hello!</prosody>");

Parameters:

  • id (int): Behavior ID
  • exuderText (string): Output pattern text

Returns: int - New exuder ID, or -1 if failed

Auto-Processing:

  • Concept Indexing: Text converted to concept indices
  • Variation Detection: {option1|option2} syntax parsed
  • Quote Fixing: Smart quotes replaced with standard quotes

SetExuderText(int id, int exuderID, string exuderText) / GetExuderText(int id, int exuderID)

Sets or gets the text pattern of an exuder.

Usage:

csharp
// Modify exuder
api.SetExuderText(behaviorID, exuderID, "Hi there!");

// Get current text
string text = api.GetExuderText(behaviorID, exuderID);

Returns: string for Get, bool for Set


RemoveExuder(int id, int exuderID)

Deletes an exuder from a behavior.

Usage:

csharp
bool removed = api.RemoveExuder(behaviorID, exuderID);

Returns: bool - True if removed


GetExuderCount(int id)

Returns number of exuders in a behavior.

Usage:

csharp
int count = api.GetExuderCount(behaviorID);

Returns: int - Exuder count, or -1 if behavior not found


SetExuderReuse(int id, int exuderID, bool reuse) / GetExuderReuse(int id, int exuderID)

Sets or gets whether exuder is available for dynamic output generation.

Purpose:

  • Markov Reuse: Allow exuder text to be sampled for dynamic responses
  • Content Pool: Build vocabulary pool for generative AI

Usage:

csharp
// Allow this exuder to be reused in dynamic generation
api.SetExuderReuse(behaviorID, exuderID, true);

bool reuse = api.GetExuderReuse(behaviorID, exuderID);

Parameters:

  • reuse (bool): True to enable reuse

Returns: bool

How It Works: When dynamic generation is enabled, SILVIA samples from reuse-enabled exuders to generate novel responses


SetExuderDynamic(int id, int exuderID, bool dynamic) / GetExuderDynamic(int id, int exuderID)

Sets or gets whether exuder should use dynamic generation instead of exact output.

Purpose:

  • Generative AI: Use Markov chains to generate novel responses
  • Variety: Never repeat same response twice
  • Natural Language: More human-like, less robotic

Usage:

csharp
// Enable dynamic generation for this exuder
api.SetExuderDynamic(behaviorID, exuderID, true);

bool dynamic = api.GetExuderDynamic(behaviorID, exuderID);

Parameters:

  • dynamic (bool): True to enable dynamic generation

Returns: bool

Note: Requires ApiBrain().SetDynamicGeneration() to be enabled globally


SetExuderExact(int id, int exuderID, bool exact) / GetExuderExact(int id, int exuderID)

Sets or gets whether exuder must output exactly as written (no variation).

Purpose:

  • Exact Output: Disable all variation systems for critical messages
  • Template Output: Output exact text, process variables only

Usage:

csharp
// Force exact output
api.SetExuderExact(behaviorID, exuderID, true);

bool exact = api.GetExuderExact(behaviorID, exuderID);

Returns: bool


SetExuderContext(int id, int exuderID, string context) / GetExuderContext(int id, int exuderID)

Sets or gets conceptual context for exuder (influences dynamic generation).

Purpose:

  • Context Bias: Guide dynamic generation toward specific topics
  • Semantic Steering: Influence Markov chain generation

Usage:

csharp
// Set context to steer dynamic generation
api.SetExuderContext(behaviorID, exuderID, "friendly casual conversational");

string context = api.GetExuderContext(behaviorID, exuderID);

Parameters:

  • context (string): Context concepts

Returns: string for Get, bool for Set


SetExuderSecurityLevel(int id, int exuderID, int securityLevel) / GetExuderSecurityLevel(int id, int exuderID)

Sets or gets security clearance required to trigger this exuder.

Purpose:

  • Fine-Grained Access Control: Different exuders for different user levels
  • Multi-Tier Responses: Admins get detailed info, users get summaries

Usage:

csharp
// Public exuder (anyone can trigger)
api.SetExuderSecurityLevel(behaviorID, publicExuderID, 0);

// Admin-only exuder (same behavior, different response)
api.SetExuderSecurityLevel(behaviorID, adminExuderID, 10);

int level = api.GetExuderSecurityLevel(behaviorID, exuderID);

Parameters:

  • securityLevel (int): Security level (0 = public, higher = restricted)

Returns: int for Get, bool for Set


SetExuderData(int id, int exuderID, string data) / GetExuderData(int id, int exuderID)

Sets or gets arbitrary application-specific data for exuder.

Usage:

csharp
// Store metadata
api.SetExuderData(behaviorID, exuderID, "{\"emotion\":\"happy\",\"energy\":0.8}");

string data = api.GetExuderData(behaviorID, exuderID);

Returns: string for Get, bool for Set


SetExuderPagerTags(int id, int exuderID, string tags) / GetExuderPagerTags(int id, int exuderID)

Sets or gets PAGER tags for avatar animation/expression control.

Purpose:

  • Avatar Animation: Trigger gestures, expressions, poses
  • Multi-Modal Output: Sync animation with speech
  • Custom Commands: Send application control messages

Usage:

csharp
// Set animation tags
string tags = "<Gesture-Wave/><Expression-Smile intensity=0.8/>";
api.SetExuderPagerTags(behaviorID, exuderID, tags);

// Retrieve tags
string pagerTags = api.GetExuderPagerTags(behaviorID, exuderID);

Parameters:

  • tags (string): PAGER tag XML string

Returns: string for Get, bool for Set

Tag Format:

xml
<TagName-Subtype field1=value1, field2=value2/>

SetExuderIsPrompt(int id, int exuderID, bool isPrompt) / GetExuderIsPrompt(int id, int exuderID)

Sets or gets whether exuder is an LLM prompt template.

Purpose:

  • Hybrid AI: Exuder text used as LLM prompt instead of direct output
  • Template Output: Generate response via language model

Usage:

csharp
api.SetExuderIsPrompt(behaviorID, exuderID, true);
bool isPrompt = api.GetExuderIsPrompt(behaviorID, exuderID);

Returns: bool


Script Management

Scripts are C# or Lua code attached to behaviors or exuders for custom logic execution.

SetBehaviorScript(int id, string stage, string language, string script)

Sets a script for a behavior at a specific execution stage.

Purpose:

  • Custom Logic: Execute code when behavior triggers
  • Data Processing: Validate input, transform output, query databases
  • Integration: Call external APIs, services, systems

Execution Stages:

  • "init" - When behavior is loaded
  • "pre" - Before absorber matching
  • "post" - After exuder execution
  • Custom stages - you define your own

Supported Languages:

  • "cs" - C# (compiled and executed)
  • "lua" - Lua (deprecated, use C# instead)

Usage:

csharp
string script = @"
public bool Invoke() {
    string userName = _core.GetVariable(""$_u"");
    _core.SetVariable(""$last_greeting_time"", DateTime.Now.ToString());
    return true;
}
";

api.SetBehaviorScript(behaviorID, "post", "cs", script);

Parameters:

  • id (int): Behavior ID
  • stage (string): Execution stage ("pre", "post", "init", custom)
  • language (string): Script language ("cs", "lua")
  • script (string): Script source code

Returns: bool - True if script set successfully

C# Script Template:

csharp
public bool Invoke() {
    // _core is available (SilviaCore reference)
    string input = _core.GetVariable("$user_input");
    
    // Your logic here
    bool success = DoSomething(input);
    
    // Set variables for exuders to use
    _core.SetVariable("$result", result);
    
    return success; // Return true to continue, false to abort
}

GetBehaviorScript(int id, string stage) / GetBehaviorScriptLanguage(int id, string stage)

Gets script code or language for a behavior stage.

Usage:

csharp
string script = api.GetBehaviorScript(behaviorID, "post");
string language = api.GetBehaviorScriptLanguage(behaviorID, "post"); // "cs"

Returns: string - Script code/language, or null if no script


SetExuderScript(int id, int exuderID, string stage, string language, string script)

Sets a script for a specific exuder.

Purpose:

  • Per-Exuder Logic: Different code for different responses
  • Output Processing: Modify exuder output before sending
  • Conditional Execution: Execute exuder only if script returns true

Usage:

csharp
string script = @"
public bool Invoke() {
    // Only execute this exuder during business hours
    int hour = DateTime.Now.Hour;
    return (hour >= 9 && hour < 17);
}
";

api.SetExuderScript(behaviorID, exuderID, "pre", "cs", script);

Parameters:

  • id (int): Behavior ID
  • exuderID (int): Exuder ID
  • stage (string): Execution stage
  • language (string): Script language
  • script (string): Script source code

Returns: bool - True if script set successfully


GetExuderScript(int id, int exuderID, string stage) / GetExuderScriptLanguage(int id, int exuderID, string stage)

Gets script code or language for an exuder stage.

Usage:

csharp
string script = api.GetExuderScript(behaviorID, exuderID, "pre");
string language = api.GetExuderScriptLanguage(behaviorID, exuderID, "pre");

Returns: string - Script code/language, or null


SetHeaderScript(string script) / GetHeaderScript()

Sets or gets the global C# header script (using statements, helper classes).

Purpose:

  • Global Imports: Add using statements for all scripts
  • Helper Functions: Define utility functions available to all scripts
  • Custom Classes: Define classes used across multiple behaviors

Usage:

csharp
string header = @"
using System.Net.Http;
using Newtonsoft.Json;

public static class Helpers {
    public static string FormatGreeting(string name) {
        return $""Hello, {name}! Welcome!"";
    }
}
";

api.SetHeaderScript(header);

Returns: string for Get, bool for Set


SetGlobalScript(string script) / GetGlobalScript()

Sets or gets the global script executed once at brain load.

Purpose:

  • One-Time Initialization: Database connections, API authentication
  • Global State: Initialize variables, load config

Usage:

csharp
string global = @"
public bool Invoke() {
    _core.SetVariable(""$app_version"", ""3.1.0"");
    _core.SetVariable(""$initialized"", ""true"");
    return true;
}
";

api.SetGlobalScript(global);

Returns: string for Get, bool for Set


Notes and Data Fields

SetBehaviorNotes(int id, string notes) / GetBehaviorNotes(int id)

Sets or gets human-readable notes for a behavior.

Purpose:

  • Documentation: Explain behavior purpose, usage
  • Authoring Comments: Leave notes for other developers

Usage:

csharp
api.SetBehaviorNotes(behaviorID, "Handles greeting responses. Updated 2025-10-13.");
string notes = api.GetBehaviorNotes(behaviorID);

Returns: string for Get, bool for Set


SetBehaviorData(int id, string data) / GetBehaviorData(int id)

Sets or gets arbitrary application-specific data for behavior.

Usage:

csharp
api.SetBehaviorData(behaviorID, "{\"category\":\"conversation\",\"priority\":5}");
string data = api.GetBehaviorData(behaviorID);

Returns: string for Get, bool for Set


Absorber Reuse

SetReuseAbsorbers(int targetBehaviorID, string sourceBehaviorGroup, string sourceBehaviorName)

SetReuseAbsorbers(int targetBehaviorID, int sourceBehaviorID)

Sets a behavior to reuse absorbers from another behavior.

Purpose:

  • DRY Principle: Don't repeat absorber patterns
  • Shared Patterns: Multiple behaviors triggered by same inputs
  • Maintenance: Update absorbers in one place

Usage:

csharp
// Create behaviors
int greetingID = api.GetBehaviorID("conversation", "greeting");
int farewell ID = api.GetBehaviorID("conversation", "farewell");

// farewellID reuses absorbers from greetingID
api.SetReuseAbsorbers(farewellID, greetingID);

// Now both behaviors trigger on same input patterns
// (but have different exuders/responses)

Parameters:

  • targetBehaviorID (int): Behavior that will reuse absorbers
  • sourceBehaviorID (int): Behavior to copy absorbers from

Returns: bool - True if set successfully

Clear Reuse:

csharp
// Use -1 to clear absorber reuse
api.SetReuseAbsorbers(behaviorID, -1);

GetReuseAbsorbersID(int behaviorID) / GetReuseAbsorbersGroup(int behaviorID) / GetReuseAbsorbersName(int behaviorID)

Gets the source behavior for absorber reuse.

Usage:

csharp
int sourceID = api.GetReuseAbsorbersID(behaviorID);
string sourceGroup = api.GetReuseAbsorbersGroup(behaviorID);
string sourceName = api.GetReuseAbsorbersName(behaviorID);

Returns: int/string - Source behavior info, or -1/null if no reuse


Typed Behavior Data (Network/Server Integration)

These methods provide structured access to behavior data, optimized for TCP/IP communication (used by SILVIA Server).

GetTypedBehaviorData(string dataType, string parameters)

Gets specific behavior data by type (structured query).

Data Types:

  • "id" - Get behavior ID
  • "count" - Get behavior count
  • "group" / "subgroup" / "name" - Get metadata
  • "absorbercount" / "exudercount" - Get counts
  • "absorbertext" / "exudertext" - Get text
  • "behaviordata" / "absorberdata" / "exuderdata" - Get data fields
  • "exuderpagertags" / "exudersecuritylevel" - Get exuder metadata
  • "allabsorbertext" / "allexudertext" - Get all patterns

Usage:

csharp
// Get behavior ID
string id = api.GetTypedBehaviorData("id", "conversation greeting");

// Get behavior count
string count = api.GetTypedBehaviorData("count", "");

// Get absorber text
string absorber = api.GetTypedBehaviorData("absorbertext", "42 0"); // behaviorID 42, absorberID 0

// Get all absorbers
string allAbsorbers = api.GetTypedBehaviorData("allabsorbertext", "42");

Parameters:

  • dataType (string): Data type identifier (case-insensitive)
  • parameters (string): Space-separated parameters

Returns: string - Requested data, or null if not found


SetTypedBehaviorData(string dataType, string parameters, string data)

Sets specific behavior data by type (structured command).

Usage:

csharp
// Set behavior name
api.SetTypedBehaviorData("name", "42", "new_name");

// Set absorber text
api.SetTypedBehaviorData("absorbertext", "42 0", "hello *");

// Set exuder data
api.SetTypedBehaviorData("exuderdata", "42 1", "{\"priority\":5}");

Returns: bool - True if set successfully


AddBehaviorData(string dataType, string parameters, string data)

Adds new behavior elements (behavior, absorber, exuder).

Usage:

csharp
// Add new behavior
string newID = api.AddBehaviorData("behavior", "", "conversation greeting");

// Add new absorber to behavior
string absorberID = api.AddBehaviorData("absorber", "42", "hello *");

// Add new exuder to behavior
string exuderID = api.AddBehaviorData("exuder", "42", "Hello there!");

Returns: string - New element ID, or null if failed


API Usage Tracking

Track API calls for security auditing, rate limiting, and performance monitoring.

SetApiTrackingEnabled(bool enabled) / GetApiTrackingEnabled()

Enables or disables API usage tracking.

Purpose:

  • Metrics: Track which API methods are called
  • Security: Audit user activity
  • Rate Limiting: Enforce call limits per user/method

Usage:

csharp
api.SetApiTrackingEnabled(true);
bool enabled = api.GetApiTrackingEnabled();

Default: Disabled


SetLoggingEnabled(bool enabled) / GetLoggingEnabled()

Enables or disables API call logging to files.

Purpose:

  • Audit Trail: Persistent log files for compliance
  • Debugging: Track API call history
  • Analytics: Analyze usage patterns

Usage:

csharp
api.SetLoggingEnabled(true);
bool enabled = api.GetLoggingEnabled();

Log Format:

YYYY-MM-DD HH:mm:ss | username | methodName | input (first 50 chars)

Log Files: SILVIA_log_YYYY-MM-DD.txt (daily rotation)


SetApiTrackingUser(string userName) / GetApiTrackingUser()

Sets current user for API tracking (used if no user specified in calls).

Usage:

csharp
api.SetApiTrackingUser("admin");
string user = api.GetApiTrackingUser();

GetTotalApiCalls(bool resetCount = false)

Gets total API call count across all users/methods.

Usage:

csharp
int total = api.GetTotalApiCalls();
Console.WriteLine($"Total API calls: {total}");

// Reset counter after reading
total = api.GetTotalApiCalls(true); // Returns count then resets to 0

Returns: int - Total call count


GetUserApiCalls(string userName = "")

Gets total API calls for a specific user.

Usage:

csharp
int userCalls = api.GetUserApiCalls("john_doe");

Parameters:

  • userName (string): Username to query (uses current user if empty)

Returns: int - User's total call count


**GetMethodApiCalls(string methodName, string userName = "")

Gets call count for a specific method and user.

Usage:

csharp
int calls = api.GetMethodApiCalls("GetOrAddConcept", "john_doe");

Parameters:

  • methodName (string): Method name
  • userName (string): Username (uses current user if empty)

Returns: int - Call count for method


GetLastApiCall(string methodName, string userName = "")

Gets timestamp of last call to a specific method.

Usage:

csharp
DateTime lastCall = api.GetLastApiCall("GetOrAddConcept", "john_doe");

Returns: DateTime - Last call timestamp, or DateTime.MinValue if never called


GetAllApiCalls()

Gets complete dictionary of all API calls.

Usage:

csharp
Dictionary<string, int> allCalls = api.GetAllApiCalls();
// Keys: "username:methodName"
// Values: call counts

Returns: Dictionary<string, int> - All tracked calls


SetRateLimit(int maxCallsPerMinute) / GetApiRateLimit()

Sets or gets maximum API calls per minute (rate limiting).

Usage:

csharp
api.SetRateLimit(100); // Max 100 calls/minute per method
int limit = api.GetApiRateLimit();

Default: 1000 calls/minute

Note: Rate limiting logic is not fully implemented - this sets the threshold but doesn't enforce it automatically


IsRateLimited(string methodName, string userName = "")

Checks if a method is currently rate limited.

Usage:

csharp
bool limited = api.IsRateLimited("GetOrAddConcept", "spammy_user");
if (limited) {
    Console.WriteLine("Rate limit exceeded! Slow down!");
}

Parameters:

  • methodName (string): Method to check
  • userName (string): Username (uses current user if empty)

Returns: bool - True if rate limit exceeded

Logic: Checks if method was called ≥ max times in last 1 minute


ClearApiTracking() / ClearApiTrackingForUser(string userName = "")

Clears all tracking data or tracking for a specific user.

Usage:

csharp
// Clear all tracking
api.ClearApiTracking();

// Clear tracking for one user
api.ClearApiTrackingForUser("john_doe");

Utility Methods

GetStringHash64(string s)

Generates a 64-bit hash from a string.

Purpose:

  • Unique Identifiers: Generate IDs for strings
  • Data Integrity: Hash verification
  • Indexing: Hash-based lookups

Usage:

csharp
ulong hash = api.GetStringHash64("hello world");

Returns: ulong - 64-bit hash value


Clear(string[] stopwords)

Clears and reinitializes the entire brain with new stopwords.

Purpose:

  • Full Reset: Wipe all knowledge and start fresh
  • Language Change: Reinitialize with different language stopwords

Usage:

csharp
string[] stopwords = new string[] { "the", "a", "is", "are", "was", "were" };
bool success = api.Clear(stopwords);

Parameters:

  • stopwords (string[]): Array of stopwords for new brain

Returns: bool - True if cleared successfully

Warning: This deletes all concepts, bindings, and behaviors - use with extreme caution!


GenerateVoiceFragments(string input, string punctuation, bool granular)

Generates voice fragments from input text for speech synthesis.

Purpose:

  • TTS Chunking: Break text into speakable fragments
  • Pause Insertion: Identify natural pause points
  • Prosody Control: Segment text for intonation

Usage:

csharp
string input = "Hello there! How are you today?";
string[] fragments = api.GenerateVoiceFragments(input, "!?.;,", true);
// Returns: ["hello there", "how are you today"]

Parameters:

  • input (string): Input text to fragment
  • punctuation (string): Punctuation characters for splitting
  • granular (bool): True for word-level splitting, false for sentence-level

Returns: string[] - Array of voice fragments, or null if failed

Granular Mode:

  • True: Splits on stopword boundaries (finer control)
  • False: Splits only on punctuation (coarser fragments)

Complete Brain Authoring Example

Building a Weather Assistant from Scratch

csharp
using CognitiveCode.Silvia.Api;

public void BuildWeatherAssistant(SilviaCore Core) {
    SilviaApiData api = Core.ApiData();
    
    // 1. CREATE CONCEPTS
    int weatherID = api.GetOrAddConcept("weather");
    int temperatureID = api.GetOrAddConcept("temperature");
    int forecastID = api.GetOrAddConcept("forecast");
    
    // 2. CREATE BINDINGS (semantic relationships)
    api.SetBinding("weather", "temperature", "partof");
    api.SetBinding("weather", "forecast", "partof");
    api.SetBinding("sunny", "weather", "isa");
    api.SetBinding("rainy", "weather", "isa");
    api.SetBinding("celsius", "temperature", "unit");
    api.SetBinding("fahrenheit", "temperature", "unit");
    
    // 3. CREATE BEHAVIOR
    int weatherBehaviorID = api.GetBehaviorID("assistant", "weather_query", "general");
    
    // 4. ADD ABSORBERS (input patterns)
    int abs1 = api.AddAbsorber(weatherBehaviorID, "what is the weather");
    int abs2 = api.AddAbsorber(weatherBehaviorID, "* weather *");
    int abs3 = api.AddAbsorber(weatherBehaviorID, "how is the weather");
    int abs4 = api.AddAbsorber(weatherBehaviorID, "weather forecast");
    
    // 5. ADD EXUDERS (responses)
    int exu1 = api.AddExuder(weatherBehaviorID, "Let me check the weather for you! <Gesture-LookUp/>");
    int exu2 = api.AddExuder(weatherBehaviorID, "Checking the current weather conditions...");
    
    // 6. ATTACH SCRIPT (custom logic)
    string script = @"
public bool Invoke() {
    // Call weather API
    string location = _core.GetVariable(""$user_location"", false) ?? ""unknown"";
    
    // Simulate weather API call
    string weather = ""sunny"";
    string temp = ""72°F"";
    
    // Set variables for exuder to use
    _core.SetVariable(""$weather"", weather, false);
    _core.SetVariable(""$temperature"", temp, false);
    _core.SetVariable(""$location"", location, false);
    
    // Log API call
    _core.ApiApp().SetDiagOutput($""Weather query for {location}: {weather}, {temp}"");
    
    return true;
}
    ";
    
    api.SetBehaviorScript(weatherBehaviorID, "post", "cs", script);
    
    // 7. ADD RESPONSE WITH VARIABLES
    int exu3 = api.AddExuder(weatherBehaviorID, 
        "The weather in $location is $weather with a temperature of $temperature.");
    
    // 8. ADD PAGER TAGS FOR ANIMATION
    api.SetExuderPagerTags(weatherBehaviorID, exu3, 
        "<Expression-Thoughtful/><Gesture-Point direction=up/>");
    
    // 9. SET METADATA
    api.SetBehaviorNotes(weatherBehaviorID, "Handles weather queries with API integration.");
    api.SetBehaviorData(weatherBehaviorID, "{\"category\":\"assistant\",\"api\":\"weather\"}");
    api.SetBehaviorSecurityLevel(weatherBehaviorID, 0); // Public access
    
    // 10. TUNE CONCEPTS
    api.TuneConcepts(true, false, true);
    
    // 11. SAVE BRAIN
    Core.SaveBrain("weather_assistant.txt");
    
    Console.WriteLine("Weather assistant brain created successfully!");
}

Result: Fully functional weather assistant with:

  • Natural language understanding (absorbers with wildcards)
  • API integration (C# script)
  • Multi-modal output (text + PAGER tags for animation)
  • Semantic knowledge (concept bindings)
  • Variable substitution
  • Security configuration
  • Metadata for management

Use Cases

1. Runtime Behavior Authoring (Chatbot Builder)

csharp
// User creates new behavior via UI
int behaviorID = api.GetBehaviorID(userGroup, userName);

// User adds input pattern
int absorberID = api.AddAbsorber(behaviorID, userInputPattern);

// User adds response
int exuderID = api.AddExuder(behaviorID, userResponse);

// Save immediately
Core.SaveBrain("user_brain.txt");

Capabilities:

  • Live brain editing
  • No restart required
  • Instant testing
  • User-friendly authoring

2. Machine Learning Integration (Learn from Conversations)

csharp
// After conversation, extract new patterns
string userInput = Core.GetVariable("$user_input");
string aiResponse = Core.GetVariable("$ai_response");
float userSatisfaction = GetUserFeedback(); // 0-1 rating

if (userSatisfaction > 0.8f) {
    // Good response - reinforce pattern
    int behaviorID = api.GetBehaviorID("learned", "conversation");
    int absID = api.AddAbsorber(behaviorID, userInput);
    int exuID = api.AddExuder(behaviorID, aiResponse);
    
    // Tune concepts based on successful interaction
    api.TuneConcepts(true, false, true);
}

Capabilities:

  • Self-improvement
  • Pattern learning
  • Feedback loops
  • Adaptive AI

3. Domain Knowledge Import (Enterprise Integration)

csharp
// Import product catalog
foreach (Product product in catalog) {
    int productID = api.GetOrAddConcept(product.Name);
    int categoryID = api.GetOrAddConcept(product.Category);
    
    // Build semantic network
    api.SetBinding(product.Name, product.Category, "isa");
    api.SetBinding(product.Name, product.Price.ToString(), "price");
    api.SetBinding(product.Name, product.SKU, "sku");
    
    // Create behavior for product queries
    int behaviorID = api.GetBehaviorID("products", product.SKU);
    api.AddAbsorber(behaviorID, $"* {product.Name} *");
    api.AddAbsorber(behaviorID, $"tell me about {product.Name}");
    
    string response = $"{product.Name} is a {product.Category} priced at ${product.Price}. {product.Description}";
    api.AddExuder(behaviorID, response);
}

// Optimize
api.TuneConcepts(true, true, true);
Core.SaveBrain("product_catalog_brain.txt");

Capabilities:

  • Database → Brain conversion
  • Semantic product catalog
  • Natural language queries
  • Dynamic updates

4. Multi-Language Support (Translation Layer)

csharp
// English brain
int enBehaviorID = api.GetBehaviorID("greetings_en", "hello");
api.AddAbsorber(enBehaviorID, "hello");
api.AddAbsorber(enBehaviorID, "hi");
api.AddExuder(enBehaviorID, "Hello there!");

// Spanish brain (reuse absorber structure)
int esBehaviorID = api.GetBehaviorID("greetings_es", "hola");
api.AddAbsorber(esBehaviorID, "hola");
api.AddAbsorber(esBehaviorID, "buenos días");
api.AddExuder(esBehaviorID, "¡Hola!");

// Link translations via bindings
api.SetBinding("hello", "hola", "translation");
api.SetBinding("goodbye", "adiós", "translation");

Capabilities:

  • Multi-language AI
  • Translation lookups
  • Cultural adaptation
  • Language detection

Migration From Legacy

Changes from SILVIA 2.x

NEW in 3.1:

  • API Usage Tracking: SetApiTrackingEnabled(), GetTotalApiCalls(), logging
  • Rate Limiting: SetRateLimit(), IsRateLimited()
  • Subgroup Support: GetBehaviorID() now accepts optional subgroup parameter
  • Typed Data Methods: GetTypedBehaviorData(), SetTypedBehaviorData(), AddBehaviorData()
  • Enhanced Metadata: GetAllBehaviorsInfos(), GetAllGroupsSubgroupsNames()
  • Prompt Templates: SetAbsorberIsPrompt(), SetExuderIsPrompt() for LLM integration

UNCHANGED:

  • All core concept/binding/behavior methods remain compatible
  • Brain file format unchanged (3.1 reads 2.x brains)
  • Script execution model unchanged

Breaking Changes:

  • None - 3.1 is fully backward compatible

Best Practices

1. Concept Management

csharp
// GOOD: Auto-create concepts as needed
int id = api.GetOrAddConcept(word);

// BAD: Don't manually track concept IDs
Dictionary<string, int> conceptCache = new Dictionary<string, int>();

// GOOD: Clean up regularly
api.RemoveUnusedConcepts();
api.CleanConcepts();

// GOOD: Tune after major changes
api.TuneConcepts(true, true, true);

2. Behavior Organization

csharp
// GOOD: Hierarchical organization
api.GetBehaviorID("support", "help", "technical");
api.GetBehaviorID("support", "help", "billing");
api.GetBehaviorID("conversation", "greeting", "formal");
api.GetBehaviorID("conversation", "greeting", "casual");

// BAD: Flat organization
api.GetBehaviorID("behaviors", "behavior_1");
api.GetBehaviorID("behaviors", "behavior_2");

3. Absorber Patterns

csharp
// GOOD: Flexible patterns with wildcards
api.AddAbsorber(id, "show * status");
api.AddAbsorber(id, "* help *");

// BAD: Too many exact variations
api.AddAbsorber(id, "show system status");
api.AddAbsorber(id, "show server status");
api.AddAbsorber(id, "show database status");
// Better: "show * status" catches all

4. Script Integration

csharp
// GOOD: Clear, focused scripts
string script = @"
public bool Invoke() {
    // Single responsibility
    bool valid = ValidateInput();
    if (!valid) return false;
    
    // Set results for exuder
    _core.SetVariable(""$result"", result);
    return true;
}
";

// BAD: Monolithic scripts
// Don't put entire application logic in one behavior script

5. API Tracking

csharp
// GOOD: Enable for production monitoring
api.SetApiTrackingEnabled(true);
api.SetLoggingEnabled(true);

// Periodic reporting
int calls = api.GetTotalApiCalls();
if (calls > 100000) {
    GenerateUsageReport();
    api.ClearApiTracking();
}

Performance Notes

Concept Operations:

  • GetOrAddConcept(): O(log n) dictionary lookup
  • RemoveUnusedConcepts(): O(n*m) where m = behaviors
  • TuneConcepts(): O(nmk) where k = avg absorbers/exuders per behavior

Behavior Operations:

  • GetBehaviorID(): O(n) linear search (cached after first call)
  • AddAbsorber()/AddExuder(): O(1) append
  • GetAbsorberText(): O(1) direct access

Optimization Tips:

  • Cache behavior IDs instead of calling GetBehaviorID() repeatedly
  • Use TuneConcepts() sparingly (expensive operation)
  • Clean concepts after bulk imports: RemoveUnusedConcepts() + CleanConcepts()

See Also

  • ApiCore - Variables, timed functions, core management
  • ApiBrain - Inference, response generation, behavior execution
  • ApiMem - Brain loading/saving, group management, merging
  • ApiFeedback - Conversational memory, context tracking
  • ApiApp - Multi-modal output, TTS, PAGER tags

© Copyright Cognitive Code Corp. 2007-2026

SILVIA is a registered Trademark of Cognitive Code Corp.

SILVIA is a registered Trademark of Cognitive Code Corp.