Skip to content

Instantly share code, notes, and snippets.

@kirilkirkov
Last active February 21, 2023 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirilkirkov/32d156040667ef2a6fce1841df9b2ce3 to your computer and use it in GitHub Desktop.
Save kirilkirkov/32d156040667ef2a6fce1841df9b2ce3 to your computer and use it in GitHub Desktop.
Access ChatGPT through PHP Using Curl Api. Easy Use of GPT3 API with Curl
<?php
define("CHATGPT_API_KEY", "your-key-goes-here");
$data = array(
"model" => "text-davinci-003",
"prompt" => "What is PHP and how it works?", // Your question or request
"temperature" => 0.5,
"max_tokens" => 500
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer ' . CHATGPT_API_KEY;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
echo $response;
@kirilkirkov
Copy link
Author

Raw CURL query:

curl https://api.openai.com/v1/completions \
  -H 'Content-Type: application/json' \
  -H "Authorization: Bearer [Your API Key]" \
  -d '{
  "model": "text-davinci-003",
  "prompt": "What is your name?",
  "max_tokens": 4000,
  "temperature": 1.0
}' \
--insecure

@kirilkirkov
Copy link
Author

Expected json result after php GPT3 request:

{
   "id":"cmpl-6manA3iq6iqoan2j3nGnanYXBFugmwulXm",
   "object":"text_completion",
   "created":1676998066,
   "model":"davinci-codex",
   "choices":[
      {
         "text":"reposnse text",
         "index":0,
         "logprobs":null,
         "finish_reason":"length"
      }
   ],
   "usage":{
      "prompt_tokens":7,
      "completion_tokens":500,
      "total_tokens":507
   }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment