Created
March 30, 2023 12:20
-
-
Save bwente/a69c3987804e712b123cc8dd39cd61da to your computer and use it in GitHub Desktop.
SummaryAI Plugin for MODX (uses OpenAi API)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$model = $modx->getOption('model', $scriptProperties); | |
$prompt = $modx->getOption('prompt', $scriptProperties); | |
$api_url = $modx->getOption('api_url', $scriptProperties); | |
$api_key = $modx->getOption('api_key', $scriptProperties); | |
switch($modx->event->name) { | |
case 'OnDocFormSave': | |
// Check if the resource has a summary | |
if (!$resource->get('introtext')) { | |
// Get the content of the resource | |
$content = $resource->get('content'); | |
// Strip HTML tags | |
$content = strip_tags($content); | |
// Grab first 1500 words | |
$words = explode(" ", $content); | |
$truncated = implode(" ", array_slice($words, 0, 1500)); | |
$stripped = preg_replace('/\s+/', ' ', $truncated); | |
$contentQuery = $prompt . " " . $stripped; | |
// Set up the Chat-GPT API request | |
$headers = array( | |
'Content-Type: application/json', | |
'Authorization: Bearer ' . $api_key | |
); | |
$data = array( | |
'model' => $model, | |
'prompt' => $contentQuery, | |
'max_tokens' => 200, | |
'temperature' => 0.5, | |
'n' => 1 | |
); | |
// Send the Chat-GPT API request | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $api_url); | |
curl_setopt($ch, CURLOPT_POST, 1); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
$response = curl_exec($ch); | |
curl_close($ch); | |
// Extract the summary from the Chat-GPT API response | |
$response_data = json_decode($response, true); | |
$summary = $response_data['choices'][0]['text']; | |
// Update the resource with the summary | |
$resource->set('introtext', trim($summary)); | |
$resource->save(); | |
$modx->log(MODX_LOG_LEVEL_INFO, print_r($response_data,true) ); | |
break; | |
} | |
} |
I am out of credits. But it should work, does it the api call work using curl manually?
I don't know. But my grant expired, too. Maybe because of that?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've done it all. It doesn't work. No errors 🤷♂️