File Coverage

File:blib/lib/Database/BI/Ask.pm
Coverage:98.5%

linestmtbrancondsubtimecode
1package Database::BI::Ask;
2
3
5
5
5
2501
5
52
use strict;
4
5
5
5
7
5
197
use warnings;
5
6our $VERSION = '0.025.0';
7
8
5
5
5
6
3
140
use Carp                qw(croak);
9
5
5
5
8
5
94
use Database::BI::Util  qw(urlencode);
10
5
5
5
8
3
76
use Readonly;
11
5
5
5
9
4
2714
use Scalar::Util        qw(looks_like_number);
12
13Readonly my %SUPPORTED_KINDS => map { $_ => 1 }
14        qw( bar pie line graph scatter heatmap stacked combo treemap histogram map table );
15
16Readonly my %KIND_ROUTE => (
17        pie       => 'pie',
18        bar       => 'bar',
19        line      => 'graph',
20        graph     => 'graph',
21        scatter   => 'scatter',
22        heatmap   => 'heatmap',
23        stacked   => 'stacked',
24        combo     => 'combo',
25        treemap   => 'treemap',
26        histogram => 'histogram',
27        map       => 'map',
28        table     => '',
29);
30
31Readonly my @MEASURE_FUNCTIONS => qw( sum avg min max count count_distinct );
32
33# ---------------------------------------------------------------------------
34# ask(%args) -> { spec, url, valid => 1 } | { error => 'code_or_code:detail' }
35#
36# args:
37#   question   -- natural language question (required)
38#   spec_key   -- l= spec, e.g. "table:sales" (required for URL construction)
39#   label      -- human-readable dataset name
40#   columns    -- arrayref of { name, type } hashrefs (from infer_column_types)
41#   ai_config  -- hashref { provider, api_key, model }
42# ---------------------------------------------------------------------------
43sub ask {
44
82
27281
        my (%args) = @_;
45
46
82
163
        my $question  = $args{question}  // '';
47
82
140
        my $spec_key  = $args{spec_key}  // '';
48
82
170
        my $label     = $args{label}     // 'dataset';
49
82
137
        my $columns   = $args{columns}   // [];
50
82
115
        my $ai_config = $args{ai_config} // {};
51
52
82
125
        return { error => 'ask_no_question' }
53                unless length $question;
54
55        return { error => 'ask_unavailable' }
56
78
179
                unless length($ai_config->{api_key} // '');
57
58
72
72
60
122
        my $raw = eval { _call_llm($question, $label, $columns, $ai_config) };
59
72
14182
        return { error => 'ask_provider_error' } if $@;
60
61
38
38
25
58
        my $visual = eval { _parse_visual($raw) };
62
38
104
        return { error => 'ask_unparseable' } unless ref $visual eq 'HASH';
63
64
30
129
27
120
        my %col_set = map { $_->{name} => 1 } @$columns;
65
30
54
        my $val_err = _validate_encode($visual, \%col_set);
66
30
51
        return { error => "ask_invalid_spec:$val_err" } if defined $val_err;
67
68
25
33
        my $url  = _build_url($visual, $spec_key);
69
25
40
        my $spec = _build_spec($visual, $label, $spec_key);
70
71
25
80
        return { spec => $spec, url => $url, valid => 1 };
72}
73
74# ---------------------------------------------------------------------------
75# infer_column_types($records, $columns_aref) -> [{ name, type }, ...]
76#
77# Type is one of: 'number', 'date', 'string'
78# ---------------------------------------------------------------------------
79sub infer_column_types {
80
68
7024
        my ($records, $columns) = @_;
81
68
273
        return [] unless ref $records eq 'ARRAY' && ref $columns eq 'ARRAY';
82
83
64
80
        my @result;
84
64
81
        for my $col (@$columns) {
85
327
1906
1906
192
1304
864
                my @vals = grep { defined $_ && length $_ } map { $_->{$col} } @$records;
86
327
290
                push @result, { name => $col, type => _infer_type(\@vals) };
87        }
88
64
80
        return \@result;
89}
90
91# ---------------------------------------------------------------------------
92# Internal helpers
93# ---------------------------------------------------------------------------
94
95sub _infer_type {
96
344
9885
        my ($vals) = @_;
97
344
236
        return 'string' unless @$vals;
98
99
340
149
        my $n       = scalar @$vals;
100
340
1950
185
971
        my $numeric = grep { looks_like_number($_) } @$vals;
101
340
387
        return 'number' if $numeric / $n > 0.5;
102
103        my $date = grep {
104
227
1301
121
1052
                /\A\d{4}-\d{2}-\d{2}\z/ || /\A\d{1,2}\/\d{1,2}\/\d{4}\z/
105        } @$vals;
106
227
255
        return 'date' if $date / $n > 0.5;
107
108
167
202
        return 'string';
109}
110
111sub _call_llm {
112
73
3835
        my ($question, $label, $columns, $ai_config) = @_;
113
114
73
334
        require LWP::UserAgent;
115
73
9681
        require HTTP::Request;
116
73
113
        require JSON::PP;       # core since Perl 5.013009; MIN_PERL_VERSION is 5.028000
117
118
73
348
72
306
        my $col_lines = join("\n", map { "- $_->{name} ($_->{type})" } @$columns);
119
73
235
        my $kinds_str = join(', ', sort keys %SUPPORTED_KINDS);
120
73
1415
        my $mfns_str  = join(', ', @MEASURE_FUNCTIONS);
121
122
73
838
        my $prompt = <<"PROMPT";
123You are a data analysis assistant. Given a dataset and a question, return ONLY a JSON object describing one visualization. Do not include any explanation, markdown, or surrounding text -- just the JSON object.
124
125Dataset: "$label"
126Columns:
127$col_lines
128
129Available chart kinds: $kinds_str
130Available measure functions: $mfns_str
131
132Encode key rules per kind:
133- pie: cat (required), val (optional)
134- bar: cat (required), val (optional)
135- line/graph: x (required), y (required), series (optional)
136- scatter: x (required), y (required), series (optional), size (optional)
137- heatmap: x (required), y (required), val (optional)
138- stacked: cat (required), series (required), val (optional)
139- combo: cat (required), bar_val (required), line_val (required)
140- treemap: group (required), size (optional)
141- histogram: col (required)
142- map: lat+lon (required pair) or loc (required)
143- table: no encode keys
144
145Question: "$question"
146
147Return ONLY valid JSON with this exact structure (no other text):
148{"kind":"<kind>","title":"<short descriptive title>","encode":{"<key>":"<column name>"}}
149
150Use only column names from the list above. Choose the most informative chart kind for the question.
151PROMPT
152
153        my $body = JSON::PP::encode_json({
154
73
373
                model      => ($ai_config->{model} // 'claude-haiku-5-5'),
155                max_tokens => 256,
156                messages   => [{ role => 'user', content => $prompt }],
157        });
158
159
73
8815
        my $ua  = LWP::UserAgent->new(timeout => 30);
160        my $req = HTTP::Request->new(
161                'POST',
162                'https://api.anthropic.com/v1/messages',
163                [
164                        'Content-Type'      => 'application/json',
165                        'x-api-key'         => $ai_config->{api_key},
166
73
12550
                        'anthropic-version' => '2023-06-01',
167                ],
168                $body,
169        );
170
171
73
14014
        my $resp = $ua->request($req);
172
62
2006240
        croak sprintf('Provider error: %s', $resp->status_line) unless $resp->is_success;
173
174
45
288
        my $data = JSON::PP::decode_json($resp->decoded_content);
175
41
41
14001
68
        my $text = eval { $data->{content}[0]{text} };
176
41
708
        croak 'No text in provider response' unless defined $text && length $text;
177
36
333
        return $text;
178}
179
180sub _parse_visual {
181
80
22216
        my ($text) = @_;
182
80
116
        require JSON::PP;
183
184        # The reply has already been decoded from the wire, so it is characters, and
185        # decode_json (which takes UTF-8 bytes) would refuse any non-ASCII title.
186
80
143
        my $json = JSON::PP->new;
187
188        # Try the full text first (clean LLM response).
189
80
80
269
68
        my $v = eval { $json->decode($text) };
190
191        # Fall back: LLM added preamble/suffix text around the JSON object.
192        # A bracket-depth counter locates the first complete balanced {..} block.
193        # This is safer than a greedy /\{.*\}/s regex, which captures from the
194        # first '{' all the way to the LAST '}' in the string -- if the LLM
195        # produced multiple JSON-like constructs the greedy form spans them all
196        # and returns unparseable input.  The depth counter handles nested objects
197        # and stops exactly at the matching brace.  A brace inside a string is text,
198        # so strings are stepped over, with a backslash escaping what follows it.
199
80
14089
        if (!ref $v) {
200
30
23
                my $start = index($text, '{');
201
30
27
                if ($start >= 0) {
202
19
18
                        my ($depth, $end, $in_string, $escaped) = (0, -1, 0, 0);
203
19
18
                        for my $i ($start .. length($text) - 1) {
204
5667
1865
                                my $ch = substr($text, $i, 1);
205
5667
1997
                                if ($in_string) {
206
462
2
242
3
                                        if ($escaped)         { $escaped = 0 }
207
2
0
                                        elsif ($ch eq '\\')   { $escaped = 1 }
208
86
28
                                        elsif ($ch eq '"')    { $in_string = 0 }
209
462
162
                                        next;
210                                }
211
5205
86
86
1872
29
32
                                if ($ch eq '"') { $in_string = 1; next }
212
5119
1859
                                $depth++ if $ch eq '{';
213
5119
2004
                                if ($ch eq '}') {
214
22
9
                                        $depth--;
215
22
14
14
16
7
9
                                        if ($depth == 0) { $end = $i; last }
216                                }
217                        }
218
19
12
                        if ($end >= 0) {
219
14
14
7
17
                                $v = eval { $json->decode(substr($text, $start, $end - $start + 1)) };
220                        }
221                }
222        }
223
224
80
2235
        return undef unless ref $v eq 'HASH';
225
62
162
        return undef unless defined $v->{kind} && $SUPPORTED_KINDS{ $v->{kind} };
226
54
246
        return undef if defined $v->{encode} && ref $v->{encode} ne 'HASH';
227
50
57
        $v->{encode} //= {};
228
50
81
        return $v;
229}
230
231sub _validate_encode {
232
43
6365
        my ($visual, $col_set) = @_;
233
43
36
        my $encode = $visual->{encode};
234
43
47
        return undef unless %$encode;
235
236
39
57
        for my $key (sort keys %$encode) {
237
61
38
                my $col = $encode->{$key};
238
61
103
                next unless defined $col && length $col;
239
57
67
                return $col unless $col_set->{$col};
240        }
241
28
26
        return undef;
242}
243
244sub _build_url {
245
45
11995
        my ($visual, $spec_key) = @_;
246
45
34
        my $kind   = $visual->{kind};
247
45
48
        my $encode = $visual->{encode} // {};
248
249
45
41
        if ($kind eq 'table') {
250
8
10
                if ($spec_key =~ /\Atable:(.+)\z/) {
251
5
5
                        return '/view/' . urlencode($1);
252                }
253
3
6
                (my $path = $spec_key) =~ s/\Apath://;
254
3
6
                require Database::BI::Model::DataSource;
255
3
8
                my ($file, $internal) = Database::BI::Model::DataSource::split_path($path);
256
3
4
                return '/open?path=' . urlencode($file) . (defined $internal ? '&it=' . urlencode($internal) : '');
257        }
258
259
37
52
        my $route  = $KIND_ROUTE{$kind} // $kind;
260
37
135
        my @params = ('l=' . urlencode($spec_key));
261
37
53
        for my $key (sort keys %$encode) {
262
61
40
                my $val = $encode->{$key};
263
61
85
                next unless defined $val && length $val;
264
57
52
                push @params, "$key=" . urlencode($val);
265        }
266
37
83
        return "/$route?" . join('&', @params);
267}
268
269sub _build_spec {
270
36
8509
        my ($visual, $label, $spec_key) = @_;
271        return {
272                name     => ($visual->{title} || "$label analysis"),
273                datasets => [{ spec => $spec_key }],
274                version  => 1,
275                visuals  => [{
276                        kind    => $visual->{kind},
277                        title   => ($visual->{title} // ''),
278
36
199
                        encode  => ($visual->{encode} // {}),
279                        options => {},
280                }],
281        };
282}
283
284
2851;
286