| 1 | use v5.20; | ||
| 2 | use strict; | ||
| 3 | use warnings; | ||
| 4 | use experimental qw( signatures lexical_subs postderef ); | ||
| 5 | |||
| 6 | package App::Chit::Util; | ||
| 7 | |||
| 8 | use AI::Chat; | ||
| 9 | use Carp qw( croak ); | ||
| 10 | use Cwd qw( getcwd ); | ||
| 11 | use Path::Tiny qw( path ); | ||
| 12 | use YAML::XS qw( LoadFile DumpFile ); | ||
| 13 | |||
| 14 | use constant CHIT_FILENAME => '.chit.yml'; | ||
| 15 | use constant CHIT_KEY_VAR => 'OPENAI_API_KEY'; | ||
| 16 | |||
| 17 | our $AUTHORITY = 'cpan:TOBYINK'; | ||
| 18 | our $VERSION = '0.001001'; | ||
| 19 | |||
| 20 | sub is_chit_dir ( $dir ) { | ||
| 21 | my $path = path( $dir ); | ||
| 22 | my $file = $path->child( CHIT_FILENAME ); | ||
| 23 | croak "Chit config file was unexpectedly a directory: $file" if $file->is_dir; | ||
| 24 | return $file->is_file; | ||
| 25 | } | ||
| 26 | |||
| 27 | sub find_chit_dir ( $starting_from=getcwd() ) { | ||
| 28 | my $path = path( $starting_from ); | ||
| 29 | while ( not is_chit_dir( $path ) ) { | ||
| 30 | return undef if $path->is_rootdir; | ||
| 31 | $path = $path->parent; | ||
| 32 | } | ||
| 33 | is_chit_dir( $path ) ? $path : undef; | ||
| 34 | } | ||
| 35 | |||
| 36 | sub load_chit ( $dir ) { | ||
| 37 | my $path = path( $dir ); | ||
| 38 | is_chit_dir( $path ) or croak "Not a chit dir: $dir"; | ||
| 39 | my ( $chit ) = LoadFile( $path->child( CHIT_FILENAME )->stringify ); | ||
| 40 | $chit->{model} //= 'gpt-4o-mini'; | ||
| 41 | $chit->{temperature} //= 0.99; | ||
| 42 | $chit->{role} //= "You are a helpful assistant, valued for your precise, accurate, and concise answers."; | ||
| 43 | $chit->{history} //= 100; | ||
| 44 | return $chit; | ||
| 45 | } | ||
| 46 | |||
| 47 | sub save_chit ( $dir, $chit ) { | ||
| 48 | my $path = path( $dir ); | ||
| 49 | if ( $chit->{chat} ) { | ||
| 50 | $chit->{history} //= 100; | ||
| 51 | shift @{ $chit->{chat} } while @{ $chit->{chat} } > $chit->{history}; | ||
| 52 | } | ||
| 53 | return DumpFile( $path->child( CHIT_FILENAME )->stringify, $chit ); | ||
| 54 | } | ||
| 55 | |||
| 56 | sub chatgpt ( $chit ) { | ||
| 57 | return AI::Chat->new( | ||
| 58 | key => $ENV{ CHIT_KEY_VAR() }, | ||
| 59 | api => 'OpenAI', | ||
| 60 | model => $chit->{model}, | ||
| 61 | role => $chit->{role}, | ||
| 62 | ); | ||
| 63 | } | ||
| 64 | |||
| 65 | 1; | ||
| 66 |