Chit/Command/chat.pm untested

filter: Statementstmt 0.0% 0 / 67 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 21 MC/DCmcdc 0.0% 0 / 13 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 136 CC 10 SCAR 31.1
CC
10
Cov
0%
execute
56.0
validate_args
20.0
abstract
2.0
CRAP 22.5
1 use v5.20;
2 use strict;
3 use warnings;
4 use experimental qw( signatures lexical_subs postderef );
5  
6 package App::Chit::Command::chat;
7  
8 use App::Chit -command;
9  
10 use App::Chit::Util ();
11 use Carp qw( croak );
12 use Path::Tiny qw( path );
13 use Term::Spinner::Color ();
14  
15 our $AUTHORITY = 'cpan:TOBYINK';
16 our $VERSION = '0.001001';
17  
18 sub abstract {
19 return "Chat with ChatGPT."
20 }
21  
22 sub opt_spec {
23 return (
24 [ "temperature=f", "temperature for response" ],
25 [ "stdin", "prompt from STDIN" ],
26 [ "file=s", "prompt from file" ],
27 );
28 }
29  
30 sub validate_args ( $self, $opt, $args ) {
31 unless ( $opt->{stdin} or $opt->{file} ) {
32 $self->usage_error( "expected a prompt on the command line, or -i, or -f" )
33 unless ( @$args == 1 and length($args->[0]) > 2 );
34 }
35
36 $self->usage_error( "cannot use both -i and -f" )
37 if ( $opt->{stdin} and $opt->{file} );
38 }
39  
40 sub execute ( $self, $opt, $args ) {
41 my $dir = App::Chit::Util::find_chit_dir()
42 or $self->usage_error("need to initialize chit first");
43 my $chit = App::Chit::Util::load_chit( $dir );
44
45 my $spin;
46 $spin = Term::Spinner::Color->new(
47 'delay' => 0.3,
48 'colorcycle' => 1,
49 ) if -t STDOUT;
50
51 $spin->auto_start if $spin;
52
53 my $prompt = do {
54 if ( $opt->{stdin} ) {
55 local $/;
56 <STDIN>;
57 }
58 elsif ( $opt->{file} ) {
59 my $f = path( $opt->{file} );
60 $f->is_file or croak("File does not exist");
61 $f->slurp_utf8;
62 }
63 else {
64 $args->[0];
65 }
66 };
67 chomp $prompt;
68
69 my @log = @{ $chit->{chat} or [] };
70 unshift @log, { role => 'system', content => $chit->{role} };
71 push @log, { role => 'user', content => $prompt };
72
73 my $temperature = $opt->{temperature} // $chit->{temperature};
74
75 my $gpt = App::Chit::Util::chatgpt( $chit );
76 my $response = $gpt->chat( \@log, $temperature );
77 $spin->auto_done if $spin;
78 if ( defined $response ) {
79 chomp $response;
80 say $response;
81 push @{ $chit->{chat} //= [] },
82 { role => 'user', content => $prompt },
83 { role => 'assistant', content => $response };
84 }
85 else {
86 croak( "Error: " . $gpt->error );
87 }
88
89 App::Chit::Util::save_chit( $dir, $chit );
90 }
91  
92 1;