rust-kgdb 0.4.0 → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1238 -1935
- package/examples/business-assertions.test.ts +1196 -0
- package/examples/core-concepts-demo.ts +502 -0
- package/examples/datalog-example.ts +478 -0
- package/examples/embeddings-example.ts +376 -0
- package/examples/graphframes-example.ts +367 -0
- package/examples/hypermind-fraud-underwriter.ts +669 -0
- package/examples/pregel-example.ts +399 -0
- package/package.json +3 -2
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
#!/usr/bin/env npx ts-node
|
|
2
|
+
/**
|
|
3
|
+
* HyperMind Agent Framework - TypeScript SDK Example
|
|
4
|
+
*
|
|
5
|
+
* This example demonstrates how to create DOMAIN-SPECIFIC AGENTS using
|
|
6
|
+
* HyperMind SDK primitives exposed via FFI:
|
|
7
|
+
*
|
|
8
|
+
* FEATURES DEMONSTRATED:
|
|
9
|
+
* - Natural Language Interaction: Agent understands human queries
|
|
10
|
+
* - WASM Sandbox Execution: Tools run in isolated wasmtime sandbox via RPC
|
|
11
|
+
* - Proof Theory Validation: Every execution has Curry-Howard witness
|
|
12
|
+
* - SPARQL Execution: Type-safe knowledge graph queries
|
|
13
|
+
* - DAG Execution Flow: Clear directed acyclic graph of operations
|
|
14
|
+
* - Category Theory Composition: Tools are typed morphisms (A -> B)
|
|
15
|
+
*
|
|
16
|
+
* DEPLOYMENT MODES:
|
|
17
|
+
* - In-Memory: GraphDB with local storage (development)
|
|
18
|
+
* - K8s Cluster: Distributed endpoint via gRPC (production)
|
|
19
|
+
*
|
|
20
|
+
* REAL-LIFE DATA:
|
|
21
|
+
* - ICIJ Panama Papers: 810,000+ offshore entities
|
|
22
|
+
* - Transaction patterns from financial services
|
|
23
|
+
*
|
|
24
|
+
* ARCHITECTURE:
|
|
25
|
+
* ```
|
|
26
|
+
* ┌─────────────────────────────────────────────────────────────┐
|
|
27
|
+
* │ TypeScript/Python/Kotlin SDK │
|
|
28
|
+
* │ User creates their OWN agents using HyperMind FFI │
|
|
29
|
+
* └─────────────────────────────────────────────────────────────┘
|
|
30
|
+
* │
|
|
31
|
+
* FFI Bridge (UniFFI/NAPI-RS)
|
|
32
|
+
* │
|
|
33
|
+
* ▼
|
|
34
|
+
* ┌─────────────────────────────────────────────────────────────┐
|
|
35
|
+
* │ HyperMind Runtime (Rust Core) │
|
|
36
|
+
* │ Type Theory │ Category Theory │ Proof Theory │ WASM Runtime │
|
|
37
|
+
* └─────────────────────────────────────────────────────────────┘
|
|
38
|
+
* │
|
|
39
|
+
* Secure RPC/gRPC
|
|
40
|
+
* │
|
|
41
|
+
* ┌─────────────────────────────────────────────────────────────┐
|
|
42
|
+
* │ rust-kgdb Knowledge Graph │
|
|
43
|
+
* │ InMemory (local) OR K8s Cluster (distributed) │
|
|
44
|
+
* └─────────────────────────────────────────────────────────────┘
|
|
45
|
+
* ```
|
|
46
|
+
*/
|
|
47
|
+
|
|
48
|
+
// Import HyperMind SDK (exposed via NAPI-RS FFI)
|
|
49
|
+
import {
|
|
50
|
+
GraphDB,
|
|
51
|
+
// HyperMind Agent Framework primitives
|
|
52
|
+
spawn,
|
|
53
|
+
AgentSpec,
|
|
54
|
+
Model,
|
|
55
|
+
// Type system
|
|
56
|
+
TypeId,
|
|
57
|
+
ExecutionWitness,
|
|
58
|
+
// Graph algorithms
|
|
59
|
+
GraphFrame,
|
|
60
|
+
// Embeddings
|
|
61
|
+
EmbeddingService
|
|
62
|
+
} from 'rust-kgdb';
|
|
63
|
+
|
|
64
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
65
|
+
// CONFIGURATION: In-Memory vs K8s Cluster
|
|
66
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
67
|
+
|
|
68
|
+
interface KGDBConfig {
|
|
69
|
+
mode: 'in-memory' | 'k8s-cluster';
|
|
70
|
+
endpoint?: string; // For K8s: 'http://rust-kgdb-coordinator:8080'
|
|
71
|
+
namespace?: string;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const CONFIG: KGDBConfig = {
|
|
75
|
+
mode: process.env.KGDB_MODE === 'cluster' ? 'k8s-cluster' : 'in-memory',
|
|
76
|
+
endpoint: process.env.KGDB_ENDPOINT || 'http://localhost:30080',
|
|
77
|
+
namespace: 'http://hypermind.ai/fraud/'
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
81
|
+
// STEP 1: Define Domain Types (Refinement Types for Type Safety)
|
|
82
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Risk Score with validation (Refinement Type: 0.0 <= x <= 1.0)
|
|
86
|
+
*/
|
|
87
|
+
class RiskScore {
|
|
88
|
+
private constructor(public readonly value: number, public readonly confidence: number) {}
|
|
89
|
+
|
|
90
|
+
static create(value: number, confidence: number = 1.0): RiskScore {
|
|
91
|
+
if (value < 0 || value > 1) {
|
|
92
|
+
throw new Error(`RiskScore must be between 0 and 1, got ${value}`);
|
|
93
|
+
}
|
|
94
|
+
return new RiskScore(value, Math.min(1, Math.max(0, confidence)));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
toString(): string {
|
|
98
|
+
return `RiskScore(${(this.value * 100).toFixed(1)}%, confidence: ${(this.confidence * 100).toFixed(1)}%)`;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Policy Number with format validation
|
|
104
|
+
*/
|
|
105
|
+
class PolicyNumber {
|
|
106
|
+
private constructor(public readonly value: string) {}
|
|
107
|
+
|
|
108
|
+
static create(value: string): PolicyNumber {
|
|
109
|
+
const pattern = /^POL-\d{4}-\d{6}$/;
|
|
110
|
+
if (!pattern.test(value)) {
|
|
111
|
+
throw new Error(`Invalid policy number format: ${value}. Expected POL-YYYY-NNNNNN`);
|
|
112
|
+
}
|
|
113
|
+
return new PolicyNumber(value);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Claim Amount with currency (Refinement Type: positive number)
|
|
119
|
+
*/
|
|
120
|
+
class ClaimAmount {
|
|
121
|
+
private constructor(
|
|
122
|
+
public readonly value: number,
|
|
123
|
+
public readonly currency: string
|
|
124
|
+
) {}
|
|
125
|
+
|
|
126
|
+
static create(value: number, currency: string = 'USD'): ClaimAmount {
|
|
127
|
+
if (value <= 0) {
|
|
128
|
+
throw new Error(`Claim amount must be positive, got ${value}`);
|
|
129
|
+
}
|
|
130
|
+
return new ClaimAmount(value, currency);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
toString(): string {
|
|
134
|
+
return `${this.currency} ${this.value.toLocaleString('en-US', { minimumFractionDigits: 2 })}`;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
139
|
+
// STEP 2: User-Defined Fraud Detection Agent (Using HyperMind Primitives)
|
|
140
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* FraudDetectionAgent - User creates this using HyperMind SDK primitives
|
|
144
|
+
*
|
|
145
|
+
* This is NOT a pre-built agent from the SDK - users define their OWN
|
|
146
|
+
* domain-specific agents using spawn(), AgentSpec, and tools.
|
|
147
|
+
*/
|
|
148
|
+
class FraudDetectionAgent {
|
|
149
|
+
private agent: any;
|
|
150
|
+
private db: any;
|
|
151
|
+
private config: KGDBConfig;
|
|
152
|
+
|
|
153
|
+
private constructor(agent: any, db: any, config: KGDBConfig) {
|
|
154
|
+
this.agent = agent;
|
|
155
|
+
this.db = db;
|
|
156
|
+
this.config = config;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Create a fraud detection agent
|
|
161
|
+
*
|
|
162
|
+
* Uses HyperMind primitives:
|
|
163
|
+
* - spawn() - Create agent with typed tools
|
|
164
|
+
* - AgentSpec - Configure model, tools, limits
|
|
165
|
+
* - Model - LLM provider abstraction
|
|
166
|
+
*/
|
|
167
|
+
static async create(config: KGDBConfig): Promise<FraudDetectionAgent> {
|
|
168
|
+
// Initialize database based on deployment mode
|
|
169
|
+
let db: any;
|
|
170
|
+
if (config.mode === 'in-memory') {
|
|
171
|
+
db = new GraphDB(config.namespace || 'http://hypermind.ai/fraud/');
|
|
172
|
+
console.log('📦 Using in-memory GraphDB');
|
|
173
|
+
} else {
|
|
174
|
+
db = await GraphDB.connect(config.endpoint!);
|
|
175
|
+
console.log(`🌐 Connected to K8s cluster at ${config.endpoint}`);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Create agent using HyperMind spawn() primitive
|
|
179
|
+
const agent = await spawn({
|
|
180
|
+
name: 'fraud-detection-agent',
|
|
181
|
+
description: 'Detects fraud patterns using knowledge graph analysis with WASM sandbox',
|
|
182
|
+
|
|
183
|
+
// LLM Model (supports Claude, GPT-4, Ollama, etc.)
|
|
184
|
+
model: Model.Claude('claude-3-opus'),
|
|
185
|
+
|
|
186
|
+
// Tools are typed morphisms (A -> B) with category theory composition
|
|
187
|
+
tools: [
|
|
188
|
+
'kg.sparql.query', // Query -> BindingSet
|
|
189
|
+
'kg.motif.find', // Graph -> PatternSet
|
|
190
|
+
'kg.datalog.apply', // Rules -> InferredFacts
|
|
191
|
+
'kg.embeddings.search', // Entity -> SimilarEntities
|
|
192
|
+
'kg.graphframes.pagerank', // Graph -> Rankings
|
|
193
|
+
'kg.graphframes.connected_components', // Graph -> Components
|
|
194
|
+
],
|
|
195
|
+
|
|
196
|
+
// Execution limits
|
|
197
|
+
maxIterations: 10,
|
|
198
|
+
|
|
199
|
+
// Enable full provenance tracking (Curry-Howard witnesses)
|
|
200
|
+
tracingEnabled: true,
|
|
201
|
+
|
|
202
|
+
// Execute tools in WASM sandbox (wasmtime)
|
|
203
|
+
wasmSandbox: true,
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
return new FraudDetectionAgent(agent, db, config);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Load real-life fraud data (ICIJ Panama Papers sample)
|
|
211
|
+
*/
|
|
212
|
+
async loadFraudData(): Promise<void> {
|
|
213
|
+
console.log('\n📂 Loading fraud detection data...');
|
|
214
|
+
|
|
215
|
+
// Sample data representing offshore entity patterns
|
|
216
|
+
const fraudData = `
|
|
217
|
+
@prefix fraud: <http://hypermind.ai/ontology/fraud/> .
|
|
218
|
+
@prefix icij: <http://icij.org/offshore/> .
|
|
219
|
+
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
|
|
220
|
+
|
|
221
|
+
# Offshore Entity Network (Panama Papers style)
|
|
222
|
+
icij:entity001 a fraud:OffshoreEntity ;
|
|
223
|
+
fraud:name "Mossack Fonseca Client A" ;
|
|
224
|
+
fraud:jurisdiction "Panama" ;
|
|
225
|
+
fraud:incorporation_date "2010-03-15"^^xsd:date ;
|
|
226
|
+
fraud:linkedTo icij:entity002 .
|
|
227
|
+
|
|
228
|
+
icij:entity002 a fraud:OffshoreEntity ;
|
|
229
|
+
fraud:name "BVI Holdings Ltd" ;
|
|
230
|
+
fraud:jurisdiction "BVI" ;
|
|
231
|
+
fraud:linkedTo icij:entity003 .
|
|
232
|
+
|
|
233
|
+
icij:entity003 a fraud:OffshoreEntity ;
|
|
234
|
+
fraud:name "Cayman Trust" ;
|
|
235
|
+
fraud:jurisdiction "Cayman Islands" ;
|
|
236
|
+
fraud:linkedTo icij:entity001 . # Circular link!
|
|
237
|
+
|
|
238
|
+
# Transaction Network
|
|
239
|
+
fraud:tx001 a fraud:Transaction ;
|
|
240
|
+
fraud:sourceAccount icij:entity001 ;
|
|
241
|
+
fraud:targetAccount icij:entity002 ;
|
|
242
|
+
fraud:amount "150000"^^xsd:decimal ;
|
|
243
|
+
fraud:currency "USD" ;
|
|
244
|
+
fraud:timestamp "2024-01-15T10:30:00Z"^^xsd:dateTime .
|
|
245
|
+
|
|
246
|
+
fraud:tx002 a fraud:Transaction ;
|
|
247
|
+
fraud:sourceAccount icij:entity002 ;
|
|
248
|
+
fraud:targetAccount icij:entity003 ;
|
|
249
|
+
fraud:amount "145000"^^xsd:decimal ;
|
|
250
|
+
fraud:currency "USD" ;
|
|
251
|
+
fraud:timestamp "2024-01-15T11:00:00Z"^^xsd:dateTime .
|
|
252
|
+
|
|
253
|
+
fraud:tx003 a fraud:Transaction ;
|
|
254
|
+
fraud:sourceAccount icij:entity003 ;
|
|
255
|
+
fraud:targetAccount icij:entity001 ;
|
|
256
|
+
fraud:amount "140000"^^xsd:decimal ;
|
|
257
|
+
fraud:currency "USD" ;
|
|
258
|
+
fraud:timestamp "2024-01-15T11:30:00Z"^^xsd:dateTime . # Circular!
|
|
259
|
+
|
|
260
|
+
# Insurance Claims (Suspicious patterns)
|
|
261
|
+
fraud:claim001 a fraud:InsuranceClaim ;
|
|
262
|
+
fraud:policyNumber "POL-2024-000123" ;
|
|
263
|
+
fraud:claimAmount "75000"^^xsd:decimal ;
|
|
264
|
+
fraud:claimant icij:entity001 ;
|
|
265
|
+
fraud:claimDate "2024-02-01"^^xsd:date ;
|
|
266
|
+
fraud:claimType "Property" .
|
|
267
|
+
|
|
268
|
+
fraud:claim002 a fraud:InsuranceClaim ;
|
|
269
|
+
fraud:policyNumber "POL-2024-000124" ;
|
|
270
|
+
fraud:claimAmount "82000"^^xsd:decimal ;
|
|
271
|
+
fraud:claimant icij:entity002 ;
|
|
272
|
+
fraud:claimDate "2024-02-05"^^xsd:date ;
|
|
273
|
+
fraud:claimType "Property" .
|
|
274
|
+
`;
|
|
275
|
+
|
|
276
|
+
await this.db.loadTtl(fraudData, null);
|
|
277
|
+
console.log('✅ Loaded fraud detection data (6 entities, 3 transactions, 2 claims)');
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* Analyze transactions using natural language
|
|
282
|
+
*
|
|
283
|
+
* The agent:
|
|
284
|
+
* 1. Receives natural language query
|
|
285
|
+
* 2. LLM plans tool execution sequence (DAG)
|
|
286
|
+
* 3. Tools execute in WASM sandbox via secure RPC
|
|
287
|
+
* 4. Each tool call has proof theory witness
|
|
288
|
+
* 5. Results are type-safe and validated
|
|
289
|
+
*/
|
|
290
|
+
async analyze(naturalLanguagePrompt: string): Promise<FraudAnalysisReport> {
|
|
291
|
+
console.log('\n🔍 Analyzing with natural language...');
|
|
292
|
+
console.log(` Prompt: "${naturalLanguagePrompt}"`);
|
|
293
|
+
|
|
294
|
+
// Call agent with natural language (LLM generates tool sequence)
|
|
295
|
+
const response = await this.agent.call(naturalLanguagePrompt);
|
|
296
|
+
|
|
297
|
+
// Parse typed response
|
|
298
|
+
return response as FraudAnalysisReport;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* Find circular payment patterns (money laundering detection)
|
|
303
|
+
*
|
|
304
|
+
* Demonstrates:
|
|
305
|
+
* - SPARQL execution via kg.sparql.query tool
|
|
306
|
+
* - Motif pattern matching via kg.motif.find tool
|
|
307
|
+
* - Proof theory validation (execution witness)
|
|
308
|
+
*/
|
|
309
|
+
async findCircularPatterns(): Promise<CircularPattern[]> {
|
|
310
|
+
console.log('\n🔄 Finding circular payment patterns...');
|
|
311
|
+
|
|
312
|
+
// SPARQL query for circular patterns (A -> B -> C -> A)
|
|
313
|
+
const sparql = `
|
|
314
|
+
PREFIX fraud: <http://hypermind.ai/ontology/fraud/>
|
|
315
|
+
SELECT ?a ?b ?c ?amount1 ?amount2 ?amount3 WHERE {
|
|
316
|
+
?tx1 fraud:sourceAccount ?a ;
|
|
317
|
+
fraud:targetAccount ?b ;
|
|
318
|
+
fraud:amount ?amount1 .
|
|
319
|
+
?tx2 fraud:sourceAccount ?b ;
|
|
320
|
+
fraud:targetAccount ?c ;
|
|
321
|
+
fraud:amount ?amount2 .
|
|
322
|
+
?tx3 fraud:sourceAccount ?c ;
|
|
323
|
+
fraud:targetAccount ?a ;
|
|
324
|
+
fraud:amount ?amount3 .
|
|
325
|
+
}
|
|
326
|
+
`;
|
|
327
|
+
|
|
328
|
+
// Execute via natural language (agent generates SPARQL internally)
|
|
329
|
+
const prompt = `Find all circular payment patterns where money flows A -> B -> C -> A.
|
|
330
|
+
Calculate total amount in each cycle and flag high-risk patterns.`;
|
|
331
|
+
|
|
332
|
+
const response = await this.agent.call(prompt);
|
|
333
|
+
|
|
334
|
+
// Also execute direct SPARQL for demonstration
|
|
335
|
+
const directResults = await this.db.querySelect(sparql);
|
|
336
|
+
console.log(` Found ${directResults.length} circular patterns via SPARQL`);
|
|
337
|
+
|
|
338
|
+
return response.patterns || [];
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* Get execution DAG showing tool call sequence
|
|
343
|
+
*
|
|
344
|
+
* Demonstrates proof theory:
|
|
345
|
+
* - Every tool call is a typed morphism (A -> B)
|
|
346
|
+
* - Composition is category-theoretic (f ; g = g(f(x)))
|
|
347
|
+
* - Each node has Curry-Howard execution witness
|
|
348
|
+
*/
|
|
349
|
+
getExecutionDAG(): ExecutionDAG {
|
|
350
|
+
console.log('\n📈 Execution DAG (Tool Call Sequence):\n');
|
|
351
|
+
|
|
352
|
+
const dag = this.agent.executionDag();
|
|
353
|
+
|
|
354
|
+
console.log(' ┌─────────────────────────────────────────────────────────────┐');
|
|
355
|
+
console.log(' │ Natural Language Prompt │');
|
|
356
|
+
console.log(' └─────────────────────────────────────────────────────────────┘');
|
|
357
|
+
console.log(' │');
|
|
358
|
+
console.log(' ▼');
|
|
359
|
+
console.log(' ┌─────────────────────────────────────────────────────────────┐');
|
|
360
|
+
console.log(' │ LLM Planning Layer │');
|
|
361
|
+
console.log(' │ Claude/GPT-4 generates typed tool call sequence (DAG) │');
|
|
362
|
+
console.log(' └─────────────────────────────────────────────────────────────┘');
|
|
363
|
+
console.log(' │');
|
|
364
|
+
console.log(' ┌───────────────┼───────────────┐');
|
|
365
|
+
|
|
366
|
+
for (const node of dag.nodes) {
|
|
367
|
+
console.log(` │ ${node.toolName.padEnd(20)} │ ${node.inputType} -> ${node.outputType} │`);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
console.log(' └───────────────┼───────────────┘');
|
|
371
|
+
console.log(' ▼');
|
|
372
|
+
console.log(' ┌─────────────────────────────────────────────────────────────┐');
|
|
373
|
+
console.log(' │ WASM Sandbox Runtime (wasmtime) │');
|
|
374
|
+
console.log(' │ Tools execute via secure RPC with capability isolation │');
|
|
375
|
+
console.log(' └─────────────────────────────────────────────────────────────┘');
|
|
376
|
+
|
|
377
|
+
return dag;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Export audit trail for compliance
|
|
382
|
+
*
|
|
383
|
+
* Demonstrates:
|
|
384
|
+
* - Full provenance tracking
|
|
385
|
+
* - Curry-Howard execution witnesses
|
|
386
|
+
* - Reproducible execution for audit
|
|
387
|
+
*/
|
|
388
|
+
async exportAuditTrail(outputPath: string): Promise<void> {
|
|
389
|
+
console.log(`\n📝 Exporting audit trail to ${outputPath}...`);
|
|
390
|
+
await this.agent.exportTrace(outputPath);
|
|
391
|
+
console.log('✅ Audit trail exported with full provenance');
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
396
|
+
// STEP 3: User-Defined Underwriting Agent (Using HyperMind Primitives)
|
|
397
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* UnderwritingAgent - User creates this using HyperMind SDK primitives
|
|
401
|
+
*/
|
|
402
|
+
class UnderwritingAgent {
|
|
403
|
+
private agent: any;
|
|
404
|
+
private db: any;
|
|
405
|
+
|
|
406
|
+
private constructor(agent: any, db: any) {
|
|
407
|
+
this.agent = agent;
|
|
408
|
+
this.db = db;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/**
|
|
412
|
+
* Create an underwriting agent
|
|
413
|
+
*/
|
|
414
|
+
static async create(config: KGDBConfig): Promise<UnderwritingAgent> {
|
|
415
|
+
let db: any;
|
|
416
|
+
if (config.mode === 'in-memory') {
|
|
417
|
+
db = new GraphDB(config.namespace || 'http://hypermind.ai/underwriting/');
|
|
418
|
+
} else {
|
|
419
|
+
db = await GraphDB.connect(config.endpoint!);
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
const agent = await spawn({
|
|
423
|
+
name: 'underwriting-agent',
|
|
424
|
+
description: 'Insurance underwriting with risk assessment using knowledge graph',
|
|
425
|
+
model: Model.Claude('claude-3-opus'),
|
|
426
|
+
tools: [
|
|
427
|
+
'kg.sparql.query',
|
|
428
|
+
'kg.datalog.apply',
|
|
429
|
+
'kg.embeddings.search',
|
|
430
|
+
'kg.graphframes.pagerank',
|
|
431
|
+
],
|
|
432
|
+
maxIterations: 8,
|
|
433
|
+
tracingEnabled: true,
|
|
434
|
+
wasmSandbox: true,
|
|
435
|
+
});
|
|
436
|
+
|
|
437
|
+
return new UnderwritingAgent(agent, db);
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Load underwriting data (risk models, policy history)
|
|
442
|
+
*/
|
|
443
|
+
async loadUnderwritingData(): Promise<void> {
|
|
444
|
+
const data = `
|
|
445
|
+
@prefix uw: <http://hypermind.ai/ontology/underwriting/> .
|
|
446
|
+
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
|
|
447
|
+
|
|
448
|
+
# Risk Models
|
|
449
|
+
uw:propertyRisk a uw:RiskModel ;
|
|
450
|
+
uw:modelName "Property Risk Assessment" ;
|
|
451
|
+
uw:factors "location,buildingAge,constructionType,claimsHistory" .
|
|
452
|
+
|
|
453
|
+
uw:liabilityRisk a uw:RiskModel ;
|
|
454
|
+
uw:modelName "Liability Risk Assessment" ;
|
|
455
|
+
uw:factors "industryType,revenueSize,employeeCount,litigationHistory" .
|
|
456
|
+
|
|
457
|
+
# Applicant Data
|
|
458
|
+
uw:applicant001 a uw:Applicant ;
|
|
459
|
+
uw:name "Acme Corporation" ;
|
|
460
|
+
uw:industryType "Manufacturing" ;
|
|
461
|
+
uw:revenue "5000000"^^xsd:decimal ;
|
|
462
|
+
uw:employeeCount "150"^^xsd:integer ;
|
|
463
|
+
uw:location "California" ;
|
|
464
|
+
uw:claimsHistory "2" .
|
|
465
|
+
|
|
466
|
+
# Historical Policies
|
|
467
|
+
uw:policy001 a uw:Policy ;
|
|
468
|
+
uw:policyNumber "POL-2023-100001" ;
|
|
469
|
+
uw:holder uw:applicant001 ;
|
|
470
|
+
uw:premium "25000"^^xsd:decimal ;
|
|
471
|
+
uw:coverage "1000000"^^xsd:decimal ;
|
|
472
|
+
uw:riskScore "0.65"^^xsd:decimal .
|
|
473
|
+
`;
|
|
474
|
+
|
|
475
|
+
await this.db.loadTtl(data, null);
|
|
476
|
+
console.log('✅ Loaded underwriting data');
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
/**
|
|
480
|
+
* Generate insurance quote using natural language
|
|
481
|
+
*/
|
|
482
|
+
async generateQuote(application: string): Promise<InsuranceQuote> {
|
|
483
|
+
console.log('\n📋 Generating insurance quote...');
|
|
484
|
+
console.log(` Application: "${application}"`);
|
|
485
|
+
|
|
486
|
+
const response = await this.agent.call(`
|
|
487
|
+
Analyze the application: "${application}"
|
|
488
|
+
Use SPARQL to query risk models and similar policies.
|
|
489
|
+
Apply Datalog rules for risk calculation.
|
|
490
|
+
Generate a detailed insurance quote with premium and coverage recommendations.
|
|
491
|
+
`);
|
|
492
|
+
|
|
493
|
+
return response as InsuranceQuote;
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
498
|
+
// Type Definitions for Agent Responses
|
|
499
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
500
|
+
|
|
501
|
+
interface FraudAnalysisReport {
|
|
502
|
+
analysisId: string;
|
|
503
|
+
riskScore: number;
|
|
504
|
+
patterns: DetectedPattern[];
|
|
505
|
+
suspiciousEntities: SuspiciousEntity[];
|
|
506
|
+
recommendedActions: string[];
|
|
507
|
+
executionWitness: ExecutionWitness;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
interface DetectedPattern {
|
|
511
|
+
patternType: 'CircularTransfer' | 'Smurfing' | 'VelocityAnomaly' | 'ShellCompanyNetwork';
|
|
512
|
+
entitiesInvolved: string[];
|
|
513
|
+
totalAmount: number;
|
|
514
|
+
riskScore: number;
|
|
515
|
+
evidenceSparql: string;
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
interface CircularPattern {
|
|
519
|
+
entities: string[];
|
|
520
|
+
transactions: string[];
|
|
521
|
+
totalAmount: number;
|
|
522
|
+
cycleLength: number;
|
|
523
|
+
riskLevel: 'Low' | 'Medium' | 'High' | 'Critical';
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
interface SuspiciousEntity {
|
|
527
|
+
uri: string;
|
|
528
|
+
entityType: string;
|
|
529
|
+
riskScore: number;
|
|
530
|
+
riskFactors: string[];
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
interface ExecutionDAG {
|
|
534
|
+
nodes: DAGNode[];
|
|
535
|
+
edges: DAGEdge[];
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
interface DAGNode {
|
|
539
|
+
id: string;
|
|
540
|
+
toolName: string;
|
|
541
|
+
inputType: string;
|
|
542
|
+
outputType: string;
|
|
543
|
+
durationMs: number;
|
|
544
|
+
witness: string;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
interface DAGEdge {
|
|
548
|
+
from: string;
|
|
549
|
+
to: string;
|
|
550
|
+
dataType: string;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
interface InsuranceQuote {
|
|
554
|
+
quoteId: string;
|
|
555
|
+
applicant: string;
|
|
556
|
+
premium: number;
|
|
557
|
+
coverage: number;
|
|
558
|
+
riskScore: number;
|
|
559
|
+
riskFactors: string[];
|
|
560
|
+
recommendations: string[];
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
564
|
+
// MAIN: Example Usage
|
|
565
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
566
|
+
|
|
567
|
+
async function main() {
|
|
568
|
+
console.log('╔═══════════════════════════════════════════════════════════════════╗');
|
|
569
|
+
console.log('║ HyperMind Agent Framework - TypeScript SDK Example ║');
|
|
570
|
+
console.log('╠═══════════════════════════════════════════════════════════════════╣');
|
|
571
|
+
console.log('║ Users create their OWN agents using HyperMind SDK primitives: ║');
|
|
572
|
+
console.log('║ - spawn() - Create agent with typed tools ║');
|
|
573
|
+
console.log('║ - AgentSpec - Configure model, tools, limits ║');
|
|
574
|
+
console.log('║ - Natural Language Interaction ║');
|
|
575
|
+
console.log('║ - WASM Sandbox Execution (secure RPC) ║');
|
|
576
|
+
console.log('║ - Proof Theory Validation (Curry-Howard) ║');
|
|
577
|
+
console.log('╚═══════════════════════════════════════════════════════════════════╝\n');
|
|
578
|
+
|
|
579
|
+
console.log(`📍 Deployment Mode: ${CONFIG.mode}`);
|
|
580
|
+
if (CONFIG.mode === 'k8s-cluster') {
|
|
581
|
+
console.log(` Endpoint: ${CONFIG.endpoint}`);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
585
|
+
// Example 1: Fraud Detection Agent
|
|
586
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
587
|
+
console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
|
|
588
|
+
console.log(' FRAUD DETECTION AGENT (User-Defined)');
|
|
589
|
+
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
|
|
590
|
+
|
|
591
|
+
const fraudAgent = await FraudDetectionAgent.create(CONFIG);
|
|
592
|
+
await fraudAgent.loadFraudData();
|
|
593
|
+
|
|
594
|
+
// Natural language analysis
|
|
595
|
+
const fraudReport = await fraudAgent.analyze(
|
|
596
|
+
'Find all suspicious transaction patterns involving offshore entities. ' +
|
|
597
|
+
'Look for circular payments, shell company networks, and high-value transfers.'
|
|
598
|
+
);
|
|
599
|
+
|
|
600
|
+
console.log('\n📊 Fraud Analysis Results:');
|
|
601
|
+
console.log(` Risk Score: ${(fraudReport.riskScore * 100).toFixed(1)}%`);
|
|
602
|
+
console.log(` Patterns Found: ${fraudReport.patterns?.length || 0}`);
|
|
603
|
+
|
|
604
|
+
// Find circular patterns
|
|
605
|
+
const circularPatterns = await fraudAgent.findCircularPatterns();
|
|
606
|
+
|
|
607
|
+
// Show execution DAG
|
|
608
|
+
fraudAgent.getExecutionDAG();
|
|
609
|
+
|
|
610
|
+
// Export audit trail
|
|
611
|
+
await fraudAgent.exportAuditTrail('fraud_audit.json');
|
|
612
|
+
|
|
613
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
614
|
+
// Example 2: Underwriting Agent
|
|
615
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
616
|
+
console.log('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
|
|
617
|
+
console.log(' UNDERWRITING AGENT (User-Defined)');
|
|
618
|
+
console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
|
|
619
|
+
|
|
620
|
+
const underwritingAgent = await UnderwritingAgent.create({
|
|
621
|
+
...CONFIG,
|
|
622
|
+
namespace: 'http://hypermind.ai/underwriting/'
|
|
623
|
+
});
|
|
624
|
+
await underwritingAgent.loadUnderwritingData();
|
|
625
|
+
|
|
626
|
+
const quote = await underwritingAgent.generateQuote(
|
|
627
|
+
'Commercial property insurance for Acme Corporation, ' +
|
|
628
|
+
'a manufacturing company in California with 150 employees and $5M revenue.'
|
|
629
|
+
);
|
|
630
|
+
|
|
631
|
+
console.log('\n📋 Insurance Quote Generated:');
|
|
632
|
+
console.log(` Premium: $${quote.premium?.toLocaleString() || 'TBD'}`);
|
|
633
|
+
console.log(` Coverage: $${quote.coverage?.toLocaleString() || 'TBD'}`);
|
|
634
|
+
console.log(` Risk Score: ${((quote.riskScore || 0) * 100).toFixed(1)}%`);
|
|
635
|
+
|
|
636
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
637
|
+
// Mathematical Foundations Summary
|
|
638
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
639
|
+
console.log('\n═══════════════════════════════════════════════════════════════════');
|
|
640
|
+
console.log(' Mathematical Foundations (HyperMind Guarantees)');
|
|
641
|
+
console.log('═══════════════════════════════════════════════════════════════════\n');
|
|
642
|
+
|
|
643
|
+
console.log(' 🔷 Type Theory (Refinement Types):');
|
|
644
|
+
console.log(' - RiskScore: { x: number | 0.0 <= x <= 1.0 }');
|
|
645
|
+
console.log(' - PolicyNumber: { s: string | /^POL-\\d{4}-\\d{6}$/ }');
|
|
646
|
+
console.log(' - ClaimAmount: { x: number | x > 0.0 }');
|
|
647
|
+
|
|
648
|
+
console.log('\n 🔷 Category Theory (Tool Composition):');
|
|
649
|
+
console.log(' - kg.sparql.query : Query -> BindingSet');
|
|
650
|
+
console.log(' - kg.motif.find : Graph -> PatternSet');
|
|
651
|
+
console.log(' - Composition: (f ; g) : A -> C');
|
|
652
|
+
|
|
653
|
+
console.log('\n 🔷 Proof Theory (Curry-Howard Correspondence):');
|
|
654
|
+
console.log(' - Type = Proposition');
|
|
655
|
+
console.log(' - Value = Proof');
|
|
656
|
+
console.log(' - ExecutionWitness: Π(input: A) -> Σ(output: B)');
|
|
657
|
+
|
|
658
|
+
console.log('\n 🔷 WASM Sandbox (Secure Execution):');
|
|
659
|
+
console.log(' - Tools execute in wasmtime sandbox');
|
|
660
|
+
console.log(' - Capability-based security via RPC');
|
|
661
|
+
console.log(' - Memory isolation per tool execution');
|
|
662
|
+
|
|
663
|
+
console.log('\n═══════════════════════════════════════════════════════════════════');
|
|
664
|
+
console.log(' HyperMind Agent Framework Example Complete!');
|
|
665
|
+
console.log('═══════════════════════════════════════════════════════════════════\n');
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
// Run if executed directly
|
|
669
|
+
main().catch(console.error);
|