kbs 0.2.1 → 0.3.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.
Files changed (134) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +68 -1
  3. data/README.md +52 -25
  4. data/lib/kbs/agenda.rb +208 -0
  5. data/lib/kbs/alpha_memory.rb +55 -7
  6. data/lib/kbs/alpha_network.rb +83 -0
  7. data/lib/kbs/beta_memory.rb +54 -19
  8. data/lib/kbs/blackboard/audit_log.rb +26 -25
  9. data/lib/kbs/blackboard/engine.rb +49 -40
  10. data/lib/kbs/blackboard/fact.rb +17 -21
  11. data/lib/kbs/blackboard/memory.rb +116 -40
  12. data/lib/kbs/blackboard/message_queue.rb +39 -28
  13. data/lib/kbs/blackboard/persistence/hybrid_store.rb +20 -9
  14. data/lib/kbs/blackboard/persistence/redis_store.rb +59 -51
  15. data/lib/kbs/blackboard/persistence/sqlite_store.rb +29 -32
  16. data/lib/kbs/blackboard/persistence/store.rb +11 -1
  17. data/lib/kbs/blackboard/redis_message_queue.rb +16 -7
  18. data/lib/kbs/condition.rb +39 -2
  19. data/lib/kbs/decompiler.rb +300 -124
  20. data/lib/kbs/dsl/condition_helpers.rb +8 -6
  21. data/lib/kbs/dsl/knowledge_base.rb +73 -93
  22. data/lib/kbs/dsl/pattern_evaluator.rb +38 -15
  23. data/lib/kbs/dsl/rule_builder.rb +118 -40
  24. data/lib/kbs/dsl/variable.rb +51 -6
  25. data/lib/kbs/dsl.rb +10 -3
  26. data/lib/kbs/engine.rb +395 -77
  27. data/lib/kbs/errors.rb +38 -0
  28. data/lib/kbs/exists_node.rb +12 -0
  29. data/lib/kbs/fact.rb +5 -19
  30. data/lib/kbs/fact_registry.rb +51 -0
  31. data/lib/kbs/introspection.rb +93 -0
  32. data/lib/kbs/join_indexing.rb +104 -0
  33. data/lib/kbs/join_node.rb +93 -57
  34. data/lib/kbs/join_test_builder.rb +80 -0
  35. data/lib/kbs/join_tests.rb +66 -0
  36. data/lib/kbs/memory_index.rb +75 -0
  37. data/lib/kbs/negation_node.rb +6 -82
  38. data/lib/kbs/network_node.rb +31 -0
  39. data/lib/kbs/pattern_matching.rb +27 -0
  40. data/lib/kbs/production_node.rb +50 -6
  41. data/lib/kbs/quantifier_node.rb +140 -0
  42. data/lib/kbs/rule.rb +26 -13
  43. data/lib/kbs/rule_source.rb +74 -0
  44. data/lib/kbs/rule_step.rb +27 -0
  45. data/lib/kbs/token.rb +60 -10
  46. data/lib/kbs/tracer.rb +80 -0
  47. data/lib/kbs/truth_maintenance.rb +82 -0
  48. data/lib/kbs/version.rb +1 -1
  49. data/lib/kbs/working_memory.rb +25 -3
  50. data/lib/kbs.rb +17 -4
  51. metadata +22 -129
  52. data/.envrc +0 -3
  53. data/.github/workflows/deploy-github-pages.yml +0 -52
  54. data/COMMITS.md +0 -196
  55. data/Rakefile +0 -8
  56. data/docs/advanced/custom-persistence.md +0 -775
  57. data/docs/advanced/debugging.md +0 -726
  58. data/docs/advanced/index.md +0 -8
  59. data/docs/advanced/performance.md +0 -865
  60. data/docs/advanced/testing.md +0 -827
  61. data/docs/api/blackboard.md +0 -1157
  62. data/docs/api/engine.md +0 -1047
  63. data/docs/api/facts.md +0 -1212
  64. data/docs/api/index.md +0 -12
  65. data/docs/api/rules.md +0 -1104
  66. data/docs/architecture/blackboard.md +0 -544
  67. data/docs/architecture/index.md +0 -277
  68. data/docs/architecture/network-structure.md +0 -343
  69. data/docs/architecture/rete-algorithm.md +0 -737
  70. data/docs/assets/css/custom.css +0 -83
  71. data/docs/assets/images/blackboard-architecture.svg +0 -136
  72. data/docs/assets/images/compiled-network.svg +0 -101
  73. data/docs/assets/images/fact-assertion-flow.svg +0 -117
  74. data/docs/assets/images/fact-rule-relationship.svg +0 -65
  75. data/docs/assets/images/fact-structure.svg +0 -42
  76. data/docs/assets/images/inference-cycle.svg +0 -47
  77. data/docs/assets/images/kb-components.svg +0 -43
  78. data/docs/assets/images/kbs.jpg +0 -0
  79. data/docs/assets/images/pattern-matching-trace.svg +0 -136
  80. data/docs/assets/images/rete-network-layers.svg +0 -96
  81. data/docs/assets/images/rule-structure.svg +0 -44
  82. data/docs/assets/images/system-layers.svg +0 -69
  83. data/docs/assets/images/trading-signal-network.svg +0 -139
  84. data/docs/assets/js/mathjax.js +0 -17
  85. data/docs/examples/index.md +0 -223
  86. data/docs/guides/blackboard-memory.md +0 -589
  87. data/docs/guides/dsl.md +0 -1321
  88. data/docs/guides/facts.md +0 -652
  89. data/docs/guides/getting-started.md +0 -385
  90. data/docs/guides/index.md +0 -23
  91. data/docs/guides/negation.md +0 -529
  92. data/docs/guides/pattern-matching.md +0 -561
  93. data/docs/guides/persistence.md +0 -451
  94. data/docs/guides/variable-binding.md +0 -491
  95. data/docs/guides/writing-rules.md +0 -914
  96. data/docs/index.md +0 -155
  97. data/docs/installation.md +0 -156
  98. data/docs/quick-start.md +0 -221
  99. data/docs/what-is-a-fact.md +0 -694
  100. data/docs/what-is-a-knowledge-base.md +0 -350
  101. data/docs/what-is-a-rule.md +0 -833
  102. data/examples/.gitignore +0 -1
  103. data/examples/README.md +0 -531
  104. data/examples/advanced_example.rb +0 -270
  105. data/examples/advanced_example_dsl.rb +0 -224
  106. data/examples/ai_enhanced_kbs.rb +0 -523
  107. data/examples/ai_enhanced_kbs_dsl.rb +0 -538
  108. data/examples/blackboard_demo.rb +0 -50
  109. data/examples/blackboard_demo_dsl.rb +0 -50
  110. data/examples/car_diagnostic.rb +0 -64
  111. data/examples/car_diagnostic_dsl.rb +0 -54
  112. data/examples/concurrent_inference_demo.rb +0 -362
  113. data/examples/concurrent_inference_demo_dsl.rb +0 -362
  114. data/examples/csv_trading_system.rb +0 -559
  115. data/examples/csv_trading_system_dsl.rb +0 -525
  116. data/examples/iot_demo_using_dsl.rb +0 -83
  117. data/examples/portfolio_rebalancing_system.rb +0 -651
  118. data/examples/portfolio_rebalancing_system_dsl.rb +0 -613
  119. data/examples/redis_trading_demo.rb +0 -177
  120. data/examples/redis_trading_demo_dsl.rb +0 -177
  121. data/examples/rule_source_demo.rb +0 -123
  122. data/examples/run_all.rb +0 -50
  123. data/examples/run_all_dsl.rb +0 -49
  124. data/examples/sample_stock_data.csv +0 -46
  125. data/examples/stock_trading_advanced.rb +0 -469
  126. data/examples/stock_trading_advanced_dsl.rb +0 -404
  127. data/examples/temp_dsl.txt +0 -9392
  128. data/examples/timestamped_trading.rb +0 -286
  129. data/examples/timestamped_trading_dsl.rb +0 -258
  130. data/examples/trading_demo.rb +0 -334
  131. data/examples/trading_demo_dsl.rb +0 -322
  132. data/examples/working_demo.rb +0 -176
  133. data/examples/working_demo_dsl.rb +0 -160
  134. data/mkdocs.yml +0 -181
@@ -1,523 +0,0 @@
1
- #!/usr/bin/env ruby
2
-
3
- require 'ruby_llm'
4
- require 'ruby_llm/mcp'
5
- require_relative '../lib/kbs'
6
- require 'json'
7
- require 'date'
8
-
9
- # Configure RubyLLM for Ollama
10
- RubyLLM.configure do |config|
11
- config.ollama_api_base = ENV['OLLAMA_API_BASE'] || 'http://localhost:11434'
12
- end
13
-
14
- module AIEnhancedKBS
15
- class AIKnowledgeSystem
16
- def initialize
17
- @engine = KBS::Engine.new
18
- @ai_client = setup_ai_client
19
- @mcp_agent = setup_mcp_agent
20
- @sentiment_cache = {}
21
- @explanation_cache = {}
22
- setup_ai_enhanced_rules
23
- end
24
-
25
- def setup_ai_client
26
- model = ENV['OLLAMA_MODEL'] || 'gpt-oss:latest'
27
- puts "šŸ¤– Initializing RubyLLM::Chat with Ollama model: #{model}"
28
- RubyLLM::Chat.new(provider: :ollama, model: model)
29
- end
30
-
31
- def setup_mcp_agent
32
- if defined?(RubyLLM::MCP::Agent)
33
- RubyLLM::MCP::Agent.new(
34
- name: "market_analyst",
35
- description: "AI agent for market analysis and trading insights"
36
- )
37
- else
38
- nil
39
- end
40
- end
41
-
42
- def setup_ai_enhanced_rules
43
- # Rule 1: AI-Powered Sentiment Analysis
44
- sentiment_rule = KBS::Rule.new(
45
- "ai_sentiment_analysis",
46
- conditions: [
47
- KBS::Condition.new(:news_data, {
48
- symbol: ->(s) { s && s.length > 0 },
49
- headline: ->(h) { h && h.length > 10 },
50
- content: ->(c) { c && c.length > 50 }
51
- })
52
- ],
53
- action: lambda do |facts, bindings|
54
- news = facts.find { |f| f.type == :news_data }
55
- symbol = news[:symbol]
56
-
57
- # AI-powered sentiment analysis
58
- sentiment = analyze_sentiment_with_ai(news[:headline], news[:content])
59
-
60
- puts "šŸ¤– AI SENTIMENT ANALYSIS: #{symbol}"
61
- puts " Headline: #{news[:headline][0..80]}..."
62
- puts " AI Sentiment: #{sentiment[:sentiment]} (#{sentiment[:confidence]}%)"
63
- puts " Key Themes: #{sentiment[:themes].join(', ')}"
64
- puts " Market Impact: #{sentiment[:market_impact]}"
65
-
66
- # Add sentiment fact to working memory
67
- @engine.add_fact(:ai_sentiment, {
68
- symbol: symbol,
69
- sentiment_score: sentiment[:score],
70
- confidence: sentiment[:confidence],
71
- themes: sentiment[:themes],
72
- market_impact: sentiment[:market_impact],
73
- timestamp: Time.now
74
- })
75
- end,
76
- priority: 20
77
- )
78
-
79
- # Rule 2: AI-Generated Trading Strategy
80
- ai_strategy_rule = KBS::Rule.new(
81
- "ai_strategy_generation",
82
- conditions: [
83
- KBS::Condition.new(:market_conditions, {
84
- volatility: ->(v) { v && v > 25 },
85
- trend: ->(t) { t && t.length > 0 }
86
- }),
87
- KBS::Condition.new(:portfolio_state, {
88
- cash_ratio: ->(c) { c && c > 0.2 }
89
- })
90
- ],
91
- action: lambda do |facts, bindings|
92
- market = facts.find { |f| f.type == :market_conditions }
93
- portfolio = facts.find { |f| f.type == :portfolio_state }
94
-
95
- # Generate AI strategy
96
- strategy = generate_ai_trading_strategy(market, portfolio)
97
-
98
- puts "🧠 AI TRADING STRATEGY"
99
- puts " Market Context: #{market[:trend]} trend, #{market[:volatility]}% volatility"
100
- puts " Strategy: #{strategy[:name]}"
101
- puts " Rationale: #{strategy[:rationale]}"
102
- puts " Actions: #{strategy[:actions].join(', ')}"
103
- puts " Risk Level: #{strategy[:risk_level]}"
104
-
105
- # Execute AI-suggested actions (would be implemented in production)
106
- # execute_ai_strategy(strategy)
107
- end,
108
- priority: 15
109
- )
110
-
111
- # Rule 3: Dynamic Rule Generation
112
- dynamic_rule_creation = KBS::Rule.new(
113
- "dynamic_rule_creation",
114
- conditions: [
115
- KBS::Condition.new(:pattern_anomaly, {
116
- pattern_type: ->(p) { p && p.length > 0 },
117
- confidence: ->(c) { c && c > 0.8 },
118
- occurrences: ->(o) { o && o > 5 }
119
- })
120
- ],
121
- action: lambda do |facts, bindings|
122
- anomaly = facts.find { |f| f.type == :pattern_anomaly }
123
-
124
- # AI generates new trading rule
125
- new_rule_spec = generate_rule_with_ai(anomaly)
126
-
127
- puts "šŸŽÆ AI RULE GENERATION"
128
- puts " Pattern: #{anomaly[:pattern_type]}"
129
- puts " New Rule: #{new_rule_spec[:name]}"
130
- puts " Logic: #{new_rule_spec[:description]}"
131
-
132
- # Dynamically add new rule to engine
133
- if new_rule_spec[:valid]
134
- dynamic_rule = create_rule_from_spec(new_rule_spec)
135
- @engine.add_rule(dynamic_rule)
136
- puts " āœ… Rule added to knowledge base"
137
- end
138
- end,
139
- priority: 12
140
- )
141
-
142
- # Rule 4: AI Risk Assessment
143
- ai_risk_assessment = KBS::Rule.new(
144
- "ai_risk_assessment",
145
- conditions: [
146
- KBS::Condition.new(:position, {
147
- unrealized_pnl: ->(pnl) { pnl && pnl.abs > 1000 }
148
- }),
149
- KBS::Condition.new(:market_data, {
150
- symbol: ->(s) { s && s.length > 0 }
151
- })
152
- ],
153
- action: lambda do |facts, bindings|
154
- position = facts.find { |f| f.type == :position }
155
- market_data = facts.find { |f| f.type == :market_data }
156
-
157
- # AI-powered risk analysis
158
- risk_analysis = analyze_position_risk_with_ai(position, market_data)
159
-
160
- puts "āš ļø AI RISK ASSESSMENT: #{position[:symbol]}"
161
- puts " Current P&L: $#{position[:unrealized_pnl]}"
162
- puts " Risk Level: #{risk_analysis[:risk_level]}"
163
- puts " Key Risks: #{risk_analysis[:risks].join(', ')}"
164
- puts " Recommendation: #{risk_analysis[:recommendation]}"
165
- puts " Confidence: #{risk_analysis[:confidence]}%"
166
-
167
- # Act on high-risk situations
168
- if risk_analysis[:risk_level] == "HIGH" && risk_analysis[:confidence] > 80
169
- puts " 🚨 HIGH RISK DETECTED - Consider position adjustment"
170
- end
171
- end,
172
- priority: 18
173
- )
174
-
175
- # Rule 5: Natural Language Explanation Generator
176
- explanation_rule = KBS::Rule.new(
177
- "ai_explanation_generator",
178
- conditions: [
179
- KBS::Condition.new(:trade_recommendation, {
180
- action: ->(a) { ["BUY", "SELL", "HOLD"].include?(a) },
181
- symbol: ->(s) { s && s.length > 0 }
182
- })
183
- ],
184
- action: lambda do |facts, bindings|
185
- recommendation = facts.find { |f| f.type == :trade_recommendation }
186
-
187
- # Generate natural language explanation
188
- explanation = generate_trade_explanation(recommendation, facts)
189
-
190
- puts "šŸ’¬ AI EXPLANATION: #{recommendation[:symbol]} #{recommendation[:action]}"
191
- puts " Reasoning: #{explanation[:reasoning]}"
192
- puts " Context: #{explanation[:context]}"
193
- puts " Confidence: #{explanation[:confidence]}%"
194
- puts " Alternative View: #{explanation[:alternative]}"
195
- end,
196
- priority: 5
197
- )
198
-
199
- # Rule 6: AI Pattern Recognition
200
- pattern_recognition_rule = KBS::Rule.new(
201
- "ai_pattern_recognition",
202
- conditions: [
203
- KBS::Condition.new(:price_history, {
204
- symbol: ->(s) { s && s.length > 0 },
205
- data_points: ->(d) { d && d.length >= 30 }
206
- })
207
- ],
208
- action: lambda do |facts, bindings|
209
- price_data = facts.find { |f| f.type == :price_history }
210
-
211
- # AI identifies patterns
212
- patterns = identify_patterns_with_ai(price_data[:data_points])
213
-
214
- if patterns.any?
215
- puts "šŸ“Š AI PATTERN RECOGNITION: #{price_data[:symbol]}"
216
- patterns.each do |pattern|
217
- puts " Pattern: #{pattern[:name]} (#{pattern[:confidence]}%)"
218
- puts " Prediction: #{pattern[:prediction]}"
219
- puts " Time Horizon: #{pattern[:time_horizon]}"
220
- end
221
- end
222
- end,
223
- priority: 10
224
- )
225
-
226
- @engine.add_rule(sentiment_rule)
227
- @engine.add_rule(ai_strategy_rule)
228
- @engine.add_rule(dynamic_rule_creation)
229
- @engine.add_rule(ai_risk_assessment)
230
- @engine.add_rule(explanation_rule)
231
- @engine.add_rule(pattern_recognition_rule)
232
- end
233
-
234
- def analyze_sentiment_with_ai(headline, content)
235
- cache_key = "#{headline[0..50]}_#{content[0..100]}".hash
236
- return @sentiment_cache[cache_key] if @sentiment_cache[cache_key]
237
-
238
- prompt = build_sentiment_prompt(headline, content)
239
- puts "\nšŸ”— Calling RubyLLM for sentiment analysis..."
240
-
241
- message = @ai_client.ask(prompt)
242
- response_text = message.content.to_s
243
- puts "āœ… Got response from Ollama (#{response_text.length} chars)"
244
- puts "šŸ“ Response: #{response_text[0..200]}..." if response_text.length > 200
245
-
246
- result = parse_sentiment_response(response_text)
247
-
248
- @sentiment_cache[cache_key] = result
249
- result
250
- end
251
-
252
- def generate_ai_trading_strategy(market_conditions, portfolio_state)
253
- prompt = build_strategy_prompt(market_conditions, portfolio_state)
254
- puts "\nšŸ”— Calling RubyLLM for trading strategy..."
255
-
256
- message = @ai_client.ask(prompt)
257
- response_text = message.content.to_s
258
- puts "āœ… Got response from Ollama (#{response_text.length} chars)"
259
- puts "šŸ“ Response: #{response_text[0..200]}..." if response_text.length > 200
260
-
261
- parse_strategy_response(response_text)
262
- end
263
-
264
- def generate_rule_with_ai(anomaly_data)
265
- prompt = build_rule_generation_prompt(anomaly_data)
266
- puts "\nšŸ”— Calling RubyLLM for rule generation..."
267
-
268
- message = @ai_client.ask(prompt)
269
- response_text = message.content.to_s
270
- puts "āœ… Got response from Ollama (#{response_text.length} chars)"
271
- puts "šŸ“ Response: #{response_text[0..200]}..." if response_text.length > 200
272
-
273
- parse_rule_specification(response_text)
274
- end
275
-
276
- def analyze_position_risk_with_ai(position, market_data)
277
- prompt = build_risk_analysis_prompt(position, market_data)
278
- puts "\nšŸ”— Calling RubyLLM for risk analysis..."
279
-
280
- message = @ai_client.ask(prompt)
281
- response_text = message.content.to_s
282
- puts "āœ… Got response from Ollama (#{response_text.length} chars)"
283
- puts "šŸ“ Response: #{response_text[0..200]}..." if response_text.length > 200
284
-
285
- parse_risk_analysis(response_text)
286
- end
287
-
288
- def generate_trade_explanation(recommendation, context_facts)
289
- cache_key = "#{recommendation[:symbol]}_#{recommendation[:action]}_#{context_facts.length}".hash
290
- return @explanation_cache[cache_key] if @explanation_cache[cache_key]
291
-
292
- prompt = build_explanation_prompt(recommendation, context_facts)
293
- puts "\nšŸ”— Calling RubyLLM for trade explanation..."
294
-
295
- message = @ai_client.ask(prompt)
296
- response_text = message.content.to_s
297
- puts "āœ… Got response from Ollama (#{response_text.length} chars)"
298
- puts "šŸ“ Response: #{response_text[0..200]}..." if response_text.length > 200
299
-
300
- result = parse_explanation_response(response_text)
301
-
302
- @explanation_cache[cache_key] = result
303
- result
304
- end
305
-
306
- def identify_patterns_with_ai(price_data)
307
- prompt = build_pattern_recognition_prompt(price_data)
308
- puts "\nšŸ”— Calling RubyLLM for pattern recognition..."
309
-
310
- message = @ai_client.ask(prompt)
311
- response_text = message.content.to_s
312
- puts "āœ… Got response from Ollama (#{response_text.length} chars)"
313
- puts "šŸ“ Response: #{response_text[0..200]}..." if response_text.length > 200
314
-
315
- parse_pattern_response(response_text)
316
- end
317
-
318
- # Prompt builders
319
- def build_sentiment_prompt(headline, content)
320
- <<~PROMPT
321
- Analyze the sentiment of this financial news for trading implications:
322
-
323
- Headline: #{headline}
324
- Content: #{content[0..500]}...
325
-
326
- Provide a JSON response with:
327
- {
328
- "sentiment": "positive|negative|neutral",
329
- "score": -1.0 to 1.0,
330
- "confidence": 0-100,
331
- "themes": ["theme1", "theme2"],
332
- "market_impact": "bullish|bearish|neutral"
333
- }
334
- PROMPT
335
- end
336
-
337
- def build_strategy_prompt(market_conditions, portfolio_state)
338
- <<~PROMPT
339
- Generate a trading strategy for these conditions:
340
-
341
- Market: #{market_conditions[:trend]} trend, #{market_conditions[:volatility]}% volatility
342
- Portfolio: #{(portfolio_state[:cash_ratio] * 100).round(1)}% cash
343
-
344
- Provide a JSON strategy with:
345
- {
346
- "name": "strategy_name",
347
- "rationale": "why this strategy fits",
348
- "actions": ["action1", "action2"],
349
- "risk_level": "LOW|MEDIUM|HIGH"
350
- }
351
- PROMPT
352
- end
353
-
354
- def build_risk_analysis_prompt(position, market_data)
355
- <<~PROMPT
356
- Analyze the risk of this trading position:
357
-
358
- Position: #{position[:symbol]}, P&L: $#{position[:unrealized_pnl]}
359
- Market Data: #{market_data.to_json}
360
-
361
- Provide risk assessment as JSON:
362
- {
363
- "risk_level": "LOW|MEDIUM|HIGH",
364
- "risks": ["risk1", "risk2"],
365
- "recommendation": "hold|reduce|exit",
366
- "confidence": 0-100
367
- }
368
- PROMPT
369
- end
370
-
371
- def build_explanation_prompt(recommendation, context_facts)
372
- <<~PROMPT
373
- Explain this trading recommendation in simple terms:
374
-
375
- Recommendation: #{recommendation[:action]} #{recommendation[:symbol]}
376
- Context: #{context_facts.length} supporting facts
377
-
378
- Provide explanation as JSON:
379
- {
380
- "explanation": "clear explanation",
381
- "reasoning": "why this makes sense",
382
- "risks": ["risk1", "risk2"]
383
- }
384
- PROMPT
385
- end
386
-
387
- def build_pattern_recognition_prompt(price_data)
388
- <<~PROMPT
389
- Identify trading patterns in this price data:
390
-
391
- Data: #{price_data.to_json}
392
-
393
- Return JSON array of patterns:
394
- [
395
- {
396
- "pattern": "pattern_name",
397
- "confidence": 0-100,
398
- "description": "what this means"
399
- }
400
- ]
401
- PROMPT
402
- end
403
-
404
- # Response parsers
405
- def extract_json(response)
406
- # Strip markdown code fences if present
407
- json_text = response.strip
408
- json_text = json_text.gsub(/^```json\s*/, '').gsub(/```\s*$/, '').strip
409
- json_text
410
- end
411
-
412
- def parse_sentiment_response(response)
413
- JSON.parse(extract_json(response), symbolize_names: true)
414
- end
415
-
416
- def parse_strategy_response(response)
417
- JSON.parse(extract_json(response), symbolize_names: true)
418
- end
419
-
420
- def parse_explanation_response(response)
421
- JSON.parse(extract_json(response), symbolize_names: true)
422
- end
423
-
424
- def parse_pattern_response(response)
425
- JSON.parse(extract_json(response), symbolize_names: true)
426
- end
427
-
428
- def parse_risk_analysis(response)
429
- JSON.parse(extract_json(response), symbolize_names: true)
430
- end
431
-
432
- def demonstrate_ai_enhancements
433
- puts "šŸ¤– AI-ENHANCED KNOWLEDGE-BASED SYSTEM"
434
- puts "=" * 70
435
- puts "Integrating #{@ai_client.class.name} and #{@mcp_agent.class.name}"
436
- puts "=" * 70
437
-
438
- # Scenario 1: AI Sentiment Analysis
439
- puts "\nšŸ“° SCENARIO 1: AI-Powered News Sentiment"
440
- puts "-" * 50
441
- @engine.working_memory.facts.clear
442
-
443
- @engine.add_fact(:news_data, {
444
- symbol: "AAPL",
445
- headline: "Apple Reports Record Q4 Earnings, Beats Expectations by 15%",
446
- content: "Apple Inc. announced exceptional fourth quarter results today, with revenue growing 12% year-over-year to $94.9 billion. iPhone sales exceeded analysts' expectations, driven by strong demand for the iPhone 15 Pro models. The company also announced a new $90 billion share buyback program and increased its dividend by 4%. CEO Tim Cook expressed optimism about the AI integration roadmap and services growth trajectory.",
447
- published_at: Time.now
448
- })
449
- @engine.run
450
-
451
- # Scenario 2: AI Strategy Generation
452
- puts "\n🧠 SCENARIO 2: AI Trading Strategy Generation"
453
- puts "-" * 50
454
- @engine.working_memory.facts.clear
455
-
456
- @engine.add_fact(:market_conditions, {
457
- volatility: 28.5,
458
- trend: "sideways",
459
- sector_rotation: "technology_to_healthcare"
460
- })
461
-
462
- @engine.add_fact(:portfolio_state, {
463
- cash_ratio: 0.25,
464
- largest_position: "AAPL",
465
- sector_concentration: 0.45
466
- })
467
- @engine.run
468
-
469
- # Scenario 3: AI Risk Assessment
470
- puts "\nāš ļø SCENARIO 3: AI Risk Assessment"
471
- puts "-" * 50
472
- @engine.working_memory.facts.clear
473
-
474
- @engine.add_fact(:position, {
475
- symbol: "TSLA",
476
- shares: 100,
477
- entry_price: 250.00,
478
- current_price: 235.00,
479
- unrealized_pnl: -1500
480
- })
481
-
482
- @engine.add_fact(:market_data, {
483
- symbol: "TSLA",
484
- volatility: 45.2,
485
- beta: 2.1,
486
- sector: "Consumer Discretionary"
487
- })
488
- @engine.run
489
-
490
- # Scenario 4: Trade Explanation
491
- puts "\nšŸ’¬ SCENARIO 4: AI Trade Explanation"
492
- puts "-" * 50
493
- @engine.working_memory.facts.clear
494
-
495
- @engine.add_fact(:trade_recommendation, {
496
- symbol: "GOOGL",
497
- action: "BUY",
498
- quantity: 50,
499
- confidence: 85
500
- })
501
-
502
- @engine.add_fact(:technical_analysis, {
503
- symbol: "GOOGL",
504
- rsi: 35,
505
- moving_average_signal: "golden_cross",
506
- volume_trend: "increasing"
507
- })
508
- @engine.run
509
-
510
- puts "\n" + "=" * 70
511
- puts "AI ENHANCEMENT DEMONSTRATION COMPLETE"
512
- puts "šŸŽÆ The system now combines rule-based logic with AI insights"
513
- puts "🧠 Dynamic pattern recognition and strategy generation"
514
- puts "šŸ’¬ Natural language explanations for all decisions"
515
- puts "⚔ Real-time sentiment analysis and risk assessment"
516
- end
517
- end
518
- end
519
-
520
- if __FILE__ == $0
521
- system = AIEnhancedKBS::AIKnowledgeSystem.new
522
- system.demonstrate_ai_enhancements
523
- end