| File: | blib/lib/Database/BI/Summary.pm |
| Coverage: | 97.7% |
| line | stmt | bran | cond | sub | time | code |
|---|---|---|---|---|---|---|
| 1 | package Database::BI::Summary; | |||||
| 2 | ||||||
| 3 | 5 5 5 | 3112 4 60 | use strict; | |||
| 4 | 5 5 5 | 20 4 155 | use warnings; | |||
| 5 | ||||||
| 6 | our $VERSION = '0.025.0'; | |||||
| 7 | ||||||
| 8 | 5 5 5 | 7 4 97 | use Carp qw(croak); | |||
| 9 | 5 5 5 | 8 4 61 | use Digest::MD5 qw(md5_hex); | |||
| 10 | 5 5 5 | 9 5 64 | use Encode qw(encode_utf8); | |||
| 11 | 5 5 5 | 5 3 1922 | use Readonly; | |||
| 12 | ||||||
| 13 | Readonly my $MAX_SUMMARY_INSIGHTS => 5; | |||||
| 14 | Readonly my $CACHE_TTL_S => 3600; # 1 hour | |||||
| 15 | ||||||
| 16 | my %_cache; # fingerprint => { text, source, ts } | |||||
| 17 | ||||||
| 18 | # --------------------------------------------------------------------------- | |||||
| 19 | # generate(%args) -> { text, source, cached } | |||||
| 20 | # | |||||
| 21 | # args: | |||||
| 22 | # insights arrayref of insight hashrefs (from Insights::compute) | |||||
| 23 | # spec_key the l= spec value (used internally; never sent to LLM) | |||||
| 24 | # label human-readable dataset name | |||||
| 25 | # row_count number of rows analysed | |||||
| 26 | # ai_config optional hashref { provider, api_key, model } | |||||
| 27 | # use_ai 1 to request LLM polish (honoured only when ai_config is set | |||||
| 28 | # and ai_config->{api_key} is non-empty) | |||||
| 29 | # ai_allowed optional code ref, called just before a provider call (not | |||||
| 30 | # for a cached answer); false means do not call, so the | |||||
| 31 | # template text is returned, uncached, as 'template_limited' | |||||
| 32 | # --------------------------------------------------------------------------- | |||||
| 33 | sub generate { | |||||
| 34 | 57 | 31404 | my (%args) = @_; | |||
| 35 | 57 | 78 | my $insights = $args{insights} // []; | |||
| 36 | 57 | 58 | my $label = $args{label} // 'dataset'; | |||
| 37 | 57 | 61 | my $row_count = $args{row_count} // 0; | |||
| 38 | my $use_ai = ($args{use_ai} && $args{ai_config} | |||||
| 39 | 57 | 144 | && length($args{ai_config}{api_key} // '')) | |||
| 40 | ? 1 : 0; | |||||
| 41 | 57 | 53 | my $ai_config = $use_ai ? $args{ai_config} : undef; | |||
| 42 | ||||||
| 43 | 57 | 65 | my $fp = _fingerprint($insights, $use_ai, $label, $row_count); | |||
| 44 | 57 | 69 | if (my $cached = $_cache{$fp}) { | |||
| 45 | 15 | 24 | if ((time() - $cached->{ts}) < $CACHE_TTL_S) { | |||
| 46 | 15 | 52 | return { text => $cached->{text}, source => $cached->{source}, cached => 1 }; | |||
| 47 | } | |||||
| 48 | } | |||||
| 49 | ||||||
| 50 | 42 | 29 | my ($text, $source); | |||
| 51 | 42 | 86 | if ($use_ai && ref($args{ai_allowed}) eq 'CODE' && !$args{ai_allowed}->()) { | |||
| 52 | # Not cached: once the limit lifts, the same summary may ask again. | |||||
| 53 | 2 | 4 | return { text => _template_summary($insights, $label, $row_count), source => 'template_limited', cached => 0 }; | |||
| 54 | } | |||||
| 55 | 40 | 34 | if ($use_ai) { | |||
| 56 | 17 17 | 9 22 | eval { ($text, $source) = _llm_summary($insights, $label, $row_count, $ai_config) }; | |||
| 57 | 17 | 5744 | if ($@) { | |||
| 58 | 14 | 33 | $text = _template_summary($insights, $label, $row_count); | |||
| 59 | 14 | 10 | $source = 'template_fallback'; | |||
| 60 | } | |||||
| 61 | } else { | |||||
| 62 | 23 | 29 | $text = _template_summary($insights, $label, $row_count); | |||
| 63 | 23 | 21 | $source = 'template'; | |||
| 64 | } | |||||
| 65 | ||||||
| 66 | 40 | 85 | $_cache{$fp} = { text => $text, source => $source, ts => time() }; | |||
| 67 | 40 | 85 | return { text => $text, source => $source, cached => 0 }; | |||
| 68 | } | |||||
| 69 | ||||||
| 70 | # --------------------------------------------------------------------------- | |||||
| 71 | # _fingerprint(\@insights, $use_ai, $label, $row_count) -> $hex | |||||
| 72 | # | |||||
| 73 | # Holds everything the text is made from. The detail counts: two period deltas | |||||
| 74 | # can share a headline while their figures differ. md5_hex takes bytes only, and | |||||
| 75 | # croaks on a wide character, so the string is encoded first. | |||||
| 76 | # --------------------------------------------------------------------------- | |||||
| 77 | sub _fingerprint { | |||||
| 78 | 67 | 2752 | my ($insights, $use_ai, $label, $row_count) = @_; | |||
| 79 | my $str = ($use_ai ? 'ai:' : 'tmpl:') | |||||
| 80 | . "L:${label}:R:${row_count}:" | |||||
| 81 | 67 70 | 115 108 | . join('|', map { "$_->{kind}:$_->{headline}:" . ($_->{detail} // '') } @$insights); | |||
| 82 | 67 | 200 | return md5_hex(encode_utf8($str)); | |||
| 83 | } | |||||
| 84 | ||||||
| 85 | # --------------------------------------------------------------------------- | |||||
| 86 | # _template_summary(\@insights, $label, $row_count) -> $text | |||||
| 87 | # --------------------------------------------------------------------------- | |||||
| 88 | sub _template_summary { | |||||
| 89 | 52 | 1969 | my ($insights, $label, $row_count) = @_; | |||
| 90 | 52 | 34 | my @sentences; | |||
| 91 | 52 | 99 | push @sentences, sprintf('%s: %d row%s analysed.', | |||
| 92 | $label, $row_count, ($row_count == 1 ? '' : 's')); | |||||
| 93 | ||||||
| 94 | 52 | 29 | my %by_kind; | |||
| 95 | 52 | 39 | for my $ins (@$insights) { | |||
| 96 | 55 55 | 28 52 | push @{ $by_kind{ $ins->{kind} } }, $ins; | |||
| 97 | } | |||||
| 98 | ||||||
| 99 | 52 | 33 | my $count = 0; | |||
| 100 | 52 | 40 | for my $kind (qw(outlier period_delta top_mover seasonality)) { | |||
| 101 | 208 | 140 | last if $count >= $MAX_SUMMARY_INSIGHTS; | |||
| 102 | 208 | 337 | my $items = $by_kind{$kind} or next; | |||
| 103 | 34 | 18 | my $first = $items->[0]; | |||
| 104 | 34 | 44 | if ($kind eq 'outlier') { | |||
| 105 | 14 | 10 | my $n = scalar @$items; | |||
| 106 | 14 | 17 | if ($n == 1) { | |||
| 107 | 8 | 9 | push @sentences, "An unusual value was detected: $first->{headline}."; | |||
| 108 | } else { | |||||
| 109 | 6 | 9 | push @sentences, "$n outliers detected, including: $first->{headline}."; | |||
| 110 | } | |||||
| 111 | } elsif ($kind eq 'period_delta') { | |||||
| 112 | 9 | 11 | push @sentences, "$first->{headline}. $first->{detail}."; | |||
| 113 | } elsif ($kind eq 'top_mover') { | |||||
| 114 | 8 | 7 | push @sentences, "Top movement: $first->{headline}."; | |||
| 115 | } elsif ($kind eq 'seasonality') { | |||||
| 116 | 3 | 4 | push @sentences, "A repeating seasonal pattern was detected: $first->{headline}."; | |||
| 117 | } | |||||
| 118 | 34 | 24 | $count++; | |||
| 119 | } | |||||
| 120 | ||||||
| 121 | 52 | 53 | push @sentences, 'No significant patterns were detected.' if $count == 0; | |||
| 122 | 52 | 96 | return join(' ', @sentences); | |||
| 123 | } | |||||
| 124 | ||||||
| 125 | # --------------------------------------------------------------------------- | |||||
| 126 | # _llm_summary(\@insights, $label, $row_count, $ai_config) -> ($text, 'llm') | |||||
| 127 | # | |||||
| 128 | # Sends only aggregate facts (insight kinds, headlines, details) to the LLM. | |||||
| 129 | # Never sends file paths, raw row data, or the spec_key. | |||||
| 130 | # --------------------------------------------------------------------------- | |||||
| 131 | sub _llm_summary { | |||||
| 132 | 19 | 1871 | my ($insights, $label, $row_count, $ai_config) = @_; | |||
| 133 | ||||||
| 134 | 19 | 27 | my $provider = lc($ai_config->{provider} // 'anthropic'); | |||
| 135 | 19 | 29 | croak "Unsupported AI provider: $provider" unless $provider eq 'anthropic'; | |||
| 136 | ||||||
| 137 | 17 | 9 | my $n = scalar @$insights; | |||
| 138 | 17 | 24 | $n = $MAX_SUMMARY_INSIGHTS if $n > $MAX_SUMMARY_INSIGHTS; | |||
| 139 | 10 | 13 | my @facts = map { "- [$_->{kind}] $_->{headline}. $_->{detail}" } | |||
| 140 | 17 17 | 38 16 | @{$insights}[0 .. $n - 1]; | |||
| 141 | ||||||
| 142 | 17 | 25 | my $prompt = 'Summarise these data insights about "' . $label . '" (' | |||
| 143 | . $row_count . ' rows) in 2-3 plain-English sentences. ' | |||||
| 144 | . "Use only the facts provided:\n\n" | |||||
| 145 | . join("\n", @facts) | |||||
| 146 | . "\n\nSummary:"; | |||||
| 147 | ||||||
| 148 | 17 | 16 | my $response_text = _call_anthropic($prompt, $ai_config); | |||
| 149 | 4 | 8 | $response_text =~ s/\A\s+//; | |||
| 150 | 4 | 6 | $response_text =~ s/\s+\z//; | |||
| 151 | 4 | 9 | return ($response_text, 'llm'); | |||
| 152 | } | |||||
| 153 | ||||||
| 154 | # --------------------------------------------------------------------------- | |||||
| 155 | # _call_anthropic($prompt, $ai_config) -> $response_text | |||||
| 156 | # --------------------------------------------------------------------------- | |||||
| 157 | sub _call_anthropic { | |||||
| 158 | 23 | 4671 | my ($prompt, $ai_config) = @_; | |||
| 159 | ||||||
| 160 | 23 | 42 | require LWP::UserAgent; | |||
| 161 | 23 | 23 | require HTTP::Request; | |||
| 162 | 23 | 25 | require JSON::PP; # core since Perl 5.013009; MIN_PERL_VERSION is 5.028000 | |||
| 163 | ||||||
| 164 | 23 | 28 | my $model = $ai_config->{model} // 'claude-haiku-5-5'; | |||
| 165 | 23 | 17 | my $api_key = $ai_config->{api_key}; | |||
| 166 | ||||||
| 167 | 23 | 68 | my $body = JSON::PP::encode_json({ | |||
| 168 | model => $model, | |||||
| 169 | max_tokens => 256, | |||||
| 170 | messages => [{ role => 'user', content => $prompt }], | |||||
| 171 | }); | |||||
| 172 | ||||||
| 173 | 23 | 2214 | my $ua = LWP::UserAgent->new(timeout => 30); | |||
| 174 | 23 | 3972 | my $req = HTTP::Request->new( | |||
| 175 | 'POST', | |||||
| 176 | 'https://api.anthropic.com/v1/messages', | |||||
| 177 | [ | |||||
| 178 | 'Content-Type' => 'application/json', | |||||
| 179 | 'x-api-key' => $api_key, | |||||
| 180 | 'anthropic-version' => '2023-06-01', | |||||
| 181 | ], | |||||
| 182 | $body, | |||||
| 183 | ); | |||||
| 184 | ||||||
| 185 | 23 | 4095 | my $resp = $ua->request($req); | |||
| 186 | 22 | 1285 | croak sprintf('Provider error: %s', $resp->status_line) unless $resp->is_success; | |||
| 187 | ||||||
| 188 | 15 | 68 | my $data = JSON::PP::decode_json($resp->decoded_content); | |||
| 189 | 11 11 | 1983 25 | my $text = eval { $data->{content}[0]{text} }; | |||
| 190 | 11 | 539 | croak 'No text in provider response' unless defined $text && length $text; | |||
| 191 | 3 | 27 | return $text; | |||
| 192 | } | |||||
| 193 | ||||||
| 194 | 1; | |||||
| 195 | ||||||