Azure GPT-4 API using PHP

290 views Asked by At

Using curl I can make a successful connection, which returns a completion:

curl "https://myazure.openai.azure.com/openai/deployments/azureGPT4/chat/completions?api-version=2023-07-01-preview" \
  -H "Content-Type: application/json" \
  -H "api-key: myapikey" \
  -d '{"messages":[{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello"}]}'

But when attempting to do the same using this PHP script

$api_url = "https://myazure.openai.azure.com/openai/deployments/azureGPT4/chat/completions?api-version=2023-07-01-preview";

$api_key = "myapikey";

$request_data = array(
    'engine' => 'azureGPT4',
    'messages' => [
        ["role" => "system", "content" => "You are a helpful assistant."],
        ["role" => "user", "content" => "Hello"]
    ]
);

$request_json = json_encode($request_data);

$ch = curl_init($api_url);
curl_setopt($ch, CURLOPT_VERBOSE, true); 
curl_setopt($ch, CURLOPT_STDERR, fopen('php://stderr', 'w')); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Ocp-Apim-Subscription-Key: ' . $api_key, 
));

$response = curl_exec($ch);

I get this error:

Error: Access denied due to invalid subscription key or wrong API endpoint. Make sure to provide a valid key for an active subscription and use a correct regional API endpoint for your resource.

1

There are 1 answers

0
haz On

This worked:

  1. remove engine parameter
    $request_data = array(
        //'engine' => 'azureGPT4',
        'messages' => [
            ["role" => "system", "content" => "You are a helpful assistant."],
            ["role" => "user", "content" => "Hello"]
        ]
    );
  1. use "api-key" instead of "Ocp-Apim-Subscription-Key"
       'Content-Type: application/json',
        'api-key: ' . $api_key,