In this code, we return the token totals for the model API call along with the response
/**
* solrai_generateResponseOpenAI ($systemMessage, $text)
*
* Generate a response to $text using API call to
* OpenAI model $model using $systemMessage
* We can also set the $temperature
*
*/
public function solrai_generateResponseOpenAI($systemMessage, $text, $model, $temperature) {
// Define the OpenAI API endpoint and parameters
$url = $this->urlOpenAI;
// Initialize the $messages array with the system message
$message = array(
array("role" => "system", "content" => $systemMessage)
);
// Define the new user message
$userMessage = array("role" => "user", "content" => $text);
// Append the new user message to the end of the $messages array
$message[] = $userMessage;
// Define the data for the API request
$data = array(
'messages' => $message, // No need to wrap $message in an array if it is set as array above
'model' => $model,
'temperature' => $temperature
);
// Define the request headers and data
$headers = [
'Authorization: Bearer ' . $this->apiOpenAI,
'Content-Type: application/json'
];
// Call the GPT API
$responseBody = $this->solrai_executeCurlRequest($url, $headers, $data);
$apiElapsedTime = $this->getElapsedTime();
// Logging
$logger = \Drupal::logger('solrai');
# Debug
# Log the response body
# $logger->notice('(generateResponseOpenAI) Response: @response', ['@response' => print_r($responseBody, TRUE)]);
// Initialize $prompt_tokens and $total_tokens;
$id = '';
$prompt_tokens = 0;
$total_tokens = 0;
// Initialize the $generated_text variable
$generated_text = '';
// Check if the response contains an error
if (isset($responseBody['error'])) {
// Extract the error message from the response
$error_message = $responseBody['error']['message'];
// Assign the error message to $generated_text
$generated_text = "Error occurred (solrai_generateResponseOpenAI): {$error_message}";
} else {
// No error occured, get usage info.
// Check if 'usage' exists in the response body
if (isset($responseBody['usage'])) {
$usage = $responseBody['usage'];
if (isset($usage['prompt_tokens'])) {
$prompt_tokens = $usage['prompt_tokens'];
}
if (isset($usage['total_tokens'])) {
$total_tokens = $usage['total_tokens'];
}
}
// No error occurred, proceed with normal response processing
if (isset($responseBody['choices'][0]['message']['content'])) {
// No error occurred, proceed with normal response processing
$generated_text = $responseBody['choices'][0]['message']['content'];
} else {
// Set to an empty string if "choices" key doesn't exist
$generated_text = '';
}
}
// Return the generated text and prompt tokens
return [
'generated_text' => $generated_text,
'prompt_tokens' => $prompt_tokens,
'total_tokens' => $total_tokens,
'apiElapsedTime' => $apiElapsedTime
];
}
Here you see the calling method grabs the token totals from the response
Here we also add them to the running total for this sequence of API calls
$response = $this->solraiService->solrai_generateSQL($systemMessage, $sql);
# Debug
# $logger->notice('Second generateSQL call response: @response', ['@response' => print_r($response, TRUE)]);
$sql = $response['generated_text'];
$total_tokens = $total_tokens + $response['total_tokens'];
$apiElapsedTime = $apiElapsedTime + $response['apiElapsedTime'];
Finally, we write the log. Badda-bing, badda-boom. It’s done.
$logUser = $username;
$now = new \DateTime();
// Format the date and time
$logDate = $now->format('Y-m-d\TH:i:s');
$logIp = \Drupal::request()->getClientIp();
$logType = 'sql';
$logSolrId = 'n/a';
$logNid = 0;
$logModel = $modelSql;
$logTime = $apiElapsedTime;
$logTokens = $total_tokens;
$logDesc = $question;
$logSource = 'site';
if ($success === 'Y') {
$logRank = 10;
} else {
$logRank = 0;
}
$this->solraiService->solrai_logEvent($logUser, $logIp, $logDate, $logType, $logSolrId, $logNid, $logModel, $logTokens, $logDesc, $logTime, $logNotes = '', $logEmail = '', $logSource, $logUrls = '', $logRank);