AGISystem2 provides a JavaScript/ES Module API for creating reasoning sessions, learning facts, querying knowledge, proving goals, and generating explanations. All methods return structured result objects.
import { Session } from 'agisystem2';
// Create a session with default geometry
const session = new Session({ geometry: 2048 });
// Learn some facts
session.learn(`
isA Socrates Human
Implies (isA ?x Human) (isA ?x Mortal)
`);
// Prove a goal
const result = session.prove('isA Socrates Mortal');
console.log(result.valid); // true
console.log(result.steps); // Proof chain
// Query the knowledge
const query = session.query('isA ?who Mortal');
console.log(query.bindings); // Map with answers
// Clean up
session.close();
# Clone the repository
git clone https://github.com/OutfinityResearch/AGISystem2
# Import directly
import { Session } from './src/runtime/session.mjs';
Creates a new reasoning session.
| Option | Type | Default | Description |
|---|---|---|---|
geometry |
number | Strategy default (exact: 256) |
Strategy-defined geometry parameter. Examples: Dense-Binary uses a bit-length (e.g. 2048 for small demos), Sparse-Polynomial uses a cardinality k (default: 4),
Metric-Affine uses a byte-channel dimension, and exact defaults to 256. You can override via SYS2_GEOMETRY or per-session options.
|
import { Session } from 'agisystem2';
// Default (recommended): exact strategy, geometry 256.
const session = new Session();
// Dense-Binary demo (small geometry for fast experimentation)
const denseBinarySession = new Session({ hdcStrategy: 'dense-binary', geometry: 2048 });
// Sparse-Polynomial (SPHDC): geometry is k (default 4)
const sphdcSession = new Session({ hdcStrategy: 'sparse-polynomial', geometry: 4 });
Parses and executes DSL statements, adding facts and rules to the session.
const result = session.learn(`
loves John Mary
loves Bob Alice
parent John Charlie
`);
// Result structure
{
success: true,
facts: 3,
errors: [],
warnings: []
}
Executes a query with holes (?variables) and returns bindings.
const result = session.query('loves ?who Mary');
// Result structure
{
success: true,
bindings: Map { "who" => { answer: "John", similarity: 0.85 } },
allResults: [
{ bindings: Map {...}, score: 0.85, method: "kb_match" }
]
}
Attempts to prove a goal through backward chaining and returns a proof structure.
| Option | Type | Default | Description |
|---|---|---|---|
timeout |
number | 2000 | Maximum time in milliseconds |
const result = session.prove('isA Socrates Mortal');
// Result structure
{
valid: true, // true if proven, false if disproven/cannot prove
result: true, // true = positive proof, false = disjoint proof
goal: "isA Socrates Mortal",
method: "rule_derivation",
steps: [
{ operation: "match", goal: "...", result: "rule found" },
{ operation: "chain_step", from: "Socrates", to: "Human" }
],
confidence: 0.92
}
Abductive reasoning: finds the best explanation for an observation.
const result = session.abduce('wet Grass');
// Returns ranked explanations
{
success: true,
explanations: [
{ hypothesis: "rained", confidence: 0.8 },
{ hypothesis: "sprinklerOn", confidence: 0.6 }
]
}
Inductive reasoning: discovers patterns and suggests rules from the knowledge base.
const result = session.induce();
// Returns discovered patterns
{
success: true,
patterns: [
{ rule: "Implies (isA ?x Bird) (canFly ?x)", support: 0.9 }
]
}
Generates natural language from operator and arguments.
const text = session.generateText('loves', ['John', 'Mary']);
// "John loves Mary."
Generates detailed explanation from a proof result.
const explanation = session.elaborate(proofResult);
// { text: "Socrates is mortal because Socrates is human...", ... }
Decodes a vector to its structural representation.
const structure = session.decode(someVector);
{
success: true,
structure: {
operator: "loves",
operatorConfidence: 0.85,
arguments: [
{ position: 1, value: "John", confidence: 0.82 },
{ position: 2, value: "Mary", confidence: 0.79 }
]
}
}
Returns natural language summary of a vector.
const summary = session.summarize(factVector);
{
success: true,
text: "John loves Mary.",
structure: { operator: "loves", arguments: [...] }
}
Returns session state for debugging.
const state = session.dump();
{
geometry: 2048,
factCount: 15,
ruleCount: 3,
vocabularySize: 45,
scopeBindings: ["f1", "f2", "r1", ...]
}
Returns reasoning statistics. Pass true to reset counters.
const stats = session.getReasoningStats();
{
queries: 10,
proofs: 5,
kbScans: 23,
similarityChecks: 156,
ruleAttempts: 12,
transitiveSteps: 8,
maxProofDepth: 4,
avgProofLength: "3.2",
methods: { "kb_match": 6, "rule_derivation": 4 },
hdcQueries: 3,
hdcSuccesses: 2
}
Cleans up session resources.
session.close();
Low-level vector operations for advanced use.
import {
bind,
bindAll,
bundle,
similarity,
distance,
topKSimilar,
unbind
} from 'agisystem2';
// Bind two vectors
const composite = bind(vectorA, vectorB);
// Unbind (strategy-specific; XOR-based strategies can reuse bind)
const recovered = unbind(composite, vectorB); // ≈ vectorA
// Bundle multiple vectors
const kb = bundle([fact1, fact2, fact3]);
// Calculate similarity
const sim = similarity(vectorA, vectorB); // 0.0 to 1.0
// Find most similar vectors
const matches = topKSimilar(query, vocabulary, 5);
import {
getPositionVector,
withPosition,
removePosition,
extractAtPosition
} from 'agisystem2';
// Get position vector (1-20)
const pos1 = getPositionVector(1, 2048);
// Add position to a vector
const positioned = withPosition(1, johnVector);
// Remove position from a vector
const extracted = removePosition(1, positionedVector);
import { initHDC, getStrategyId } from './src/hdc/facade.mjs';
// Initialize specific strategy
initHDC('dense-binary'); // Classic: 2048-bit binary vectors
initHDC('sparse-polynomial'); // SPHDC: k=4 exponent sets
initHDC('metric-affine'); // Byte-channel vectors (fast baseline)
initHDC('metric-affine-elastic'); // EMA: elastic geometry + chunked bundling
initHDC('exact'); // EXACT: lossless session-local bitset-polynomials (UNBIND differs from bind)
// Check current strategy
console.log(getStrategyId()); // e.g. "dense-binary", "metric-affine", "exact", ...
import { parse, Lexer, Parser, ParseError } from 'agisystem2';
// Parse DSL to AST
const ast = parse('loves John Mary');
// Manual lexing
const lexer = new Lexer('loves John Mary');
const tokens = lexer.tokenize();
// Manual parsing
const parser = new Parser(tokens);
const ast = parser.parse();
import { TestSession, Assertions } from 'agisystem2';
const test = new TestSession({ geometry: 2048 });
test.learn('isA Dog Animal');
test.assertProves('isA Dog Animal');
test.assertNotProves('isA Cat Dog');
test.assertQueryReturns('isA ?x Animal', 'x', 'Dog');
interface LearnResult {
success: boolean;
facts: number;
errors: string[];
warnings: string[];
}
interface QueryResult {
success: boolean;
bindings: Map<string, { answer: string, similarity: number }>;
allResults: Array<{
bindings: Map<string, any>,
score: number,
method: string
}>;
}
interface ProveResult {
valid: boolean;
result?: boolean; // true = positive, false = disjoint proof
goal: string;
method?: string;
steps: ProofStep[];
confidence?: number;
reason?: string; // If invalid, why
}
interface ProofStep {
operation: string;
goal?: string;
from?: string;
to?: string;
result?: string;
}
import { ParseError, ExecutionError } from 'agisystem2';
try {
session.learn('invalid!!! syntax @@@');
} catch (e) {
if (e instanceof ParseError) {
console.log(`Parse error at line ${e.line}: ${e.message}`);
} else if (e instanceof ExecutionError) {
console.log(`Execution error: ${e.message}`);
}
}
import { Session } from 'agisystem2';
async function reasoningDemo() {
const session = new Session({ geometry: 2048 });
// Define knowledge
session.learn(`
# Facts
isA Socrates Human
isA Plato Human
teaches Socrates Plato
# Rules
Implies (isA ?x Human) (isA ?x Mortal)
Implies (teaches ?x ?y) (knows ?y ?x)
`);
// Query: Who is mortal?
const q1 = session.query('isA ?who Mortal');
if (q1.success) {
console.log('Mortals:', q1.bindings.get('who')?.answer);
}
// Prove with explanation
const proof = session.prove('isA Socrates Mortal');
console.log('Proof valid:', proof.valid);
console.log('Method:', proof.method);
console.log('Steps:', proof.steps.length);
// Natural language
const text = session.generateText('isA', ['Socrates', 'Mortal']);
console.log('Generated:', text);
// Stats
console.log('Stats:', session.getReasoningStats());
session.close();
}
reasoningDemo();