| | | 1 | | using Intentum.Core.Intents; |
| | | 2 | | |
| | | 3 | | namespace Intentum.Explainability; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Default implementation of intent explainability using signal weights. |
| | | 7 | | /// </summary> |
| | | 8 | | public sealed class IntentExplainer : IIntentExplainer |
| | | 9 | | { |
| | | 10 | | /// <inheritdoc /> |
| | | 11 | | public IReadOnlyList<SignalContribution> GetSignalContributions(Intent intent) |
| | 3 | 12 | | { |
| | 3 | 13 | | if (intent.Signals.Count == 0) |
| | 1 | 14 | | return []; |
| | | 15 | | |
| | 6 | 16 | | var total = intent.Signals.Sum(s => s.Weight); |
| | 2 | 17 | | if (total <= 0) |
| | 0 | 18 | | return intent.Signals.Select(s => new SignalContribution(s.Source, s.Description, s.Weight, 0)).ToList(); |
| | | 19 | | |
| | 2 | 20 | | return intent.Signals |
| | 4 | 21 | | .Select(s => new SignalContribution( |
| | 4 | 22 | | s.Source, |
| | 4 | 23 | | s.Description, |
| | 4 | 24 | | s.Weight, |
| | 4 | 25 | | 100.0 * s.Weight / total)) |
| | 3 | 26 | | .OrderByDescending(c => c.ContributionPercent) |
| | 2 | 27 | | .ToList(); |
| | 3 | 28 | | } |
| | | 29 | | |
| | | 30 | | /// <inheritdoc /> |
| | | 31 | | public string GetExplanation(Intent intent, int maxSignals = 5) |
| | 1 | 32 | | { |
| | 1 | 33 | | var level = intent.Confidence.Level; |
| | 1 | 34 | | var score = intent.Confidence.Score; |
| | 1 | 35 | | var contributions = GetSignalContributions(intent).Take(maxSignals).ToList(); |
| | | 36 | | |
| | 1 | 37 | | var parts = new List<string> |
| | 1 | 38 | | { |
| | 1 | 39 | | $"Intent \"{intent.Name}\" inferred with confidence {level} ({score:F2})." |
| | 1 | 40 | | }; |
| | 1 | 41 | | if (contributions.Count > 0) |
| | 1 | 42 | | { |
| | 1 | 43 | | var top = string.Join("; ", contributions.Select(c => |
| | 2 | 44 | | $"{c.Description} ({c.ContributionPercent:F0}%)")); |
| | 1 | 45 | | parts.Add($"Top contributors: {top}."); |
| | 1 | 46 | | } |
| | 1 | 47 | | if (!string.IsNullOrWhiteSpace(intent.Reasoning)) |
| | 0 | 48 | | parts.Add($"Reasoning: {intent.Reasoning}"); |
| | 1 | 49 | | return string.Join(" ", parts); |
| | 1 | 50 | | } |
| | | 51 | | } |