‘POST’,
‘callback’ => ‘amom_ai_chat_handler’,
‘permission_callback’ => ‘__return_true’,
]);
register_rest_route(‘amom/v1’, ‘/firecrawl’, [
‘methods’ => ‘POST’,
‘callback’ => ‘amom_store_firecrawl_data’,
‘permission_callback’ => ‘__return_true’,
]);
});
function amom_store_firecrawl_data($request) {
$content = wp_strip_all_tags($request->get_param(‘markdown’));
update_option(‘amom_firecrawl_content’, $content);
return new WP_REST_Response([‘status’ => ‘stored’], 200);
}
function amom_ai_chat_handler($request) {
$question = sanitize_text_field($request[‘question’]);
$firecrawl_content = get_option(‘amom_firecrawl_content’);
$context = “Here is information from our website:\n” . $firecrawl_content . “\nAnswer this question based on the content above: ” . $question;
$response = wp_remote_post(‘https://api.openai.com/v1/chat/completions’, [
‘headers’ => [
‘Content-Type’ => ‘application/json’,
‘Authorization’ => ‘Bearer YOUR_OPENAI_API_KEY_HERE’
],
‘body’ => json_encode([
‘model’ => ‘gpt-4’,
‘messages’ => [
[‘role’ => ‘system’, ‘content’ => ‘You are a helpful assistant for a massage and acupuncture school.’],
[‘role’ => ‘user’, ‘content’ => $context]
]
])
]);
if (is_wp_error($response)) {
return new WP_REST_Response([‘answer’ => ‘Error contacting AI.’], 500);
}
$body = json_decode(wp_remote_retrieve_body($response), true);
$answer = $body[‘choices’][0][‘message’][‘content’] ?? ‘No answer generated.’;
return new WP_REST_Response([‘answer’ => $answer], 200);
}