Skip to content

Chat

LabsLLM allows you to maintain conversations with AI models through its chat interface. This enables more natural interactions where the model can remember previous messages in the conversation.

Continuing Conversations with Chat History

You can continue an existing conversation by providing a message history:

php
// Create or load an existing message history
$messages = MessagesBag::create([
    Message::user('Hello, how are you?'),
    Message::assistant('I\'m doing well! How can I help you today?')
]);

$execute = LabsLLM::text()
    ->using(new OpenAI('your-api-key', 'gpt-4o'))
    ->executeChat($messages); // Use executeChat instead of executePrompt

$response = $execute->getResponseData();

echo $response->response;

How Chat Works

Chat functionality in LabsLLM works by:

  1. Creating a MessagesBag object that contains the history of the conversation
  2. Using executeChat() instead of executePrompt() to send the entire history to the model
  3. Appending new messages to the history for future requests

This is particularly useful for applications like:

  • Chatbots that need to maintain context over multiple turns
  • Customer service applications where history is important
  • Interactive applications that require multi-step interactions

Working with Chat

php
// Using OpenAI for chat
$messages = MessagesBag::create([
    Message::assistant('I\'m doing well! How can I help you today?')
    Message::user('Tell me about quantum computing.')
]);

$execute = LabsLLM::text()
    ->using(new OpenAI('your-api-key', 'gpt-4o'))
    ->executeChat($messages);

$response = $execute->getResponseData();
echo $response->response;

// Continue the conversation
$messages = $execute->getMessagesBag();
$messages->add(Message::user('How is it different from classical computing?'));

$execute = LabsLLM::text()
    ->using(new OpenAI('your-api-key', 'gpt-4o'))
    ->executeChat($messages);

$response = $execute->getResponseData();
echo $response->response;

Understanding Chat Responses

Just like with prompt execution, when you call getResponseData() after a chat interaction, you receive a response object that contains:

php
$response = $execute->getResponseData();

// The model's text response
echo $response->response;

// Any tool calls that were made
if (!empty($response->function_calls)) {
    // Handle function calls
}

// Results of executed tools
if (!empty($response->called_tools)) {
    // Handle tool results
}

For a detailed explanation of the response structure, see the API Response Object guide.

Saving and Loading Conversation History

LabsLLM makes it easy to save conversation history for later use, allowing you to persist conversations across sessions or store them in a database.

Getting the MessageBag After Execution

After executing a chat, you can retrieve the updated MessageBag:

php
$execute = LabsLLM::text()
    ->using(new OpenAI('your-api-key', 'gpt-4o'))
    ->executeChat($messages);

// Get the response
$response = $execute->getResponseData();

// Get the updated MessageBag with all messages including the new response
$updatedMessageBag = $execute->getMessagesBag();

Persisting Conversations

You can serialize the MessageBag to JSON for storage:

php
// Convert MessageBag to JSON string
$jsonHistory = $updatedMessageBag->asJson();

// Store in database or file
file_put_contents('conversation_history.json', $jsonHistory);
// Or in a database
// $db->query("INSERT INTO conversations (user_id, history) VALUES (?, ?)", [$userId, $jsonHistory]);

Restoring Conversations

Later, you can restore the conversation from the saved JSON:

php
// Retrieve from file or database
$jsonHistory = file_get_contents('conversation_history.json');
// Or from database
// $jsonHistory = $db->query("SELECT history FROM conversations WHERE user_id = ?", [$userId])->fetchColumn();

// Create MessageBag from saved JSON
$messages = MessagesBag::createFromJson($jsonHistory);

// Continue the conversation
$messages->add(Message::user('Tell me more about quantum gates.'));

$execute = LabsLLM::text()
    ->using(new OpenAI('your-api-key', 'gpt-4o'))
    ->executeChat($messages);

$response = $execute->getResponseData();
echo $response->response;

This approach allows you to:

  • Persist conversations between user sessions
  • Store conversation history in databases, files, or caches
  • Implement features like conversation history browsing
  • Create multi-session chatbots that remember past interactions

TIP

See the MessageBag and Messages sections for more details on how to work with chat messages.

Released under the MIT License.