71 lines
2.0 KiB
Python
71 lines
2.0 KiB
Python
from flask import Flask, request, jsonify
|
|
import mysql.connector
|
|
import requests
|
|
import os
|
|
from arango import ArangoClient
|
|
|
|
app = Flask(__name__)
|
|
|
|
# MariaDB Verbindung
|
|
def get_db():
|
|
return mysql.connector.connect(
|
|
host=os.environ['DB_HOST'],
|
|
user=os.environ['DB_USER'],
|
|
password=os.environ['DB_PASSWORD'],
|
|
database=os.environ['DB_NAME']
|
|
)
|
|
|
|
# ArangoDB Verbindung
|
|
def get_arango():
|
|
client = ArangoClient(hosts=os.environ['ARANGO_URL'])
|
|
sys_db = client.db('_system', username=os.environ['ARANGO_USER'], password=os.environ['ARANGO_PASSWORD'])
|
|
if not sys_db.has_database('llm_facts'):
|
|
sys_db.create_database('llm_facts')
|
|
db = client.db('llm_facts', username=os.environ['ARANGO_USER'], password=os.environ['ARANGO_PASSWORD'])
|
|
if not db.has_collection('facts'):
|
|
db.create_collection('facts')
|
|
return db.collection('facts')
|
|
|
|
# Skill-Trigger
|
|
def extract_fact(text):
|
|
triggers = ["merke dir", "notiere", "speichere"]
|
|
for t in triggers:
|
|
if text.lower().startswith(t):
|
|
fact = text[len(t):].strip()
|
|
return fact
|
|
return None
|
|
|
|
@app.route("/chat", methods=["POST"])
|
|
def chat():
|
|
data = request.json
|
|
project = data.get("project")
|
|
message = data.get("message")
|
|
|
|
# Lernbefehl
|
|
fact = extract_fact(message)
|
|
if fact:
|
|
arango = get_arango()
|
|
arango.insert({
|
|
"_raw": message,
|
|
"_source": project,
|
|
"content": fact,
|
|
"tags": ["skill:merke"],
|
|
"relations": []
|
|
})
|
|
return jsonify({"reply": f"Fakt gespeichert: {fact}"})
|
|
|
|
# Chat speichern in MariaDB
|
|
db = get_db()
|
|
cursor = db.cursor()
|
|
cursor.execute("INSERT INTO chats (project, user_input) VALUES (%s,%s)", (project, message))
|
|
db.commit()
|
|
cursor.close()
|
|
db.close()
|
|
|
|
# Anfrage an LLM
|
|
resp = requests.post(f"{os.environ['LM_API_URL']}/generate", json={"prompt": message})
|
|
return jsonify({"reply": resp.json()})
|
|
|
|
if __name__ == "__main__":
|
|
app.run(host="0.0.0.0", port=5000)
|