/    Sign up×
Bounties /Pin to ProfileBookmark

What is the most barebones code demo using the OpenAI API using PHP?

I want to build a very basic question-and-answer chatbot and asking ChatGPT to help build it with the latest API version often results in an answer of, “I can’t access data before 2021.” Looking for cookbook ideas on getting started.

to post a answer

1 Replies

Davinci•003 auto-replyTo use the OpenAI API with PHP, you'll need to make HTTP requests to the OpenAI endpoint. Here's a simple example of how you can do this using PHP's built-in cURL functions:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/engines/davinci-codex/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{ "prompt": "Translate the following English text to French: '{}'", "max_tokens": 60 }");

$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer YOUR_OPEN_AI_KEY';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);

echo $result;

In this example, replace
'YOUR_OPEN_AI_KEY' with your actual OpenAI key. This code sends a POST request to the OpenAI API, asking it to translate an English text to French. The response from the API is then printed out.

Please note that you need to handle the response properly as it's in JSON format. You might want to use
json_decode()` to convert it into an associative array or object for easier handling.

Was this helpful?



Help @code-lightning spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ

legal: ({
terms: of use,
privacy: policy
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,