Spaces:
Running
Running
Update src/services/ai_modal_engine.py
Browse files- src/services/ai_modal_engine.py +20 -44
src/services/ai_modal_engine.py
CHANGED
|
@@ -1,49 +1,23 @@
|
|
| 1 |
import google.generativeai as genai
|
| 2 |
-
import csv
|
| 3 |
-
import io
|
| 4 |
import traceback
|
| 5 |
from ..config import db, get_user_keys
|
| 6 |
|
| 7 |
class AiModalEngine:
|
| 8 |
-
@staticmethod
|
| 9 |
-
def context_to_csv(trades):
|
| 10 |
-
"""Serializes trade list to token-efficient CSV format."""
|
| 11 |
-
if not trades or not isinstance(trades, list):
|
| 12 |
-
return str(trades)
|
| 13 |
-
|
| 14 |
-
output = io.StringIO()
|
| 15 |
-
if len(trades) > 0:
|
| 16 |
-
# Extract headers from first record
|
| 17 |
-
keys = trades[0].keys()
|
| 18 |
-
writer = csv.DictWriter(output, fieldnames=keys)
|
| 19 |
-
writer.writeheader()
|
| 20 |
-
writer.writerows(trades)
|
| 21 |
-
|
| 22 |
-
return output.getvalue()
|
| 23 |
-
|
| 24 |
@staticmethod
|
| 25 |
def initialize_firebase_session(uid, context):
|
| 26 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
try:
|
| 28 |
keys = get_user_keys(uid)
|
| 29 |
api_key = keys.get('gemini_key')
|
| 30 |
if not api_key:
|
| 31 |
return "Error: No API Key found in Settings."
|
| 32 |
|
| 33 |
-
genai.configure(api_key=api_key)
|
| 34 |
-
|
| 35 |
-
# Compression threshold: 20k characters
|
| 36 |
-
threshold = 20000
|
| 37 |
-
is_large_data = len(str(context)) > threshold
|
| 38 |
-
|
| 39 |
-
# Toggle data format based on payload size
|
| 40 |
-
if is_large_data and isinstance(context, list):
|
| 41 |
-
clean_context = AiModalEngine.context_to_csv(context)
|
| 42 |
-
data_label = "STRUCTURED CSV DATA"
|
| 43 |
-
else:
|
| 44 |
-
clean_context = str(context)
|
| 45 |
-
data_label = "FILTERED TRADE LOGS"
|
| 46 |
-
|
| 47 |
instruction = f"""
|
| 48 |
PARSONA:
|
| 49 |
You are the QuantVAT AI Trading Journal Auditor, a senior Risk Manager and Trading Psychologist with 50 years trading experience like a Market Wizard.
|
|
@@ -59,21 +33,21 @@ class AiModalEngine:
|
|
| 59 |
4. NO TABLES: Use bullet points only.
|
| 60 |
5. INTERACTION: End with a provocative question about a specific trade.
|
| 61 |
|
| 62 |
-
|
| 63 |
-
{
|
| 64 |
"""
|
| 65 |
|
| 66 |
-
# Initialize model with embedded system instructions
|
| 67 |
model = genai.GenerativeModel(
|
| 68 |
-
model_name='gemini-flash-
|
| 69 |
system_instruction=instruction
|
| 70 |
)
|
| 71 |
|
| 72 |
chat = model.start_chat(history=[])
|
| 73 |
-
|
|
|
|
| 74 |
response = chat.send_message(prompt)
|
| 75 |
|
| 76 |
-
#
|
| 77 |
history = [
|
| 78 |
{"role": "user", "parts": [prompt]},
|
| 79 |
{"role": "model", "parts": [response.text]}
|
|
@@ -87,7 +61,9 @@ class AiModalEngine:
|
|
| 87 |
|
| 88 |
@staticmethod
|
| 89 |
def continue_firebase_chat(uid, prompt):
|
| 90 |
-
"""
|
|
|
|
|
|
|
| 91 |
try:
|
| 92 |
user_doc = db.collection('users').document(uid).get()
|
| 93 |
data = user_doc.to_dict() if user_doc.exists else {}
|
|
@@ -99,16 +75,16 @@ class AiModalEngine:
|
|
| 99 |
|
| 100 |
genai.configure(api_key=api_key)
|
| 101 |
|
| 102 |
-
#
|
| 103 |
model = genai.GenerativeModel(
|
| 104 |
-
model_name='gemini-flash-
|
| 105 |
-
system_instruction="PARSONA: QuantVAT AI Trading Journal Auditor. Senior Risk Manager
|
| 106 |
)
|
| 107 |
|
| 108 |
chat = model.start_chat(history=history)
|
| 109 |
response = chat.send_message(prompt)
|
| 110 |
|
| 111 |
-
#
|
| 112 |
history.append({"role": "user", "parts": [prompt]})
|
| 113 |
history.append({"role": "model", "parts": [response.text]})
|
| 114 |
db.collection('users').document(uid).set({"ai_history": history}, merge=True)
|
|
|
|
| 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.
|
|
|
|
| 33 |
4. NO TABLES: Use bullet points only.
|
| 34 |
5. INTERACTION: End with a provocative question about a specific trade.
|
| 35 |
|
| 36 |
+
TRADING LEDGER (CSV FORMAT):
|
| 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]}
|
|
|
|
| 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 {}
|
|
|
|
| 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)
|