kbs 0.0.1

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.
Files changed (55) hide show
  1. checksums.yaml +7 -0
  2. data/.envrc +3 -0
  3. data/CHANGELOG.md +5 -0
  4. data/COMMITS.md +196 -0
  5. data/LICENSE.txt +21 -0
  6. data/README.md +481 -0
  7. data/Rakefile +8 -0
  8. data/examples/README.md +531 -0
  9. data/examples/advanced_example.rb +270 -0
  10. data/examples/ai_enhanced_kbs.rb +523 -0
  11. data/examples/blackboard_demo.rb +50 -0
  12. data/examples/car_diagnostic.rb +64 -0
  13. data/examples/concurrent_inference_demo.rb +363 -0
  14. data/examples/csv_trading_system.rb +559 -0
  15. data/examples/iot_demo_using_dsl.rb +83 -0
  16. data/examples/portfolio_rebalancing_system.rb +651 -0
  17. data/examples/redis_trading_demo.rb +177 -0
  18. data/examples/sample_stock_data.csv +46 -0
  19. data/examples/stock_trading_advanced.rb +469 -0
  20. data/examples/stock_trading_system.rb.bak +563 -0
  21. data/examples/timestamped_trading.rb +286 -0
  22. data/examples/trading_demo.rb +334 -0
  23. data/examples/working_demo.rb +176 -0
  24. data/lib/kbs/alpha_memory.rb +37 -0
  25. data/lib/kbs/beta_memory.rb +57 -0
  26. data/lib/kbs/blackboard/audit_log.rb +115 -0
  27. data/lib/kbs/blackboard/engine.rb +83 -0
  28. data/lib/kbs/blackboard/fact.rb +65 -0
  29. data/lib/kbs/blackboard/memory.rb +191 -0
  30. data/lib/kbs/blackboard/message_queue.rb +96 -0
  31. data/lib/kbs/blackboard/persistence/hybrid_store.rb +118 -0
  32. data/lib/kbs/blackboard/persistence/redis_store.rb +218 -0
  33. data/lib/kbs/blackboard/persistence/sqlite_store.rb +242 -0
  34. data/lib/kbs/blackboard/persistence/store.rb +55 -0
  35. data/lib/kbs/blackboard/redis_audit_log.rb +107 -0
  36. data/lib/kbs/blackboard/redis_message_queue.rb +111 -0
  37. data/lib/kbs/blackboard.rb +23 -0
  38. data/lib/kbs/condition.rb +26 -0
  39. data/lib/kbs/dsl/condition_helpers.rb +57 -0
  40. data/lib/kbs/dsl/knowledge_base.rb +86 -0
  41. data/lib/kbs/dsl/pattern_evaluator.rb +69 -0
  42. data/lib/kbs/dsl/rule_builder.rb +115 -0
  43. data/lib/kbs/dsl/variable.rb +35 -0
  44. data/lib/kbs/dsl.rb +18 -0
  45. data/lib/kbs/fact.rb +43 -0
  46. data/lib/kbs/join_node.rb +117 -0
  47. data/lib/kbs/negation_node.rb +88 -0
  48. data/lib/kbs/production_node.rb +28 -0
  49. data/lib/kbs/rete_engine.rb +108 -0
  50. data/lib/kbs/rule.rb +46 -0
  51. data/lib/kbs/token.rb +37 -0
  52. data/lib/kbs/version.rb +5 -0
  53. data/lib/kbs/working_memory.rb +32 -0
  54. data/lib/kbs.rb +20 -0
  55. metadata +164 -0
@@ -0,0 +1,531 @@
1
+ # KBS Examples
2
+
3
+ This directory contains comprehensive examples demonstrating the capabilities of the KBS (Knowledge-Based System) gem. Each example showcases different features and use cases of the RETE II inference engine and blackboard architecture.
4
+
5
+ ## Table of Contents
6
+
7
+ - [Getting Started](#getting-started)
8
+ - [Basic Examples](#basic-examples)
9
+ - [car_diagnostic.rb](#car_diagnosticrb)
10
+ - [working_demo.rb](#working_demorb)
11
+ - [DSL Examples](#dsl-examples)
12
+ - [iot_demo_using_dsl.rb](#iot_demo_using_dslrb)
13
+ - [trading_demo.rb](#trading_demorb)
14
+ - [Advanced Trading Examples](#advanced-trading-examples)
15
+ - [advanced_example.rb](#advanced_examplerb)
16
+ - [stock_trading_advanced.rb](#stock_trading_advancedrb)
17
+ - [timestamped_trading.rb](#timestamped_tradingrb)
18
+ - [csv_trading_system.rb](#csv_trading_systemrb)
19
+ - [portfolio_rebalancing_system.rb](#portfolio_rebalancing_systemrb)
20
+ - [Blackboard & Persistence Examples](#blackboard--persistence-examples)
21
+ - [blackboard_demo.rb](#blackboard_demorb)
22
+ - [redis_trading_demo.rb](#redis_trading_demorb)
23
+ - [Concurrency Examples](#concurrency-examples)
24
+ - [concurrent_inference_demo.rb](#concurrent_inference_demorb)
25
+ - [AI Integration Examples](#ai-integration-examples)
26
+ - [ai_enhanced_kbs.rb](#ai_enhanced_kbsrb)
27
+
28
+ ## Getting Started
29
+
30
+ All examples can be run directly:
31
+
32
+ ```bash
33
+ ./examples/example_name.rb
34
+ # or
35
+ ruby examples/example_name.rb
36
+ ```
37
+
38
+ Some examples require additional dependencies:
39
+ - **redis_trading_demo.rb**: Requires Redis server running (`redis-server`)
40
+ - **ai_enhanced_kbs.rb**: Requires Ollama with a model installed
41
+
42
+ ---
43
+
44
+ ## Basic Examples
45
+
46
+ ### car_diagnostic.rb
47
+
48
+ **Description:** A simple expert system for diagnosing car problems. This is the most basic example, perfect for understanding the fundamentals of rule-based reasoning.
49
+
50
+ **Demonstrates:**
51
+ - Basic rule creation with `KBS::Rule.new`
52
+ - Condition matching with `KBS::Condition`
53
+ - Fact assertion and retraction
54
+ - Negated conditions (absence of facts)
55
+ - Simple forward-chaining inference
56
+
57
+ **What It Does:**
58
+ Diagnoses car problems based on symptoms:
59
+ - Dead battery (won't start + no lights)
60
+ - Flat tire (pulling to side + low pressure)
61
+ - Engine overheating (high temp + steam, but no coolant leak)
62
+
63
+ **Key Concepts:**
64
+ - Rule-based expert systems
65
+ - Pattern matching
66
+ - Negative conditions (checking for absence of facts)
67
+
68
+ ---
69
+
70
+ ### working_demo.rb
71
+
72
+ **Description:** A stock trading signal generator demonstrating multi-condition rules and pattern matching.
73
+
74
+ **Demonstrates:**
75
+ - Multiple conditions per rule
76
+ - Hash-based pattern matching
77
+ - Lambda predicates for dynamic conditions
78
+ - Rule priority
79
+ - Working memory management
80
+
81
+ **What It Does:**
82
+ Generates trading signals based on:
83
+ - Golden cross patterns (moving average crossovers)
84
+ - High volume confirmation
85
+ - Price breakouts with momentum
86
+ - Risk management rules
87
+
88
+ **Key Concepts:**
89
+ - Forward-chaining inference
90
+ - Fact-based reasoning
91
+ - Trading signal generation
92
+
93
+ ---
94
+
95
+ ## DSL Examples
96
+
97
+ ### iot_demo_using_dsl.rb
98
+
99
+ **Description:** IoT sensor monitoring system using the declarative KBS DSL. Shows how to write rules in a more natural, readable syntax.
100
+
101
+ **Demonstrates:**
102
+ - Declarative DSL with `KBS.knowledge_base`
103
+ - Helper functions: `greater_than`, `less_than`, `range`
104
+ - Rule descriptions and metadata
105
+ - Multi-fact pattern matching
106
+ - Negative patterns with `without`
107
+
108
+ **What It Does:**
109
+ Monitors IoT sensors and triggers alerts:
110
+ - Temperature warnings
111
+ - Humidity alerts
112
+ - Combined sensor analysis
113
+ - System health monitoring
114
+
115
+ **Key Concepts:**
116
+ - DSL-based rule definition
117
+ - Sensor data processing
118
+ - Alert generation
119
+ - Readable rule syntax
120
+
121
+ ---
122
+
123
+ ### trading_demo.rb
124
+
125
+ **Description:** Comprehensive trading system demonstrating the full DSL capabilities with multiple trading strategies.
126
+
127
+ **Demonstrates:**
128
+ - Full DSL syntax
129
+ - Multiple trading rules
130
+ - Priority-based rule execution
131
+ - Complex pattern matching
132
+ - Condition helpers (greater_than, one_of, range)
133
+
134
+ **What It Does:**
135
+ Implements various trading strategies:
136
+ - Momentum breakouts
137
+ - Mean reversion
138
+ - Volume analysis
139
+ - Multi-timeframe analysis
140
+
141
+ **Key Concepts:**
142
+ - Strategy combination
143
+ - Priority-based firing
144
+ - Complex condition logic
145
+
146
+ ---
147
+
148
+ ## Advanced Trading Examples
149
+
150
+ ### advanced_example.rb
151
+
152
+ **Description:** Advanced trading patterns with golden cross detection and technical analysis.
153
+
154
+ **Demonstrates:**
155
+ - Complex multi-condition rules
156
+ - Moving average crossover detection
157
+ - Volume confirmation
158
+ - Historical data analysis
159
+ - State tracking across facts
160
+
161
+ **What It Does:**
162
+ - Detects golden cross patterns (50-MA > 200-MA)
163
+ - Validates with volume confirmation
164
+ - Generates buy signals with context
165
+ - Tracks previous state for crossover detection
166
+
167
+ **Key Concepts:**
168
+ - Technical indicator analysis
169
+ - Crossover pattern detection
170
+ - Multi-factor validation
171
+
172
+ ---
173
+
174
+ ### stock_trading_advanced.rb
175
+
176
+ **Description:** Production-grade trading system with position management, stop losses, and portfolio tracking.
177
+
178
+ **Demonstrates:**
179
+ - Position sizing
180
+ - Stop loss management
181
+ - Portfolio state tracking
182
+ - Risk management rules
183
+ - Trade execution simulation
184
+
185
+ **What It Does:**
186
+ - Manages open positions
187
+ - Implements trailing stops
188
+ - Calculates position sizes
189
+ - Tracks P&L
190
+ - Simulates realistic trading
191
+
192
+ **Key Concepts:**
193
+ - Position management
194
+ - Risk control
195
+ - Portfolio tracking
196
+ - Trade lifecycle
197
+
198
+ ---
199
+
200
+ ### timestamped_trading.rb
201
+
202
+ **Description:** Time-aware trading system demonstrating temporal reasoning and time-based rules.
203
+
204
+ **Demonstrates:**
205
+ - Timestamp-based facts
206
+ - Time window analysis
207
+ - Temporal pattern matching
208
+ - Event sequencing
209
+ - Time-based filtering
210
+
211
+ **What It Does:**
212
+ - Analyzes price movements over time
213
+ - Detects trends within time windows
214
+ - Implements time-decay logic
215
+ - Manages time-sensitive signals
216
+
217
+ **Key Concepts:**
218
+ - Temporal reasoning
219
+ - Time-series analysis
220
+ - Event ordering
221
+
222
+ ---
223
+
224
+ ### csv_trading_system.rb
225
+
226
+ **Description:** Real-world example loading market data from CSV files and generating trading signals.
227
+
228
+ **Demonstrates:**
229
+ - External data integration
230
+ - CSV file processing
231
+ - Data transformation
232
+ - Batch fact assertion
233
+ - Historical backtesting
234
+
235
+ **What It Does:**
236
+ - Loads stock data from CSV
237
+ - Calculates technical indicators
238
+ - Generates trading signals
239
+ - Produces analysis reports
240
+
241
+ **Key Concepts:**
242
+ - Data pipeline integration
243
+ - Batch processing
244
+ - Real-world data handling
245
+
246
+ ---
247
+
248
+ ### portfolio_rebalancing_system.rb
249
+
250
+ **Description:** Sophisticated portfolio management system with rebalancing logic and allocation rules.
251
+
252
+ **Demonstrates:**
253
+ - Portfolio-level reasoning
254
+ - Asset allocation
255
+ - Rebalancing triggers
256
+ - Risk distribution
257
+ - Multi-asset coordination
258
+
259
+ **What It Does:**
260
+ - Monitors portfolio allocation
261
+ - Detects imbalances
262
+ - Suggests rebalancing trades
263
+ - Maintains target allocations
264
+ - Manages risk exposure
265
+
266
+ **Key Concepts:**
267
+ - Portfolio optimization
268
+ - Asset allocation
269
+ - Rebalancing strategies
270
+
271
+ ---
272
+
273
+ ## Blackboard & Persistence Examples
274
+
275
+ ### blackboard_demo.rb
276
+
277
+ **Description:** Demonstrates the blackboard architecture with SQLite persistence for durable fact storage.
278
+
279
+ **Demonstrates:**
280
+ - Blackboard pattern
281
+ - SQLite persistence
282
+ - Fact history tracking
283
+ - Message passing
284
+ - Knowledge source registration
285
+ - Audit logging
286
+
287
+ **What It Does:**
288
+ - Stores facts in SQLite database
289
+ - Tracks fact lifecycle (add/update/retract)
290
+ - Implements message queue
291
+ - Maintains audit trail
292
+ - Demonstrates multi-agent coordination
293
+
294
+ **Key Concepts:**
295
+ - Blackboard architecture
296
+ - Persistent storage
297
+ - Message-based coordination
298
+ - Audit trails
299
+
300
+ **Persistence Features:**
301
+ - Durable fact storage
302
+ - Query history
303
+ - Session management
304
+ - Transactional updates
305
+
306
+ ---
307
+
308
+ ### redis_trading_demo.rb
309
+
310
+ **Description:** High-frequency trading system using Redis for fast in-memory fact storage and hybrid persistence.
311
+
312
+ **Demonstrates:**
313
+ - Redis persistence (fast)
314
+ - Hybrid storage (Redis + SQLite)
315
+ - Message queue in Redis
316
+ - High-frequency data handling
317
+ - Performance optimization
318
+ - Dual-store pattern
319
+
320
+ **What It Does:**
321
+ - Stores facts in Redis for speed
322
+ - Uses SQLite for audit trail
323
+ - Implements real-time messaging
324
+ - Handles high-frequency updates
325
+ - Demonstrates production patterns
326
+
327
+ **Key Concepts:**
328
+ - In-memory storage
329
+ - Hybrid persistence
330
+ - Real-time processing
331
+ - Performance optimization
332
+
333
+ **Storage Patterns:**
334
+ - Pure Redis: Fast, volatile
335
+ - Hybrid: Fast reads + durable audit
336
+ - Message queue for inter-component communication
337
+
338
+ **Requirements:** Redis server running on localhost:6379
339
+
340
+ ---
341
+
342
+ ## Concurrency Examples
343
+
344
+ ### concurrent_inference_demo.rb
345
+
346
+ **Description:** Demonstrates concurrent rule execution and automatic inference with background threads.
347
+
348
+ **Demonstrates:**
349
+ - Auto-inference mode
350
+ - Background inference threads
351
+ - Thread-safe fact assertion
352
+ - Concurrent rule firing
353
+ - Blackboard-based coordination
354
+
355
+ **What It Does:**
356
+ - Runs inference in background
357
+ - Allows concurrent fact updates
358
+ - Demonstrates thread safety
359
+ - Shows async processing patterns
360
+
361
+ **Key Concepts:**
362
+ - Concurrent execution
363
+ - Thread safety
364
+ - Auto-inference
365
+ - Background processing
366
+
367
+ **Use Cases:**
368
+ - Real-time monitoring systems
369
+ - Event-driven architectures
370
+ - Continuous processing
371
+
372
+ ---
373
+
374
+ ## AI Integration Examples
375
+
376
+ ### ai_enhanced_kbs.rb
377
+
378
+ **Description:** Cutting-edge integration of LLM AI (via Ollama) with rule-based reasoning, demonstrating hybrid AI systems.
379
+
380
+ **Demonstrates:**
381
+ - LLM integration with RubyLLM
382
+ - AI-powered sentiment analysis
383
+ - Dynamic strategy generation
384
+ - Natural language explanations
385
+ - Hybrid symbolic/neural reasoning
386
+ - Real-time AI inference
387
+
388
+ **What It Does:**
389
+ - Analyzes news sentiment with AI
390
+ - Generates trading strategies using LLMs
391
+ - Creates natural language explanations
392
+ - Performs AI-driven risk assessment
393
+ - Combines rules with machine learning
394
+
395
+ **Key Concepts:**
396
+ - Hybrid AI (symbolic + neural)
397
+ - LLM integration
398
+ - AI-enhanced decision making
399
+ - Natural language generation
400
+
401
+ **AI Capabilities:**
402
+ - News sentiment analysis
403
+ - Strategy generation
404
+ - Risk assessment
405
+ - Trade explanation
406
+ - Pattern recognition
407
+
408
+ **Requirements:**
409
+ - Ollama installed with a model (e.g., `gpt-oss:latest`)
410
+ - Model configured via `OLLAMA_MODEL` environment variable
411
+ - RubyLLM gem
412
+
413
+ **Configuration:**
414
+ ```bash
415
+ export OLLAMA_MODEL=gpt-oss:latest
416
+ ./examples/ai_enhanced_kbs.rb
417
+ ```
418
+
419
+ ---
420
+
421
+ ## Summary of Capabilities
422
+
423
+ ### Core KBS Features
424
+ - ✅ RETE II inference engine
425
+ - ✅ Forward-chaining reasoning
426
+ - ✅ Pattern matching
427
+ - ✅ Negated conditions
428
+ - ✅ Rule priorities
429
+ - ✅ Working memory management
430
+
431
+ ### DSL Features
432
+ - ✅ Declarative rule syntax
433
+ - ✅ Condition helpers (greater_than, less_than, range, one_of)
434
+ - ✅ Readable rule definitions
435
+ - ✅ Negative patterns (without)
436
+
437
+ ### Blackboard Architecture
438
+ - ✅ Multi-agent coordination
439
+ - ✅ Message passing
440
+ - ✅ Knowledge source registration
441
+ - ✅ Shared workspace pattern
442
+
443
+ ### Persistence
444
+ - ✅ SQLite storage (durable, transactional)
445
+ - ✅ Redis storage (fast, in-memory)
446
+ - ✅ Hybrid storage (best of both)
447
+ - ✅ Fact history and audit trails
448
+ - ✅ Session management
449
+
450
+ ### Advanced Features
451
+ - ✅ Concurrent execution
452
+ - ✅ Auto-inference mode
453
+ - ✅ Temporal reasoning
454
+ - ✅ External data integration
455
+ - ✅ AI/LLM integration
456
+ - ✅ Real-time processing
457
+
458
+ ### Use Case Coverage
459
+ - 🏭 Industrial IoT monitoring
460
+ - 📈 Financial trading systems
461
+ - 🚗 Expert systems (diagnostics)
462
+ - 💼 Portfolio management
463
+ - 🤖 AI-enhanced reasoning
464
+ - 📊 Real-time analytics
465
+
466
+ ---
467
+
468
+ ## Running the Examples
469
+
470
+ ### Basic Usage
471
+ ```bash
472
+ # Simple examples
473
+ ./examples/car_diagnostic.rb
474
+ ./examples/working_demo.rb
475
+
476
+ # DSL examples
477
+ ./examples/iot_demo_using_dsl.rb
478
+ ./examples/trading_demo.rb
479
+
480
+ # Advanced trading
481
+ ./examples/advanced_example.rb
482
+ ./examples/stock_trading_advanced.rb
483
+
484
+ # Persistence (requires Redis)
485
+ redis-server &
486
+ ./examples/redis_trading_demo.rb
487
+
488
+ # AI integration (requires Ollama)
489
+ export OLLAMA_MODEL=gpt-oss:latest
490
+ ./examples/ai_enhanced_kbs.rb
491
+ ```
492
+
493
+ ### Viewing Output
494
+ All examples produce detailed console output showing:
495
+ - Rules being fired
496
+ - Facts being asserted
497
+ - Pattern matches
498
+ - Inference results
499
+ - Performance statistics
500
+
501
+ ---
502
+
503
+ ## Learning Path
504
+
505
+ **Recommended order for learning:**
506
+
507
+ 1. **Start Here:** `car_diagnostic.rb` - Basic concepts
508
+ 2. **DSL Syntax:** `iot_demo_using_dsl.rb` - Readable rules
509
+ 3. **Pattern Matching:** `working_demo.rb` - Multi-condition rules
510
+ 4. **Advanced Logic:** `advanced_example.rb` - Complex patterns
511
+ 5. **Persistence:** `blackboard_demo.rb` - Durable storage
512
+ 6. **Performance:** `redis_trading_demo.rb` - Fast storage
513
+ 7. **Concurrency:** `concurrent_inference_demo.rb` - Async processing
514
+ 8. **AI Integration:** `ai_enhanced_kbs.rb` - Hybrid AI systems
515
+
516
+ ---
517
+
518
+ ## Contributing Examples
519
+
520
+ When adding new examples:
521
+ - Include clear comments
522
+ - Demonstrate specific capabilities
523
+ - Provide realistic use cases
524
+ - Show expected output
525
+ - Update this README
526
+
527
+ ---
528
+
529
+ ## License
530
+
531
+ All examples are part of the KBS gem and share the same license.