The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

OpenAI::API::Request - Base module for making requests to the OpenAI API

SYNOPSIS

This module is a base module for making HTTP requests to the OpenAI API. It should not be used directly.

    package OpenAI::API::Request::NewRequest;
    use Moo;
    extends 'OpenAI::API::Request';

    sub endpoint {
        '/my_endpoint'
    }

    sub method {
        'POST'
    }

    # somewhere else...

    use OpenAI::API::Request::NewRequest;

    my $req = OpenAI::API::Request::NewRequest->new(...);

    my $res = $req->send();    # or: my $res = $req->send_async();

DESCRIPTION

This module provides a base class for creating request objects for the OpenAI API. It includes methods for sending synchronous and asynchronous requests, with support for HTTP GET and POST methods.

ATTRIBUTES

config

An instance of OpenAI::API::Config that provides configuration options for the OpenAI API client. Defaults to a new instance of OpenAI::API::Config.

user_agent

An instance of LWP::UserAgent that is used to make HTTP requests. Defaults to a new instance of LWP::UserAgent with a timeout set to the value of config->timeout.

event_loop

An instance of an event loop class, specified by config->event_loop_class option.

METHODS

endpoint

This method must be implemented by subclasses. It should return the API endpoint for the specific request.

method

This method must be implemented by subclasses. It should return the HTTP method for the specific request.

send(%args)

This method sends the request and returns the parsed response. If the 'http_response' key is present in the %args hash, it returns the raw HTTP::Response object instead of the parsed response.

    my $response = $request->send();

    my $response = $request->send( http_response => 1 );

send_async(%args)

This method sends the request asynchronously and returns a IO::Async::Future object. If the 'http_response' key is present in the %args hash, it resolves to the raw HTTP::Response object instead of the parsed response.

Here's an example usage:

    use IO::Async::Loop;

    my $loop = IO::Async::Loop->new();

    my $future = $request->send_async()->then(
        sub {
            my $content = shift;
            # ...
        }
    )->catch(
        sub {
            my $error = shift;
            # ...
        }
    );

    $loop->await($future);

    my $res = $future->get;

Note: if you want to use a different event loop, you must pass it via the config attribute.