LibreChat/src/components/TextChat.jsx

84 lines
2.2 KiB
React
Raw Normal View History

2023-02-05 15:29:35 -05:00
import React, { useState } from 'react';
import { SSE } from '../../app/sse';
const handleSubmit = (text, messageHandler, convo, convoHandler) => {
let payload = { text };
if (convo.conversationId && convo.parentMessageId) {
payload = {
...payload,
conversationId: convo.conversationId,
parentMessageId: convo.parentMessageId
};
}
2023-02-05 15:29:35 -05:00
const events = new SSE('http://localhost:3050/ask', {
payload: JSON.stringify(payload),
2023-02-05 15:29:35 -05:00
headers: { 'Content-Type': 'application/json' }
});
2023-02-05 15:29:35 -05:00
events.onopen = function () {
console.log('connection is opened');
};
events.onmessage = function (e) {
const data = JSON.parse(e.data);
if (!!data.message) {
messageHandler(data.text.replace(/^\n/, ''));
} else {
console.log(data);
convoHandler(data);
}
2023-02-05 15:29:35 -05:00
};
events.onerror = function (e) {
console.log(e, 'error in opening conn.');
events.close();
};
events.stream();
};
2023-02-04 20:48:33 -05:00
export default function TextChat({ messages, setMessages, conversation = null }) {
2023-02-05 15:29:35 -05:00
const [text, setText] = useState('');
const [convo, setConvo] = useState({ conversationId: null, parentMessageId: null });
if (!!conversation) {
setConvo(conversation);
}
2023-02-05 15:29:35 -05:00
2023-02-04 20:48:33 -05:00
const handleKeyPress = (e) => {
if (e.key === 'Enter' && e.shiftKey) {
console.log('Enter + Shift');
}
if (e.key === 'Enter' && !e.shiftKey) {
const payload = text.trim();
const currentMsg = { sender: 'user', text: payload, current: true };
setMessages([...messages, currentMsg]);
setText('');
const messageHandler = (data) => {
setMessages([...messages, currentMsg, { sender: 'GPT', text: data }]);
};
const convoHandler = (data) => {
if (convo.conversationId === null && convo.parentMessageId === null) {
const { conversationId, parentMessageId } = data;
setConvo({ conversationId, parentMessageId: data.id });
}
};
console.log('User Input:', payload);
handleSubmit(payload, messageHandler, convo, convoHandler);
2023-02-04 20:48:33 -05:00
}
};
return (
<>
<textarea
className="m-10 h-16 p-4"
value={text}
2023-02-04 20:48:33 -05:00
onKeyUp={handleKeyPress}
2023-02-05 15:29:35 -05:00
onChange={(e) => setText(e.target.value)}
2023-02-04 20:48:33 -05:00
/>
</>
);
}