Skip to content

Instantly share code, notes, and snippets.

@ggorlen
Created July 12, 2024 14:19
Show Gist options
  • Save ggorlen/96d4bc3050ed20e555cae92c1ea9245b to your computer and use it in GitHub Desktop.
Save ggorlen/96d4bc3050ed20e555cae92c1ea9245b to your computer and use it in GitHub Desktop.
OpenAI API request with PHP
<?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