Created
July 12, 2024 14:19
-
-
Save ggorlen/96d4bc3050ed20e555cae92c1ea9245b to your computer and use it in GitHub Desktop.
OpenAI API request with PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function openAICompletion(array $messages): string { | |
$apiKey = 'OpenAI API key here'; | |
$url = 'https://api.openai.com/v1/chat/completions'; | |
$payload = [ | |
'messages' => $messages, | |
'model' => 'gpt-4o', | |
'temperature' => 0 | |
]; | |
$options = [ | |
'http' => [ | |
'header' => "Content-Type: application/json\r\n". | |
"Authorization: Bearer $apiKey\r\n", | |
'method' => 'POST', | |
'content' => json_encode($payload), | |
], | |
]; | |
$context = stream_context_create($options); | |
$use_include_path = false; | |
$json = @file_get_contents($url, $use_include_path, $context); | |
if (!$json) { | |
throw new Exception("Error making POST request"); | |
} | |
$data = json_decode($json, true); | |
if (isset($data['error'])) { | |
throw new Exception('Error from API: ' . $data['error']['message']); | |
} | |
return $data['choices'][0]['message']['content']; | |
} | |
$messages = [['role' => 'user', 'content' => 'ping']]; | |
var_export(openAICompletion($messages)); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment