File size: 8,695 Bytes
1796b3c 9f2a4d0 1796b3c 291e6b7 1796b3c 291e6b7 1796b3c 291e6b7 1796b3c 291e6b7 1796b3c 291e6b7 1796b3c 291e6b7 1796b3c | 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from sentence_transformers import SentenceTransformer
from groq import Groq
from firebase_admin import credentials, firestore
from google.cloud.firestore_v1.base_query import FieldFilter
import firebase_admin
import numpy as np
import os
import json
from dotenv import load_dotenv
import uvicorn
# π₯ LOAD ENV
load_dotenv()
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
# π₯ FIREBASE INIT
firebase_creds = os.getenv("FIREBASE_CREDENTIALS")
if firebase_creds:
# Running on Hugging Face (Load from Secret)
cred_dict = json.loads(firebase_creds)
cred = credentials.Certificate(cred_dict)
else:
# Running locally (Load from file)
cred = credentials.Certificate("serviceAccountKey.json")
firebase_admin.initialize_app(cred)
db = firestore.client()
# π₯ GROQ
groq_client = Groq(api_key=GROQ_API_KEY)
# π₯ EMBEDDING MODEL
model = SentenceTransformer('all-MiniLM-L6-v2')
# π₯ FASTAPI
app = FastAPI()
# π₯ CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# π₯ INTENT CLASSIFIER
def classify_intent(question: str):
q = question.lower().strip()
greetings = ["hi", "hello", "hey", "hii", "yo"]
if any(q == word or q.startswith(word) for word in greetings):
return "greeting"
decision_keywords = [
"should i",
"what should i do",
"choose",
"decision",
"which is better",
"do i",
"whether i should",
"i should",
"can i",
"whether"
]
if any(word in q for word in decision_keywords):
return "decision"
return "irrelevant"
class DecisionEngine:
# π₯ EMBEDDING
def embed(self, text):
try:
return model.encode(text).tolist()
except Exception as e:
print("Embedding Error:", e)
return None
# π₯ GET PERSONALITY
def get_personality(self, user_id):
try:
doc = db.collection("personality_profiles") \
.document(user_id) \
.get()
if doc.exists:
data = doc.to_dict()
return data.get("trait_scores", {})
return {}
except Exception as e:
print("Personality Error:", e)
return {}
# π₯ GET MEMORY (RAG)
def get_memory(self, user_id, question):
try:
query_vec = self.embed(question)
if query_vec is None:
return ""
query_vec = np.array(query_vec)
docs = db.collection("chat_history") \
.where(filter=FieldFilter("userId", "==", user_id)) \
.stream()
data = [doc.to_dict() for doc in docs]
if not data:
return ""
scored = []
for row in data:
emb = row.get("embedding")
if emb is None:
continue
emb = np.array(emb, dtype=float)
similarity = np.dot(query_vec, emb) / (
np.linalg.norm(query_vec) * np.linalg.norm(emb)
)
scored.append((similarity, row))
if not scored:
return ""
scored.sort(reverse=True, key=lambda x: x[0])
top = scored[:3]
memory = ""
for _, row in top:
memory += f"{row['message']} β {row['response']}\n"
return memory
except Exception as e:
print("Memory Error:", e)
return ""
# π₯ GENERATE AI RESPONSE
def generate(self, question, personality, memory):
prompt = f"""
You are a strict decision-making AI.
Your primary source for making a decision MUST be the User personality:
{personality}
You should lightly consider, but not strictly rely on Past behavior:
{memory}
Question:
{question}
Rules:
- Give ONLY ONE decision
- No "it depends"
- No multiple options
- Be confident
- Base your decision primarily on the user's personality traits
Format:
Decision:
Reason:
"""
try:
completion = groq_client.chat.completions.create(
model="llama-3.1-8b-instant",
messages=[
{
"role": "system",
"content": "You are a decisive AI."
},
{
"role": "user",
"content": prompt
}
],
temperature=0.3,
max_tokens=512,
top_p=1,
stream=False
)
return completion.choices[0].message.content
except Exception as e:
print("Groq Error:", e)
return self.generate_fallback_openrouter(prompt)
def generate_fallback_openrouter(self, prompt):
try:
import urllib.request
openrouter_api_key = os.getenv("OPENROUTER_API_KEY")
if not openrouter_api_key:
return "AI failed: Groq error and no OpenRouter API key provided."
url = "https://openrouter.ai/api/v1/chat/completions"
headers = {
"Authorization": f"Bearer {openrouter_api_key}",
"Content-Type": "application/json",
}
data = {
"model": "mistralai/mistral-7b-instruct:free",
"messages": [
{"role": "system", "content": "You are a decisive AI."},
{"role": "user", "content": prompt}
],
"temperature": 0.3,
"max_tokens": 512,
"top_p": 1
}
req = urllib.request.Request(url, headers=headers, data=json.dumps(data).encode('utf-8'))
with urllib.request.urlopen(req) as response:
result = json.loads(response.read().decode('utf-8'))
return result['choices'][0]['message']['content']
except Exception as fallback_error:
print("OpenRouter Fallback Error:", fallback_error)
return "AI failed on both primary and fallback APIs."
# π₯ SAVE CHAT
def save_chat(self, user_id, question, response):
try:
embedding = self.embed(question)
db.collection("chat_history").add({
"userId": user_id,
"message": question,
"response": response,
"embedding": embedding
})
except Exception as e:
print("Save Error:", e)
# π₯ ENGINE
engine = DecisionEngine()
# π₯ MAIN API
@app.post("/ask")
def ask(data: dict):
try:
user_id = data.get("user_id")
question = data.get("question")
if not user_id or not question:
return {
"response": "Invalid input"
}
# π₯ INTENT CHECK
intent = classify_intent(question)
if intent == "greeting":
return {
"response": "Hello π Tell me what decision you want help with today."
}
if intent == "irrelevant":
return {
"response": "I only help with decision-making. Please ask something like 'Should I do this or that?'"
}
# π₯ GET USER DATA
personality = engine.get_personality(user_id)
memory = engine.get_memory(user_id, question)
# π₯ GENERATE RESPONSE
response = engine.generate(
question,
personality,
memory
)
# π₯ SAVE CHAT
engine.save_chat(
user_id,
question,
response
)
return {
"response": response
}
except Exception as e:
print("Server Error:", e)
return {
"response": str(e)
}
# π₯ HEALTH CHECK
@app.get("/")
def home():
return {
"message": "Thinkless AI Backend Running with Firebase π"
}
# π₯ RUN SERVER
if __name__ == "__main__":
uvicorn.run(
"app:app",
host="0.0.0.0",
port=7860,
reload=True
) |