| | | 1 | | using Intentum.Core.Behavior; |
| | | 2 | | using Intentum.Core.Intents; |
| | | 3 | | using Intentum.Core.Models; |
| | | 4 | | |
| | | 5 | | namespace Intentum.Core.Pipeline; |
| | | 6 | | |
| | | 7 | | /// <summary> |
| | | 8 | | /// Rule-based inference step: evaluates rules against behavior space and vector; returns raw result (name, score, signa |
| | | 9 | | /// Used by IntentResolutionPipeline; also used by RuleBasedIntentModel internally. |
| | | 10 | | /// </summary> |
| | | 11 | | public sealed class RuleBasedInferenceStep : IIntentInferenceStep |
| | | 12 | | { |
| | | 13 | | private readonly IReadOnlyList<Func<BehaviorSpace, RuleMatch?>> _rules; |
| | | 14 | | |
| | | 15 | | /// <summary> |
| | | 16 | | /// Creates a rule-based inference step with the given rules. First matching rule wins. |
| | | 17 | | /// </summary> |
| | 8 | 18 | | public RuleBasedInferenceStep(IEnumerable<Func<BehaviorSpace, RuleMatch?>> rules) |
| | 8 | 19 | | { |
| | 8 | 20 | | _rules = rules.ToList(); |
| | 8 | 21 | | } |
| | | 22 | | |
| | | 23 | | /// <inheritdoc /> |
| | | 24 | | public IntentInferenceResult Infer(BehaviorSpace behaviorSpace, BehaviorVector vector) |
| | 8 | 25 | | { |
| | 33 | 26 | | foreach (var rule in _rules) |
| | 8 | 27 | | { |
| | 8 | 28 | | var match = rule(behaviorSpace); |
| | 8 | 29 | | if (match == null) |
| | 1 | 30 | | continue; |
| | | 31 | | |
| | 7 | 32 | | var score = Math.Clamp(match.Score, 0, 1); |
| | 7 | 33 | | var signals = vector.Dimensions.Select(d => |
| | 17 | 34 | | new IntentSignal("rule", d.Key, d.Value)).ToList(); |
| | | 35 | | |
| | 7 | 36 | | return new IntentInferenceResult( |
| | 7 | 37 | | Name: match.Name, |
| | 7 | 38 | | Score: score, |
| | 7 | 39 | | Signals: signals, |
| | 7 | 40 | | Reasoning: match.Reasoning |
| | 7 | 41 | | ); |
| | | 42 | | } |
| | | 43 | | |
| | 1 | 44 | | var unknownSignals = vector.Dimensions.Select(d => |
| | 2 | 45 | | new IntentSignal("rule", d.Key, d.Value)).ToList(); |
| | | 46 | | |
| | 1 | 47 | | return new IntentInferenceResult( |
| | 1 | 48 | | Name: "Unknown", |
| | 1 | 49 | | Score: 0, |
| | 1 | 50 | | Signals: unknownSignals, |
| | 1 | 51 | | Reasoning: "No rule matched" |
| | 1 | 52 | | ); |
| | 8 | 53 | | } |
| | | 54 | | } |