Welcome back! In the previous lessons, you learned how to send a simple message to OpenAI's language model and explored various model parameters to customize the AI's responses. Now, we will delve into the concept of message types and the importance of maintaining conversation history. These elements are crucial for creating dynamic and context-aware interactions with the AI, allowing your chatbot to engage in more meaningful conversations.
Before we dive into building and managing conversation history, it’s important to understand the concept of message types and how a conversation history is structured. In a chatbot interaction, messages are typically categorized by roles officially recognized by OpenAI: "system", "user", and "assistant". While we’ll explore system prompts more thoroughly in a later lesson, remember that these primary roles help define the flow of dialogue and ensure the AI understands who is speaking at any given time. You can technically specify other roles, but doing so may produce unpredictable results because they are not officially supported by OpenAI’s chat completion API.
OpenAI expects the conversation history to be formatted as an array of associative arrays, where each associative array represents a message with two key-value pairs: "role"
and "content"
. Here’s an example of what a simple conversation history might look like:
php1[ 2 ["role" => "user", "content" => "Can you recommend a good book?"], 3 ["role" => "assistant", "content" => "I recommend 'To Kill a Mockingbird' by Harper Lee."], 4 ["role" => "user", "content" => "What's it about?"], 5 ["role" => "assistant", "content" => "It's a novel about racial injustice and moral growth in the American South."] 6]
In this example, the conversation history consists of alternating messages between the user (the person interacting with the AI) and the assistant (the AI itself). Each message is stored with its respective role, providing context for the AI to generate appropriate responses. Understanding this structure is key to effectively managing conversations and ensuring that the AI can engage in more meaningful interactions.
To manage conversations effectively, we will create a function called sendMessage
. This function will send messages to the AI and receive responses, allowing us to handle multiple interactions seamlessly. Here's how the function is structured using PHP and the OpenAI SDK:
php1require 'vendor/autoload.php'; 2 3use Dotenv\Dotenv; 4 5// Load environment variables 6$dotenv = Dotenv::createImmutable(__DIR__); 7$dotenv->load(); 8 9// Fetch API Key 10$apiKey = $_ENV['OPENAI_API_KEY'] ?? getenv('OPENAI_API_KEY'); 11$baseUrl = $_ENV['OPENAI_BASE_URI'] ?? getenv('OPENAI_BASE_URI'); 12 13$client = \OpenAI::factory() 14 ->withApiKey($apiKey) 15 ->withBaseUri($baseUrl) 16 ->make(); 17 18// Function to send a message and receive a response 19function sendMessage($client, $messages) { 20 $response = $client->chat()->create([ 21 'model' => 'gpt-4', 22 'messages' => $messages 23 ]); 24 25 return trim($response['choices'][0]['message']['content']); 26}
The messages
parameter contains the conversation history, which provides context for the AI's response. The function returns the AI's response, which is extracted from the API result and stripped of any leading or trailing whitespace.
Maintaining a conversation history is crucial for providing context to the AI. This allows the AI to generate responses that are relevant to the ongoing dialogue. Let's see how we can build and manage conversation history using PHP:
php1// Start a conversation history with an initial message 2$conversation = [ 3 ["role" => "user", "content" => "What's the capital of France?"] 4]; 5 6// Get first response 7$reply = sendMessage($client, $conversation); 8echo "Assistant: " . $reply . "\n";
After sending the initial message, the AI responds with the capital of France, showcasing its ability to provide factual information:
Plain text1Assistant: The capital of France is Paris.
To maintain a conversation where the AI remembers previous messages, we append responses to the conversation history before sending the next request.
php1// Add the assistant's response to conversation history 2$conversation[] = ["role" => "assistant", "content" => $reply]; 3 4// Add a follow-up question 5$conversation[] = ["role" => "user", "content" => "Is it a large city?"]; 6 7// Get response with conversation context 8$followUpReply = sendMessage($client, $conversation); 9echo "Assistant follow-up: " . $followUpReply . "\n"; 10 11// Add assistant's follow-up response to history 12$conversation[] = ["role" => "assistant", "content" => $followUpReply];
With the conversation history maintained, the AI provides a contextually relevant follow-up response, confirming the size of the city:
Plain text1Assistant follow-up: Yes, Paris is a large city.
By maintaining this history, we provide context for subsequent interactions, allowing the AI to generate more coherent and relevant responses.
To better understand how the conversation has evolved, we can print the entire conversation history using PHP:
php1// Print the entire conversation history 2foreach ($conversation as $message) { 3 echo ucfirst($message['role']) . ": " . $message['content'] . "\n"; 4}
This will output the complete dialogue, showing both user inputs and AI responses:
Plain text1User: What's the capital of France? 2Assistant: The capital of France is Paris. 3User: Is it a large city? 4Assistant: Yes, Paris is a large city.
Having access to the conversation history allows you to track the flow of dialogue and ensure that the AI's responses remain contextually relevant.
In this lesson, you learned about message types and the importance of maintaining conversation history in chatbot interactions. We explored how to set up your environment, initialize the OpenAI client, and create a function to handle conversations. You also saw how to build and manage conversation history, enabling the AI to generate contextually relevant responses.
As you move on to the practice exercises, I encourage you to experiment with different conversation scenarios and observe how the AI's responses change based on the context provided. This hands-on practice will reinforce what you've learned and prepare you for the next unit, where we'll continue to build on these concepts. Keep up the great work, and enjoy the journey of creating your chatbot with OpenAI!