Home  >  Article  >  Backend Development  >  ChatGPT PHP development practice: creating intelligent marketing chat assistant function

ChatGPT PHP development practice: creating intelligent marketing chat assistant function

PHPz
PHPzOriginal
2023-10-27 18:02:031085browse

ChatGPT PHP开发实践:打造智能营销聊天助手功能

ChatGPT PHP development practice: creating intelligent marketing chat assistant function

In today's digital business environment, providing customer satisfaction service experience has become one of the key factors for enterprise competition. one. With the continuous development of artificial intelligence technology, intelligent chat assistants are playing an increasingly important role in enhancing customer communication and improving sales performance. This article will introduce how to use PHP and OpenAI's ChatGPT API to develop intelligent marketing chat assistant functions, and provide specific code examples.

  1. Preparation
    Before starting development, you need to meet the following requirements:
  2. An OpenAI account and API key. For details, please refer to the OpenAI official documentation;
  3. Server environment for PHP 7.4 and above;
  4. Planned chat scenarios and question collections.
  5. Install the OpenAI API client library
    First, use Composer to install the OpenAI API client library in your PHP project. Create a composer.json file in the project root directory and add the following content:
{
  "require": {
    "openai/api": "0.2.*"
  }
}

Then, run the composer install command in the terminal to install the library.

  1. Writing PHP Code
    Create a file named ChatGPT.php and write the following code:
<?php

use OpenAIApiDefaultApi;
use OpenAIConfiguration;
use OpenAIModelChatCompletionRequest;
use OpenAIModelChatCompletionResponse;

class ChatGPT {
  private DefaultApi $api;

  public function __construct(string $apiKey) {
    $config = Configuration::getDefaultConfiguration()->setApiKey('Authorization', 'Bearer ' . $apiKey);
    $this->api = new DefaultApi($config);
  }

  public function generateResponse(string $message): string {
    $request = new ChatCompletionRequest([
      'messages' => [['role' => 'system', 'content' => 'You are a helpful assistant.']],
      'messages' => [['role' => 'user', 'content' => $message]],
      'model' => 'gpt-3.5-turbo',
      'maxTokens' => 100,
      'temperature' => 0.6,
      'n' => 1,
      'stop' => ['
']
    ]);

    $response = $this->api->createCompletion($request);
    $choices = $response->getChoices();
    if (!empty($choices)) {
      /** @var ChatCompletionResponse $choice */
      $choice = $choices[0];
      $responseMessage = $choice->getMessages()[0]['content'];
      return $responseMessage;
    }

    return '';
  }
}

In this code , we first initialize the client library using the OpenAI API key. Then, we define a generateResponse method that receives the message from the user and uses the ChatGPT API to generate and return a smart reply.

  1. Using ChatGPT
    In your PHP project, use the following code to initialize ChatGPT and handle user requests:
<?php

require 'ChatGPT.php';

$apiKey = 'YOUR_OPENAI_API_KEY'; // 替换为您的OpenAI API密钥
$chatBot = new ChatGPT($apiKey);

// 处理用户请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $message = $_POST['message'];

  $response = $chatBot->generateResponse($message);

  // 返回JSON响应
  header('Content-Type: application/json');
  echo json_encode(['response' => $response]);
}

The above code initializes ChatGPT and handles user requests when receiving When the POST request is made, the user's message is read and a reply is generated using ChatGPT, and finally the reply is returned to the client in JSON format.

  1. Front-end integration
    In order to interact with users in real time, you can use HTML and JavaScript to integrate the front-end interface. Create a file named index.html and add the following content:
<!DOCTYPE html>
<html>
<head>
  <title>ChatGPT</title>
</head>
<body>
  <h1>ChatGPT - 智能营销聊天助手</h1>
  <div id="chat">
    <div id="messages"></div>
    <div id="input-container">
      <input type="text" id="input" placeholder="请输入消息..." autocomplete="off">
      <button id="send">发送</button>
    </div>
  </div>

  <script>
    const messagesContainer = document.getElementById('messages');
    const input = document.getElementById('input');
    const sendButton = document.getElementById('send');

    sendButton.addEventListener('click', () => sendMessage());
    input.addEventListener('keydown', (event) => {
      if (event.key === 'Enter') {
        sendMessage();
      }
    });

    function sendMessage() {
      const message = input.value.trim();
      if (message.length === 0) {
        return;
      }

      addMessage(message, 'user');
      input.value = '';

      fetch('/chat.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `message=${encodeURIComponent(message)}`
      })
        .then(response => response.json())
        .then(data => handleResponse(data.response))
        .catch(error => console.error(error));
    }

    function addMessage(content, role) {
      const messageContainer = document.createElement('div');
      messageContainer.className = `message ${role}`;
      messageContainer.textContent = content;
      messagesContainer.appendChild(messageContainer);
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    function handleResponse(response) {
      addMessage(response, 'bot');
    }
  </script>
</body>
</html>

The above code creates a simple chat interface where users can enter messages in the input box, and click the send button. Send user messages to the PHP server through JavaScript, then receive the reply returned by the server and display it on the interface.

  1. Run the Application
    Deploy your PHP files and front-end files to your PHP server. Make sure the server supports PHP and has the required extensions and dependencies installed.

Access the deployed application and you can interact with the intelligent marketing chat assistant in real time!

Conclusion
This article introduces how to use PHP and OpenAI’s ChatGPT API to develop intelligent marketing chat assistant functions. By leveraging ChatGPT, you can provide more intelligent and personalized services, improving customer satisfaction and sales performance. The above code examples are for reference only and can be customized and extended according to actual needs.

I hope this article will be helpful to you in developing intelligent chat assistants!

The above is the detailed content of ChatGPT PHP development practice: creating intelligent marketing chat assistant function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn