File Coverage

blib/lib/OpenAIGPT4.pm
Criterion Covered Total %
statement 18 25 72.0
branch 0 2 0.0
condition n/a
subroutine 6 7 85.7
pod 0 2 0.0
total 24 36 66.6


line stmt bran cond sub pod time code
1             package OpenAIGPT4;
2              
3 1     1   669 use strict;
  1         2  
  1         28  
4 1     1   5 use warnings;
  1         1  
  1         37  
5              
6             our $VERSION = '0.01';
7              
8             # ABSTRACT: Interact with the OpenAI GPT-4 API
9              
10 1     1   700 use LWP::UserAgent;
  1         51638  
  1         42  
11 1     1   466 use HTTP::Request::Common qw(POST);
  1         2182  
  1         59  
12 1     1   736 use JSON;
  1         8166  
  1         5  
13              
14             sub new {
15 1     1 0 573 my ($class, $api_key) = @_;
16              
17 1         6 my $self = {
18             api_key => $api_key,
19             ua => LWP::UserAgent->new,
20             };
21              
22 1         2465 return bless $self, $class;
23             }
24              
25             sub generate_text {
26 0     0 0   my ($self, $prompt) = @_;
27              
28             my $req = POST 'https://api.openai.com/v1/engines/davinci-codex/completions',
29             Content_Type => 'application/json',
30             Content => to_json({ prompt => $prompt, max_tokens => 100 }),
31 0           'Authorization' => 'Bearer ' . $self->{api_key};
32              
33 0           my $res = $self->{ua}->request($req);
34              
35 0 0         if ($res->is_success) {
36 0           my $data = from_json($res->decoded_content);
37 0           return $data->{choices}[0]{text};
38             }
39             else {
40 0           die $res->status_line;
41             }
42             }
43              
44             1;