Home > Enterprise >  PHP CURL Open Ai Remove The Quotes From Post Data
PHP CURL Open Ai Remove The Quotes From Post Data

Time:01-14

Below is my PHP Curl script that works to post to Open AI, this is all working as it should.

I want to be able to set the values from posted data like this.

 $getOpenAITemperature = $_POST[OpenAITemperature]; 
 $getmaxtokens = $_POST[OpenAIMaximumLength]; 
 $getTopp = $_POST[OpenAITopP];`

But when I do it added quotes to the posted values and it stops working.

Like this.

 $postData = [
  'model' => $getOpenAIModel,
  'prompt' => $getRequest,
  'temperature' => "0.24",
  'max_tokens => "250",
  'top_p' => "1",

But it needs to look like this to work.

 $postData = [
   'model' => $getOpenAIModel,
   'prompt' => $getRequest,
   'temperature' => 0.24,
   'max_tokens => 250,
   'top_p' => 1,

How can I remove the quotes around the numbers ? The quotes around the model and prompt are fine its just the numbers.

*** The script below here works fine ***

  $getOpenAITemperature = 0.5;
  $getmax_tokens = 250;
  $gettop_p = 1;


  $OPENAI_API_KEY = "sk-123";
  $getOpenAIModel = "text-davinci-003";
  $getRequest "My Question";
  $ch = curl_init();
  $headers  = [
        'Accept: application/json',
        'Content-Type: application/json',
        'Authorization: Bearer '.$OPENAI_API_KEY.''
    ];
 $postData = [
   'model' => $getOpenAIModel,
   'prompt' => $getRequest,
   'temperature' => $getOpenAITemperature,
   'max_tokens' => $getTopp,
   'top_p' => $getmaxtokens,
   'best_of' => 2,
   'frequency_penalty' => 0.0,
   'presence_penalty' => 0.0,
    'stop' => '["\n"]',
  ];

  curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/completions');
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData)); 

  $result = curl_exec($ch);`

I have tried a number of things like php trim() and str_replace but nothing worked.

CodePudding user response:

You can cast the strings to an int or a float like so:

$postData['temperature'] = (float) $postData['temperature'];
$postData['max_tokens'] = (int) $postData['max_tokens'];

Check the PHP docs for type casting https://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting

  • Related