AGISystem2 provides a JavaScript/TypeScript API for creating reasoning sessions, learning facts, querying knowledge, and generating explanations. All methods return structured result objects with confidence scores.
import { createSpockEngine, createSessionApi } from 'agisystem2';
// Create engine with default geometry (32K bits)
const engine = createSpockEngine({ dimensions: 32768 });
// Create a session
const session = engine.createSession();
const api = createSessionApi(session);
// Learn some facts
api.learn(`
@f1 Socrates Is Human
@f2 Humans Are Mortal
`);
// Query the knowledge
const result = api.query(`@q ?who Is Mortal`);
console.log(result.bindings.who.answer); // "Socrates"
console.log(result.confidence); // ~0.75
// Generate explanation
const explanation = api.summarize(result);
console.log(explanation.text); // "Socrates is Mortal"
// Clean up
session.close();
Creates a new AGISystem2 engine instance.
| Option | Type | Default | Description |
|---|---|---|---|
dimensions |
number | 32768 | Vector geometry (1024, 8192, 32768, 65536) |
theoryPaths |
string[] | [] | Additional theory search paths |
logLevel |
string | "warn" | Logging level (debug, info, warn, error) |
const engine = createSpockEngine({
dimensions: 32768,
theoryPaths: ['./my-theories'],
logLevel: 'info'
});
Creates a new isolated reasoning session.
const session = engine.createSession({
name: 'my-session',
preloadTheories: ['Commerce', 'Physics']
});
Parses and executes DSL statements, adding facts and definitions to the session.
const result = session.learn(`
@f1 loves John Mary
@f2 loves Bob Alice
@f3 parent John Charlie
`);
// Result structure
{
success: true,
statements: 3,
warnings: [],
errors: []
}
Executes a query with holes (?variables) and returns bindings.
const result = session.query(`@q loves ?who Mary`);
// Result structure
{
success: true,
bindings: {
"who": {
answer: "John",
similarity: 0.78,
alternatives: [
{ value: "Bob", similarity: 0.52 }
]
}
},
confidence: 0.78,
ambiguous: false
}
Attempts to prove a goal through backward chaining and returns a proof tree.
const result = session.prove(`@goal isA Socrates Mortal`);
// Result structure
{
valid: true,
proof: {
goal: "isA Socrates Mortal",
method: "rule",
rule: "humans_are_mortal",
premises: [
{ goal: "isA Socrates Human", method: "direct", confidence: 0.95 }
]
},
steps: [
{ operation: "match", goal: "isA Socrates Mortal", result: "rule found" },
{ operation: "prove", goal: "isA Socrates Human", result: "direct KB" }
],
confidence: 0.92
}
Generates concise natural language from a vector or query result.
const summary = session.summarize(queryResult);
// Result structure
{
success: true,
text: "John loves Mary.",
confidence: 0.78,
structure: { operator: "loves", arguments: [...] }
}
Generates detailed narrative explanation, optionally using LLM refinement.
const detailed = session.elaborate(queryResult, { useLLM: true });
// Result structure
{
success: true,
text: "John has romantic feelings for Mary.",
baseText: "John loves Mary.",
confidence: 0.78,
llmRefined: true
}
Returns complete session state for debugging.
const state = session.dump();
// Result structure
{
scope: { "f1": {...}, "f2": {...} },
facts: [
{ name: "f1", dsl: "loves John Mary", confidence: 1.0 }
],
vocabulary: { count: 156, theories: ["Core", "session"] },
theories: ["Core"],
stats: {
learnCalls: 3,
queryCalls: 1,
proveCalls: 0,
startTime: "2024-01-15T10:30:00Z"
}
}
Returns detailed information about a named vector.
const info = session.inspect("f1");
// Result structure
{
name: "f1",
type: "fact",
density: 0.501,
popcount: 16412,
similarTo: [
{ name: "f2", similarity: 0.68 },
{ name: "loves", similarity: 0.55 }
],
structure: {
operator: "loves",
arguments: [
{ position: 1, value: "John", confidence: 0.85 },
{ position: 2, value: "Mary", confidence: 0.82 }
]
},
inKB: true
}
const theories = session.listTheories();
// ["Core", "Commerce", "Physics"]
const atoms = session.listAtoms("Core");
// [{ name: "__Atom", theory: "Core" }, ...]
const macros = session.listMacros();
// [{ name: "definePerson", params: ["name", "age"], theory: "People" }]
const facts = session.listFacts();
// [{ name: "f1", dsl: "loves John Mary" }, ...]
const sim = session.similarity("John", "Mary");
// 0.502 (near random - unrelated concepts)
const structure = session.decode(someVector);
// { operator: "loves", arguments: [...], confidence: 0.82 }
interface LearnResult {
success: boolean;
statements: number;
warnings: string[];
errors: Array<{
message: string;
line: number;
column: number;
}>;
}
interface QueryResult {
success: boolean;
bindings: Record<string, Binding>;
confidence: number;
ambiguous: boolean;
reason?: string;
}
interface Binding {
answer: string;
similarity: number;
alternatives: Array<{ value: string; similarity: number }>;
}
interface ProveResult {
valid: boolean;
proof: ProofTree | null;
steps: ProofStep[];
confidence: number;
reason?: string;
}
interface ProofTree {
goal: string;
method: "direct" | "rule" | "assumption";
rule?: string;
premises?: ProofTree[];
confidence: number;
}
interface ProofStep {
operation: string;
goal: string;
result: string;
timestamp: string;
}
import { AGIError, ParseError, QueryError } from 'agisystem2';
try {
const result = session.learn(`@invalid syntax!!!`);
} catch (e) {
if (e instanceof ParseError) {
console.log(`Parse error at line ${e.line}, column ${e.column}`);
console.log(`Expected: ${e.expected}, Found: ${e.found}`);
} else if (e instanceof AGIError) {
console.log(`AGI error: ${e.message}`);
}
}
| Geometry | Memory/Vector | KB Capacity | Use Case |
|---|---|---|---|
| 1024 | 128 bytes | ~10 facts | Toy examples |
| 8192 | 1 KB | ~50 facts | Small domains |
| 32768 | 4 KB | ~200 facts | Production (default) |
| 65536 | 8 KB | ~400 facts | Large KBs |
const engine = createSpockEngine({
thresholds: {
strongMatch: 0.80, // Trust completely
goodMatch: 0.65, // Probably correct
weakMatch: 0.55, // Verify if critical
noMatch: 0.50 // Random noise
}
});
import { createSpockEngine, createSessionApi } from 'agisystem2';
async function reasoningExample() {
// Initialize
const engine = createSpockEngine({ dimensions: 32768 });
const session = engine.createSession();
const api = createSessionApi(session);
// Define domain knowledge
api.learn(`
# People
@f1 isA Socrates Human
@f2 isA Plato Human
@f3 isA Aristotle Human
# Relationships
@f4 teaches Socrates Plato
@f5 teaches Plato Aristotle
# Rules
@r1 Implies (isA ?x Human) (isA ?x Mortal)
@r2 Implies (teaches ?x ?y) (knows ?y ?x)
`);
// Query: Who is mortal?
const q1 = api.query(`@q isA ?who Mortal`);
console.log("Mortals:", q1.bindings.who.answer);
// Query: Who does Plato know?
const q2 = api.query(`@q knows Plato ?who`);
console.log("Plato knows:", q2.bindings.who.answer);
// Prove with explanation
const proof = api.prove(`@goal isA Socrates Mortal`);
console.log("Proof valid:", proof.valid);
console.log("Steps:", proof.steps.length);
// Generate explanation
const explanation = api.elaborate(proof, { useLLM: false });
console.log("Explanation:", explanation.text);
// Debug
console.log("Session stats:", session.dump().stats);
// Cleanup
session.close();
}
reasoningExample();