Hello everyone,
I am currently trying to use the API in a personal Laravel project ; I don’t really know what is currently wrong in my code, any help would be appreciated.
The JavaScript :
Summary
const xhr = new XMLHttpRequest();
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
xhr.open("GET", "web.php", true);
xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
const button = document.getElementById('button-submit');
const input = document.getElementById('input').value;
const chatWindow = document.getElementById('chat-window');
button.addEventListener('click', function (){
chatWindow.innerHTML += `<div class="messages-user">
<div class="__user">
<p>${input}</p>
</div>
<img src="{{ asset('/images/avatar.png') }}" alt="Avatar">
<div style="clear: both"></div>
</div>`;
input.value = '';
fetch('{{ url('send') }}', {
method: 'POST',
body: JSON.stringify(input),
headers: { 'Content-Type': 'application/json' }
}).then(function(response) {
if (response.ok) {
return response.text();
} else {
throw new Error('Erreur de réponse du serveur.');
}
}).then(function(data) {
chatWindow.innerHTML += `<div class="messages-bot">
<div class="__bot">
<p>${data}</p>
</div>
<img src="{{ asset('/images/chatbot.png') }}" alt="Avatar">
</div>
`;
}).catch(function(error) {
console.log('Erreur lors de la requête fetch:', error.message);
});
})
web.php :
Summary
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ChatBotController;
Route::get(‘/’, function () {
return view(‘welcome’);
});
Route::post(‘send’, [ChatBotController::class, ‘sendChat’]);
The Controller :
Summary
public function sendChat(Request $request){
$result = OpenAI::completions()->create([
‘max-token’ => 100,
‘model’ => ‘text-davinci-003’,
‘prompt’ => $request->input
]);
$response = array_reduce(
$result->toArray()['choices'],
fn(string $result, array $choice) => $result . $choice['text'], ""
);
return $response;
}
Thanks