Sending a Simple Message to OpenAI Using PHP

Sending a Simple Message to OpenAI

Welcome to the first lesson of our course on creating a chatbot with OpenAI. In this lesson, we will explore the basics of interacting with OpenAI's API, which is a powerful tool for building chatbots. OpenAI provides advanced language models that can understand and generate human-like text, making it an excellent choice for chatbot development. Our goal in this lesson is to send a simple message to OpenAI's language model and receive a response. This foundational step will set the stage for more complex interactions in future lessons.

Setting Up Your Environment

Before we can send a message to OpenAI, we need to set up our development environment. This involves installing the necessary tools and libraries. For this course, you will need the openai-php/client package, which allows us to interact with OpenAI's API.

To install this package, you can use the following command in your terminal with Composer:

composer require openai-php/client

In CodeSignal platform this library is pre-installed, so you can focus on writing and running your code without worrying about installation.

Setting the OpenAI API Key as an Environment Variable

In this course, you'll be using a coding environment where we've already set up everything you need to start working with OpenAI models. This means you don't need to worry about setting up an API key or configuring environment variables — it's all taken care of for you.

However, it's still useful to understand how this process works in case you want to set it up on your own computer in the future. To work with OpenAI models outside of a pre-configured environment, you need to set up a payment method and obtain an API key from their website. This API key is essential for accessing OpenAI's services and making requests to their API.

To keep your API key secure, you can use a .env file with a library like vlucas/phpdotenv. This file acts like a special note that your application can read to find out important details, such as your OpenAI API key, without having to write it directly in your code. This helps keep your key safe and secure.

Here's how you would set it up:

  1. Install vlucas/phpdotenv using Composer:

    composer require vlucas/phpdotenv
  2. Create a .env file in the root of your project and add your API key:

    OPENAI_API_KEY=your_api_key_here
  3. Load the environment variables in your PHP script:

    require 'vendor/autoload.php';
    
    $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
    $dotenv->load();

Initializing the OpenAI Client

Sending Your First Message to OpenAI

Understanding OpenAI Response Structure

When you send a request to OpenAI's API, it returns a structured JSON response. Understanding this structure is essential for extracting the information you need and for debugging your application. Let's examine a typical response:

{
    "id": "chatcmpl-12345",
    "object": "chat.completion",
    "created": 1677652284,
    "model": "gpt-4",
    "choices": [
        {
            "index": 0,
            "message": {
                "role": "assistant",
                "content": "Why don't scientists trust atoms? Because they make up everything!"
            },
            "finish_reason": "stop"
        }
    ],
    "usage": {
        "prompt_tokens": 10,
        "completion_tokens": 20,
        "total_tokens": 30
    }
}

The OpenAI API response contains several important fields:

  • choices: This array contains the AI's responses. For most simple requests, you'll only have one item in this array (at index 0).

  • message: Within each choice, this object holds the AI-generated message.

  • role: Indicates who sent the message. In responses, this will be "assistant" to show it's from the AI.

  • content: The actual text of the AI's response, which is what we extract in our code.

  • finish_reason: Explains why the response ended. A value of "stop" means the AI completed its reply naturally.

  • usage: This object tracks token consumption, which is important for monitoring API usage and costs.

    • prompt_tokens: Number of tokens used in your input message.

    • completion_tokens: Number of tokens in the AI's response.

    • total_tokens: The sum of prompt and completion tokens.

Understanding this structure helps you properly extract the AI's response and handle any potential errors or edge cases in your application.

Extracting and Displaying the AI's Reply

Minimal Error Handling for API Calls

Example: Full Code Implementation

Summary and Next Steps

In this lesson, we covered the essential steps to send a simple message to OpenAI's language model. We set up our environment, configured API access, and sent a message to receive a response. This foundational knowledge is crucial as we move forward in building more complex chatbot interactions.

As you proceed to the practice exercises, I encourage you to experiment with different prompts and explore the AI's responses. This hands-on practice will reinforce what you've learned and prepare you for the next unit, where we'll delve deeper into handling API parameters. Keep up the great work, and enjoy the journey of creating your chatbot with OpenAI!

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal