Files changed (1) hide show
  1. app.py +66 -26
app.py CHANGED
@@ -2,7 +2,7 @@ import os
2
  import google.generativeai as genai
3
  from flask import Flask, request, jsonify
4
  from flask_cors import CORS
5
- from google.generativeai.types import ToolConfig, GoogleSearchRetrieval # Neue Imports
6
 
7
  app = Flask(__name__)
8
  CORS(app)
@@ -10,29 +10,48 @@ CORS(app)
10
  # --- Konfiguration & Gemini Initialisierung ---
11
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
12
  if not GOOGLE_API_KEY:
13
- raise ValueError("GOOGLE_API_KEY nicht gesetzt!")
14
 
15
  genai.configure(api_key=GOOGLE_API_KEY)
16
 
17
- # Korrekte Tool-Konfiguration für Gemini 2.0+
 
 
 
 
 
 
 
18
  model = genai.GenerativeModel(
19
  'gemini-1.5-pro',
20
- tools=[
21
- ToolConfig(
22
- google_search_retrieval=GoogleSearchRetrieval(
23
- disable_attribution=False,
24
- max_records=5
25
- )
26
- )
27
- ],
28
- system_instruction="Du bist Moejra... (deine Systemanweisung)"
29
  )
30
 
31
  chat = model.start_chat(history=[])
32
 
33
- # --- Wissensdatenbank (RAG) Funktion unverändert ---
34
  def retrieve_info_from_kb(query):
35
- ... # Deine existierende RAG-Logik
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
  # --- API-Endpunkt für den Chat ---
38
  @app.route('/chat', methods=['POST'])
@@ -41,24 +60,45 @@ def handle_chat():
41
  if not user_input:
42
  return jsonify({"error": "Kein Text übermittelt"}), 400
43
 
44
- kb_info = retrieve_info_from_kb(user_input)
45
-
46
- prompt_parts = [f"Nutzerfrage: {user_input}"]
47
- if kb_info:
48
- prompt_parts.append(f"Kontext: {kb_info}")
49
-
50
  try:
 
 
 
 
 
 
 
 
 
 
 
51
  response = chat.send_message("\n".join(prompt_parts))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  return jsonify({
53
- "response_text": response.text,
54
- "image_urls": [part.image.base64 for part in response.parts if hasattr(part, 'image')]
55
  })
56
-
57
  except Exception as e:
58
- print(f"Fehler: {str(e)}")
59
  return jsonify({
60
- "response_text": "🤖 Temporärer Fehler, bitte versuche es später erneut.",
61
- "image_urls": []
62
  }), 500
63
 
64
  if __name__ == '__main__':
 
2
  import google.generativeai as genai
3
  from flask import Flask, request, jsonify
4
  from flask_cors import CORS
5
+ from google.generativeai import protos
6
 
7
  app = Flask(__name__)
8
  CORS(app)
 
10
  # --- Konfiguration & Gemini Initialisierung ---
11
  GOOGLE_API_KEY = os.environ.get("GOOGLE_API_KEY")
12
  if not GOOGLE_API_KEY:
13
+ raise ValueError("GOOGLE_API_KEY nicht gesetzt! Bitte als HF Space Secret hinterlegen.")
14
 
15
  genai.configure(api_key=GOOGLE_API_KEY)
16
 
17
+ # Korrekte Tool-Initialisierung für Google Search
18
+ search_tool = protos.Tool(
19
+ google_search_retrieval=protos.Tool.GoogleSearchRetrieval(
20
+ disable_attribution=False,
21
+ max_return_results=3
22
+ )
23
+ )
24
+
25
  model = genai.GenerativeModel(
26
  'gemini-1.5-pro',
27
+ tools=[search_tool],
28
+ system_instruction="Du bist Moejra, eine hilfsbereite KI-Lernbegleitung. Antworte im unterstützenden Stil und nutze Webrecherche bei Unsicherheiten. Generiere bei Bildanfragen explizit ein Bild."
 
 
 
 
 
 
 
29
  )
30
 
31
  chat = model.start_chat(history=[])
32
 
33
+ # --- Wissensdatenbank (RAG) Funktion ---
34
  def retrieve_info_from_kb(query):
35
+ relevant_text = []
36
+ knowledge_base_dir = "knowledge_base"
37
+
38
+ if not os.path.exists(knowledge_base_dir):
39
+ return ""
40
+
41
+ query_keywords = [word.lower() for word in query.split() if len(word) > 2]
42
+
43
+ for filename in os.listdir(knowledge_base_dir):
44
+ if filename.endswith(".txt"):
45
+ filepath = os.path.join(knowledge_base_dir, filename)
46
+ try:
47
+ with open(filepath, "r", encoding="utf-8") as f:
48
+ content = f.read()
49
+ if any(keyword in content.lower() for keyword in query_keywords):
50
+ relevant_text.append(content)
51
+ except Exception as e:
52
+ print(f"Dateilesefehler: {e}")
53
+
54
+ return "\n---\n".join(relevant_text) if relevant_text else ""
55
 
56
  # --- API-Endpunkt für den Chat ---
57
  @app.route('/chat', methods=['POST'])
 
60
  if not user_input:
61
  return jsonify({"error": "Kein Text übermittelt"}), 400
62
 
 
 
 
 
 
 
63
  try:
64
+ # RAG-Phase
65
+ kb_info = retrieve_info_from_kb(user_input)
66
+
67
+ # Prompt-Konstruktion
68
+ prompt_parts = [
69
+ f"Nutzeranfrage: {user_input}",
70
+ f"Kontext aus Wissensdatenbank:\n{kb_info}" if kb_info else "Kein relevanter Kontext gefunden",
71
+ "Antworte im unterstützenden Moejra-Stil. Bei Unsicherheiten recherchiere im Web."
72
+ ]
73
+
74
+ # Gemini-Abfrage
75
  response = chat.send_message("\n".join(prompt_parts))
76
+
77
+ # Antwortverarbeitung
78
+ response_text = ""
79
+ image_data = []
80
+
81
+ for part in response.candidates[0].content.parts:
82
+ if part.text:
83
+ response_text += part.text
84
+ if hasattr(part, 'image'):
85
+ img_data = part.image.data
86
+ if hasattr(img_data, 'mime_type') and hasattr(img_data, 'data'):
87
+ image_data.append({
88
+ "mime": img_data.mime_type,
89
+ "data": f"data:{img_data.mime_type};base64,{img_data.data}"
90
+ })
91
+
92
  return jsonify({
93
+ "text": response_text.strip(),
94
+ "images": image_data
95
  })
96
+
97
  except Exception as e:
98
+ print(f"API-Fehler: {str(e)}")
99
  return jsonify({
100
+ "text": "😞 Entschuldige, ein unerwarteter Fehler ist aufgetreten. Bitte versuche es später erneut.",
101
+ "images": []
102
  }), 500
103
 
104
  if __name__ == '__main__':