How to use OpenAI API without Composer (PHP) to generate text

Perry

Administrator
Staff member
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.

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:
To effectively modify the queryOpenAI function in the future, it's essential to understand its key components and how they interact with the OpenAI API. Here's a detailed breakdown:

  1. Function Parameters:
    • $systemPrompt and $assistantPrompt: Define the context and initial message for the AI model.
    • $model: Specifies the AI model to use (e.g., chatgpt-4o-latest). See updated list here: https://platform.openai.com/docs/models#current-model-aliases
    • $temp, $topP, $freqPenalty, $presencePenalty: Control the randomness and creativity of the AI's responses.
    • $tokens: Sets the maximum number of tokens in the response.
  2. Global API Key:
    • global $oaiKey;: Retrieves the OpenAI API key stored globally.
  3. API Endpoint:
  4. Payload Construction:
    • The $postData array is structured to include the model, messages, and various parameters that influence the AI's output.
    • Messages are formatted with roles ('system' and 'assistant') to guide the AI's behavior.
  5. cURL Configuration:
    • Initializes a cURL session and sets options for the POST request, including headers and the JSON-encoded payload.
  6. Error Handling:
    • Checks for cURL execution errors and JSON decoding issues, providing informative messages for troubleshooting.
  7. Response Processing:
    • Decodes the JSON response and extracts the AI's message content for use.
Considerations for Future Modifications:

  • Adding New Parameters:
    • To introduce additional parameters (e.g., logit_bias), include them in the function's parameters list and append them to the $postData array as needed.
  • Changing API Endpoints:
    • If OpenAI updates their API endpoints, update the $url variable accordingly.
  • Model Updates:
    • As new models become available, adjust the $model parameter to utilize them.
  • Enhanced Error Handling:
    • Implement more robust error handling to manage different types of API errors or network issues gracefully.
  • Security Enhancements:
    • Ensure the API key ($oaiKey) is securely stored and accessed, possibly using environment variables or secure vaults.
By understanding these components and considerations, you can confidently modify the queryOpenAI function to accommodate future requirements or API changes.


Usage Example:

PHP:
$systemPrompt = "You are a witty assistant with a knack for humor.";
$assistantPrompt = "Summarize the following in a humorous limerick: 'The complexities of OpenAI API usage in PHP'.";
$response = queryOpenAI($systemPrompt, $assistantPrompt, 'chatgpt-4o-latest', 1.0, 200, 1, 0.5, 0.2);

echo $response;
 
Last edited by a moderator:
To obtain an OpenAI API key for accessing the API, follow these steps:
  1. Sign Up or Log In:
    • Visit OpenAI's platform.
    • If you don't have an account, click "Sign Up" to create one.
    • If you have an account, click "Log In" and enter your credentials.
  2. Access API Keys:
    • After logging in, click on your profile icon in the top-right corner.
    • Select "View API keys" from the dropdown menu.
  3. Generate a New API Key:
    • Click the "Create new secret key" button.
    • Your new API key will appear.
    • Important: Copy and store this key securely; you won't be able to view it again once you leave the page.
  4. Set Up Billing Information:
    • Navigate to the "Billing" section in the left-hand menu.
    • Add a payment method to activate your API key.
  5. Implement the API Key in Your Application:
    • Use the API key in your application's code to authenticate requests to OpenAI's APIs.
    • Ensure you keep the key confidential to prevent unauthorized access.
For detailed information, refer to OpenAI's Quickstart Guide.
 
Back
Top