Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,36 +1,168 @@
|
|
| 1 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from huggingface_hub import hf_hub_download
|
| 3 |
from llama_cpp import Llama
|
| 4 |
-
import
|
|
|
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
model_path = hf_hub_download(
|
| 9 |
repo_id="Anoopsingh53/nexai-v1",
|
| 10 |
filename="nexai-v1-Q4_K_M.gguf"
|
| 11 |
)
|
| 12 |
|
| 13 |
-
# 2. Initialize Llama model
|
| 14 |
llm = Llama(
|
| 15 |
model_path=model_path,
|
| 16 |
-
n_ctx=
|
| 17 |
n_threads=4
|
| 18 |
)
|
| 19 |
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
#
|
|
|
|
|
|
|
| 23 |
def predict(message, history):
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
for user_msg, bot_msg in history:
|
|
|
|
| 26 |
messages.append({"role": "user", "content": user_msg})
|
| 27 |
-
messages.append({"role": "assistant", "content":
|
| 28 |
messages.append({"role": "user", "content": message})
|
| 29 |
|
| 30 |
response = llm.create_chat_completion(
|
| 31 |
messages=messages,
|
| 32 |
max_tokens=512,
|
| 33 |
-
temperature=0.
|
| 34 |
stream=True
|
| 35 |
)
|
| 36 |
|
|
@@ -41,12 +173,19 @@ def predict(message, history):
|
|
| 41 |
partial_text += delta["content"]
|
| 42 |
yield partial_text
|
| 43 |
|
| 44 |
-
#
|
|
|
|
|
|
|
| 45 |
demo = gr.ChatInterface(
|
| 46 |
fn=predict,
|
| 47 |
-
title="π NexAI-v1
|
| 48 |
-
description="
|
| 49 |
-
examples=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
)
|
| 51 |
|
| 52 |
if __name__ == "__main__":
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import json
|
| 3 |
+
import requests
|
| 4 |
+
import urllib.request
|
| 5 |
+
import urllib.parse
|
| 6 |
+
import xml.etree.ElementTree as ET
|
| 7 |
+
import re
|
| 8 |
from huggingface_hub import hf_hub_download
|
| 9 |
from llama_cpp import Llama
|
| 10 |
+
from tavily import TavilyClient
|
| 11 |
+
from duckduckgo_search import DDGS
|
| 12 |
|
| 13 |
+
# ==============================================================================
|
| 14 |
+
# 1. API KEYS CONFIGURATION
|
| 15 |
+
# ==============================================================================
|
| 16 |
+
TAVILY_API_KEY = "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"
|
| 17 |
+
SERPER_API_KEY = "934f29a2bff6c477732baebb7e208e57d43303e7"
|
| 18 |
+
|
| 19 |
+
# Initialize Tavily
|
| 20 |
+
try:
|
| 21 |
+
tavily_client = TavilyClient(api_key=TAVILY_API_KEY)
|
| 22 |
+
except Exception:
|
| 23 |
+
tavily_client = None
|
| 24 |
+
|
| 25 |
+
# ==============================================================================
|
| 26 |
+
# 2. 4-TIER MULTI-SEARCH FALLBACK ENGINE
|
| 27 |
+
# ==============================================================================
|
| 28 |
+
def search_tier1_tavily(query: str):
|
| 29 |
+
"""Tier 1: Tavily AI-Powered Fact Extraction"""
|
| 30 |
+
if not tavily_client:
|
| 31 |
+
raise Exception("Tavily client not ready")
|
| 32 |
+
response = tavily_client.search(query=query, search_depth="basic", max_results=3)
|
| 33 |
+
snippets = []
|
| 34 |
+
for r in response.get("results", []):
|
| 35 |
+
snippets.append(f"β’ {r.get('title')}: {r.get('content')}")
|
| 36 |
+
if snippets:
|
| 37 |
+
return "[Source: Tavily AI Search]\n" + "\n".join(snippets)
|
| 38 |
+
raise Exception("Tavily returned 0 results")
|
| 39 |
+
|
| 40 |
+
def search_tier2_serper_google(query: str):
|
| 41 |
+
"""Tier 2: Serper.dev Official Google Search"""
|
| 42 |
+
url = "https://google.serper.dev/search"
|
| 43 |
+
headers = {
|
| 44 |
+
"X-API-KEY": SERPER_API_KEY,
|
| 45 |
+
"Content-Type": "application/json"
|
| 46 |
+
}
|
| 47 |
+
payload = json.dumps({"q": query, "gl": "in", "hl": "hi"})
|
| 48 |
+
res = requests.post(url, headers=headers, data=payload, timeout=6)
|
| 49 |
+
if res.status_code == 200:
|
| 50 |
+
data = res.json()
|
| 51 |
+
snippets = []
|
| 52 |
+
if "knowledgeGraph" in data:
|
| 53 |
+
kg = data["knowledgeGraph"]
|
| 54 |
+
snippets.append(f"β’ Fact: {kg.get('title')} - {kg.get('description', '')}")
|
| 55 |
+
for item in data.get("organic", [])[:3]:
|
| 56 |
+
snippets.append(f"β’ {item.get('title')}: {item.get('snippet')}")
|
| 57 |
+
if snippets:
|
| 58 |
+
return "[Source: Google Serper]\n" + "\n".join(snippets)
|
| 59 |
+
raise Exception(f"Serper error status {res.status_code}")
|
| 60 |
+
|
| 61 |
+
def search_tier3_duckduckgo(query: str):
|
| 62 |
+
"""Tier 3: DuckDuckGo Fallback"""
|
| 63 |
+
snippets = []
|
| 64 |
+
with DDGS() as ddgs:
|
| 65 |
+
for r in ddgs.text(query, max_results=3):
|
| 66 |
+
snippets.append(f"β’ {r.get('title')}: {r.get('body')}")
|
| 67 |
+
if snippets:
|
| 68 |
+
return "[Source: DuckDuckGo]\n" + "\n".join(snippets)
|
| 69 |
+
raise Exception("DuckDuckGo failed")
|
| 70 |
+
|
| 71 |
+
def search_tier4_google_news_rss(query: str):
|
| 72 |
+
"""Tier 4: Unlimited Free Google News RSS Feed (No API Key Required)"""
|
| 73 |
+
encoded_query = urllib.parse.quote(query)
|
| 74 |
+
url = f"https://news.google.com/rss/search?q={encoded_query}&hl=en-IN&gl=IN&ceid=IN:en"
|
| 75 |
+
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
| 76 |
+
with urllib.request.urlopen(req, timeout=6) as response:
|
| 77 |
+
xml_data = response.read()
|
| 78 |
+
root = ET.fromstring(xml_data)
|
| 79 |
+
items = []
|
| 80 |
+
for item in root.findall("./channel/item")[:4]:
|
| 81 |
+
title = item.find("title").text
|
| 82 |
+
pub_date = item.find("pubDate").text if item.find("pubDate") is not None else ""
|
| 83 |
+
items.append(f"β’ [{pub_date}] {title}")
|
| 84 |
+
if items:
|
| 85 |
+
return "[Source: Google News Live RSS]\n" + "\n".join(items)
|
| 86 |
+
raise Exception("Google News RSS failed")
|
| 87 |
+
|
| 88 |
+
def multi_tier_search(query: str) -> str:
|
| 89 |
+
"""Cascade through Tier 1 -> Tier 2 -> Tier 3 -> Tier 4"""
|
| 90 |
+
# 1. Try Tavily
|
| 91 |
+
try:
|
| 92 |
+
return search_tier1_tavily(query)
|
| 93 |
+
except Exception as e1:
|
| 94 |
+
print(f"Tier 1 (Tavily) failed: {e1}")
|
| 95 |
+
|
| 96 |
+
# 2. Try Serper (Google)
|
| 97 |
+
try:
|
| 98 |
+
return search_tier2_serper_google(query)
|
| 99 |
+
except Exception as e2:
|
| 100 |
+
print(f"Tier 2 (Serper) failed: {e2}")
|
| 101 |
+
|
| 102 |
+
# 3. Try DuckDuckGo
|
| 103 |
+
try:
|
| 104 |
+
return search_tier3_duckduckgo(query)
|
| 105 |
+
except Exception as e3:
|
| 106 |
+
print(f"Tier 3 (DuckDuckGo) failed: {e3}")
|
| 107 |
+
|
| 108 |
+
# 4. Try Free Google News RSS
|
| 109 |
+
try:
|
| 110 |
+
return search_tier4_google_news_rss(query)
|
| 111 |
+
except Exception as e4:
|
| 112 |
+
print(f"Tier 4 (Google News RSS) failed: {e4}")
|
| 113 |
+
|
| 114 |
+
return "Real-time search temporarily unavailable."
|
| 115 |
+
|
| 116 |
+
# ==============================================================================
|
| 117 |
+
# 3. LOAD NEXAI GGUF MODEL
|
| 118 |
+
# ==============================================================================
|
| 119 |
+
print("π₯ Loading NexAI-v1 GGUF Model...")
|
| 120 |
model_path = hf_hub_download(
|
| 121 |
repo_id="Anoopsingh53/nexai-v1",
|
| 122 |
filename="nexai-v1-Q4_K_M.gguf"
|
| 123 |
)
|
| 124 |
|
|
|
|
| 125 |
llm = Llama(
|
| 126 |
model_path=model_path,
|
| 127 |
+
n_ctx=3072,
|
| 128 |
n_threads=4
|
| 129 |
)
|
| 130 |
|
| 131 |
+
def is_search_needed(query: str) -> bool:
|
| 132 |
+
"""Auto-detect if query asks for live/real-time information"""
|
| 133 |
+
keywords = [
|
| 134 |
+
"today", "latest", "aaj", "current", "news", "price", "weather",
|
| 135 |
+
"match", "score", "update", "2026", "2025", "who won", "koun",
|
| 136 |
+
"stock", "status", "recent", "kab", "kya chal raha", "taaza"
|
| 137 |
+
]
|
| 138 |
+
q = query.lower()
|
| 139 |
+
return any(kw in q for kw in keywords)
|
| 140 |
|
| 141 |
+
# ==============================================================================
|
| 142 |
+
# 4. CHAT GENERATION WITH REAL-TIME CONTEXT
|
| 143 |
+
# ==============================================================================
|
| 144 |
def predict(message, history):
|
| 145 |
+
live_context = ""
|
| 146 |
+
|
| 147 |
+
if is_search_needed(message):
|
| 148 |
+
yield "π *Searching live web with multi-tier fallback (Tavily / Serper / Google)...*\n"
|
| 149 |
+
search_data = multi_tier_search(message)
|
| 150 |
+
live_context = f"\n\n[REAL-TIME LIVE DATA]:\n{search_data}\n\nBased on the above real-time data, provide a direct, accurate answer."
|
| 151 |
+
|
| 152 |
+
system_prompt = f"""You are NexAI, an intelligent, real-time AI assistant.
|
| 153 |
+
Answer politely and clearly in Hindi or English using provided real-time data.{live_context}"""
|
| 154 |
+
|
| 155 |
+
messages = [{"role": "system", "content": system_prompt}]
|
| 156 |
for user_msg, bot_msg in history:
|
| 157 |
+
clean_bot = re.sub(r"π \*.*?\*\n", "", bot_msg)
|
| 158 |
messages.append({"role": "user", "content": user_msg})
|
| 159 |
+
messages.append({"role": "assistant", "content": clean_bot})
|
| 160 |
messages.append({"role": "user", "content": message})
|
| 161 |
|
| 162 |
response = llm.create_chat_completion(
|
| 163 |
messages=messages,
|
| 164 |
max_tokens=512,
|
| 165 |
+
temperature=0.6,
|
| 166 |
stream=True
|
| 167 |
)
|
| 168 |
|
|
|
|
| 173 |
partial_text += delta["content"]
|
| 174 |
yield partial_text
|
| 175 |
|
| 176 |
+
# ==============================================================================
|
| 177 |
+
# 5. GRADIO UI
|
| 178 |
+
# ==============================================================================
|
| 179 |
demo = gr.ChatInterface(
|
| 180 |
fn=predict,
|
| 181 |
+
title="π NexAI-v1 β Real-Time AI Agent",
|
| 182 |
+
description="Powered by NexAI 3B GGUF + Multi-Tier Search (Tavily β Serper Google β DuckDuckGo β Google News RSS).",
|
| 183 |
+
examples=[
|
| 184 |
+
"Tell me today's latest tech & AI news",
|
| 185 |
+
"What is the current status of ISRO Gaganyaan mission?",
|
| 186 |
+
"Who is the current Prime Minister of India?",
|
| 187 |
+
"Explain Neural Networks in simple Hinglish"
|
| 188 |
+
],
|
| 189 |
)
|
| 190 |
|
| 191 |
if __name__ == "__main__":
|