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 library, which allows us to interact with OpenAI's API.

To install this library, you can use the following command in your terminal:

composer require openai-php/client

If you are following the course on CodeSignal, the library is already 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 server 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 or server configuration. Here's how you can do it using a .env file:

  1. Create a file named .env in the root of your project.

  2. Add the following line to the .env file:

    OPENAI_API_KEY=your_api_key_here
  3. Use a library like vlucas/phpdotenv to load the environment variables in your PHP script:

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

This approach helps keep your key safe and secure.

Initializing the OpenAI Client
Sending Your First Message to OpenAI
Understanding OpenAI Response

When you send a request to OpenAI's API, it returns a structured JSON response. Below is an example:

{
    "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
    }
}
Key Fields
  1. choices: Contains the AI's response.

    • message: Holds the AI-generated message.
      • role: Indicates the sender (assistant).
      • content: The AI's response text.
    • finish_reason: Explains why the response ended (e.g., stop means the AI completed its reply naturally).
  2. usage: Tracks token consumption.

    • prompt_tokens: Number of tokens used in the input message.
    • completion_tokens: Number of tokens in the AI's response.
    • total_tokens: Sum of both, useful for monitoring API usage and costs.
Extracting and Displaying the AI's Reply
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