AI-Chat
view release on metacpan or search on metacpan
lib/AI/Chat.pm view on Meta::CPAN
}
# Get a reply from a full chat
sub chat {
my ($self, $chat, $temperature) = @_;
if (ref($chat) ne 'ARRAY') {
$self->{'error'} = 'chat method requires an arrayref';
return undef;
}
$temperature = 1.0 unless $temperature;
my $response = $http->post($url{$self->{'api'}}, {
'headers' => {
'Authorization' => 'Bearer ' . $self->{'key'},
'Content-type' => 'application/json'
},
content => encode_json {
model => $self->{'model'},
messages => [ @$chat ],
temperature => $temperature,
}
});
if ($response->{'content'} =~ 'invalid_api_key') {
croak 'Incorrect API Key - check your API Key is correct';
}
if ($self->{'debug'} and !$response->{'success'}) {
croak $response if $self->{'debug'} eq 'verbose';
croak $response->{'content'};
}
my $reply = decode_json($response->{'content'});
return $reply->{'choices'}[0]->{'message'}->{'content'};
}
__END__
=head1 NAME
AI::Chat - Interact with AI Chat APIs
=head1 VERSION
Version 0.6
=head1 SYNOPSIS
use AI::Chat;
my $chat = AI::Chat->new(
key => 'your-api-key',
api => 'OpenAI',
model => 'gpt-4o-mini',
);
my $reply = $chat->prompt("What is the meaning of life?");
print $reply;
=head1 DESCRIPTION
This module provides a simple interface for interacting with AI Chat APIs,
currently supporting OpenAI.
The AI chat agent can be given a I<role> and then passed I<prompts>. It will
reply to the prompts in natural language. Being AI, the responses are
non-deterministic, that is, the same prompt will result in diferent responses
on different occasions.
Further control of the creativity of the responses is possible by specifying
at optional I<temperature> parameter.
=head1 API KEYS
A free OpenAI API can be obtained from L<https://platform.openai.com/account/api-keys>
=head1 MODELS
Although the API Key is free, each use incurs a cost. This is dependent on the
number of tokens in the prompt and the reply. Different models have different costs.
The default model C<gpt-4o-mini> is the lowest cost of the useful models and
is a good place to start using this module. Previous versions of this module
defaulted to C<gpt-3.5-turbo-0125> but the current default is cheaper and
quicker. For most purposes, the default model should be used.
See also L<https://platform.openai.com/docs/models/overview>
=head1 METHODS
=head2 new
my $chat = AI::Chat->new(%params);
Creates a new AI::Chat object.
=head3 Parameters
=over 4
=item key
C<required> Your API key for the chosen service.
=item api
The API to use (currently only 'OpenAI' is supported).
=item model
The language model to use (default: 'gpt-4o-mini').
See L<https://platform.openai.com/docs/models/overview>
=item role
The role to use for the bot in conversations.
This tells the bot what it's purpose when answering prompts.
( run in 0.570 second using v1.01-cache-2.11-cpan-39bf76dae61 )