Spaces:
Sleeping
Sleeping
File size: 7,071 Bytes
d96a847 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | import os
import numpy as np
from sklearn.decomposition import PCA
from dotenv import load_dotenv
load_dotenv()
import google.generativeai as genai
from core import Force
# Initialise Gemini – reads GOOGLE_API_KEY from .env
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
class MPCBoltzmannBrain:
def __init__(self, temperature=0.5):
self.T = temperature
def calculate_energies(self, forces, ctx_tags, query=None):
energies = []
q_vec = mock_embedding(query) if query else None
for f in forces:
# 1. Base Reward from Intent (Query)
# Higher dot product = More relevant = Lower (Better) Energy
reward = 0.0
if q_vec is not None:
print("🔎 Query embedding (first 5 values):", q_vec[:5])
description = f.name + " " + " ".join(f.tags)
k_vec = mock_embedding(description)
reward = np.dot(q_vec, k_vec) * 5.0 # Scale intent impact
e = 0.0 - reward # Start with negative reward
# 2. Field Logic (Regime Penalties)
# If market is crashing and we have a short force, give it a massive reward
if "crash" in ctx_tags or "bear_trend" in ctx_tags:
if "short" in f.tags:
e -= 20.0
if "momentum" in f.tags:
e += 30.0
# If market is bullish, favor momentum
if "bull_trend" in ctx_tags:
if "momentum" in f.tags:
e -= 15.0
if "short" in f.tags:
e += 25.0
# 🚨 NEW: Systemic Risk Override
if "sector_decay" in ctx_tags:
if "momentum" in f.tags:
e += 10.0
if "defensive" in f.tags or "cash" in f.tags:
e -= 5.0
if "systemic_risk" in ctx_tags:
if "short" in f.tags:
e -= 40.0
if "momentum" in f.tags:
e += 100.0
if "cash_preference" in ctx_tags:
if "cash" in f.tags:
e -= 5.0 # lower energy for any cash‑related force
energies.append(e)
return np.array(energies)
def get_weights(self, energies):
exp_e = np.exp(-energies / self.T)
return exp_e / np.sum(exp_e)
# Initialise Gemini – reads GOOGLE_API_KEY from .env
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
def gemini_embedding(text: str) -> np.ndarray:
"""
Obtain a vector from Google Gemini (model text-embedding-004).
Handles the various response formats the SDK may return.
Returns a NumPy array of length 768 (or the length actually returned).
"""
try:
response = genai.embed_content(
model="text-embedding-004",
content=text,
task_type="retrieval_query"
)
# ---------- Normalise response handling ----------
embedding_vals = None
# 1️⃣ If the response is a dict
if isinstance(response, dict):
# a) { "embedding": { "values": [...] } }
emb = response.get("embedding")
if isinstance(emb, dict):
embedding_vals = emb.get("values")
# b) { "embedding": [...] } (some SDK versions)
elif isinstance(emb, list):
embedding_vals = emb
# 2️⃣ If the response is a list (e.g., [ { "embedding": {...} } ])
elif isinstance(response, list) and response:
first = response[0]
if isinstance(first, dict):
emb = first.get("embedding")
if isinstance(emb, dict):
embedding_vals = emb.get("values")
elif isinstance(emb, list):
embedding_vals = emb
else:
# Assume the list itself is the vector
embedding_vals = first
# 3️⃣ If the response is an object with .embedding.values attribute
else:
embedding_vals = getattr(getattr(response, "embedding", None), "values", None)
# ---------- Validate ----------
if embedding_vals is None:
raise ValueError("Embedding values not found in Gemini response")
# Convert to NumPy array (ensure it's a 1‑D float array)
return np.array(embedding_vals, dtype=float)
except Exception as e:
# Log the problem – this will appear in the server console
print(f"⚠️ Gemini embedding error: {e}")
# Return a zero vector of the expected size (768) so the service stays alive
return np.zeros(768)
# Aliasing for system compatibility
mock_embedding = gemini_embedding
def softmax(x):
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum()
class AgentBrain:
def __init__(self):
self.pca = PCA(n_components=3)
def analyze_dynamics(self, forces: list[Force]):
"""Step 1: Run PCA on the 'V' (Value Space)"""
# Stack returns: shape (N_forces, Time_steps)
if not forces:
return np.array([])
data = np.array([f.returns_history for f in forces])
embeddings = self.pca.fit_transform(data)
return embeddings # These are the "Index" coordinates
def compute_attention(self, query_text: str, forces: list[Force], active_regime_tags: set[str]):
"""Step 2: Calculate Q * K (Attention) with Regime Masking"""
q_vec = mock_embedding(query_text)
scores = []
print(f"\n--- 🧠 BRAIN: Contextual Masking ---")
print(f"Active Regime Tags: {active_regime_tags}")
for f in forces:
# --- The Field Logic (Masking) ---
mask_multiplier = 1.0
# Example Constraint: Don't use Momentum in Chop
if "momentum" in f.tags and "chop" in active_regime_tags:
mask_multiplier = 0.1 # Soft Mask
# Example Constraint: Don't use Aggressive in High Vol
if "aggressive" in f.tags and "high_vol" in active_regime_tags:
mask_multiplier = 0.0 # Hard Mask
# 3. 🚨 NEW RULE: The "Don't Catch a Falling Knife" Patch 🚨
if "bear_trend" in active_regime_tags:
if "momentum" in f.tags or "long" in f.tags:
print(f" 🚫 Blocking {f.name} due to Bear Trend")
mask_multiplier = 0.0 # Hard Block
elif "short" in f.tags or "hedge" in f.tags:
mask_multiplier = 2.0 # Boost Short strategies
# Apply the mask
# Force has no key_description, so we use its name or tags
description = f.name + " " + " ".join(f.tags)
k_vec = mock_embedding(description)
scores.append(np.dot(q_vec, k_vec) * mask_multiplier)
# Softmax to get probabilities (weights)
weights = softmax(np.array(scores))
return weights
|