Log in Register
Home Search Categories About
Bilel T
read article

Building a Chatbot with ChatGPT API and PHP

Chatgpt api

Chatbots have become an integral part of modern web applications, enhancing user interaction and providing instant assistance. In this tutorial, we'll explore how to create a simple chatbot using the ChatGPT API and PHP. The ChatGPT API allows developers to integrate OpenAI's powerful language model into their applications, enabling natural language conversations.

Prerequisites

Before we begin, ensure you have the following:

  1. OpenAI API Key: Obtain your API key by signing up on the OpenAI platform.
  2. PHP installed on your server.

Step 1: Set Up Your Project

Create a new directory for your project and navigate to it using the terminal.

mkdir chatbot_project
cd chatbot_project

Step 2: Install GuzzleHTTP Library

We'll use GuzzleHTTP to make HTTP requests to the ChatGPT API. Install it using Composer:

composer require guzzlehttp/guzzle

Step 3: Get Your API Key

Visit the OpenAI platform, create an account, and obtain your API key. Keep it secure, as it will be used to authenticate requests to the ChatGPT API.

Step 4: Create a PHP Script

Create a new PHP file, e.g., `chatbot.php`, and open it in your preferred code editor.

<?php
require 'vendor/autoload.php';

$apiKey = 'your_api_key_here'; // Replace with your actual API key
$endpoint = 'https://api.openai.com/v1/engines/davinci-codex/completions';

// User input
$userInput = $_GET['message'];

// Request to ChatGPT API
$client = new GuzzleHttp\Client();

$response = $client->post($endpoint, [
    'headers' => [
        'Authorization' => 'Bearer ' . $apiKey,
        'Content-Type' => 'application/json',
    ],
    'json' => [
        'prompt' => $userInput,
        'max_tokens' => 150, // Adjust as needed
    ],
]);

// Extract and output the chatbot's response
$data = json_decode($response->getBody(), true);

$botResponse = $data['choices'][0]['text'];

echo $botResponse;
?>

Step 5: Test Your Chatbot

Run a local PHP server: 

php -S localhost:8000

Visit http://localhost:8000/chatbot.php?message=Hello in your browser, replacing "Hello" with your desired input. You should receive a response from the ChatGPT API.

Conclusion

Congratulations! You've successfully created a basic chatbot using the ChatGPT API and PHP. This example provides a foundation that you can expand upon to integrate the chatbot into your web applications and improve user engagement. Experiment with different prompts and customize the code to suit your specific requirements. Happy coding!