Merge branch 'main' of interstellardevelopment.org:YasinOnm08/interstellar_ai

This commit is contained in:
YasinOnm08 2024-10-10 08:01:34 +02:00
commit 939cdd4497
13 changed files with 984 additions and 206 deletions

View file

@ -5,6 +5,8 @@ import InputFrontend from "../components/InputFrontend";
import { sendToVoiceRecognition } from "./voice_backend"
import axios from "axios";
import { useChatHistory } from '../hooks/useChatHistory';
import { getWeather } from "./weather";
import { changeHistory, getHistory } from "./database";
const InputOutputBackend: React.FC = () => {
// # variables
@ -24,6 +26,9 @@ const InputOutputBackend: React.FC = () => {
const [messages, setMessages] = useState<Message[]>(chatHistory.chats[chatHistory.selectedIndex].messages || []);
const [myBoolean, setMyBoolean] = useState<boolean>(false);
const [systemMessage, setSystemMessage] = useState<string>("You are a helpful assistant")
const [weatherData, setWeatherData] = useState<string>("")
const [weatherTriggered, setWeatherTriggered] = useState<boolean>(false)
const [chatHistoryTriggered, setChatHistoryTriggered] = useState<boolean>(false)
const apiURL = new URL("http://localhost:5000/interstellar_ai/api/ai_create")
if (typeof window !== 'undefined') {
apiURL.hostname = window.location.hostname;
@ -34,7 +39,7 @@ const InputOutputBackend: React.FC = () => {
console.log(setSelectedIndex)
useEffect(() => {
useEffect(() => {
console.log("History", chatHistory);
console.log("Messages", messages);
@ -43,14 +48,14 @@ useEffect(() => {
// If the selected chat has messages, set them
if (currentMessages.length > 0) {
setMessages(currentMessages);
setMessages(currentMessages);
} else if (currentMessages.length === 0) {
// When creating a new chat and no messages exist yet, set default messages
addMessage("system", systemMessage)
addMessage("assistant", "Hello! How can I help you?")
console.log(systemMessage)
}
}, [chatHistory, chatHistory.selectedIndex, systemMessage]);
}, [chatHistory, chatHistory.selectedIndex, systemMessage]);
// Update messages when any of the settings change
useEffect(() => {
@ -62,10 +67,43 @@ useEffect(() => {
setTimeZone(localStorage.getItem("timeZone") || "GMT");
setDateFormat(localStorage.getItem("dateFormat") || "DD-MM-YYYY");
setMyBoolean(localStorage.getItem('myBoolean') === 'true');
getWeatherHere()
getChatHistory()
}
},[])
}, [])
useEffect(() => {
const username = localStorage.getItem("accountName")
const password = localStorage.getItem("accountPassword")
if (username && password && chatHistoryTriggered) {
changeHistory(username, password, chatHistory)
console.log("changed history in backend")
}
}, [chatHistory])
const getWeatherHere = async () => {
setWeatherData(await getWeather({ "unit_type": preferredMeasurement, "city": localStorage.getItem("weatherInfo") || "New York" }))
console.log("Got the Data!")
setWeatherTriggered(true)
}
const getChatHistory = async () => {
const username = localStorage.getItem("accountName")
const password = localStorage.getItem("accountPassword")
if (username && password) {
const tempChatHistory = await getHistory(username, password)
if (tempChatHistory && typeof tempChatHistory == "object") {
setChatHistory(tempChatHistory)
console.log("got history from backend")
}
}
setChatHistoryTriggered(true)
}
useEffect(() => {
console.log("creating system prompt")
console.log(weatherData)
const measurementString = (preferredMeasurement == "Metric")
? "All measurements follow the metric system. Refuse to use any other measurement system."
: "All measurements follow the imperial system. Refuse to use any other measurement system.";
@ -76,17 +114,18 @@ useEffect(() => {
The currency is ${preferredCurrency}.
Communicate in the language specified by the user (country code: ${preferredLanguage}), and only in this language.
You are only able to change language if the user specifically states you must.
Do not answer in multiple languages or multiple measurement systems under any circumstances other than the user requesting it.`
: `You are a helpful assistant`;
Do not answer in multiple languages or multiple measurement systems under any circumstances other than the user requesting it.
These are the currently newest Weather infos for the region. In case the user asks about anything weather related, you can use the following data to help the user: ${weatherData}. If there is nothing there say there is no data`
: `You are a helpful assistant.`;
console.log(newSystemMessage)
setSystemMessage(newSystemMessage)
}, [preferredCurrency, preferredLanguage, timeFormat, preferredMeasurement, timeZone, dateFormat, myBoolean]);
}, [preferredCurrency, preferredLanguage, timeFormat, preferredMeasurement, timeZone, dateFormat, myBoolean, weatherTriggered]);
useEffect(() => {
const messageIndex = 0 // system prompt is the first so index 0
updateMessage(messageIndex, systemMessage)
console.log(messages)
},[systemMessage])
}, [systemMessage])
const conversationRef = useRef<HTMLDivElement>(null)
@ -185,8 +224,8 @@ useEffect(() => {
if (newContent == "") {
newContent = "Generating answer..."
}
const messageIndex = chatHistory.chats[chatHistory.selectedIndex].messages.length-1
updateMessage(messageIndex,newContent)
const messageIndex = chatHistory.chats[chatHistory.selectedIndex].messages.length - 1
updateMessage(messageIndex, newContent)
};
const addMessage = (role: string, content: string) => {
@ -194,7 +233,7 @@ useEffect(() => {
setMessages((prevMessages) => [...prevMessages, newMessage])
const updatedChats = [...chatHistory.chats]
updatedChats[chatHistory.selectedIndex].messages.push(newMessage)
setChatHistory({...chatHistory, chats:updatedChats})
setChatHistory({ ...chatHistory, chats: updatedChats })
}
const handleSendClick = (inputValue: string, override: boolean) => {
if (inputValue != "") {
@ -202,7 +241,7 @@ useEffect(() => {
setInputDisabled(true)
if (postWorkerRef.current) {
addMessage("user", inputValue)
let type:string = "local"
let type: string = "local"
let api_key: string = ""
if (typeof localStorage !== 'undefined') {
type = localStorage.getItem('type') || "local"
@ -215,7 +254,7 @@ useEffect(() => {
}
setInputMessage("")
const windowname = window.location.hostname
postWorkerRef.current.postMessage({ messages: [...messages, { role: "user", content: inputValue }], ai_model: "llama3.2", model_type: type, access_token: accessToken, api_key: api_key, windowname })
postWorkerRef.current.postMessage({ messages: [...messages, { role: "user", content: inputValue }], ai_model: localStorage.getItem("model") || "llama3.2", model_type: type, access_token: accessToken, api_key: api_key, windowname })
startGetWorker()
}
}

23
app/backend/weather.ts Normal file
View file

@ -0,0 +1,23 @@
import axios from "axios";
const apiURL = new URL("http://localhost:5000/interstellar_ai/api/weather")
if (typeof window !== 'undefined') {
apiURL.hostname = window.location.hostname;
} else {
apiURL.hostname = "localhost"
}
export const getWeather = async (data: object): Promise<string> => {
try {
const response = await axios.post(apiURL.href, data);
const status = response.data.status;
const success = response.data.response;
postMessage({ status, success });
console.log(JSON.stringify(success))
return JSON.stringify(success);
} catch (error) {
postMessage({ status: 500, success: false });
console.log(error)
return "";
}
};