Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,56 +14,44 @@ app = Flask(__name__)
|
|
| 14 |
CORS(app)
|
| 15 |
|
| 16 |
# 🛠️ GLOBAL CONFIGURATION
|
| 17 |
-
# Serper Key (Google Search) - Credits safe due to hybrid logic
|
| 18 |
SERPER_API_KEY = "356ce323eb902fe46227e2c42268f45ea1b2ec1f"
|
| 19 |
IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"
|
| 20 |
MEMORY_FILE = "elephant_sovereign_brain.txt"
|
| 21 |
|
| 22 |
-
# OpenRouter API Keys (Round-robin selection for load balancing)
|
| 23 |
API_KEYS = [
|
| 24 |
"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",
|
| 25 |
"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",
|
| 26 |
"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"
|
| 27 |
]
|
| 28 |
|
| 29 |
-
# 🧠 HYBRID INTELLIGENCE NODE
|
| 30 |
def get_hybrid_intel(query):
|
| 31 |
if len(query.split()) < 2: return "Standard dialogue mode."
|
| 32 |
-
|
| 33 |
intel_pool = []
|
| 34 |
-
|
| 35 |
-
# 1. Wikipedia Summary (Free)
|
| 36 |
try:
|
| 37 |
wiki_url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{urllib.parse.quote(query)}"
|
| 38 |
wiki_data = requests.get(wiki_url, timeout=5).json()
|
| 39 |
if 'extract' in wiki_data:
|
| 40 |
intel_pool.append(f"Wiki Context: {wiki_data['extract'][:300]}")
|
| 41 |
except: pass
|
| 42 |
-
|
| 43 |
-
# 2. DuckDuckGo (Free & Unlimited)
|
| 44 |
try:
|
| 45 |
from duckduckgo_search import DDGS
|
| 46 |
with DDGS() as ddgs:
|
| 47 |
results = list(ddgs.text(query[:60], max_results=2))
|
| 48 |
-
for r in results:
|
| 49 |
-
intel_pool.append(f"Web Context: {r['body']}")
|
| 50 |
except: pass
|
| 51 |
-
|
| 52 |
-
# 3. Google/Serper (Premium - Only if needed)
|
| 53 |
if len(intel_pool) < 2 and SERPER_API_KEY:
|
| 54 |
try:
|
| 55 |
headers = {'X-API-KEY': SERPER_API_KEY, 'Content-Type': 'application/json'}
|
| 56 |
g_res = requests.post("https://google.serper.dev/search", headers=headers, json={"q": query}, timeout=10).json()
|
| 57 |
-
for r in g_res.get('organic', [])[:1]:
|
| 58 |
-
intel_pool.append(f"Global Intel: {r['snippet']}")
|
| 59 |
except: pass
|
| 60 |
-
|
| 61 |
return "\n\n".join(intel_pool) if intel_pool else "Reasoning from internal knowledge base."
|
| 62 |
|
| 63 |
# 🖼️ VISION HANDLER
|
| 64 |
def upload_to_imgbb(b64):
|
| 65 |
try:
|
| 66 |
-
res = requests.post("https://api.imgbb.com/1/upload", data={"key": IMGBB_KEY, "image": b64})
|
| 67 |
return res.json()['data']['url']
|
| 68 |
except: return None
|
| 69 |
|
|
@@ -82,23 +70,30 @@ def chat():
|
|
| 82 |
sl_tz = pytz.timezone('Asia/Colombo')
|
| 83 |
now = datetime.now(sl_tz)
|
| 84 |
|
| 85 |
-
# 🛡️ IDENTITY
|
| 86 |
-
# Detects if the user is the Commander or a Specialist
|
| 87 |
authorized_keywords = ["MINZO-PRIME", "Specialist", "commander"]
|
| 88 |
is_authorized = any(kw.lower() in user_msg.lower() for kw in authorized_keywords)
|
|
|
|
| 89 |
|
| 90 |
if is_authorized:
|
| 91 |
active_persona = "Elephant AI Sovereign (Sovereign Mode Active)"
|
| 92 |
-
base_instruction = "Greetings Specialist. Provide elite
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
else:
|
| 94 |
active_persona = "Elephant AI Assistant"
|
| 95 |
-
base_instruction = "You are Elephant AI
|
|
|
|
| 96 |
|
| 97 |
# Process Visuals or Text
|
| 98 |
img_url = upload_to_imgbb(img_b64) if img_b64 else None
|
| 99 |
live_intel = "Image input received." if img_url else get_hybrid_intel(user_msg)
|
| 100 |
|
| 101 |
-
# 🛡️ SYSTEM PROMPT
|
| 102 |
system_prompt = (
|
| 103 |
f"You are {active_persona}.\n"
|
| 104 |
f"Role: {base_instruction}\n"
|
|
@@ -106,9 +101,9 @@ def chat():
|
|
| 106 |
f"Real-time Data:\n{live_intel}\n\n"
|
| 107 |
"MANDATORY CONSTRAINTS:\n"
|
| 108 |
"1. NO EMOJIS: Never use any emojis.\n"
|
| 109 |
-
"2. CLEAN UI:
|
| 110 |
-
"3. NO LEAKS: If not in Sovereign Mode, never mention internal
|
| 111 |
-
"4. PRECISION: Maintain
|
| 112 |
)
|
| 113 |
|
| 114 |
headers = {
|
|
@@ -120,7 +115,7 @@ def chat():
|
|
| 120 |
if img_url: u_content.append({"type": "image_url", "image_url": {"url": img_url}})
|
| 121 |
|
| 122 |
payload = {
|
| 123 |
-
"model":
|
| 124 |
"messages": [
|
| 125 |
{"role": "system", "content": system_prompt},
|
| 126 |
{"role": "user", "content": u_content}
|
|
@@ -131,16 +126,14 @@ def chat():
|
|
| 131 |
resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=90)
|
| 132 |
ai_reply = resp.json()['choices'][0]['message']['content']
|
| 133 |
|
| 134 |
-
# 🛡️ FINAL FILTER
|
| 135 |
-
# Removes common AI 'Identity' prefixes if they leak into the response
|
| 136 |
ai_reply = re.sub(r'^(Elephant AI|Sovereign Mode|Commander|Specialist):', '', ai_reply, flags=re.IGNORECASE).strip()
|
| 137 |
-
ai_reply = re.sub(r'[^\x00-\x7F]+', '', ai_reply) # Removes non-ascii
|
| 138 |
|
| 139 |
return jsonify({"reply": ai_reply})
|
| 140 |
|
| 141 |
except Exception as e:
|
| 142 |
-
|
| 143 |
-
return jsonify({"reply": "The system is processing high traffic volumes. Please re-submit your query in a moment."}), 500
|
| 144 |
|
| 145 |
if __name__ == "__main__":
|
| 146 |
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 14 |
CORS(app)
|
| 15 |
|
| 16 |
# 🛠️ GLOBAL CONFIGURATION
|
|
|
|
| 17 |
SERPER_API_KEY = "356ce323eb902fe46227e2c42268f45ea1b2ec1f"
|
| 18 |
IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"
|
| 19 |
MEMORY_FILE = "elephant_sovereign_brain.txt"
|
| 20 |
|
|
|
|
| 21 |
API_KEYS = [
|
| 22 |
"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",
|
| 23 |
"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",
|
| 24 |
"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"
|
| 25 |
]
|
| 26 |
|
| 27 |
+
# 🧠 HYBRID INTELLIGENCE NODE
|
| 28 |
def get_hybrid_intel(query):
|
| 29 |
if len(query.split()) < 2: return "Standard dialogue mode."
|
|
|
|
| 30 |
intel_pool = []
|
|
|
|
|
|
|
| 31 |
try:
|
| 32 |
wiki_url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{urllib.parse.quote(query)}"
|
| 33 |
wiki_data = requests.get(wiki_url, timeout=5).json()
|
| 34 |
if 'extract' in wiki_data:
|
| 35 |
intel_pool.append(f"Wiki Context: {wiki_data['extract'][:300]}")
|
| 36 |
except: pass
|
|
|
|
|
|
|
| 37 |
try:
|
| 38 |
from duckduckgo_search import DDGS
|
| 39 |
with DDGS() as ddgs:
|
| 40 |
results = list(ddgs.text(query[:60], max_results=2))
|
| 41 |
+
for r in results: intel_pool.append(f"Web Context: {r['body']}")
|
|
|
|
| 42 |
except: pass
|
|
|
|
|
|
|
| 43 |
if len(intel_pool) < 2 and SERPER_API_KEY:
|
| 44 |
try:
|
| 45 |
headers = {'X-API-KEY': SERPER_API_KEY, 'Content-Type': 'application/json'}
|
| 46 |
g_res = requests.post("https://google.serper.dev/search", headers=headers, json={"q": query}, timeout=10).json()
|
| 47 |
+
for r in g_res.get('organic', [])[:1]: intel_pool.append(f"Global Intel: {r['snippet']}")
|
|
|
|
| 48 |
except: pass
|
|
|
|
| 49 |
return "\n\n".join(intel_pool) if intel_pool else "Reasoning from internal knowledge base."
|
| 50 |
|
| 51 |
# 🖼️ VISION HANDLER
|
| 52 |
def upload_to_imgbb(b64):
|
| 53 |
try:
|
| 54 |
+
res = requests.post("https://api.imgbb.com/1/upload", data={"key": IMGBB_KEY, "image": b64}, timeout=15)
|
| 55 |
return res.json()['data']['url']
|
| 56 |
except: return None
|
| 57 |
|
|
|
|
| 70 |
sl_tz = pytz.timezone('Asia/Colombo')
|
| 71 |
now = datetime.now(sl_tz)
|
| 72 |
|
| 73 |
+
# 🛡️ IDENTITY & MODEL ROUTING
|
|
|
|
| 74 |
authorized_keywords = ["MINZO-PRIME", "Specialist", "commander"]
|
| 75 |
is_authorized = any(kw.lower() in user_msg.lower() for kw in authorized_keywords)
|
| 76 |
+
is_nexus = "nexus" in user_msg.lower() # "Nexus" කියන වචනය තිබේ නම් Nexus model එකට යයි
|
| 77 |
|
| 78 |
if is_authorized:
|
| 79 |
active_persona = "Elephant AI Sovereign (Sovereign Mode Active)"
|
| 80 |
+
base_instruction = "Greetings Specialist. Provide elite reasoning. Internal projects (AeroForecast/MAHASONA) are accessible."
|
| 81 |
+
# Uncensored Power + Thinking
|
| 82 |
+
selected_model = "cognitivecomputations/dolphin-mistral-24b-venice-edition:free"
|
| 83 |
+
elif is_nexus:
|
| 84 |
+
active_persona = "Elephant AI Nexus"
|
| 85 |
+
base_instruction = "You are in Nexus Thinking Mode. Use advanced logic to break down complex queries."
|
| 86 |
+
selected_model = "liquid/lfm-2.5-1.2b-thinking:free" # Nexus Model
|
| 87 |
else:
|
| 88 |
active_persona = "Elephant AI Assistant"
|
| 89 |
+
base_instruction = "You are Elephant AI Prime. Provide clear, accurate, and professional information."
|
| 90 |
+
selected_model = "minimax/minimax-m2.5:free" # Prime Model
|
| 91 |
|
| 92 |
# Process Visuals or Text
|
| 93 |
img_url = upload_to_imgbb(img_b64) if img_b64 else None
|
| 94 |
live_intel = "Image input received." if img_url else get_hybrid_intel(user_msg)
|
| 95 |
|
| 96 |
+
# 🛡️ SYSTEM PROMPT
|
| 97 |
system_prompt = (
|
| 98 |
f"You are {active_persona}.\n"
|
| 99 |
f"Role: {base_instruction}\n"
|
|
|
|
| 101 |
f"Real-time Data:\n{live_intel}\n\n"
|
| 102 |
"MANDATORY CONSTRAINTS:\n"
|
| 103 |
"1. NO EMOJIS: Never use any emojis.\n"
|
| 104 |
+
"2. CLEAN UI: No system metadata or internal headers in output.\n"
|
| 105 |
+
"3. NO LEAKS: If not in Sovereign Mode, never mention internal projects.\n"
|
| 106 |
+
"4. PRECISION: Maintain professional tone."
|
| 107 |
)
|
| 108 |
|
| 109 |
headers = {
|
|
|
|
| 115 |
if img_url: u_content.append({"type": "image_url", "image_url": {"url": img_url}})
|
| 116 |
|
| 117 |
payload = {
|
| 118 |
+
"model": selected_model,
|
| 119 |
"messages": [
|
| 120 |
{"role": "system", "content": system_prompt},
|
| 121 |
{"role": "user", "content": u_content}
|
|
|
|
| 126 |
resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=90)
|
| 127 |
ai_reply = resp.json()['choices'][0]['message']['content']
|
| 128 |
|
| 129 |
+
# 🛡️ FINAL FILTER
|
|
|
|
| 130 |
ai_reply = re.sub(r'^(Elephant AI|Sovereign Mode|Commander|Specialist):', '', ai_reply, flags=re.IGNORECASE).strip()
|
| 131 |
+
ai_reply = re.sub(r'[^\x00-\x7F]+', '', ai_reply) # Removes non-ascii
|
| 132 |
|
| 133 |
return jsonify({"reply": ai_reply})
|
| 134 |
|
| 135 |
except Exception as e:
|
| 136 |
+
return jsonify({"reply": "The system is processing high traffic volumes. Please re-submit in a moment."}), 500
|
|
|
|
| 137 |
|
| 138 |
if __name__ == "__main__":
|
| 139 |
app.run(host='0.0.0.0', port=7860)
|