Here's how to use OpenAI API without the Composer PHP client. Perfect for small projects!
I just find the composer thing super annoying to use, especially on shared hosting. Also, ChatGPT has a really nasty habit of using old functions and omitting the part where you really get the AI-generated content back (when designing a function like this). Rather, it usually returns the complete JSON array including ten or more quite pointless elements.
Nothing wrong with the Github client... at https://github.com/openai-php/client
But here's a faster way.
Call
I just find the composer thing super annoying to use, especially on shared hosting. Also, ChatGPT has a really nasty habit of using old functions and omitting the part where you really get the AI-generated content back (when designing a function like this). Rather, it usually returns the complete JSON array including ten or more quite pointless elements.
Nothing wrong with the Github client... at https://github.com/openai-php/client
But here's a faster way.
PHP:
$oaiKey = "Your key";
function queryOpenAI($systemPrompt, $assistantPrompt, $model = 'gpt-4o', $temp = 1.2, $tokens = 0, $topP = 1, $freqPenalty = 0.4, $presencePenalty = 0.2) {
global $oaiKey;
$url = 'https://api.openai.com/v1/chat/completions';
$postData = [
'model' => $model,
'messages' => [
[
'role' => 'system',
'content' => $systemPrompt
],
[
'role' => 'assistant',
'content' => $assistantPrompt
]
],
'temperature' => $temp,
'top_p' => $topP,
'frequency_penalty' => $freqPenalty,
'presence_penalty' => $presencePenalty,
];
if (!empty($tokens)) {
$postData['max_tokens'] = $tokens;
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"Authorization: Bearer {$oaiKey}",
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
$response = curl_exec($ch);
if (curl_errno($ch)) {
$error_msg = curl_error($ch);
curl_close($ch);
echo "cURL Error queryOpenAI: $error_msg <br/> SystemPrompt: $systemPrompt <br/> AssistantPrompt: $assistantPrompt";
exit();
}
curl_close($ch);
$decodedResponse = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return ['error' => 'Failed to decode JSON'];
}
if (isset($decodedResponse['error'])) {
echo "OpenAI API Error queryOpenAI: " . $decodedResponse['error']['message'] . "<br/> SystemPrompt: $systemPrompt <br/> AssistantPrompt: $assistantPrompt";
exit();
}
return $decodedResponse['choices'][0]['message']['content'];
}
Call
PHP:
$systemPrompt = "You are a helpful assistant.";
$assistantPrompt = "Generate a summary for this topic: 'OpenAI API usage in PHP'.";
$response = queryOpenAI($systemPrompt, $assistantPrompt, 'chatgpt-4o-latest', 1.0, 200, 1, 0.5, 0.2);
echo $response;
Last edited: