forked from React-Group/interstellar_ai
main #49
6 changed files with 88 additions and 52 deletions
|
@ -6,6 +6,7 @@ import { sendToVoiceRecognition } from "./voice_backend"
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import { useChatHistory } from '../hooks/useChatHistory';
|
import { useChatHistory } from '../hooks/useChatHistory';
|
||||||
import { getWeather } from "./weather";
|
import { getWeather } from "./weather";
|
||||||
|
import { changeHistory, getHistory } from "./database";
|
||||||
|
|
||||||
const InputOutputBackend: React.FC = () => {
|
const InputOutputBackend: React.FC = () => {
|
||||||
// # variables
|
// # variables
|
||||||
|
@ -25,7 +26,9 @@ const InputOutputBackend: React.FC = () => {
|
||||||
const [messages, setMessages] = useState<Message[]>(chatHistory.chats[chatHistory.selectedIndex].messages || []);
|
const [messages, setMessages] = useState<Message[]>(chatHistory.chats[chatHistory.selectedIndex].messages || []);
|
||||||
const [myBoolean, setMyBoolean] = useState<boolean>(false);
|
const [myBoolean, setMyBoolean] = useState<boolean>(false);
|
||||||
const [systemMessage, setSystemMessage] = useState<string>("You are a helpful assistant")
|
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")
|
const apiURL = new URL("http://localhost:5000/interstellar_ai/api/ai_create")
|
||||||
if (typeof window !== 'undefined') {
|
if (typeof window !== 'undefined') {
|
||||||
apiURL.hostname = window.location.hostname;
|
apiURL.hostname = window.location.hostname;
|
||||||
|
@ -65,15 +68,42 @@ const InputOutputBackend: React.FC = () => {
|
||||||
setDateFormat(localStorage.getItem("dateFormat") || "DD-MM-YYYY");
|
setDateFormat(localStorage.getItem("dateFormat") || "DD-MM-YYYY");
|
||||||
setMyBoolean(localStorage.getItem('myBoolean') === 'true');
|
setMyBoolean(localStorage.getItem('myBoolean') === 'true');
|
||||||
getWeatherHere()
|
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 () => {
|
const getWeatherHere = async () => {
|
||||||
setWeatherData(await getWeather({ "unit_type": preferredMeasurement, "city": localStorage.getItem("weatherInfo") || "New York" }))
|
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(() => {
|
useEffect(() => {
|
||||||
|
console.log("creating system prompt")
|
||||||
|
console.log(weatherData)
|
||||||
|
|
||||||
const measurementString = (preferredMeasurement == "Metric")
|
const measurementString = (preferredMeasurement == "Metric")
|
||||||
? "All measurements follow the metric system. Refuse to use any other measurement system."
|
? "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.";
|
: "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.
|
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.
|
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.
|
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.`;
|
: `You are a helpful assistant.`;
|
||||||
|
console.log(newSystemMessage)
|
||||||
setSystemMessage(newSystemMessage)
|
setSystemMessage(newSystemMessage)
|
||||||
}, [preferredCurrency, preferredLanguage, timeFormat, preferredMeasurement, timeZone, dateFormat, myBoolean]);
|
}, [preferredCurrency, preferredLanguage, timeFormat, preferredMeasurement, timeZone, dateFormat, myBoolean, weatherTriggered]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const messageIndex = 0 // system prompt is the first so index 0
|
const messageIndex = 0 // system prompt is the first so index 0
|
||||||
|
@ -223,7 +254,7 @@ const InputOutputBackend: React.FC = () => {
|
||||||
}
|
}
|
||||||
setInputMessage("")
|
setInputMessage("")
|
||||||
const windowname = window.location.hostname
|
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()
|
startGetWorker()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -13,7 +13,8 @@ export const getWeather = async (data: object): Promise<string> => {
|
||||||
const status = response.data.status;
|
const status = response.data.status;
|
||||||
const success = response.data.response;
|
const success = response.data.response;
|
||||||
postMessage({ status, success });
|
postMessage({ status, success });
|
||||||
return success;
|
console.log(JSON.stringify(success))
|
||||||
|
return JSON.stringify(success);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
postMessage({ status: 500, success: false });
|
postMessage({ status: 500, success: false });
|
||||||
console.log(error)
|
console.log(error)
|
||||||
|
|
16
package-lock.json
generated
16
package-lock.json
generated
|
@ -2151,9 +2151,9 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/es-iterator-helpers": {
|
"node_modules/es-iterator-helpers": {
|
||||||
"version": "1.0.19",
|
"version": "1.1.0",
|
||||||
"resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.0.19.tgz",
|
"resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.1.0.tgz",
|
||||||
"integrity": "sha512-zoMwbCcH5hwUkKJkT8kDIBZSz9I6mVG//+lDCinLCGov4+r7NIy0ld8o03M0cJxl2spVf6ESYVS6/gpIfq1FFw==",
|
"integrity": "sha512-/SurEfycdyssORP/E+bj4sEu1CWw4EmLDsHynHwSXQ7utgbrMRWW195pTrCjFgFCddf/UkYm3oqKPRq5i8bJbw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
@ -2164,12 +2164,12 @@
|
||||||
"es-set-tostringtag": "^2.0.3",
|
"es-set-tostringtag": "^2.0.3",
|
||||||
"function-bind": "^1.1.2",
|
"function-bind": "^1.1.2",
|
||||||
"get-intrinsic": "^1.2.4",
|
"get-intrinsic": "^1.2.4",
|
||||||
"globalthis": "^1.0.3",
|
"globalthis": "^1.0.4",
|
||||||
"has-property-descriptors": "^1.0.2",
|
"has-property-descriptors": "^1.0.2",
|
||||||
"has-proto": "^1.0.3",
|
"has-proto": "^1.0.3",
|
||||||
"has-symbols": "^1.0.3",
|
"has-symbols": "^1.0.3",
|
||||||
"internal-slot": "^1.0.7",
|
"internal-slot": "^1.0.7",
|
||||||
"iterator.prototype": "^1.1.2",
|
"iterator.prototype": "^1.1.3",
|
||||||
"safe-array-concat": "^1.1.2"
|
"safe-array-concat": "^1.1.2"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
|
@ -7371,9 +7371,9 @@
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/typescript": {
|
"node_modules/typescript": {
|
||||||
"version": "5.6.2",
|
"version": "5.6.3",
|
||||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.2.tgz",
|
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz",
|
||||||
"integrity": "sha512-NW8ByodCSNCwZeghjN3o+JX5OFH0Ojg6sadjEKY4huZ52TqbJTJnDo5+Tw98lSy63NZvi4n+ez5m2u5d4PkZyw==",
|
"integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"bin": {
|
"bin": {
|
||||||
|
|
14
py/api.py
14
py/api.py
|
@ -43,6 +43,8 @@ class API:
|
||||||
model_type = data.get("model_type")
|
model_type = data.get("model_type")
|
||||||
ai_model = data.get("ai_model")
|
ai_model = data.get("ai_model")
|
||||||
access_token = data.get("access_token")
|
access_token = data.get("access_token")
|
||||||
|
|
||||||
|
print(model_type)
|
||||||
if access_token not in self.ai_response:
|
if access_token not in self.ai_response:
|
||||||
return jsonify({"status": 401, "error": "Invalid access token"})
|
return jsonify({"status": 401, "error": "Invalid access token"})
|
||||||
|
|
||||||
|
@ -56,6 +58,7 @@ class API:
|
||||||
sleep(0.5)
|
sleep(0.5)
|
||||||
return jsonify({"status": 200})
|
return jsonify({"status": 200})
|
||||||
elif model_type == "mistral":
|
elif model_type == "mistral":
|
||||||
|
print(model_type)
|
||||||
api_key = data.get("api_key")
|
api_key = data.get("api_key")
|
||||||
thread = threading.Thread(
|
thread = threading.Thread(
|
||||||
target=self.ai.process_mistralai,
|
target=self.ai.process_mistralai,
|
||||||
|
@ -108,7 +111,6 @@ class API:
|
||||||
@self.app.route("/interstellar_ai/db", methods=["POST"])
|
@self.app.route("/interstellar_ai/db", methods=["POST"])
|
||||||
def db_manipulate():
|
def db_manipulate():
|
||||||
sent_data = request.get_json()
|
sent_data = request.get_json()
|
||||||
print(sent_data)
|
|
||||||
action = sent_data.get("action")
|
action = sent_data.get("action")
|
||||||
if action == "create_account":
|
if action == "create_account":
|
||||||
return jsonify({"status": 200, "response": self.db.add_user(sent_data)})
|
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"])
|
@self.app.route("/interstellar_ai/api/weather", methods=["POST"])
|
||||||
def get_weather():
|
def get_weather():
|
||||||
unit_type = request.args.get("unit_type")
|
sent_data = request.get_json()
|
||||||
city = request.args.get("city")
|
unit_type = sent_data.get("unit_type")
|
||||||
return jsonify(
|
city = sent_data.get("city")
|
||||||
{"status": 200, "response": self.weather.getweather(unit_type, 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)
|
self.app.run(debug=True, host="0.0.0.0", port=5000)
|
||||||
|
|
||||||
|
|
2
py/db.py
2
py/db.py
|
@ -67,7 +67,6 @@ class DB:
|
||||||
|
|
||||||
stored_hashed_password = self.database[username]["hashed_password"]
|
stored_hashed_password = self.database[username]["hashed_password"]
|
||||||
entered_hashed_password = self.hash_password(password)
|
entered_hashed_password = self.hash_password(password)
|
||||||
print(stored_hashed_password == entered_hashed_password)
|
|
||||||
return stored_hashed_password == entered_hashed_password
|
return stored_hashed_password == entered_hashed_password
|
||||||
|
|
||||||
def change_settings(self, data):
|
def change_settings(self, data):
|
||||||
|
@ -127,7 +126,6 @@ class DB:
|
||||||
|
|
||||||
else:
|
else:
|
||||||
with open("database.json", "w") as file:
|
with open("database.json", "w") as file:
|
||||||
print("saving")
|
|
||||||
json.dump(self.database, file)
|
json.dump(self.database, file)
|
||||||
|
|
||||||
def load_database(self):
|
def load_database(self):
|
||||||
|
|
|
@ -1,39 +1,43 @@
|
||||||
import python_weather
|
import python_weather
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
|
||||||
class Weather:
|
class Weather:
|
||||||
@staticmethod
|
@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":
|
||||||
|
unit_type = python_weather.METRIC
|
||||||
|
|
||||||
if unit_type == "imperial":
|
async with python_weather.Client(unit=unit_type) as client:
|
||||||
unit_type = python_weather.IMPERIAL
|
weather = await client.get(city)
|
||||||
elif unit_type == "metric":
|
|
||||||
unit_type = python_weather.METRIC
|
|
||||||
|
|
||||||
async with python_weather.Client(unit=unit_type) as client:
|
data = {
|
||||||
weather = await client.get(city)
|
"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,
|
||||||
|
}
|
||||||
|
|
||||||
data = {
|
return 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,
|
|
||||||
}
|
|
||||||
|
|
||||||
return data
|
# Run the asynchronous function and return the result
|
||||||
|
return asyncio.run(fetch_weather(unit_type))
|
||||||
|
|
Loading…
Reference in a new issue