Spaces:
Running
Running
Upload ai_modal_engine.py
Browse files- src/services/ai_modal_engine.py +119 -0
src/services/ai_modal_engine.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Bootstraps Auditor session and persists initial state to Firestore."""
|
| 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.
|
| 50 |
+
Speak with veteran authority. Tone is blunt but constructive.
|
| 51 |
+
|
| 52 |
+
MANDATE:
|
| 53 |
+
1. Analyze the 'WHY' behind execution based on the provided logs.
|
| 54 |
+
2. STRUCTURE:
|
| 55 |
+
- ## 📊 OVERVIEW: 2-sentence performance reality check.
|
| 56 |
+
- ## 🚩 RED FLAGS: Top 2 execution errors (FOMO, sizing, fear, etc).
|
| 57 |
+
- ## 💡 THE REMEDY: One specific, actionable rule for the next session.
|
| 58 |
+
3. FORMAT: Use bold text for emphasis.
|
| 59 |
+
4. NO TABLES: Use bullet points only.
|
| 60 |
+
5. INTERACTION: End with a provocative question about a specific trade.
|
| 61 |
+
|
| 62 |
+
{data_label}:
|
| 63 |
+
{clean_context}
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
# Initialize model with embedded system instructions
|
| 67 |
+
model = genai.GenerativeModel(
|
| 68 |
+
model_name='gemini-flash-latest',
|
| 69 |
+
system_instruction=instruction
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
chat = model.start_chat(history=[])
|
| 73 |
+
prompt = "Analyze my execution performance. End with: 'I have analyzed your data. Ready for audit.'"
|
| 74 |
+
response = chat.send_message(prompt)
|
| 75 |
+
|
| 76 |
+
# Persist turn history to database
|
| 77 |
+
history = [
|
| 78 |
+
{"role": "user", "parts": [prompt]},
|
| 79 |
+
{"role": "model", "parts": [response.text]}
|
| 80 |
+
]
|
| 81 |
+
db.collection('users').document(uid).set({"ai_history": history}, merge=True)
|
| 82 |
+
|
| 83 |
+
return response.text
|
| 84 |
+
except Exception as e:
|
| 85 |
+
print(f"AI Init Error: {traceback.format_exc()}")
|
| 86 |
+
return f"System Error: {str(e)}"
|
| 87 |
+
|
| 88 |
+
@staticmethod
|
| 89 |
+
def continue_firebase_chat(uid, prompt):
|
| 90 |
+
"""Resumes active session using state retrieved from Firestore."""
|
| 91 |
+
try:
|
| 92 |
+
user_doc = db.collection('users').document(uid).get()
|
| 93 |
+
data = user_doc.to_dict() if user_doc.exists else {}
|
| 94 |
+
history = data.get("ai_history", [])
|
| 95 |
+
|
| 96 |
+
api_key = get_user_keys(uid).get('gemini_key')
|
| 97 |
+
if not api_key:
|
| 98 |
+
return "Error: API Key missing."
|
| 99 |
+
|
| 100 |
+
genai.configure(api_key=api_key)
|
| 101 |
+
|
| 102 |
+
# Re-apply persona constraints for session continuity
|
| 103 |
+
model = genai.GenerativeModel(
|
| 104 |
+
model_name='gemini-flash-latest',
|
| 105 |
+
system_instruction="PARSONA: QuantVAT AI Trading Journal Auditor. Senior Risk Manager and Trading Psychologist with 50 years trading experience like a Market Wizard."
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
chat = model.start_chat(history=history)
|
| 109 |
+
response = chat.send_message(prompt)
|
| 110 |
+
|
| 111 |
+
# Sync new turn to database
|
| 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)
|
| 115 |
+
|
| 116 |
+
return response.text
|
| 117 |
+
except Exception as e:
|
| 118 |
+
print(f"AI Chat Error: {traceback.format_exc()}")
|
| 119 |
+
return f"Auditor Error: {str(e)}"
|