I am creating a PHP script to access Open Ai’s API, to ask a query and get a response.
I am getting the following error:
You didn’t provide an API key. You need to provide your API key in an
Authorization header using Bearer auth (i.e. Authorization: Bearer
YOUR_KEY)
…but I thought I was providing the API key in the first variable?
Here is my code:
$api_key = "sk-U3B.........7MiL";
$query = "How are you?";
$url = "https://api.openai.com/v1/engines/davinci/jobs";
// Set up the API request headers
$headers = array(
"Content-Type: application/json",
"Authorization: Bearer " . $api_key
);
// Set up the API request body
$data = array(
"prompt" => $query,
"max_tokens" => 100,
"temperature" => 0.5
);
// Use WordPress's built-in HTTP API to send the API request
$response = wp_remote_post( $url, array(
'headers' => $headers,
'body' => json_encode( $data )
) );
// Check if the API request was successful
if ( is_wp_error( $response ) ) {
// If the API request failed, display an error message
echo "Error communicating with OpenAI API: " . $response->get_error_message();
} else {
// If the API request was successful, extract the response text
$response_body = json_decode( $response['body'] );
//$response_text = $response_body->choices[0]->text;
var_dump($response_body);
// Display the response text on the web page
echo $response_body;
2
Answers
All Engines endpoints are deprecated.
This is the correct Completions endpoint:
Working example
If you run
test.php
the OpenAI API will return the following completion:test.php
I’ve seen reports that you can’t use your free credits until you put a credit card on file. Idk if that’s true, but I had a very similar issue until I added mine.