kbs 0.0.1 â 0.2.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 +291 -362
- 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 +865 -0
- data/docs/advanced/testing.md +827 -0
- data/docs/api/blackboard.md +1157 -0
- data/docs/api/engine.md +1047 -0
- data/docs/api/facts.md +1212 -0
- data/docs/api/index.md +12 -0
- data/docs/api/rules.md +1104 -0
- data/docs/architecture/blackboard.md +544 -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/fact-rule-relationship.svg +65 -0
- data/docs/assets/images/fact-structure.svg +42 -0
- data/docs/assets/images/inference-cycle.svg +47 -0
- data/docs/assets/images/kb-components.svg +43 -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/rule-structure.svg +44 -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/index.md +223 -0
- data/docs/guides/blackboard-memory.md +589 -0
- data/docs/guides/dsl.md +1321 -0
- data/docs/guides/facts.md +652 -0
- data/docs/guides/getting-started.md +385 -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 +914 -0
- data/docs/index.md +155 -0
- data/docs/installation.md +156 -0
- data/docs/quick-start.md +221 -0
- data/docs/what-is-a-fact.md +694 -0
- data/docs/what-is-a-knowledge-base.md +350 -0
- data/docs/what-is-a-rule.md +833 -0
- data/examples/.gitignore +1 -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 -6
- data/examples/concurrent_inference_demo_dsl.rb +362 -0
- data/examples/csv_trading_system.rb +1 -1
- data/examples/csv_trading_system_dsl.rb +525 -0
- data/examples/iot_demo_using_dsl.rb +1 -1
- 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/rule_source_demo.rb +123 -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_dsl.txt +9392 -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/decompiler.rb +204 -0
- data/lib/kbs/dsl/knowledge_base.rb +101 -2
- data/lib/kbs/dsl/variable.rb +1 -1
- data/lib/kbs/dsl.rb +3 -1
- data/lib/kbs/{rete_engine.rb â engine.rb} +42 -1
- data/lib/kbs/fact.rb +1 -1
- data/lib/kbs/version.rb +1 -1
- data/lib/kbs.rb +15 -13
- data/mkdocs.yml +181 -0
- metadata +74 -9
- data/examples/stock_trading_system.rb.bak +0 -563
data/README.md
CHANGED
|
@@ -1,456 +1,381 @@
|
|
|
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
|
-
|
|
41
|
-
|
|
42
|
-
# Create a simple rule engine
|
|
43
|
-
engine = KBS::ReteEngine.new
|
|
44
|
-
|
|
45
|
-
# Define a rule
|
|
46
|
-
rule = KBS::Rule.new(
|
|
47
|
-
"high_temperature_alert",
|
|
48
|
-
conditions: [
|
|
49
|
-
KBS::Condition.new(:sensor, { type: "temperature" }),
|
|
50
|
-
KBS::Condition.new(:reading, { value: ->(v) { v > 100 } })
|
|
51
|
-
],
|
|
52
|
-
action: lambda do |facts, bindings|
|
|
53
|
-
puts "ðĻ HIGH TEMPERATURE ALERT!"
|
|
54
|
-
reading = facts.find { |f| f.type == :reading }
|
|
55
|
-
puts "Temperature: #{reading[:value]}°C"
|
|
56
|
-
end
|
|
57
|
-
)
|
|
72
|
+
require 'kbs'
|
|
58
73
|
|
|
59
|
-
|
|
74
|
+
# Create knowledge base with DSL
|
|
75
|
+
kb = KBS.knowledge_base do
|
|
76
|
+
rule "high_temperature_alert" do
|
|
77
|
+
on :sensor, type: "temperature"
|
|
78
|
+
on :reading, value: greater_than(100)
|
|
79
|
+
|
|
80
|
+
perform do |facts, bindings|
|
|
81
|
+
reading = facts.find { |f| f.type == :reading }
|
|
82
|
+
puts "ðĻ HIGH TEMPERATURE: #{reading[:value]}°C"
|
|
83
|
+
end
|
|
84
|
+
end
|
|
60
85
|
|
|
61
|
-
# Add facts
|
|
62
|
-
|
|
63
|
-
|
|
86
|
+
# Add facts
|
|
87
|
+
fact :sensor, type: "temperature", location: "reactor"
|
|
88
|
+
fact :reading, value: 105, unit: "celsius"
|
|
64
89
|
|
|
65
|
-
# Run inference
|
|
66
|
-
|
|
90
|
+
# Run inference
|
|
91
|
+
run
|
|
92
|
+
end
|
|
93
|
+
# => ðĻ HIGH TEMPERATURE: 105°C
|
|
67
94
|
```
|
|
68
95
|
|
|
69
96
|
### Using the DSL
|
|
70
97
|
|
|
71
98
|
```ruby
|
|
72
|
-
|
|
99
|
+
require 'kbs'
|
|
73
100
|
|
|
74
101
|
kb = KBS.knowledge_base do
|
|
75
|
-
rule "
|
|
76
|
-
desc "Detect momentum breakouts"
|
|
102
|
+
rule "momentum_breakout" do
|
|
103
|
+
desc "Detect stock momentum breakouts"
|
|
77
104
|
priority 10
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
105
|
+
|
|
106
|
+
on :stock, volume: greater_than(1_000_000)
|
|
107
|
+
on :stock, price_change_pct: greater_than(3)
|
|
108
|
+
without :position, status: "open"
|
|
109
|
+
|
|
110
|
+
perform do |facts, bindings|
|
|
84
111
|
stock = facts.find { |f| f.type == :stock }
|
|
85
|
-
puts "ð
|
|
86
|
-
puts " Price Change: +#{stock[:price_change]}%"
|
|
87
|
-
puts " Volume: #{stock[:volume]}"
|
|
112
|
+
puts "ð BREAKOUT: #{stock[:symbol]} +#{stock[:price_change_pct]}%"
|
|
88
113
|
end
|
|
89
114
|
end
|
|
90
115
|
end
|
|
91
116
|
|
|
92
|
-
|
|
93
|
-
kb.fact :stock, symbol: "AAPL", volume: 1_500_000, price_change: 4.2
|
|
117
|
+
kb.fact :stock, symbol: "AAPL", volume: 1_500_000, price_change_pct: 4.2
|
|
94
118
|
kb.run
|
|
119
|
+
# => ð BREAKOUT: AAPL +4.2%
|
|
95
120
|
```
|
|
96
121
|
|
|
97
|
-
###
|
|
122
|
+
### Blackboard with SQLite Persistence
|
|
98
123
|
|
|
99
124
|
```ruby
|
|
100
|
-
|
|
125
|
+
require 'kbs/blackboard'
|
|
101
126
|
|
|
102
|
-
# Create persistent
|
|
103
|
-
engine = KBS::
|
|
127
|
+
# Create persistent blackboard with DSL
|
|
128
|
+
engine = KBS::Blackboard::Engine.new(db_path: 'knowledge.db')
|
|
104
129
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
130
|
+
kb = KBS.knowledge_base(engine: engine) do
|
|
131
|
+
rule "temperature_monitor" do
|
|
132
|
+
on :sensor, type: "temperature", value: greater_than(25)
|
|
108
133
|
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
134
|
+
perform do |facts|
|
|
135
|
+
sensor = facts.first
|
|
136
|
+
puts "â ïļ High temperature at #{sensor[:location]}: #{sensor[:value]}°C"
|
|
137
|
+
end
|
|
138
|
+
end
|
|
112
139
|
|
|
113
|
-
#
|
|
114
|
-
|
|
115
|
-
|
|
140
|
+
# Add persistent facts
|
|
141
|
+
fact :sensor, type: "temperature", location: "room1", value: 22
|
|
142
|
+
fact :sensor, type: "temperature", location: "room2", value: 28
|
|
116
143
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
puts "Alert: #{alert[:content]}" if alert
|
|
120
|
-
```
|
|
144
|
+
run
|
|
145
|
+
end
|
|
121
146
|
|
|
122
|
-
|
|
147
|
+
# Query facts
|
|
148
|
+
sensors = engine.blackboard.get_facts(:sensor)
|
|
149
|
+
sensors.each { |s| puts "#{s[:type]} at #{s[:location]}: #{s[:value]}°C" }
|
|
123
150
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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
|
|
151
|
+
# View audit history
|
|
152
|
+
history = engine.blackboard.get_history(limit: 10)
|
|
153
|
+
history.each do |entry|
|
|
154
|
+
puts "[#{entry[:timestamp]}] #{entry[:action]}: #{entry[:fact_type]}"
|
|
155
|
+
end
|
|
145
156
|
```
|
|
146
157
|
|
|
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
|
|
158
|
+
### Redis for High-Speed Storage
|
|
173
159
|
|
|
174
160
|
```ruby
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
#
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
#
|
|
188
|
-
#
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
161
|
+
require 'kbs/blackboard'
|
|
162
|
+
|
|
163
|
+
# High-frequency trading with Redis and DSL
|
|
164
|
+
store = KBS::Blackboard::Persistence::RedisStore.new(url: 'redis://localhost:6379/0')
|
|
165
|
+
engine = KBS::Blackboard::Engine.new(store: store)
|
|
166
|
+
|
|
167
|
+
kb = KBS.knowledge_base(engine: engine) do
|
|
168
|
+
rule "price_alert" do
|
|
169
|
+
on :market_price, volume: greater_than(500_000)
|
|
170
|
+
|
|
171
|
+
perform do |facts|
|
|
172
|
+
price = facts.first
|
|
173
|
+
puts "ð High volume: #{price[:symbol]} - #{price[:volume]} shares"
|
|
174
|
+
# Post message for other components
|
|
175
|
+
engine.post_message("PriceAlert", "high_volume",
|
|
176
|
+
{ symbol: price[:symbol], volume: price[:volume] },
|
|
177
|
+
priority: 10
|
|
178
|
+
)
|
|
179
|
+
end
|
|
180
|
+
end
|
|
193
181
|
|
|
194
|
-
|
|
195
|
-
|
|
182
|
+
# Fast in-memory fact storage
|
|
183
|
+
fact :market_price, symbol: "AAPL", price: 150.25, volume: 1_000_000
|
|
196
184
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
system.simulate_rebalancing_scenarios
|
|
185
|
+
run
|
|
186
|
+
end
|
|
200
187
|
|
|
201
|
-
#
|
|
202
|
-
|
|
203
|
-
#
|
|
204
|
-
# Target: 40.0%
|
|
205
|
-
# Drift: +24.3%
|
|
206
|
-
# Action: REDUCE Technology allocation
|
|
188
|
+
# Consume messages
|
|
189
|
+
message = engine.consume_message("high_volume", "TradingStrategy")
|
|
190
|
+
puts "Received: #{message[:content]}" if message
|
|
207
191
|
```
|
|
208
192
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
The system includes cutting-edge AI integration through `ruby_llm` and `ruby_llm-mcp` gems:
|
|
193
|
+
### AI-Enhanced Reasoning
|
|
212
194
|
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
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
|
|
195
|
+
```ruby
|
|
196
|
+
require 'kbs'
|
|
197
|
+
require 'ruby_llm'
|
|
220
198
|
|
|
221
|
-
|
|
199
|
+
# Requires Ollama with a model installed
|
|
200
|
+
# export OLLAMA_MODEL=gpt-oss:latest
|
|
222
201
|
|
|
223
|
-
|
|
224
|
-
|
|
202
|
+
kb = KBS.knowledge_base do
|
|
203
|
+
rule "ai_sentiment_analysis" do
|
|
204
|
+
on :news_data, symbol: satisfies { |s| s && s.length > 0 }
|
|
205
|
+
|
|
206
|
+
perform do |facts|
|
|
207
|
+
news = facts.first
|
|
208
|
+
# AI-powered sentiment analysis
|
|
209
|
+
client = RubyLLM::Chat.new(provider: :ollama, model: 'gpt-oss:latest')
|
|
210
|
+
response = client.ask("Analyze sentiment: #{news[:headline]}")
|
|
211
|
+
|
|
212
|
+
puts "ðĪ AI SENTIMENT ANALYSIS: #{news[:symbol]}"
|
|
213
|
+
puts " Headline: #{news[:headline]}"
|
|
214
|
+
puts " AI Analysis: #{response.content}"
|
|
215
|
+
end
|
|
216
|
+
end
|
|
225
217
|
|
|
226
|
-
#
|
|
227
|
-
|
|
228
|
-
|
|
218
|
+
# Add news for AI sentiment analysis
|
|
219
|
+
fact :news_data,
|
|
220
|
+
symbol: "AAPL",
|
|
221
|
+
headline: "Apple Reports Record Q4 Earnings, Beats Expectations by 15%",
|
|
222
|
+
content: "Apple Inc. announced exceptional results..."
|
|
229
223
|
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
symbol: "AAPL",
|
|
233
|
-
headline: "Apple Reports Record Q4 Earnings, Beats Expectations by 15%",
|
|
234
|
-
content: "Apple Inc. announced exceptional results with 12% revenue growth..."
|
|
235
|
-
})
|
|
224
|
+
run
|
|
225
|
+
end
|
|
236
226
|
|
|
237
227
|
# Output:
|
|
238
228
|
# ðĪ AI SENTIMENT ANALYSIS: AAPL
|
|
239
|
-
# Headline: Apple Reports Record Q4 Earnings, Beats Expectations by 15
|
|
240
|
-
# AI
|
|
241
|
-
# Key Themes: earnings, growth
|
|
242
|
-
# Market Impact: bullish
|
|
229
|
+
# Headline: Apple Reports Record Q4 Earnings, Beats Expectations by 15%
|
|
230
|
+
# AI Analysis: positive (92%) - strong earnings growth, bullish outlook
|
|
243
231
|
```
|
|
244
232
|
|
|
245
|
-
|
|
233
|
+
## ð Examples
|
|
246
234
|
|
|
247
|
-
|
|
235
|
+
The `examples/` directory contains 13 comprehensive examples demonstrating all features:
|
|
248
236
|
|
|
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
|
-
```
|
|
237
|
+
### Basic Examples
|
|
238
|
+
- **car_diagnostic.rb** - Simple expert system for car diagnostics
|
|
239
|
+
- **working_demo.rb** - Stock trading signal generator
|
|
262
240
|
|
|
263
|
-
|
|
241
|
+
### DSL Examples
|
|
242
|
+
- **iot_demo_using_dsl.rb** - IoT sensor monitoring with declarative DSL
|
|
243
|
+
- **trading_demo.rb** - Multiple trading strategies
|
|
264
244
|
|
|
265
|
-
|
|
245
|
+
### Advanced Trading
|
|
246
|
+
- **advanced_example.rb** - Golden cross detection and technical analysis
|
|
247
|
+
- **stock_trading_advanced.rb** - Position management with stop losses
|
|
248
|
+
- **timestamped_trading.rb** - Time-aware temporal reasoning
|
|
249
|
+
- **csv_trading_system.rb** - CSV data integration and backtesting
|
|
250
|
+
- **portfolio_rebalancing_system.rb** - Portfolio optimization
|
|
266
251
|
|
|
267
|
-
###
|
|
268
|
-
- **
|
|
269
|
-
- **
|
|
270
|
-
- **Negation Handling**: Improved support for NOT conditions
|
|
271
|
-
- **Memory Efficiency**: Reduced memory usage through intelligent unlinking
|
|
252
|
+
### Persistence & Architecture
|
|
253
|
+
- **blackboard_demo.rb** - SQLite persistence and message queue
|
|
254
|
+
- **redis_trading_demo.rb** - Redis and hybrid storage patterns
|
|
272
255
|
|
|
273
|
-
###
|
|
274
|
-
- **
|
|
275
|
-
- **
|
|
276
|
-
- **Reduced Join Operations**: Unlinking eliminates unnecessary join computations
|
|
277
|
-
- **Better Scalability**: Handles large rule sets more efficiently
|
|
256
|
+
### Advanced Features
|
|
257
|
+
- **concurrent_inference_demo.rb** - Auto-inference and background threads
|
|
258
|
+
- **ai_enhanced_kbs.rb** - LLM integration with Ollama
|
|
278
259
|
|
|
279
|
-
|
|
260
|
+
See [examples/README.md](examples/README.md) for detailed documentation of each example.
|
|
280
261
|
|
|
281
|
-
|
|
262
|
+
## ðïļ Architecture
|
|
282
263
|
|
|
283
|
-
|
|
284
|
-
- **Blackboard**: Shared memory space for facts and hypotheses
|
|
285
|
-
- **Control**: Manages knowledge source activation and scheduling
|
|
286
|
-
- **Persistence**: SQLite backend for fault tolerance
|
|
264
|
+
### RETE Network Structure
|
|
287
265
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
266
|
+
```
|
|
267
|
+
Facts â Alpha Network â Beta Network â Production Nodes
|
|
268
|
+
(Pattern (Join Nodes) (Rule Actions)
|
|
269
|
+
Matching)
|
|
270
|
+
```
|
|
293
271
|
|
|
294
|
-
|
|
272
|
+
**Key Optimizations:**
|
|
273
|
+
- **Left/Right Unlinking**: Join nodes unlink when memories are empty
|
|
274
|
+
- **Selective Activation**: Only affected network nodes are updated
|
|
275
|
+
- **Token Firing State**: Prevents duplicate rule executions
|
|
276
|
+
- **Shared Patterns**: Common sub-patterns shared across rules
|
|
295
277
|
|
|
296
|
-
###
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
278
|
+
### Blackboard Pattern
|
|
279
|
+
|
|
280
|
+
```
|
|
281
|
+
âââââââââââââââââââââââââââââââââââââââââââ
|
|
282
|
+
â Blackboard (Memory) â
|
|
283
|
+
â ââââââââââââââââââââââââââââââââââââââ â
|
|
284
|
+
â â Facts, Messages, Audit Trail â â
|
|
285
|
+
â ââââââââââââââââââââââââââââââââââââââ â
|
|
286
|
+
âââââââââââââââââââââââââââââââââââââââââââ
|
|
287
|
+
â â
|
|
288
|
+
â â
|
|
289
|
+
ââââââââââ âââââââââââ
|
|
290
|
+
â KS â â KS â Knowledge Sources
|
|
291
|
+
â #1 â â #2 â (Agents)
|
|
292
|
+
ââââââââââ âââââââââââ
|
|
308
293
|
```
|
|
309
294
|
|
|
310
|
-
|
|
311
|
-
```ruby
|
|
312
|
-
# Functional patterns
|
|
313
|
-
when :stock, price: ->(p) { p > 100 && p < 200 }
|
|
295
|
+
## ðŊ Use Cases
|
|
314
296
|
|
|
315
|
-
|
|
316
|
-
|
|
297
|
+
### Expert Systems
|
|
298
|
+
- Medical diagnosis
|
|
299
|
+
- Fault detection and troubleshooting
|
|
300
|
+
- Configuration and design assistance
|
|
301
|
+
- Technical support automation
|
|
302
|
+
|
|
303
|
+
### Financial Applications
|
|
304
|
+
- Algorithmic trading systems
|
|
305
|
+
- Portfolio management and rebalancing
|
|
306
|
+
- Risk assessment and monitoring
|
|
307
|
+
- Market analysis and signal generation
|
|
308
|
+
|
|
309
|
+
### Real-Time Monitoring
|
|
310
|
+
- IoT sensor analysis and alerts
|
|
311
|
+
- Network monitoring and anomaly detection
|
|
312
|
+
- Industrial process control
|
|
313
|
+
- Fraud detection systems
|
|
314
|
+
|
|
315
|
+
### Business Automation
|
|
316
|
+
- Workflow automation
|
|
317
|
+
- Compliance checking
|
|
318
|
+
- Policy enforcement
|
|
319
|
+
- Dynamic pricing and promotions
|
|
317
320
|
|
|
318
|
-
|
|
319
|
-
when :stock, sector: one_of("Technology", "Healthcare")
|
|
321
|
+
## ⥠Performance
|
|
320
322
|
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
323
|
+
### Benchmarks
|
|
324
|
+
- **Rule Compilation**: ~1ms per rule for typical patterns
|
|
325
|
+
- **Fact Addition**: ~0.1ms per fact (warm network)
|
|
326
|
+
- **Pattern Matching**: ~10Ξs per pattern evaluation
|
|
327
|
+
- **SQLite vs Redis**: Redis ~100x faster for high-frequency operations
|
|
324
328
|
|
|
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
|
-
```
|
|
329
|
+
### Complexity
|
|
330
|
+
- **Time**: O(RFP) where R=rules, F=facts, P=patterns per rule
|
|
331
|
+
- **Space**: O(RF) with unlinking optimization
|
|
332
|
+
- **Updates**: O(log R) for incremental fact changes
|
|
337
333
|
|
|
338
334
|
## ð§Š Testing
|
|
339
335
|
|
|
340
|
-
Run the test suite:
|
|
336
|
+
Run the comprehensive test suite:
|
|
341
337
|
|
|
342
338
|
```bash
|
|
343
|
-
|
|
339
|
+
rake test
|
|
344
340
|
```
|
|
345
341
|
|
|
346
|
-
|
|
342
|
+
Individual test files:
|
|
347
343
|
|
|
348
344
|
```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
|
|
345
|
+
ruby test/kbs_test.rb
|
|
346
|
+
ruby test/blackboard_test.rb
|
|
347
|
+
ruby test/dsl_test.rb
|
|
366
348
|
```
|
|
367
349
|
|
|
368
|
-
|
|
350
|
+
**Test Coverage**: 100% with 199 tests, 447 assertions, 0 failures
|
|
369
351
|
|
|
370
|
-
|
|
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
|
|
352
|
+
## ð Documentation
|
|
375
353
|
|
|
376
|
-
###
|
|
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
|
|
354
|
+
### Core Classes
|
|
381
355
|
|
|
382
|
-
|
|
356
|
+
- **KBS::ReteEngine** - Main inference engine
|
|
357
|
+
- **KBS::Rule** - Rule definition
|
|
358
|
+
- **KBS::Condition** - Pattern matching conditions
|
|
359
|
+
- **KBS::Fact** - Working memory facts
|
|
360
|
+
- **KBS::Blackboard::Engine** - Blackboard coordination
|
|
361
|
+
- **KBS::Blackboard::Persistence::SQLiteStore** - SQLite backend
|
|
362
|
+
- **KBS::Blackboard::Persistence::RedisStore** - Redis backend
|
|
363
|
+
- **KBS::Blackboard::Persistence::HybridStore** - Hybrid storage
|
|
383
364
|
|
|
384
|
-
###
|
|
385
|
-
- Medical diagnosis systems
|
|
386
|
-
- Fault detection and diagnostics
|
|
387
|
-
- Configuration and design systems
|
|
388
|
-
- Planning and scheduling
|
|
365
|
+
### DSL Helpers
|
|
389
366
|
|
|
390
|
-
|
|
391
|
-
-
|
|
392
|
-
-
|
|
393
|
-
-
|
|
394
|
-
-
|
|
395
|
-
|
|
396
|
-
### Real-Time Systems
|
|
397
|
-
- IoT event processing
|
|
398
|
-
- Network monitoring
|
|
399
|
-
- Fraud detection
|
|
400
|
-
- Trading systems
|
|
367
|
+
- `greater_than(n)` - Match values > n
|
|
368
|
+
- `less_than(n)` - Match values < n
|
|
369
|
+
- `range(min, max)` - Match values between min and max
|
|
370
|
+
- `one_of(*values)` - Match any of the values
|
|
371
|
+
- `matches(regex)` - Match regex pattern
|
|
401
372
|
|
|
402
|
-
|
|
403
|
-
- AI reasoning systems
|
|
404
|
-
- Knowledge representation
|
|
405
|
-
- Multi-agent systems
|
|
406
|
-
- Cognitive architectures
|
|
373
|
+
## ð§ Requirements
|
|
407
374
|
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
Facts â Alpha Network â Beta Network â Production Nodes
|
|
413
|
-
(Pattern (Join Nodes) (Actions)
|
|
414
|
-
Matching)
|
|
415
|
-
```
|
|
416
|
-
|
|
417
|
-
### Unlinking Algorithm
|
|
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
|
-
```
|
|
433
|
-
|
|
434
|
-
### Blackboard Schema
|
|
435
|
-
```sql
|
|
436
|
-
-- Core fact storage
|
|
437
|
-
CREATE TABLE facts (
|
|
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
|
-
```
|
|
375
|
+
- Ruby >= 3.2.0
|
|
376
|
+
- SQLite3 (bundled with most systems)
|
|
377
|
+
- Redis (optional, for Redis storage)
|
|
378
|
+
- Ollama (optional, for AI integration)
|
|
454
379
|
|
|
455
380
|
## ðĪ Contributing
|
|
456
381
|
|
|
@@ -466,8 +391,9 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
|
|
|
466
391
|
|
|
467
392
|
## ð Acknowledgments
|
|
468
393
|
|
|
469
|
-
- Charles Forgy for the original RETE algorithm
|
|
470
|
-
-
|
|
394
|
+
- **Charles Forgy** for the original RETE algorithm
|
|
395
|
+
- **Robert Doorenbos** for RETE/UL and unlinking optimizations
|
|
396
|
+
- The AI and knowledge systems research community
|
|
471
397
|
- Ruby community for excellent tooling and libraries
|
|
472
398
|
|
|
473
399
|
## ð References
|
|
@@ -475,7 +401,10 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file
|
|
|
475
401
|
- Forgy, C. L. (1982). "Rete: A fast algorithm for the many pattern/many object pattern match problem"
|
|
476
402
|
- Doorenbos, R. B. (1995). "Production Matching for Large Learning Systems" (RETE/UL)
|
|
477
403
|
- Friedman-Hill, E. (2003). "Jess in Action: Java Rule-based Systems"
|
|
404
|
+
- Englemore, R. & Morgan, T. (1988). "Blackboard Systems"
|
|
478
405
|
|
|
479
406
|
---
|
|
480
407
|
|
|
481
|
-
Built with âĪïļ for the
|
|
408
|
+
**Built with âĪïļ for the Ruby community**
|
|
409
|
+
|
|
410
|
+
For more information, visit the [GitHub repository](https://github.com/madbomber/kbs).
|