Hello everyone,
my Laravel project using the openai-php/laravel works great in local but I can’t manage to get a response on the online prod hosted version. Though I uploaded all the project files and everything is exactly the same, the URL, the route and the following code, when I send a POST request it just returns a 404 error.
POST DOMAIN_NAME/api/send 404
fetchAndUpdateHTML @ (index):67
(index):90 Fetch error: Server error.
I don’t know if it’s a route issue, an URL that would need to be redefined for an online use of the API…
The JavaScript :
//CSRF TOKEN
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.openai.com/v1/chat/completions', true);
xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
//VARIABLES
const button = document.getElementById('button-submit');
const chatWindow = document.getElementById('chat-window');
const url = '{{ url('/api/send') }}';
const inputField = document.getElementById('input');
const clean = document.getElementById('button-clean');
//API FETCH AND HTML UPDATE
function fetchAndUpdateHTML() {
const input = document.getElementById('input').value;
if(isInputValid(input)){
chatWindow.insertAdjacentHTML('beforeend', `<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>`);
inputField.value = '';
fetch(url, {
method: 'POST',
body: JSON.stringify({input: input}),
headers: {
'Content-Type': 'application/json',
}
}).then(function (response) {
if (response.ok) {
return response.text();
} else {
throw new Error('Server error.');
}
}).then(function (data) {
chatWindow.insertAdjacentHTML('beforeend', `<div class="messages-bot">
<img src="{{ asset('/images/chatbot.png') }}" alt="Avatar">
<div class="__bot">
<p>${data}</p>
</div>
</div>
`);
}).catch(function (error) {
console.log('Fetch error:', error.message);
});
}
}
The web.php :
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ChatBotController;
Route::get(‘/’, function () {
return view(‘welcome’);
});
Route::post(‘send’, [ChatBotController::class, ‘sendChat’]);
The Controller :
public function sendChat(Request $request){
$result = OpenAI::completions()->create([
‘max-token’ => 150,
‘model’ => ‘text-davinci-003’,
‘prompt’ => $request->input
]);
$response = array_reduce(
$result->toArray()['choices'],
fn(string $result, array $choice) => $result . $choice['text'], ""
);
return $response;
}
Thanks for your time !