chat.js 996 B

123456789101112131415161718192021222324252627282930
  1. async function sendMessage(message, messageList, userName, token) {
  2. if (!token) {
  3. return "not_init";
  4. }
  5. messageList.push({ role: "user", content: message });
  6. const cuerpo = { messages: messageList, user: userName }
  7. const response = await fetch("/api/chat/completions", {
  8. method: "POST",
  9. headers: {
  10. "Content-Type": "application/json",
  11. "Authorization": `Bearer ${token}`
  12. },
  13. body: JSON.stringify(cuerpo)
  14. });
  15. if (!response.ok) {
  16. const errorData = await response.json().catch(() => ({ message: "Respuesta no válida del servidor." }));
  17. throw new Error(errorData.message || `Error del servidor: ${response.status}`);
  18. }
  19. const data = await response.json();
  20. const assistantResponse = data.response;
  21. if (assistantResponse) {
  22. messageList.push({ role: "assistant", content: assistantResponse });
  23. return { messageList, assistantResponse };
  24. } else {
  25. throw new Error("Respuesta vacía del asistente.");
  26. }
  27. }
  28. export { sendMessage };