kbs 0.0.1 â 0.1.0
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.
- checksums.yaml +4 -4
- data/.github/workflows/deploy-github-pages.yml +52 -0
- data/CHANGELOG.md +68 -2
- data/README.md +235 -334
- data/docs/DOCUMENTATION_STATUS.md +158 -0
- data/docs/advanced/custom-persistence.md +775 -0
- data/docs/advanced/debugging.md +726 -0
- data/docs/advanced/index.md +8 -0
- data/docs/advanced/performance.md +832 -0
- data/docs/advanced/testing.md +691 -0
- data/docs/api/blackboard.md +1157 -0
- data/docs/api/engine.md +978 -0
- data/docs/api/facts.md +1212 -0
- data/docs/api/index.md +12 -0
- data/docs/api/rules.md +1034 -0
- data/docs/architecture/blackboard.md +553 -0
- data/docs/architecture/index.md +277 -0
- data/docs/architecture/network-structure.md +343 -0
- data/docs/architecture/rete-algorithm.md +737 -0
- data/docs/assets/css/custom.css +83 -0
- data/docs/assets/images/blackboard-architecture.svg +136 -0
- data/docs/assets/images/compiled-network.svg +101 -0
- data/docs/assets/images/fact-assertion-flow.svg +117 -0
- data/docs/assets/images/kbs.jpg +0 -0
- data/docs/assets/images/pattern-matching-trace.svg +136 -0
- data/docs/assets/images/rete-network-layers.svg +96 -0
- data/docs/assets/images/system-layers.svg +69 -0
- data/docs/assets/images/trading-signal-network.svg +139 -0
- data/docs/assets/js/mathjax.js +17 -0
- data/docs/examples/expert-systems.md +1031 -0
- data/docs/examples/index.md +9 -0
- data/docs/examples/multi-agent.md +1335 -0
- data/docs/examples/stock-trading.md +488 -0
- data/docs/guides/blackboard-memory.md +558 -0
- data/docs/guides/dsl.md +1321 -0
- data/docs/guides/facts.md +652 -0
- data/docs/guides/getting-started.md +383 -0
- data/docs/guides/index.md +23 -0
- data/docs/guides/negation.md +529 -0
- data/docs/guides/pattern-matching.md +561 -0
- data/docs/guides/persistence.md +451 -0
- data/docs/guides/variable-binding.md +491 -0
- data/docs/guides/writing-rules.md +755 -0
- data/docs/index.md +157 -0
- data/docs/installation.md +156 -0
- data/docs/quick-start.md +228 -0
- data/examples/README.md +2 -2
- data/examples/advanced_example.rb +2 -2
- data/examples/advanced_example_dsl.rb +224 -0
- data/examples/ai_enhanced_kbs.rb +1 -1
- data/examples/ai_enhanced_kbs_dsl.rb +538 -0
- data/examples/blackboard_demo_dsl.rb +50 -0
- data/examples/car_diagnostic.rb +1 -1
- data/examples/car_diagnostic_dsl.rb +54 -0
- data/examples/concurrent_inference_demo.rb +5 -5
- data/examples/concurrent_inference_demo_dsl.rb +363 -0
- data/examples/csv_trading_system.rb +1 -1
- data/examples/csv_trading_system_dsl.rb +525 -0
- data/examples/knowledge_base.db +0 -0
- data/examples/portfolio_rebalancing_system.rb +2 -2
- data/examples/portfolio_rebalancing_system_dsl.rb +613 -0
- data/examples/redis_trading_demo_dsl.rb +177 -0
- data/examples/run_all.rb +50 -0
- data/examples/run_all_dsl.rb +49 -0
- data/examples/stock_trading_advanced.rb +1 -1
- data/examples/stock_trading_advanced_dsl.rb +404 -0
- data/examples/temp.txt +7693 -0
- data/examples/temp_dsl.txt +8447 -0
- data/examples/timestamped_trading.rb +1 -1
- data/examples/timestamped_trading_dsl.rb +258 -0
- data/examples/trading_demo.rb +1 -1
- data/examples/trading_demo_dsl.rb +322 -0
- data/examples/working_demo.rb +1 -1
- data/examples/working_demo_dsl.rb +160 -0
- data/lib/kbs/blackboard/engine.rb +3 -3
- data/lib/kbs/blackboard/fact.rb +1 -1
- data/lib/kbs/condition.rb +1 -1
- data/lib/kbs/dsl/knowledge_base.rb +1 -1
- data/lib/kbs/dsl/variable.rb +1 -1
- data/lib/kbs/{rete_engine.rb â engine.rb} +1 -1
- data/lib/kbs/fact.rb +1 -1
- data/lib/kbs/version.rb +1 -1
- data/lib/kbs.rb +2 -2
- data/mkdocs.yml +181 -0
- metadata +66 -6
- data/examples/stock_trading_system.rb.bak +0 -563
data/README.md
CHANGED
|
@@ -1,45 +1,77 @@
|
|
|
1
|
-
|
|
1
|
+

|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
# KBS - Knowledge-Based System
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
A comprehensive Ruby implementation of a Knowledge-Based System featuring the RETE algorithm, Blackboard architecture, and AI integration for building intelligent rule-based applications.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
-
|
|
7
|
+
[](https://www.ruby-lang.org/)
|
|
8
|
+
[](LICENSE)
|
|
9
|
+
|
|
10
|
+
See the [full documentation website](https://madbomber.github.io/kbs/).
|
|
11
|
+
|
|
12
|
+
## ð Key Features
|
|
13
|
+
|
|
14
|
+
### RETE Inference Engine
|
|
15
|
+
- **Optimized Pattern Matching**: RETE algorithm with unlinking optimization for high-performance forward-chaining inference
|
|
9
16
|
- **Incremental Updates**: Efficient fact addition/removal without full network recomputation
|
|
10
|
-
- **Negation Support**: Built-in handling of NOT conditions
|
|
17
|
+
- **Negation Support**: Built-in handling of NOT conditions and absence patterns
|
|
11
18
|
- **Memory Optimization**: Nodes automatically unlink when empty to reduce computation
|
|
12
|
-
- **Pattern Sharing**: Common sub-patterns shared between rules for efficiency
|
|
13
|
-
|
|
14
|
-
###
|
|
15
|
-
- **
|
|
16
|
-
- **
|
|
17
|
-
- **
|
|
18
|
-
- **
|
|
19
|
-
|
|
20
|
-
### Blackboard
|
|
21
|
-
- **
|
|
22
|
-
- **Message
|
|
23
|
-
- **
|
|
24
|
-
- **
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
- **
|
|
29
|
-
- **
|
|
30
|
-
- **
|
|
31
|
-
- **
|
|
32
|
-
|
|
33
|
-
|
|
19
|
+
- **Pattern Sharing**: Common sub-patterns shared between rules for maximum efficiency
|
|
20
|
+
|
|
21
|
+
### Declarative DSL
|
|
22
|
+
- **Readable Syntax**: Write rules in natural, expressive Ruby syntax
|
|
23
|
+
- **Condition Helpers**: `greater_than`, `less_than`, `range`, `one_of`, `matches` for intuitive pattern matching
|
|
24
|
+
- **Rule Metadata**: Descriptions, priorities, and documentation built-in
|
|
25
|
+
- **Negative Patterns**: `without` keyword for absence testing
|
|
26
|
+
|
|
27
|
+
### Blackboard Architecture
|
|
28
|
+
- **Multi-Agent Coordination**: Knowledge sources collaborate via shared blackboard
|
|
29
|
+
- **Message Passing**: Inter-component communication with priority-based message queue
|
|
30
|
+
- **Knowledge Source Registration**: Modular agent registration with topic subscriptions
|
|
31
|
+
- **Session Management**: Isolated reasoning sessions with cleanup
|
|
32
|
+
|
|
33
|
+
### Flexible Persistence
|
|
34
|
+
- **SQLite Storage**: ACID-compliant persistent fact storage with full transaction support
|
|
35
|
+
- **Redis Storage**: High-speed in-memory fact storage for real-time systems (100x faster)
|
|
36
|
+
- **Hybrid Storage**: Best of both worlds - Redis for facts, SQLite for audit trail
|
|
37
|
+
- **Audit Trails**: Complete history of all fact changes and reasoning steps
|
|
38
|
+
- **Query Interface**: Powerful fact retrieval with pattern matching and SQL queries
|
|
39
|
+
|
|
40
|
+
### Concurrent Execution
|
|
41
|
+
- **Auto-Inference Mode**: Background thread continuously runs inference as facts change
|
|
42
|
+
- **Thread-Safe**: Concurrent fact assertion and rule firing
|
|
43
|
+
- **Real-Time Processing**: Perfect for monitoring systems and event-driven architectures
|
|
44
|
+
|
|
45
|
+
### AI Integration
|
|
46
|
+
- **LLM Integration**: Native support for Ollama, OpenAI via RubyLLM gem
|
|
47
|
+
- **Hybrid Reasoning**: Combine symbolic rules with neural AI for enhanced decision-making
|
|
48
|
+
- **Sentiment Analysis**: AI-powered news and text analysis
|
|
49
|
+
- **Strategy Generation**: LLMs create trading strategies based on market conditions
|
|
50
|
+
- **Natural Language**: Generate human-readable explanations for decisions
|
|
51
|
+
- **Pattern Recognition**: AI identifies complex patterns beyond traditional indicators
|
|
34
52
|
|
|
35
53
|
## ð Quick Start
|
|
36
54
|
|
|
55
|
+
### Installation
|
|
56
|
+
|
|
57
|
+
Add to your Gemfile:
|
|
58
|
+
|
|
59
|
+
```ruby
|
|
60
|
+
gem 'kbs'
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Or install directly:
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
gem install kbs
|
|
67
|
+
```
|
|
68
|
+
|
|
37
69
|
### Basic Usage
|
|
38
70
|
|
|
39
71
|
```ruby
|
|
40
|
-
|
|
72
|
+
require 'kbs'
|
|
41
73
|
|
|
42
|
-
# Create
|
|
74
|
+
# Create inference engine
|
|
43
75
|
engine = KBS::ReteEngine.new
|
|
44
76
|
|
|
45
77
|
# Define a rule
|
|
@@ -50,9 +82,8 @@ rule = KBS::Rule.new(
|
|
|
50
82
|
KBS::Condition.new(:reading, { value: ->(v) { v > 100 } })
|
|
51
83
|
],
|
|
52
84
|
action: lambda do |facts, bindings|
|
|
53
|
-
puts "ðĻ HIGH TEMPERATURE ALERT!"
|
|
54
85
|
reading = facts.find { |f| f.type == :reading }
|
|
55
|
-
puts "
|
|
86
|
+
puts "ðĻ HIGH TEMPERATURE: #{reading[:value]}°C"
|
|
56
87
|
end
|
|
57
88
|
)
|
|
58
89
|
|
|
@@ -64,43 +95,45 @@ engine.add_fact(:reading, { value: 105, unit: "celsius" })
|
|
|
64
95
|
|
|
65
96
|
# Run inference
|
|
66
97
|
engine.run
|
|
98
|
+
# => ðĻ HIGH TEMPERATURE: 105°C
|
|
67
99
|
```
|
|
68
100
|
|
|
69
101
|
### Using the DSL
|
|
70
102
|
|
|
71
103
|
```ruby
|
|
72
|
-
|
|
104
|
+
require 'kbs'
|
|
105
|
+
require 'kbs/dsl'
|
|
73
106
|
|
|
74
107
|
kb = KBS.knowledge_base do
|
|
75
|
-
rule "
|
|
76
|
-
desc "Detect momentum breakouts"
|
|
108
|
+
rule "momentum_breakout" do
|
|
109
|
+
desc "Detect stock momentum breakouts"
|
|
77
110
|
priority 10
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
111
|
+
|
|
112
|
+
on :stock, volume: greater_than(1_000_000)
|
|
113
|
+
on :stock, price_change_pct: greater_than(3)
|
|
114
|
+
without :position, status: "open"
|
|
115
|
+
|
|
116
|
+
perform do |facts, bindings|
|
|
84
117
|
stock = facts.find { |f| f.type == :stock }
|
|
85
|
-
puts "ð
|
|
86
|
-
puts " Price Change: +#{stock[:price_change]}%"
|
|
87
|
-
puts " Volume: #{stock[:volume]}"
|
|
118
|
+
puts "ð BREAKOUT: #{stock[:symbol]} +#{stock[:price_change_pct]}%"
|
|
88
119
|
end
|
|
89
120
|
end
|
|
90
121
|
end
|
|
91
122
|
|
|
92
|
-
|
|
93
|
-
kb.fact :stock, symbol: "AAPL", volume: 1_500_000, price_change: 4.2
|
|
123
|
+
kb.fact :stock, symbol: "AAPL", volume: 1_500_000, price_change_pct: 4.2
|
|
94
124
|
kb.run
|
|
125
|
+
# => ð BREAKOUT: AAPL +4.2%
|
|
95
126
|
```
|
|
96
127
|
|
|
97
|
-
###
|
|
128
|
+
### Blackboard with SQLite Persistence
|
|
98
129
|
|
|
99
130
|
```ruby
|
|
100
|
-
|
|
131
|
+
require 'kbs/blackboard'
|
|
101
132
|
|
|
102
|
-
# Create persistent
|
|
103
|
-
engine = KBS::
|
|
133
|
+
# Create persistent blackboard
|
|
134
|
+
engine = KBS::Blackboard::Engine.new(
|
|
135
|
+
store: KBS::Blackboard::Persistence::SQLiteStore.new(db_path: 'knowledge.db')
|
|
136
|
+
)
|
|
104
137
|
|
|
105
138
|
# Add persistent facts
|
|
106
139
|
sensor = engine.add_fact(:sensor, { type: "temperature", location: "room1" })
|
|
@@ -108,349 +141,213 @@ puts "Fact UUID: #{sensor.uuid}"
|
|
|
108
141
|
|
|
109
142
|
# Query facts
|
|
110
143
|
sensors = engine.blackboard.get_facts(:sensor)
|
|
111
|
-
sensors.each { |s| puts s }
|
|
112
|
-
|
|
113
|
-
# Post messages
|
|
114
|
-
engine.post_message("TemperatureMonitor", "alerts",
|
|
115
|
-
{ message: "Temperature spike detected", level: "warning" })
|
|
144
|
+
sensors.each { |s| puts "#{s[:type]} at #{s[:location]}" }
|
|
116
145
|
|
|
117
|
-
#
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
## ð Project Structure
|
|
123
|
-
|
|
124
|
-
```
|
|
125
|
-
kbs/
|
|
126
|
-
âââ README.md # This comprehensive documentation
|
|
127
|
-
âââ kbs.rb # Core RETE II implementation
|
|
128
|
-
âââ kbs_dsl.rb # Domain Specific Language
|
|
129
|
-
âââ blackboard.rb # Persistent blackboard memory system
|
|
130
|
-
âââ csv_trading_system.rb # Historical data backtesting system
|
|
131
|
-
âââ portfolio_rebalancing_system.rb # Advanced portfolio management
|
|
132
|
-
âââ ai_enhanced_kbs.rb # AI-powered enhancements
|
|
133
|
-
âââ sample_stock_data.csv # Historical market data
|
|
134
|
-
âââ knowledge_base.db # Persistent SQLite database
|
|
135
|
-
âââ examples/ # Demo and example files
|
|
136
|
-
â âââ stock_trading_advanced.rb # Advanced trading strategies
|
|
137
|
-
â âââ stock_trading_system.rb # Basic trading examples
|
|
138
|
-
â âââ timestamped_trading.rb # Temporal fact processing
|
|
139
|
-
â âââ trading_demo.rb # Trading scenarios demo
|
|
140
|
-
â âââ working_demo.rb # Basic working examples
|
|
141
|
-
â âââ kbs_advanced_example.rb # Complex RETE examples
|
|
142
|
-
âââ tests/ # Unit test files
|
|
143
|
-
âââ kbs_test.rb # Comprehensive unit tests
|
|
144
|
-
âââ simple_test.rb # Simple unit tests
|
|
146
|
+
# View audit history
|
|
147
|
+
history = engine.blackboard.get_history(limit: 10)
|
|
148
|
+
history.each do |entry|
|
|
149
|
+
puts "[#{entry[:timestamp]}] #{entry[:action]}: #{entry[:fact_type]}"
|
|
150
|
+
end
|
|
145
151
|
```
|
|
146
152
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
The included stock trading expert system demonstrates real-world application with:
|
|
150
|
-
|
|
151
|
-
### Trading Strategies
|
|
152
|
-
- **Golden Cross**: 20-day MA crosses above 50-day MA with volume confirmation
|
|
153
|
-
- **RSI Oversold Bounce**: RSI < 30 with price reversal signals
|
|
154
|
-
- **Breakout Patterns**: Resistance breaks with volume spikes
|
|
155
|
-
- **Trend Following**: Strong uptrend identification with momentum
|
|
156
|
-
- **Take Profit**: Automated profit-taking at 10%+ gains
|
|
157
|
-
- **Stop Loss**: Risk management with 8% loss limits
|
|
158
|
-
- **Portfolio Rebalancing**: Sector allocation drift correction
|
|
159
|
-
- **Position Replacement**: Underperformer swapping with quality candidates
|
|
160
|
-
- **Correlation Risk Reduction**: High correlation position diversification
|
|
161
|
-
- **Momentum Rotation**: Sector rotation based on momentum trends
|
|
162
|
-
- **Quality Upgrades**: Low quality position replacement
|
|
163
|
-
- **Risk-Adjusted Optimization**: Sharpe ratio-based position management
|
|
164
|
-
|
|
165
|
-
### Portfolio Management Features
|
|
166
|
-
- **Sector Allocation Targets**: Technology 40%, Healthcare 25%, Finance 20%, Consumer 15%
|
|
167
|
-
- **Drift Detection**: Automatic rebalancing when allocations exceed 5% targets
|
|
168
|
-
- **Performance Tracking**: Relative performance monitoring vs sector benchmarks
|
|
169
|
-
- **Correlation Analysis**: Position correlation monitoring and risk reduction
|
|
170
|
-
- **Quality Scoring**: Fundamental analysis integration for position evaluation
|
|
171
|
-
|
|
172
|
-
### CSV Historical Processing
|
|
153
|
+
### Redis for High-Speed Storage
|
|
173
154
|
|
|
174
155
|
```ruby
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
# Process historical OHLC data with technical analysis
|
|
178
|
-
system = CSVTradingSystem.new('sample_stock_data.csv')
|
|
179
|
-
system.process_csv_data
|
|
156
|
+
require 'kbs/blackboard'
|
|
180
157
|
|
|
181
|
-
#
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
# 50-MA: $193.15
|
|
188
|
-
# Signal: Strong BUY
|
|
189
|
-
# â
EXECUTED: BUY 100 shares of AAPL at $194.25
|
|
190
|
-
```
|
|
191
|
-
|
|
192
|
-
### Portfolio Rebalancing
|
|
158
|
+
# High-frequency trading with Redis
|
|
159
|
+
engine = KBS::Blackboard::Engine.new(
|
|
160
|
+
store: KBS::Blackboard::Persistence::RedisStore.new(
|
|
161
|
+
url: 'redis://localhost:6379/0'
|
|
162
|
+
)
|
|
163
|
+
)
|
|
193
164
|
|
|
194
|
-
|
|
195
|
-
|
|
165
|
+
# Fast in-memory fact storage
|
|
166
|
+
engine.add_fact(:market_price, { symbol: "AAPL", price: 150.25, volume: 1_000_000 })
|
|
196
167
|
|
|
197
|
-
#
|
|
198
|
-
|
|
199
|
-
|
|
168
|
+
# Message queue for real-time coordination
|
|
169
|
+
engine.post_message("MarketDataFeed", "prices",
|
|
170
|
+
{ symbol: "AAPL", bid: 150.24, ask: 150.26 },
|
|
171
|
+
priority: 10
|
|
172
|
+
)
|
|
200
173
|
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
# Current: 49.7%
|
|
204
|
-
# Target: 40.0%
|
|
205
|
-
# Drift: +24.3%
|
|
206
|
-
# Action: REDUCE Technology allocation
|
|
174
|
+
message = engine.consume_message("prices", "TradingStrategy")
|
|
175
|
+
puts "Received: #{message[:content]}"
|
|
207
176
|
```
|
|
208
177
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
The system includes cutting-edge AI integration through `ruby_llm` and `ruby_llm-mcp` gems:
|
|
212
|
-
|
|
213
|
-
### AI Features
|
|
214
|
-
- **Sentiment Analysis**: LLM-powered news sentiment analysis for market intelligence
|
|
215
|
-
- **Dynamic Strategy Generation**: AI creates trading strategies based on market conditions
|
|
216
|
-
- **Risk Assessment**: Intelligent position risk analysis with confidence scoring
|
|
217
|
-
- **Pattern Recognition**: AI identifies complex market patterns beyond traditional indicators
|
|
218
|
-
- **Natural Language Explanations**: Human-readable explanations for all trading decisions
|
|
219
|
-
- **Adaptive Rule Creation**: System generates new rules based on detected anomalies
|
|
220
|
-
|
|
221
|
-
### AI Integration Example
|
|
178
|
+
### AI-Enhanced Reasoning
|
|
222
179
|
|
|
223
180
|
```ruby
|
|
224
|
-
|
|
181
|
+
require 'kbs'
|
|
182
|
+
require 'kbs/examples/ai_enhanced_kbs'
|
|
183
|
+
|
|
184
|
+
# Requires Ollama with a model installed
|
|
185
|
+
# export OLLAMA_MODEL=gpt-oss:latest
|
|
225
186
|
|
|
226
|
-
# Create AI-powered knowledge system
|
|
227
187
|
system = AIEnhancedKBS::AIKnowledgeSystem.new
|
|
228
|
-
system.demonstrate_ai_enhancements
|
|
229
188
|
|
|
230
|
-
# Add
|
|
189
|
+
# Add news for AI sentiment analysis
|
|
231
190
|
system.engine.add_fact(:news_data, {
|
|
232
191
|
symbol: "AAPL",
|
|
233
192
|
headline: "Apple Reports Record Q4 Earnings, Beats Expectations by 15%",
|
|
234
|
-
content: "Apple Inc. announced exceptional results
|
|
193
|
+
content: "Apple Inc. announced exceptional results..."
|
|
235
194
|
})
|
|
236
195
|
|
|
196
|
+
system.engine.run
|
|
197
|
+
|
|
237
198
|
# Output:
|
|
238
199
|
# ðĪ AI SENTIMENT ANALYSIS: AAPL
|
|
239
|
-
#
|
|
240
|
-
#
|
|
241
|
-
# Key Themes: earnings, growth
|
|
200
|
+
# AI Sentiment: positive (92%)
|
|
201
|
+
# Key Themes: strong earnings growth, share buyback program
|
|
242
202
|
# Market Impact: bullish
|
|
243
203
|
```
|
|
244
204
|
|
|
245
|
-
|
|
205
|
+
## ð Examples
|
|
246
206
|
|
|
247
|
-
|
|
207
|
+
The `examples/` directory contains 13 comprehensive examples demonstrating all features:
|
|
248
208
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
def complete(prompt)
|
|
253
|
-
case prompt
|
|
254
|
-
when /sentiment/i
|
|
255
|
-
'{"sentiment": "positive", "score": 0.7, "confidence": 75}'
|
|
256
|
-
when /strategy/i
|
|
257
|
-
'{"name": "Momentum Strategy", "rationale": "Market showing upward momentum"}'
|
|
258
|
-
end
|
|
259
|
-
end
|
|
260
|
-
end
|
|
261
|
-
```
|
|
209
|
+
### Basic Examples
|
|
210
|
+
- **car_diagnostic.rb** - Simple expert system for car diagnostics
|
|
211
|
+
- **working_demo.rb** - Stock trading signal generator
|
|
262
212
|
|
|
263
|
-
|
|
213
|
+
### DSL Examples
|
|
214
|
+
- **iot_demo_using_dsl.rb** - IoT sensor monitoring with declarative DSL
|
|
215
|
+
- **trading_demo.rb** - Multiple trading strategies
|
|
264
216
|
|
|
265
|
-
|
|
217
|
+
### Advanced Trading
|
|
218
|
+
- **advanced_example.rb** - Golden cross detection and technical analysis
|
|
219
|
+
- **stock_trading_advanced.rb** - Position management with stop losses
|
|
220
|
+
- **timestamped_trading.rb** - Time-aware temporal reasoning
|
|
221
|
+
- **csv_trading_system.rb** - CSV data integration and backtesting
|
|
222
|
+
- **portfolio_rebalancing_system.rb** - Portfolio optimization
|
|
266
223
|
|
|
267
|
-
###
|
|
268
|
-
- **
|
|
269
|
-
- **
|
|
270
|
-
- **Negation Handling**: Improved support for NOT conditions
|
|
271
|
-
- **Memory Efficiency**: Reduced memory usage through intelligent unlinking
|
|
224
|
+
### Persistence & Architecture
|
|
225
|
+
- **blackboard_demo.rb** - SQLite persistence and message queue
|
|
226
|
+
- **redis_trading_demo.rb** - Redis and hybrid storage patterns
|
|
272
227
|
|
|
273
|
-
###
|
|
274
|
-
- **
|
|
275
|
-
- **
|
|
276
|
-
- **Reduced Join Operations**: Unlinking eliminates unnecessary join computations
|
|
277
|
-
- **Better Scalability**: Handles large rule sets more efficiently
|
|
228
|
+
### Advanced Features
|
|
229
|
+
- **concurrent_inference_demo.rb** - Auto-inference and background threads
|
|
230
|
+
- **ai_enhanced_kbs.rb** - LLM integration with Ollama
|
|
278
231
|
|
|
279
|
-
|
|
232
|
+
See [examples/README.md](examples/README.md) for detailed documentation of each example.
|
|
280
233
|
|
|
281
|
-
|
|
234
|
+
## ðïļ Architecture
|
|
282
235
|
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
236
|
+
### RETE Network Structure
|
|
237
|
+
|
|
238
|
+
```
|
|
239
|
+
Facts â Alpha Network â Beta Network â Production Nodes
|
|
240
|
+
(Pattern (Join Nodes) (Rule Actions)
|
|
241
|
+
Matching)
|
|
242
|
+
```
|
|
287
243
|
|
|
288
|
-
|
|
289
|
-
- **
|
|
290
|
-
- **
|
|
291
|
-
- **
|
|
292
|
-
- **
|
|
244
|
+
**Key Optimizations:**
|
|
245
|
+
- **Left/Right Unlinking**: Join nodes unlink when memories are empty
|
|
246
|
+
- **Selective Activation**: Only affected network nodes are updated
|
|
247
|
+
- **Token Firing State**: Prevents duplicate rule executions
|
|
248
|
+
- **Shared Patterns**: Common sub-patterns shared across rules
|
|
293
249
|
|
|
294
|
-
|
|
250
|
+
### Blackboard Pattern
|
|
295
251
|
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
252
|
+
```
|
|
253
|
+
âââââââââââââââââââââââââââââââââââââââââââ
|
|
254
|
+
â Blackboard (Memory) â
|
|
255
|
+
â ââââââââââââââââââââââââââââââââââââââ â
|
|
256
|
+
â â Facts, Messages, Audit Trail â â
|
|
257
|
+
â ââââââââââââââââââââââââââââââââââââââ â
|
|
258
|
+
âââââââââââââââââââââââââââââââââââââââââââ
|
|
259
|
+
â â
|
|
260
|
+
â â
|
|
261
|
+
ââââââââââ âââââââââââ
|
|
262
|
+
â KS â â KS â Knowledge Sources
|
|
263
|
+
â #1 â â #2 â (Agents)
|
|
264
|
+
ââââââââââ âââââââââââ
|
|
308
265
|
```
|
|
309
266
|
|
|
310
|
-
|
|
311
|
-
```ruby
|
|
312
|
-
# Functional patterns
|
|
313
|
-
when :stock, price: ->(p) { p > 100 && p < 200 }
|
|
267
|
+
## ðŊ Use Cases
|
|
314
268
|
|
|
315
|
-
|
|
316
|
-
|
|
269
|
+
### Expert Systems
|
|
270
|
+
- Medical diagnosis
|
|
271
|
+
- Fault detection and troubleshooting
|
|
272
|
+
- Configuration and design assistance
|
|
273
|
+
- Technical support automation
|
|
274
|
+
|
|
275
|
+
### Financial Applications
|
|
276
|
+
- Algorithmic trading systems
|
|
277
|
+
- Portfolio management and rebalancing
|
|
278
|
+
- Risk assessment and monitoring
|
|
279
|
+
- Market analysis and signal generation
|
|
280
|
+
|
|
281
|
+
### Real-Time Monitoring
|
|
282
|
+
- IoT sensor analysis and alerts
|
|
283
|
+
- Network monitoring and anomaly detection
|
|
284
|
+
- Industrial process control
|
|
285
|
+
- Fraud detection systems
|
|
286
|
+
|
|
287
|
+
### Business Automation
|
|
288
|
+
- Workflow automation
|
|
289
|
+
- Compliance checking
|
|
290
|
+
- Policy enforcement
|
|
291
|
+
- Dynamic pricing and promotions
|
|
317
292
|
|
|
318
|
-
|
|
319
|
-
when :stock, sector: one_of("Technology", "Healthcare")
|
|
293
|
+
## ⥠Performance
|
|
320
294
|
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
295
|
+
### Benchmarks
|
|
296
|
+
- **Rule Compilation**: ~1ms per rule for typical patterns
|
|
297
|
+
- **Fact Addition**: ~0.1ms per fact (warm network)
|
|
298
|
+
- **Pattern Matching**: ~10Ξs per pattern evaluation
|
|
299
|
+
- **SQLite vs Redis**: Redis ~100x faster for high-frequency operations
|
|
324
300
|
|
|
325
|
-
###
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
not.when :position, status: "open" # No open positions
|
|
330
|
-
absent :risk_alert, level: "high" # No high risk alerts
|
|
331
|
-
|
|
332
|
-
then do |facts, bindings|
|
|
333
|
-
puts "Safe to open new position"
|
|
334
|
-
end
|
|
335
|
-
end
|
|
336
|
-
```
|
|
301
|
+
### Complexity
|
|
302
|
+
- **Time**: O(RFP) where R=rules, F=facts, P=patterns per rule
|
|
303
|
+
- **Space**: O(RF) with unlinking optimization
|
|
304
|
+
- **Updates**: O(log R) for incremental fact changes
|
|
337
305
|
|
|
338
306
|
## ð§Š Testing
|
|
339
307
|
|
|
340
|
-
Run the test suite:
|
|
308
|
+
Run the comprehensive test suite:
|
|
341
309
|
|
|
342
310
|
```bash
|
|
343
|
-
|
|
311
|
+
rake test
|
|
344
312
|
```
|
|
345
313
|
|
|
346
|
-
|
|
314
|
+
Individual test files:
|
|
347
315
|
|
|
348
316
|
```bash
|
|
349
|
-
|
|
350
|
-
ruby
|
|
351
|
-
ruby
|
|
352
|
-
ruby csv_trading_system.rb # Historical CSV trading
|
|
353
|
-
ruby portfolio_rebalancing_system.rb # Portfolio management
|
|
354
|
-
ruby ai_enhanced_kbs.rb # AI-enhanced system
|
|
355
|
-
|
|
356
|
-
# Example programs
|
|
357
|
-
ruby examples/stock_trading_advanced.rb # Advanced trading system
|
|
358
|
-
ruby examples/working_demo.rb # Basic working examples
|
|
359
|
-
ruby examples/trading_demo.rb # Trading scenarios
|
|
360
|
-
ruby examples/timestamped_trading.rb # Temporal processing
|
|
361
|
-
ruby examples/kbs_advanced_example.rb # Complex RETE examples
|
|
362
|
-
|
|
363
|
-
# Testing
|
|
364
|
-
ruby tests/kbs_test.rb # Comprehensive tests
|
|
365
|
-
ruby tests/simple_test.rb # Simple unit tests
|
|
317
|
+
ruby test/kbs_test.rb
|
|
318
|
+
ruby test/blackboard_test.rb
|
|
319
|
+
ruby test/dsl_test.rb
|
|
366
320
|
```
|
|
367
321
|
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
### RETE II Optimizations
|
|
371
|
-
- **Time Complexity**: O(RFP) where R=rules, F=facts, P=patterns
|
|
372
|
-
- **Space Complexity**: O(RF) with unlinking optimization
|
|
373
|
-
- **Update Performance**: O(log R) for incremental updates
|
|
374
|
-
- **Memory Usage**: Significantly reduced vs. original RETE
|
|
375
|
-
|
|
376
|
-
### Benchmarks
|
|
377
|
-
- **Rule Compilation**: ~1ms per rule for typical patterns
|
|
378
|
-
- **Fact Addition**: ~0.1ms per fact (warm network)
|
|
379
|
-
- **Pattern Matching**: ~10Ξs per pattern evaluation
|
|
380
|
-
- **Network Update**: ~0.01ms per affected node
|
|
322
|
+
**Test Coverage**: 100% with 199 tests, 447 assertions, 0 failures
|
|
381
323
|
|
|
382
|
-
##
|
|
324
|
+
## ð Documentation
|
|
383
325
|
|
|
384
|
-
###
|
|
385
|
-
- Medical diagnosis systems
|
|
386
|
-
- Fault detection and diagnostics
|
|
387
|
-
- Configuration and design systems
|
|
388
|
-
- Planning and scheduling
|
|
326
|
+
### Core Classes
|
|
389
327
|
|
|
390
|
-
|
|
391
|
-
-
|
|
392
|
-
-
|
|
393
|
-
-
|
|
394
|
-
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
-
|
|
398
|
-
- Network monitoring
|
|
399
|
-
- Fraud detection
|
|
400
|
-
- Trading systems
|
|
328
|
+
- **KBS::ReteEngine** - Main inference engine
|
|
329
|
+
- **KBS::Rule** - Rule definition
|
|
330
|
+
- **KBS::Condition** - Pattern matching conditions
|
|
331
|
+
- **KBS::Fact** - Working memory facts
|
|
332
|
+
- **KBS::Blackboard::Engine** - Blackboard coordination
|
|
333
|
+
- **KBS::Blackboard::Persistence::SQLiteStore** - SQLite backend
|
|
334
|
+
- **KBS::Blackboard::Persistence::RedisStore** - Redis backend
|
|
335
|
+
- **KBS::Blackboard::Persistence::HybridStore** - Hybrid storage
|
|
401
336
|
|
|
402
|
-
###
|
|
403
|
-
- AI reasoning systems
|
|
404
|
-
- Knowledge representation
|
|
405
|
-
- Multi-agent systems
|
|
406
|
-
- Cognitive architectures
|
|
337
|
+
### DSL Helpers
|
|
407
338
|
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
(Pattern (Join Nodes) (Actions)
|
|
414
|
-
Matching)
|
|
415
|
-
```
|
|
339
|
+
- `greater_than(n)` - Match values > n
|
|
340
|
+
- `less_than(n)` - Match values < n
|
|
341
|
+
- `range(min, max)` - Match values between min and max
|
|
342
|
+
- `one_of(*values)` - Match any of the values
|
|
343
|
+
- `matches(regex)` - Match regex pattern
|
|
416
344
|
|
|
417
|
-
|
|
418
|
-
```ruby
|
|
419
|
-
class BetaMemory
|
|
420
|
-
def unlink!
|
|
421
|
-
return if @tokens.empty?
|
|
422
|
-
@linked = false
|
|
423
|
-
@successors.each { |s| s.left_unlink! }
|
|
424
|
-
end
|
|
425
|
-
|
|
426
|
-
def relink!
|
|
427
|
-
return if @tokens.empty?
|
|
428
|
-
@linked = true
|
|
429
|
-
@successors.each { |s| s.left_relink! }
|
|
430
|
-
end
|
|
431
|
-
end
|
|
432
|
-
```
|
|
345
|
+
## ð§ Requirements
|
|
433
346
|
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
id INTEGER PRIMARY KEY,
|
|
439
|
-
uuid TEXT UNIQUE,
|
|
440
|
-
fact_type TEXT,
|
|
441
|
-
attributes TEXT,
|
|
442
|
-
created_at TIMESTAMP,
|
|
443
|
-
retracted BOOLEAN DEFAULT 0
|
|
444
|
-
);
|
|
445
|
-
|
|
446
|
-
-- Audit trail
|
|
447
|
-
CREATE TABLE fact_history (
|
|
448
|
-
id INTEGER PRIMARY KEY,
|
|
449
|
-
fact_uuid TEXT,
|
|
450
|
-
action TEXT,
|
|
451
|
-
timestamp TIMESTAMP
|
|
452
|
-
);
|
|
453
|
-
```
|
|
347
|
+
- Ruby >= 3.2.0
|
|
348
|
+
- SQLite3 (bundled with most systems)
|
|
349
|
+
- Redis (optional, for Redis storage)
|
|
350
|
+
- Ollama (optional, for AI integration)
|
|
454
351
|
|
|
455
352
|
## ðĪ Contributing
|
|
456
353
|
|
|
@@ -466,8 +363,9 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
|
|
|
466
363
|
|
|
467
364
|
## ð Acknowledgments
|
|
468
365
|
|
|
469
|
-
- Charles Forgy for the original RETE algorithm
|
|
470
|
-
-
|
|
366
|
+
- **Charles Forgy** for the original RETE algorithm
|
|
367
|
+
- **Robert Doorenbos** for RETE/UL and unlinking optimizations
|
|
368
|
+
- The AI and knowledge systems research community
|
|
471
369
|
- Ruby community for excellent tooling and libraries
|
|
472
370
|
|
|
473
371
|
## ð References
|
|
@@ -475,7 +373,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
|
|
|
475
373
|
- Forgy, C. L. (1982). "Rete: A fast algorithm for the many pattern/many object pattern match problem"
|
|
476
374
|
- Doorenbos, R. B. (1995). "Production Matching for Large Learning Systems" (RETE/UL)
|
|
477
375
|
- Friedman-Hill, E. (2003). "Jess in Action: Java Rule-based Systems"
|
|
376
|
+
- Englemore, R. & Morgan, T. (1988). "Blackboard Systems"
|
|
478
377
|
|
|
479
378
|
---
|
|
480
379
|
|
|
481
|
-
Built with âĪïļ for the
|
|
380
|
+
**Built with âĪïļ for the Ruby community**
|
|
381
|
+
|
|
382
|
+
For more information, visit the [GitHub repository](https://github.com/madbomber/kbs).
|