main #49

Merged
sageTheDm merged 7 commits from React-Group/interstellar_ai:main into main 2024-10-10 07:48:11 +02:00
6 changed files with 88 additions and 52 deletions

View file

@ -6,6 +6,7 @@ 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
@ -25,7 +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>("false")
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;
@ -65,15 +68,42 @@ const InputOutputBackend: React.FC = () => {
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(weatherData)
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.";
@ -85,10 +115,11 @@ const InputOutputBackend: React.FC = () => {
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.
When asked about the weather use those infos: ${weatherData}. If there is nothing there say there is no data`
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
@ -223,7 +254,7 @@ const InputOutputBackend: React.FC = () => {
}
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()
}
}

View file

@ -13,7 +13,8 @@ export const getWeather = async (data: object): Promise<string> => {
const status = response.data.status;
const success = response.data.response;
postMessage({ status, success });
return success;
console.log(JSON.stringify(success))
return JSON.stringify(success);
} catch (error) {
postMessage({ status: 500, success: false });
console.log(error)

16
package-lock.json generated
View file

@ -2151,9 +2151,9 @@
}
},
"node_modules/es-iterator-helpers": {
"version": "1.0.19",
"resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.0.19.tgz",
"integrity": "sha512-zoMwbCcH5hwUkKJkT8kDIBZSz9I6mVG//+lDCinLCGov4+r7NIy0ld8o03M0cJxl2spVf6ESYVS6/gpIfq1FFw==",
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.1.0.tgz",
"integrity": "sha512-/SurEfycdyssORP/E+bj4sEu1CWw4EmLDsHynHwSXQ7utgbrMRWW195pTrCjFgFCddf/UkYm3oqKPRq5i8bJbw==",
"dev": true,
"license": "MIT",
"dependencies": {
@ -2164,12 +2164,12 @@
"es-set-tostringtag": "^2.0.3",
"function-bind": "^1.1.2",
"get-intrinsic": "^1.2.4",
"globalthis": "^1.0.3",
"globalthis": "^1.0.4",
"has-property-descriptors": "^1.0.2",
"has-proto": "^1.0.3",
"has-symbols": "^1.0.3",
"internal-slot": "^1.0.7",
"iterator.prototype": "^1.1.2",
"iterator.prototype": "^1.1.3",
"safe-array-concat": "^1.1.2"
},
"engines": {
@ -7371,9 +7371,9 @@
}
},
"node_modules/typescript": {
"version": "5.6.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.2.tgz",
"integrity": "sha512-NW8ByodCSNCwZeghjN3o+JX5OFH0Ojg6sadjEKY4huZ52TqbJTJnDo5+Tw98lSy63NZvi4n+ez5m2u5d4PkZyw==",
"version": "5.6.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz",
"integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==",
"dev": true,
"license": "Apache-2.0",
"bin": {

View file

@ -43,6 +43,8 @@ class API:
model_type = data.get("model_type")
ai_model = data.get("ai_model")
access_token = data.get("access_token")
print(model_type)
if access_token not in self.ai_response:
return jsonify({"status": 401, "error": "Invalid access token"})
@ -56,6 +58,7 @@ class API:
sleep(0.5)
return jsonify({"status": 200})
elif model_type == "mistral":
print(model_type)
api_key = data.get("api_key")
thread = threading.Thread(
target=self.ai.process_mistralai,
@ -108,7 +111,6 @@ class API:
@self.app.route("/interstellar_ai/db", methods=["POST"])
def db_manipulate():
sent_data = request.get_json()
print(sent_data)
action = sent_data.get("action")
if action == "create_account":
return jsonify({"status": 200, "response": self.db.add_user(sent_data)})
@ -157,11 +159,11 @@ class API:
@self.app.route("/interstellar_ai/api/weather", methods=["POST"])
def get_weather():
unit_type = request.args.get("unit_type")
city = request.args.get("city")
return jsonify(
{"status": 200, "response": self.weather.getweather(unit_type, city)}
)
sent_data = request.get_json()
unit_type = sent_data.get("unit_type")
city = sent_data.get("city")
weather_data = self.weather.getweather(unit_type, city)
return jsonify({"status": 200, "response": weather_data})
self.app.run(debug=True, host="0.0.0.0", port=5000)

View file

@ -67,7 +67,6 @@ class DB:
stored_hashed_password = self.database[username]["hashed_password"]
entered_hashed_password = self.hash_password(password)
print(stored_hashed_password == entered_hashed_password)
return stored_hashed_password == entered_hashed_password
def change_settings(self, data):
@ -127,7 +126,6 @@ class DB:
else:
with open("database.json", "w") as file:
print("saving")
json.dump(self.database, file)
def load_database(self):

View file

@ -1,10 +1,12 @@
import python_weather
import asyncio
class Weather:
@staticmethod
async def getweather(unit_type, city):
def getweather(unit_type, city):
# Define an inner asynchronous function
async def fetch_weather(unit_type):
if unit_type == "imperial":
unit_type = python_weather.IMPERIAL
elif unit_type == "metric":
@ -14,26 +16,28 @@ class Weather:
weather = await client.get(city)
data = {
'temperature': weather.temperature,
'humidity': weather.humidity,
'unit': weather.unit,
'datetime': weather.datetime,
'coordinates': weather.coordinates,
'country': weather.country,
'daily_forecasts': weather.daily_forecasts,
'description': weather.description,
'feels_like': weather.feels_like,
'kind': weather.kind,
'local_population': weather.local_population,
'locale': weather.locale,
'location': weather.location,
'precipitation': weather.precipitation,
'pressure': weather.pressure,
'region': weather.region,
'ultraviolet': weather.ultraviolet,
'visibility': weather.visibility,
'wind_direction': weather.wind_direction,
'wind_speed': weather.wind_speed,
"temperature": weather.temperature,
"humidity": weather.humidity,
"unit": str(weather.unit),
"datetime": weather.datetime,
"coordinates": weather.coordinates,
"country": weather.country,
"description": weather.description,
"feels_like": weather.feels_like,
"kind": str(weather.kind),
"local_population": weather.local_population,
"locale": str(weather.locale),
"location": weather.location,
"precipitation": weather.precipitation,
"pressure": weather.pressure,
"region": weather.region,
"ultraviolet": str(weather.ultraviolet),
"visibility": weather.visibility,
"wind_direction": str(weather.wind_direction),
"wind_speed": weather.wind_speed,
}
return data
# Run the asynchronous function and return the result
return asyncio.run(fetch_weather(unit_type))