heisbuba commited on
Commit
faf123b
·
verified ·
1 Parent(s): ea7a6ee

Update src/services/ai_modal_engine.py

Browse files
Files changed (1) hide show
  1. src/services/ai_modal_engine.py +50 -34
src/services/ai_modal_engine.py CHANGED
@@ -1,23 +1,24 @@
1
- import google.generativeai as genai
 
2
  import traceback
3
  from ..config import db, get_user_keys
4
 
5
  class AiModalEngine:
 
 
 
 
6
  @staticmethod
7
  def initialize_firebase_session(uid, context):
8
- """
9
- Bootstraps Auditor session.
10
- Args:
11
- uid: User ID.
12
- context: Raw CSV string provided by frontend.
13
- """
14
  try:
15
  keys = get_user_keys(uid)
16
  api_key = keys.get('gemini_key')
17
  if not api_key:
18
  return "Error: No API Key found in Settings."
19
 
20
- genai.configure(api_key=api_key)
 
 
21
  instruction = f"""
22
  PARSONA:
23
  You are the QuantVAT AI Trading Journal Auditor, a senior Risk Manager and Trading Psychologist with 50 years trading experience like a Market Wizard.
@@ -37,22 +38,25 @@ class AiModalEngine:
37
  {context}
38
  """
39
 
40
- model = genai.GenerativeModel(
41
- model_name='gemini-3-flash-preview',
42
- system_instruction=instruction
43
- )
44
-
45
- chat = model.start_chat(history=[])
46
- # Priming prompt to force immediate analysis
47
  prompt = "Analyze my execution performance based on the CSV data above. End with: 'I have analyzed your data. Ready for audit.'"
48
- response = chat.send_message(prompt)
49
 
50
- # Persist initial state to Firestore for session continuity
 
 
 
 
 
 
 
51
  history = [
52
- {"role": "user", "parts": [prompt]},
53
- {"role": "model", "parts": [response.text]}
54
  ]
55
- db.collection('users').document(uid).set({"ai_history": history}, merge=True)
 
 
 
 
56
 
57
  return response.text
58
  except Exception as e:
@@ -61,32 +65,44 @@ class AiModalEngine:
61
 
62
  @staticmethod
63
  def continue_firebase_chat(uid, prompt):
64
- """
65
- Resumes active session using state retrieved from Firestore.
66
- """
67
  try:
68
  user_doc = db.collection('users').document(uid).get()
69
  data = user_doc.to_dict() if user_doc.exists else {}
70
  history = data.get("ai_history", [])
 
71
 
72
  api_key = get_user_keys(uid).get('gemini_key')
73
  if not api_key:
74
  return "Error: API Key missing."
75
 
76
- genai.configure(api_key=api_key)
77
 
78
- # Re-assert persona for stateless continuity
79
- model = genai.GenerativeModel(
80
- model_name='gemini-3-flash-preview',
81
- system_instruction="PARSONA: QuantVAT AI Trading Journal Auditor. Senior Risk Manager."
82
- )
 
 
 
 
83
 
84
- chat = model.start_chat(history=history)
85
- response = chat.send_message(prompt)
 
 
 
 
 
 
 
 
 
 
86
 
87
- # Append new turn and sync to DB
88
- history.append({"role": "user", "parts": [prompt]})
89
- history.append({"role": "model", "parts": [response.text]})
90
  db.collection('users').document(uid).set({"ai_history": history}, merge=True)
91
 
92
  return response.text
 
1
+ from google import genai
2
+ from google.genai import types
3
  import traceback
4
  from ..config import db, get_user_keys
5
 
6
  class AiModalEngine:
7
+ @staticmethod
8
+ def _get_client(api_key):
9
+ return genai.Client(api_key=api_key)
10
+
11
  @staticmethod
12
  def initialize_firebase_session(uid, context):
 
 
 
 
 
 
13
  try:
14
  keys = get_user_keys(uid)
15
  api_key = keys.get('gemini_key')
16
  if not api_key:
17
  return "Error: No API Key found in Settings."
18
 
19
+ client = AiModalEngine._get_client(api_key)
20
+
21
+ # Parsona
22
  instruction = f"""
23
  PARSONA:
24
  You are the QuantVAT AI Trading Journal Auditor, a senior Risk Manager and Trading Psychologist with 50 years trading experience like a Market Wizard.
 
38
  {context}
39
  """
40
 
 
 
 
 
 
 
 
41
  prompt = "Analyze my execution performance based on the CSV data above. End with: 'I have analyzed your data. Ready for audit.'"
 
42
 
43
+ response = client.models.generate_content(
44
+ model='gemini-3-flash-preview',
45
+ contents=prompt,
46
+ config=types.GenerateContentConfig(
47
+ system_instruction=instruction
48
+ )
49
+ )
50
+
51
  history = [
52
+ {"role": "user", "parts": [{"text": prompt}]},
53
+ {"role": "model", "parts": [{"text": response.text}]}
54
  ]
55
+
56
+ db.collection('users').document(uid).set({
57
+ "ai_history": history,
58
+ "ai_context": context
59
+ }, merge=True)
60
 
61
  return response.text
62
  except Exception as e:
 
65
 
66
  @staticmethod
67
  def continue_firebase_chat(uid, prompt):
 
 
 
68
  try:
69
  user_doc = db.collection('users').document(uid).get()
70
  data = user_doc.to_dict() if user_doc.exists else {}
71
  history = data.get("ai_history", [])
72
+ context = data.get("ai_context", "")
73
 
74
  api_key = get_user_keys(uid).get('gemini_key')
75
  if not api_key:
76
  return "Error: API Key missing."
77
 
78
+ client = AiModalEngine._get_client(api_key)
79
 
80
+ # Robust mapping
81
+ contents = []
82
+ for h in history:
83
+ p = h['parts'][0]
84
+ text_content = p['text'] if isinstance(p, dict) else str(p)
85
+ contents.append(types.Content(
86
+ role=h['role'],
87
+ parts=[types.Part.from_text(text=text_content)]
88
+ ))
89
 
90
+ contents.append(types.Content(role="user", parts=[types.Part.from_text(text=prompt)]))
91
+
92
+ # Re-injects Persona
93
+ instruction = f"PARSONA: QuantVAT AI Trading Journal Auditor. Senior Risk Manager.\nDATA:\n{context}"
94
+
95
+ response = client.models.generate_content(
96
+ model='gemini-3-flash-preview',
97
+ contents=contents,
98
+ config=types.GenerateContentConfig(
99
+ system_instruction=instruction
100
+ )
101
+ )
102
 
103
+ # Append new turn and sync to Firestore
104
+ history.append({"role": "user", "parts": [{"text": prompt}]})
105
+ history.append({"role": "model", "parts": [{"text": response.text}]})
106
  db.collection('users').document(uid).set({"ai_history": history}, merge=True)
107
 
108
  return response.text