Spaces:
Paused
Paused
Upload main.py
Browse files
main.py
CHANGED
|
@@ -7,14 +7,13 @@ from datetime import datetime
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
-
# ---
|
|
|
|
| 11 |
COLLECTION_KNOWLEDGE = "knowledge_base"
|
| 12 |
-
COLLECTION_INBOX = "inbox"
|
| 13 |
|
| 14 |
-
# --- FIREBASE
|
| 15 |
db = None
|
| 16 |
-
project_id = "Unbekannt"
|
| 17 |
-
|
| 18 |
try:
|
| 19 |
firebase_key_json = os.environ.get("FIREBASE_KEY")
|
| 20 |
if firebase_key_json:
|
|
@@ -23,31 +22,26 @@ try:
|
|
| 23 |
if not firebase_admin._apps:
|
| 24 |
firebase_admin.initialize_app(cred)
|
| 25 |
db = firestore.client()
|
| 26 |
-
|
| 27 |
-
print(f"✅ SYSTEM: Verbunden mit Projekt '{project_id}'")
|
| 28 |
else:
|
| 29 |
-
print("⚠️ FEHLER: Kein
|
| 30 |
except Exception as e:
|
| 31 |
-
print(f"❌ FEHLER: {e}")
|
| 32 |
|
| 33 |
@app.get("/")
|
| 34 |
def home():
|
| 35 |
-
return {"status": "
|
| 36 |
|
| 37 |
@app.post("/search")
|
| 38 |
async def search_knowledge(request: Request):
|
| 39 |
-
#
|
| 40 |
-
debug_log = []
|
| 41 |
-
debug_log.append(f"Verbinde mit Projekt-ID: {project_id}")
|
| 42 |
-
|
| 43 |
-
# 1. Parsing
|
| 44 |
try:
|
| 45 |
data = await request.json()
|
| 46 |
except:
|
| 47 |
-
return {"result": "Fehler: Kein JSON"}
|
| 48 |
|
|
|
|
| 49 |
query_text = ""
|
| 50 |
-
# Robuste Extraktion
|
| 51 |
if "query" in data and isinstance(data["query"], str):
|
| 52 |
query_text = data["query"]
|
| 53 |
elif "message" in data and "toolCalls" in data["message"]:
|
|
@@ -61,72 +55,67 @@ async def search_knowledge(request: Request):
|
|
| 61 |
query_text = json.loads(args).get("query", "") if isinstance(args, str) else args.get("query", "")
|
| 62 |
except: pass
|
| 63 |
|
| 64 |
-
|
| 65 |
|
|
|
|
|
|
|
| 66 |
if not db:
|
| 67 |
-
return {"result": "
|
| 68 |
|
| 69 |
-
#
|
| 70 |
-
antwort = "
|
| 71 |
treffer = False
|
| 72 |
|
| 73 |
try:
|
| 74 |
-
# Wir
|
| 75 |
-
|
| 76 |
-
docs = list(docs_stream) # Liste laden
|
| 77 |
-
debug_log.append(f"Anzahl Dokumente in '{COLLECTION_KNOWLEDGE}': {len(docs)}")
|
| 78 |
-
|
| 79 |
-
# Falls leer, zeigen wir die Collections an, die es gibt
|
| 80 |
-
if len(docs) == 0:
|
| 81 |
-
cols = [c.id for c in db.collections()]
|
| 82 |
-
debug_log.append(f"WARNUNG: Sammlung leer! Vorhandene Sammlungen: {cols}")
|
| 83 |
-
|
| 84 |
query_lower = query_text.lower()
|
| 85 |
|
| 86 |
for doc in docs:
|
| 87 |
d = doc.to_dict()
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
t_keywords = d.get("keywords") or []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
# Match
|
| 94 |
-
if isinstance(t_keywords, list)
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
| 99 |
|
| 100 |
-
|
|
|
|
|
|
|
| 101 |
antwort = t_answer
|
| 102 |
treffer = True
|
| 103 |
-
|
| 104 |
break
|
| 105 |
|
| 106 |
-
#
|
| 107 |
if not treffer:
|
| 108 |
-
|
| 109 |
try:
|
| 110 |
-
|
| 111 |
-
ref = db.collection(COLLECTION_INBOX).add({
|
| 112 |
"question": query_text,
|
| 113 |
"status": "open",
|
| 114 |
"timestamp": firestore.SERVER_TIMESTAMP,
|
| 115 |
-
"
|
| 116 |
})
|
| 117 |
-
|
| 118 |
-
antwort = "Dazu habe ich keine Infos, habe es aber notiert."
|
| 119 |
except Exception as e:
|
| 120 |
-
|
| 121 |
|
| 122 |
except Exception as e:
|
| 123 |
-
|
|
|
|
| 124 |
|
| 125 |
-
#
|
| 126 |
-
|
| 127 |
-
print(json.dumps(debug_log, indent=2))
|
| 128 |
-
|
| 129 |
-
return {
|
| 130 |
-
"result": antwort,
|
| 131 |
-
"system_debug": debug_log # <-- Schau hier rein!
|
| 132 |
-
}
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
+
# --- EINSTELLUNGEN ---
|
| 11 |
+
# Deine korrekten Sammlungs-Namen aus dem Screenshot
|
| 12 |
COLLECTION_KNOWLEDGE = "knowledge_base"
|
| 13 |
+
COLLECTION_INBOX = "inbox" # Kleingeschrieben, wie Standard
|
| 14 |
|
| 15 |
+
# --- FIREBASE VERBINDUNG ---
|
| 16 |
db = None
|
|
|
|
|
|
|
| 17 |
try:
|
| 18 |
firebase_key_json = os.environ.get("FIREBASE_KEY")
|
| 19 |
if firebase_key_json:
|
|
|
|
| 22 |
if not firebase_admin._apps:
|
| 23 |
firebase_admin.initialize_app(cred)
|
| 24 |
db = firestore.client()
|
| 25 |
+
print(f"✅ SYSTEM: Verbunden mit Projekt '{db.project}'")
|
|
|
|
| 26 |
else:
|
| 27 |
+
print("⚠️ FEHLER: Kein FIREBASE_KEY gefunden.")
|
| 28 |
except Exception as e:
|
| 29 |
+
print(f"❌ FEHLER beim Start: {e}")
|
| 30 |
|
| 31 |
@app.get("/")
|
| 32 |
def home():
|
| 33 |
+
return {"status": "Udo Agent API (Live) ist bereit."}
|
| 34 |
|
| 35 |
@app.post("/search")
|
| 36 |
async def search_knowledge(request: Request):
|
| 37 |
+
# 1. DATEN EMPFANGEN
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
try:
|
| 39 |
data = await request.json()
|
| 40 |
except:
|
| 41 |
+
return {"result": "Fehler: Kein JSON."}
|
| 42 |
|
| 43 |
+
# 2. FRAGE EXTRAHIEREN (Robust für Vapi)
|
| 44 |
query_text = ""
|
|
|
|
| 45 |
if "query" in data and isinstance(data["query"], str):
|
| 46 |
query_text = data["query"]
|
| 47 |
elif "message" in data and "toolCalls" in data["message"]:
|
|
|
|
| 55 |
query_text = json.loads(args).get("query", "") if isinstance(args, str) else args.get("query", "")
|
| 56 |
except: pass
|
| 57 |
|
| 58 |
+
print(f"🔎 FRAGE: '{query_text}'")
|
| 59 |
|
| 60 |
+
if not query_text:
|
| 61 |
+
return {"result": "Ich habe die Frage akustisch nicht verstanden."}
|
| 62 |
if not db:
|
| 63 |
+
return {"result": "Server-Fehler: Datenbank nicht verbunden."}
|
| 64 |
|
| 65 |
+
# 3. INTELLIGENTE SUCHE (Deine 752 Dokumente)
|
| 66 |
+
antwort = "Dazu habe ich leider keine Informationen in meiner Datenbank. Ich habe die Frage für das Team notiert."
|
| 67 |
treffer = False
|
| 68 |
|
| 69 |
try:
|
| 70 |
+
# Wir laden alle Dokumente (Caching wäre bei >2000 Docs nötig, für 750 geht es noch)
|
| 71 |
+
docs = db.collection(COLLECTION_KNOWLEDGE).stream()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
query_lower = query_text.lower()
|
| 73 |
|
| 74 |
for doc in docs:
|
| 75 |
d = doc.to_dict()
|
| 76 |
+
|
| 77 |
+
# Felder sicher auslesen (auch wenn mal eins fehlt)
|
| 78 |
+
t_answer = d.get("answer") or d.get("Antwort") or d.get("content")
|
| 79 |
+
t_keywords = d.get("keywords") or d.get("Keywords") or []
|
| 80 |
+
t_question = d.get("question") or d.get("Frage") or ""
|
| 81 |
+
|
| 82 |
+
if not t_answer:
|
| 83 |
+
continue
|
| 84 |
|
| 85 |
+
# A) Keyword-Match (Sehr stark!)
|
| 86 |
+
if isinstance(t_keywords, list):
|
| 87 |
+
# Prüft, ob ein Keyword in der Frage vorkommt
|
| 88 |
+
if any(k.lower() in query_lower for k in t_keywords):
|
| 89 |
+
antwort = t_answer
|
| 90 |
+
treffer = True
|
| 91 |
+
print(f"✅ TREFFER (Keyword) in Doc {doc.id}")
|
| 92 |
+
break
|
| 93 |
|
| 94 |
+
# B) Frage-Match (Fuzzy)
|
| 95 |
+
# Prüft, ob die User-Frage in der DB-Frage steckt (oder umgekehrt)
|
| 96 |
+
if t_question and (t_question.lower() in query_lower or query_lower in t_question.lower()):
|
| 97 |
antwort = t_answer
|
| 98 |
treffer = True
|
| 99 |
+
print(f"✅ TREFFER (Frage-Match) in Doc {doc.id}")
|
| 100 |
break
|
| 101 |
|
| 102 |
+
# 4. LERN-LOGIK (INBOX)
|
| 103 |
if not treffer:
|
| 104 |
+
print(f"⚠️ KEIN TREFFER. Speichere in '{COLLECTION_INBOX}'...")
|
| 105 |
try:
|
| 106 |
+
db.collection(COLLECTION_INBOX).add({
|
|
|
|
| 107 |
"question": query_text,
|
| 108 |
"status": "open",
|
| 109 |
"timestamp": firestore.SERVER_TIMESTAMP,
|
| 110 |
+
"source": "Vapi Call"
|
| 111 |
})
|
| 112 |
+
print("📩 Erfolgreich in Inbox gespeichert.")
|
|
|
|
| 113 |
except Exception as e:
|
| 114 |
+
print(f"❌ Fehler beim Speichern in Inbox: {e}")
|
| 115 |
|
| 116 |
except Exception as e:
|
| 117 |
+
print(f"❌ DATABASE ERROR: {e}")
|
| 118 |
+
return {"result": "Es gab ein technisches Problem beim Zugriff auf das Wissen."}
|
| 119 |
|
| 120 |
+
# Sauberes Ergebnis für Vapi
|
| 121 |
+
return {"result": antwort}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|