Skip to content

Instantly share code, notes, and snippets.

@FCO
Created April 1, 2023 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FCO/def7e030c05d7285d210aac4b8fce0e4 to your computer and use it in GitHub Desktop.
Save FCO/def7e030c05d7285d210aac4b8fce0e4 to your computer and use it in GitHub Desktop.
use Cro::HTTP::Client;
use Red;
model ChatGPTConversation {
has Int $.id is serial;
has Str $.question is column;
has Str $.answer is column;
}
sub chat_with_gpt($prompt) {
my $base-url = "https://api.openai.com/v1/engines/davinci-codex/completions";
my $headers = {'Authorization' => "Bearer YOUR_API_KEY_HERE",
'Content-Type' => 'application/json'};
my $payload = {'prompt' => $prompt, 'temperature' => 0.5, 'max_tokens' => 50};
my $response = await Cro::HTTP::Client.post($base-url, headers => $headers, json => $payload);
if $response.status == 200 {
my $json = from-json($response.body);
my $answer = $json<choices>[0]<text>;
my $conversation = ChatGPTConversation.^create(question => $prompt, answer => $answer);
return $answer;
} else {
die "Failed to communicate with GPT: {$response.status} {$response.reason-phrase}"
}
}
# Example usage:
say chat_with_gpt("Hello, can you help me write a ChatGPT client in Raku?");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment