Spaces:
Sleeping
Sleeping
Update veryfinal.py
Browse files- veryfinal.py +36 -84
veryfinal.py
CHANGED
|
@@ -82,22 +82,10 @@ try:
|
|
| 82 |
except ImportError:
|
| 83 |
GROQ_AVAILABLE = False
|
| 84 |
|
| 85 |
-
try:
|
| 86 |
-
from langchain_nvidia_ai_endpoints import ChatNVIDIA
|
| 87 |
-
NVIDIA_AVAILABLE = True
|
| 88 |
-
except ImportError:
|
| 89 |
-
NVIDIA_AVAILABLE = False
|
| 90 |
-
|
| 91 |
-
try:
|
| 92 |
-
import google.generativeai as genai
|
| 93 |
-
GEMINI_AVAILABLE = True
|
| 94 |
-
except ImportError:
|
| 95 |
-
GEMINI_AVAILABLE = False
|
| 96 |
-
|
| 97 |
import requests
|
| 98 |
|
| 99 |
def deepseek_generate(prompt, api_key=None):
|
| 100 |
-
"""Call DeepSeek API."""
|
| 101 |
if not api_key:
|
| 102 |
return "DeepSeek API key not provided"
|
| 103 |
|
|
@@ -122,15 +110,28 @@ def deepseek_generate(prompt, api_key=None):
|
|
| 122 |
return f"DeepSeek API error: {e}"
|
| 123 |
|
| 124 |
def baidu_ernie_generate(prompt, api_key=None):
|
| 125 |
-
"""Call Baidu ERNIE API
|
| 126 |
if not api_key:
|
| 127 |
return "Baidu ERNIE API key not provided"
|
| 128 |
|
| 129 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
try:
|
| 131 |
-
|
|
|
|
|
|
|
|
|
|
| 132 |
except Exception as e:
|
| 133 |
-
return f"ERNIE API error: {e}"
|
| 134 |
|
| 135 |
# ---- Graph State ----
|
| 136 |
class EnhancedAgentState(TypedDict):
|
|
@@ -151,38 +152,24 @@ class HybridLangGraphMultiLLMSystem:
|
|
| 151 |
self.graph = self._build_graph()
|
| 152 |
|
| 153 |
def _build_graph(self):
|
| 154 |
-
# Initialize
|
| 155 |
groq_llm = None
|
| 156 |
-
nvidia_llm = None
|
| 157 |
|
| 158 |
if GROQ_AVAILABLE and os.getenv("GROQ_API_KEY"):
|
| 159 |
try:
|
|
|
|
| 160 |
groq_llm = ChatGroq(
|
| 161 |
-
model="
|
| 162 |
temperature=0,
|
| 163 |
api_key=os.getenv("GROQ_API_KEY")
|
| 164 |
)
|
| 165 |
except Exception as e:
|
| 166 |
print(f"Failed to initialize Groq: {e}")
|
| 167 |
-
|
| 168 |
-
if NVIDIA_AVAILABLE and os.getenv("NVIDIA_API_KEY"):
|
| 169 |
-
try:
|
| 170 |
-
nvidia_llm = ChatNVIDIA(
|
| 171 |
-
model="meta/llama3-70b-instruct",
|
| 172 |
-
temperature=0,
|
| 173 |
-
api_key=os.getenv("NVIDIA_API_KEY")
|
| 174 |
-
)
|
| 175 |
-
except Exception as e:
|
| 176 |
-
print(f"Failed to initialize NVIDIA: {e}")
|
| 177 |
|
| 178 |
def router(st: EnhancedAgentState) -> EnhancedAgentState:
|
| 179 |
q = st["query"].lower()
|
| 180 |
if "groq" in q and groq_llm:
|
| 181 |
t = "groq"
|
| 182 |
-
elif "nvidia" in q and nvidia_llm:
|
| 183 |
-
t = "nvidia"
|
| 184 |
-
elif ("gemini" in q or "google" in q) and GEMINI_AVAILABLE:
|
| 185 |
-
t = "gemini"
|
| 186 |
elif "deepseek" in q:
|
| 187 |
t = "deepseek"
|
| 188 |
elif "ernie" in q or "baidu" in q:
|
|
@@ -191,12 +178,10 @@ class HybridLangGraphMultiLLMSystem:
|
|
| 191 |
# Default to first available provider
|
| 192 |
if groq_llm:
|
| 193 |
t = "groq"
|
| 194 |
-
elif
|
| 195 |
-
t = "nvidia"
|
| 196 |
-
elif GEMINI_AVAILABLE:
|
| 197 |
-
t = "gemini"
|
| 198 |
-
else:
|
| 199 |
t = "deepseek"
|
|
|
|
|
|
|
| 200 |
return {**st, "agent_type": t}
|
| 201 |
|
| 202 |
def groq_node(st: EnhancedAgentState) -> EnhancedAgentState:
|
|
@@ -205,45 +190,17 @@ class HybridLangGraphMultiLLMSystem:
|
|
| 205 |
|
| 206 |
t0 = time.time()
|
| 207 |
try:
|
| 208 |
-
sys = SystemMessage(content="You are a helpful AI assistant. Provide accurate and detailed answers.")
|
| 209 |
res = groq_llm.invoke([sys, HumanMessage(content=st["query"])])
|
| 210 |
return {**st, "final_answer": res.content, "perf": {"time": time.time() - t0, "prov": "Groq"}}
|
| 211 |
except Exception as e:
|
| 212 |
return {**st, "final_answer": f"Groq error: {e}", "perf": {"error": str(e)}}
|
| 213 |
|
| 214 |
-
def nvidia_node(st: EnhancedAgentState) -> EnhancedAgentState:
|
| 215 |
-
if not nvidia_llm:
|
| 216 |
-
return {**st, "final_answer": "NVIDIA not available", "perf": {"error": "No NVIDIA LLM"}}
|
| 217 |
-
|
| 218 |
-
t0 = time.time()
|
| 219 |
-
try:
|
| 220 |
-
sys = SystemMessage(content="You are a helpful AI assistant. Provide accurate and detailed answers.")
|
| 221 |
-
res = nvidia_llm.invoke([sys, HumanMessage(content=st["query"])])
|
| 222 |
-
return {**st, "final_answer": res.content, "perf": {"time": time.time() - t0, "prov": "NVIDIA"}}
|
| 223 |
-
except Exception as e:
|
| 224 |
-
return {**st, "final_answer": f"NVIDIA error: {e}", "perf": {"error": str(e)}}
|
| 225 |
-
|
| 226 |
-
def gemini_node(st: EnhancedAgentState) -> EnhancedAgentState:
|
| 227 |
-
if not GEMINI_AVAILABLE:
|
| 228 |
-
return {**st, "final_answer": "Gemini not available", "perf": {"error": "Gemini not installed"}}
|
| 229 |
-
|
| 230 |
-
t0 = time.time()
|
| 231 |
-
try:
|
| 232 |
-
api_key = os.getenv("GEMINI_API_KEY")
|
| 233 |
-
if not api_key:
|
| 234 |
-
return {**st, "final_answer": "Gemini API key not provided", "perf": {"error": "No API key"}}
|
| 235 |
-
|
| 236 |
-
genai.configure(api_key=api_key)
|
| 237 |
-
model = genai.GenerativeModel("gemini-1.5-pro-latest")
|
| 238 |
-
res = model.generate_content(st["query"])
|
| 239 |
-
return {**st, "final_answer": res.text, "perf": {"time": time.time() - t0, "prov": "Gemini"}}
|
| 240 |
-
except Exception as e:
|
| 241 |
-
return {**st, "final_answer": f"Gemini error: {e}", "perf": {"error": str(e)}}
|
| 242 |
-
|
| 243 |
def deepseek_node(st: EnhancedAgentState) -> EnhancedAgentState:
|
| 244 |
t0 = time.time()
|
| 245 |
try:
|
| 246 |
-
|
|
|
|
| 247 |
return {**st, "final_answer": resp, "perf": {"time": time.time() - t0, "prov": "DeepSeek"}}
|
| 248 |
except Exception as e:
|
| 249 |
return {**st, "final_answer": f"DeepSeek error: {e}", "perf": {"error": str(e)}}
|
|
@@ -251,10 +208,11 @@ class HybridLangGraphMultiLLMSystem:
|
|
| 251 |
def baidu_node(st: EnhancedAgentState) -> EnhancedAgentState:
|
| 252 |
t0 = time.time()
|
| 253 |
try:
|
| 254 |
-
|
| 255 |
-
|
|
|
|
| 256 |
except Exception as e:
|
| 257 |
-
return {**st, "final_answer": f"ERNIE error: {e}", "perf": {"error": str(e)}}
|
| 258 |
|
| 259 |
def pick(st: EnhancedAgentState) -> str:
|
| 260 |
return st["agent_type"]
|
|
@@ -262,19 +220,15 @@ class HybridLangGraphMultiLLMSystem:
|
|
| 262 |
g = StateGraph(EnhancedAgentState)
|
| 263 |
g.add_node("router", router)
|
| 264 |
g.add_node("groq", groq_node)
|
| 265 |
-
g.add_node("nvidia", nvidia_node)
|
| 266 |
-
g.add_node("gemini", gemini_node)
|
| 267 |
g.add_node("deepseek", deepseek_node)
|
| 268 |
g.add_node("baidu", baidu_node)
|
| 269 |
g.set_entry_point("router")
|
| 270 |
g.add_conditional_edges("router", pick, {
|
| 271 |
"groq": "groq",
|
| 272 |
-
"
|
| 273 |
-
"gemini": "gemini",
|
| 274 |
-
"deepseek": "deepseek",
|
| 275 |
"baidu": "baidu"
|
| 276 |
})
|
| 277 |
-
for n in ["groq", "
|
| 278 |
g.add_edge(n, END)
|
| 279 |
return g.compile(checkpointer=MemorySaver())
|
| 280 |
|
|
@@ -294,9 +248,7 @@ class HybridLangGraphMultiLLMSystem:
|
|
| 294 |
|
| 295 |
# Clean up the answer
|
| 296 |
if isinstance(raw_answer, str):
|
| 297 |
-
|
| 298 |
-
answer_part = parts[1].strip() if len(parts) > 1 and len(parts[1].strip()) > 10 else raw_answer.strip()
|
| 299 |
-
return answer_part
|
| 300 |
return str(raw_answer)
|
| 301 |
except Exception as e:
|
| 302 |
return f"Error processing query: {e}"
|
|
@@ -308,7 +260,7 @@ def build_graph(provider="groq"):
|
|
| 308 |
return system.graph
|
| 309 |
|
| 310 |
if __name__ == "__main__":
|
| 311 |
-
query = "What are the
|
| 312 |
system = HybridLangGraphMultiLLMSystem()
|
| 313 |
result = system.process_query(query)
|
| 314 |
-
print("LangGraph
|
|
|
|
| 82 |
except ImportError:
|
| 83 |
GROQ_AVAILABLE = False
|
| 84 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
import requests
|
| 86 |
|
| 87 |
def deepseek_generate(prompt, api_key=None):
|
| 88 |
+
"""Call DeepSeek API directly."""
|
| 89 |
if not api_key:
|
| 90 |
return "DeepSeek API key not provided"
|
| 91 |
|
|
|
|
| 110 |
return f"DeepSeek API error: {e}"
|
| 111 |
|
| 112 |
def baidu_ernie_generate(prompt, api_key=None):
|
| 113 |
+
"""Call Baidu ERNIE API."""
|
| 114 |
if not api_key:
|
| 115 |
return "Baidu ERNIE API key not provided"
|
| 116 |
|
| 117 |
+
# Baidu ERNIE API endpoint (replace with actual endpoint)
|
| 118 |
+
url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions"
|
| 119 |
+
headers = {
|
| 120 |
+
"Content-Type": "application/json",
|
| 121 |
+
"Authorization": f"Bearer {api_key}"
|
| 122 |
+
}
|
| 123 |
+
data = {
|
| 124 |
+
"messages": [{"role": "user", "content": prompt}],
|
| 125 |
+
"temperature": 0.1,
|
| 126 |
+
"top_p": 0.8
|
| 127 |
+
}
|
| 128 |
try:
|
| 129 |
+
resp = requests.post(url, headers=headers, json=data, timeout=30)
|
| 130 |
+
resp.raise_for_status()
|
| 131 |
+
result = resp.json().get("result", "")
|
| 132 |
+
return result if result else "No response from Baidu ERNIE"
|
| 133 |
except Exception as e:
|
| 134 |
+
return f"Baidu ERNIE API error: {e}"
|
| 135 |
|
| 136 |
# ---- Graph State ----
|
| 137 |
class EnhancedAgentState(TypedDict):
|
|
|
|
| 152 |
self.graph = self._build_graph()
|
| 153 |
|
| 154 |
def _build_graph(self):
|
| 155 |
+
# Initialize Groq LLM with error handling
|
| 156 |
groq_llm = None
|
|
|
|
| 157 |
|
| 158 |
if GROQ_AVAILABLE and os.getenv("GROQ_API_KEY"):
|
| 159 |
try:
|
| 160 |
+
# Use Groq for multiple model access
|
| 161 |
groq_llm = ChatGroq(
|
| 162 |
+
model="llama-3.1-70b-versatile", # Updated to a current model
|
| 163 |
temperature=0,
|
| 164 |
api_key=os.getenv("GROQ_API_KEY")
|
| 165 |
)
|
| 166 |
except Exception as e:
|
| 167 |
print(f"Failed to initialize Groq: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
def router(st: EnhancedAgentState) -> EnhancedAgentState:
|
| 170 |
q = st["query"].lower()
|
| 171 |
if "groq" in q and groq_llm:
|
| 172 |
t = "groq"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
elif "deepseek" in q:
|
| 174 |
t = "deepseek"
|
| 175 |
elif "ernie" in q or "baidu" in q:
|
|
|
|
| 178 |
# Default to first available provider
|
| 179 |
if groq_llm:
|
| 180 |
t = "groq"
|
| 181 |
+
elif os.getenv("DEEPSEEK_API_KEY"):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
t = "deepseek"
|
| 183 |
+
else:
|
| 184 |
+
t = "baidu"
|
| 185 |
return {**st, "agent_type": t}
|
| 186 |
|
| 187 |
def groq_node(st: EnhancedAgentState) -> EnhancedAgentState:
|
|
|
|
| 190 |
|
| 191 |
t0 = time.time()
|
| 192 |
try:
|
| 193 |
+
sys = SystemMessage(content="You are a helpful AI assistant. Provide accurate and detailed answers. Be concise but thorough.")
|
| 194 |
res = groq_llm.invoke([sys, HumanMessage(content=st["query"])])
|
| 195 |
return {**st, "final_answer": res.content, "perf": {"time": time.time() - t0, "prov": "Groq"}}
|
| 196 |
except Exception as e:
|
| 197 |
return {**st, "final_answer": f"Groq error: {e}", "perf": {"error": str(e)}}
|
| 198 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
def deepseek_node(st: EnhancedAgentState) -> EnhancedAgentState:
|
| 200 |
t0 = time.time()
|
| 201 |
try:
|
| 202 |
+
prompt = f"You are a helpful AI assistant. Provide accurate and detailed answers. Be concise but thorough.\n\nUser question: {st['query']}"
|
| 203 |
+
resp = deepseek_generate(prompt, api_key=os.getenv("DEEPSEEK_API_KEY"))
|
| 204 |
return {**st, "final_answer": resp, "perf": {"time": time.time() - t0, "prov": "DeepSeek"}}
|
| 205 |
except Exception as e:
|
| 206 |
return {**st, "final_answer": f"DeepSeek error: {e}", "perf": {"error": str(e)}}
|
|
|
|
| 208 |
def baidu_node(st: EnhancedAgentState) -> EnhancedAgentState:
|
| 209 |
t0 = time.time()
|
| 210 |
try:
|
| 211 |
+
prompt = f"You are a helpful AI assistant. Provide accurate and detailed answers. Be concise but thorough.\n\nUser question: {st['query']}"
|
| 212 |
+
resp = baidu_ernie_generate(prompt, api_key=os.getenv("BAIDU_API_KEY"))
|
| 213 |
+
return {**st, "final_answer": resp, "perf": {"time": time.time() - t0, "prov": "Baidu ERNIE"}}
|
| 214 |
except Exception as e:
|
| 215 |
+
return {**st, "final_answer": f"Baidu ERNIE error: {e}", "perf": {"error": str(e)}}
|
| 216 |
|
| 217 |
def pick(st: EnhancedAgentState) -> str:
|
| 218 |
return st["agent_type"]
|
|
|
|
| 220 |
g = StateGraph(EnhancedAgentState)
|
| 221 |
g.add_node("router", router)
|
| 222 |
g.add_node("groq", groq_node)
|
|
|
|
|
|
|
| 223 |
g.add_node("deepseek", deepseek_node)
|
| 224 |
g.add_node("baidu", baidu_node)
|
| 225 |
g.set_entry_point("router")
|
| 226 |
g.add_conditional_edges("router", pick, {
|
| 227 |
"groq": "groq",
|
| 228 |
+
"deepseek": "deepseek",
|
|
|
|
|
|
|
| 229 |
"baidu": "baidu"
|
| 230 |
})
|
| 231 |
+
for n in ["groq", "deepseek", "baidu"]:
|
| 232 |
g.add_edge(n, END)
|
| 233 |
return g.compile(checkpointer=MemorySaver())
|
| 234 |
|
|
|
|
| 248 |
|
| 249 |
# Clean up the answer
|
| 250 |
if isinstance(raw_answer, str):
|
| 251 |
+
return raw_answer.strip()
|
|
|
|
|
|
|
| 252 |
return str(raw_answer)
|
| 253 |
except Exception as e:
|
| 254 |
return f"Error processing query: {e}"
|
|
|
|
| 260 |
return system.graph
|
| 261 |
|
| 262 |
if __name__ == "__main__":
|
| 263 |
+
query = "What are the main benefits of using multiple LLM providers?"
|
| 264 |
system = HybridLangGraphMultiLLMSystem()
|
| 265 |
result = system.process_query(query)
|
| 266 |
+
print("LangGraph Multi-LLM Result:", result)
|