josondev commited on
Commit
b1b09d8
Β·
verified Β·
1 Parent(s): 58a708e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +91 -40
app.py CHANGED
@@ -1,39 +1,61 @@
1
- """ Enhanced Multi-LLM Agent Evaluation Runner with Vector Database Integration"""
2
  import os
3
  import gradio as gr
4
  import requests
5
  import pandas as pd
6
  from langchain_core.messages import HumanMessage
7
- from veryfinal import build_graph, HybridLangGraphMultiLLMSystem
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  # --- Constants ---
10
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
11
 
12
  # --- Enhanced Agent Definition ---
13
  class EnhancedMultiLLMAgent:
14
- """A multi-provider LangGraph agent with vector database integration."""
15
  def __init__(self):
16
- print("Enhanced Multi-LLM Agent with Vector Database initialized.")
 
 
 
 
 
 
 
17
  try:
18
- self.system = HybridLangGraphMultiLLMSystem(provider="groq")
 
19
  self.graph = self.system.graph
20
 
21
- # Load metadata if available
22
- if os.path.exists("metadata.jsonl"):
23
- print("Loading question metadata...")
24
- count = self.system.load_metadata_from_jsonl("metadata.jsonl")
25
- print(f"Loaded {count} questions into vector database")
 
 
26
 
27
- print("Enhanced Multi-LLM Graph built successfully.")
28
  except Exception as e:
29
- print(f"Error building graph: {e}")
30
  self.graph = None
31
  self.system = None
32
 
33
  def __call__(self, question: str) -> str:
34
  print(f"Agent received question: {question[:100]}...")
35
 
36
- if self.graph is None or self.system is None:
37
  return "Error: Agent not properly initialized"
38
 
39
  try:
@@ -43,8 +65,15 @@ class EnhancedMultiLLMAgent:
43
  # Additional validation
44
  if not answer or answer == question or len(answer.strip()) == 0:
45
  return "Information not available"
46
-
47
- return answer.strip()
 
 
 
 
 
 
 
48
 
49
  except Exception as e:
50
  error_msg = f"Error: {str(e)}"
@@ -52,7 +81,7 @@ class EnhancedMultiLLMAgent:
52
  return error_msg
53
 
54
  def run_and_submit_all(profile: gr.OAuthProfile | None):
55
- """Fetch questions, run enhanced agent, and submit answers."""
56
  space_id = os.getenv("SPACE_ID")
57
 
58
  if profile:
@@ -66,11 +95,11 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
66
  questions_url = f"{api_url}/questions"
67
  submit_url = f"{api_url}/submit"
68
 
69
- # 1. Instantiate Agent
70
  try:
71
  agent = EnhancedMultiLLMAgent()
72
- if agent.graph is None:
73
- return "Error: Failed to initialize agent properly", None
74
  except Exception as e:
75
  print(f"Error instantiating agent: {e}")
76
  return f"Error initializing agent: {e}", None
@@ -92,10 +121,10 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
92
  print(f"Error fetching questions: {e}")
93
  return f"Error fetching questions: {e}", None
94
 
95
- # 3. Run Enhanced Agent
96
  results_log = []
97
  answers_payload = []
98
- print(f"Running Enhanced Multi-LLM agent with vector database on {len(questions_data)} questions...")
99
 
100
  for i, item in enumerate(questions_data):
101
  task_id = item.get("task_id")
@@ -136,7 +165,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
136
 
137
  # 4. Prepare Submission
138
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
139
- status_update = f"Enhanced Multi-LLM Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
140
  print(status_update)
141
 
142
  # 5. Submit
@@ -163,7 +192,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
163
 
164
  # --- Build Gradio Interface ---
165
  with gr.Blocks() as demo:
166
- gr.Markdown("# Enhanced Multi-LLM Agent with Vector Database Integration")
167
  gr.Markdown(
168
  """
169
  **Instructions:**
@@ -171,25 +200,32 @@ with gr.Blocks() as demo:
171
  2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
172
 
173
  **Enhanced Agent Features:**
174
- - **Multi-LLM Support**: Groq (Llama-3 8B/70B, DeepSeek)
175
- - **Vector Database Integration**: FAISS + Supabase for similar question retrieval
176
- - **Intelligent Routing**: Automatically selects best provider based on query complexity
177
- - **Enhanced Tools**: Mathematical operations, web search, Wikipedia integration
178
- - **Question-Answering**: Optimized for evaluation tasks with proper formatting
179
- - **Similar Questions Context**: Uses vector similarity to provide relevant context
180
- - **Error Handling**: Robust fallback mechanisms and comprehensive logging
 
 
 
 
 
 
 
181
 
182
  **Routing Examples:**
183
- - Math: "What is 25 multiplied by 17?" β†’ Llama-3 70B
184
- - Search: "Find information about Mercedes Sosa" β†’ Search-Enhanced
185
- - Complex: "Analyze quantum computing principles" β†’ DeepSeek
186
- - Simple: "What is the capital of France?" β†’ Llama-3 8B
 
187
 
188
- **Vector Database Features:**
189
- - Automatic loading of metadata.jsonl if present
190
- - Similar question retrieval for enhanced context
191
- - Supabase integration for persistent storage
192
- - FAISS for fast vector similarity search
193
  """
194
  )
195
 
@@ -206,5 +242,20 @@ with gr.Blocks() as demo:
206
  )
207
 
208
  if __name__ == "__main__":
209
- print("\n" + "-"*30 + " Enhanced Multi-LLM Agent with Vector DB Starting " + "-"*30)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  demo.launch(debug=True, share=False)
 
1
+ """ Enhanced Multi-LLM Agent Evaluation Runner with Agno Integration"""
2
  import os
3
  import gradio as gr
4
  import requests
5
  import pandas as pd
6
  from langchain_core.messages import HumanMessage
7
+
8
+ # Import the enhanced classes from veryfinal.py in the same directory
9
+ try:
10
+ from veryfinal import (
11
+ build_graph,
12
+ UnifiedAgnoEnhancedSystem,
13
+ AgnoEnhancedAgentSystem,
14
+ AgnoEnhancedModelManager
15
+ )
16
+ VERYFINAL_AVAILABLE = True
17
+ except ImportError as e:
18
+ print(f"Error importing from veryfinal.py: {e}")
19
+ VERYFINAL_AVAILABLE = False
20
 
21
  # --- Constants ---
22
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
23
 
24
  # --- Enhanced Agent Definition ---
25
  class EnhancedMultiLLMAgent:
26
+ """A multi-provider Agno agent with NVIDIA + open-source model integration."""
27
  def __init__(self):
28
+ print("Enhanced Multi-LLM Agent with Agno Integration initialized.")
29
+
30
+ if not VERYFINAL_AVAILABLE:
31
+ print("Error: veryfinal.py not properly imported")
32
+ self.system = None
33
+ self.graph = None
34
+ return
35
+
36
  try:
37
+ # Use the unified Agno enhanced system
38
+ self.system = UnifiedAgnoEnhancedSystem()
39
  self.graph = self.system.graph
40
 
41
+ # Display system information
42
+ if self.system.agno_system:
43
+ info = self.system.get_system_info()
44
+ print(f"System initialized with {info.get('total_models', 0)} models")
45
+ if info.get('nvidia_available'):
46
+ print("βœ… NVIDIA NIM models available")
47
+ print(f"Active agents: {info.get('active_agents', [])}")
48
 
49
+ print("Enhanced Agno Multi-LLM System built successfully.")
50
  except Exception as e:
51
+ print(f"Error building enhanced system: {e}")
52
  self.graph = None
53
  self.system = None
54
 
55
  def __call__(self, question: str) -> str:
56
  print(f"Agent received question: {question[:100]}...")
57
 
58
+ if self.system is None:
59
  return "Error: Agent not properly initialized"
60
 
61
  try:
 
65
  # Additional validation
66
  if not answer or answer == question or len(answer.strip()) == 0:
67
  return "Information not available"
68
+
69
+ # Clean up the answer
70
+ answer = answer.strip()
71
+
72
+ # Ensure proper formatting for evaluation
73
+ if "FINAL ANSWER:" in answer:
74
+ answer = answer.split("FINAL ANSWER:")[-1].strip()
75
+
76
+ return answer
77
 
78
  except Exception as e:
79
  error_msg = f"Error: {str(e)}"
 
81
  return error_msg
82
 
83
  def run_and_submit_all(profile: gr.OAuthProfile | None):
84
+ """Fetch questions, run enhanced Agno agent, and submit answers."""
85
  space_id = os.getenv("SPACE_ID")
86
 
87
  if profile:
 
95
  questions_url = f"{api_url}/questions"
96
  submit_url = f"{api_url}/submit"
97
 
98
+ # 1. Instantiate Enhanced Agent
99
  try:
100
  agent = EnhancedMultiLLMAgent()
101
+ if agent.system is None:
102
+ return "Error: Failed to initialize enhanced agent properly", None
103
  except Exception as e:
104
  print(f"Error instantiating agent: {e}")
105
  return f"Error initializing agent: {e}", None
 
121
  print(f"Error fetching questions: {e}")
122
  return f"Error fetching questions: {e}", None
123
 
124
+ # 3. Run Enhanced Agno Agent
125
  results_log = []
126
  answers_payload = []
127
+ print(f"Running Enhanced Agno Multi-LLM agent on {len(questions_data)} questions...")
128
 
129
  for i, item in enumerate(questions_data):
130
  task_id = item.get("task_id")
 
165
 
166
  # 4. Prepare Submission
167
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
168
+ status_update = f"Enhanced Agno Multi-LLM Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
169
  print(status_update)
170
 
171
  # 5. Submit
 
192
 
193
  # --- Build Gradio Interface ---
194
  with gr.Blocks() as demo:
195
+ gr.Markdown("# Enhanced Multi-LLM Agent with Agno + NVIDIA Integration")
196
  gr.Markdown(
197
  """
198
  **Instructions:**
 
200
  2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
201
 
202
  **Enhanced Agent Features:**
203
+ - **NVIDIA NIM Models**: Enterprise-grade optimized models for maximum accuracy
204
+ - **Open-Source Models**: Groq, Ollama, Together AI, Anyscale, Hugging Face
205
+ - **Specialized Agents**: Enterprise research, advanced math, coding, fast response
206
+ - **Intelligent Routing**: Automatically selects best model/agent for each task
207
+ - **Advanced Tools**: DuckDuckGo search, Wikipedia, calculator, reasoning tools
208
+ - **Agno Framework**: Professional agent framework with memory and tool integration
209
+
210
+ **Available Model Providers:**
211
+ - **NVIDIA NIM**: meta/llama3-70b-instruct, meta/codellama-70b-instruct, etc.
212
+ - **Groq (Free)**: llama3-70b-8192, llama3-8b-8192, mixtral-8x7b-32768
213
+ - **Ollama (Local)**: llama3, mistral, phi3, codellama, gemma, qwen
214
+ - **Together AI**: Meta-Llama models, Mistral, Qwen
215
+ - **Anyscale**: Enterprise hosting for open-source models
216
+ - **Hugging Face**: Direct model access
217
 
218
  **Routing Examples:**
219
+ - Enterprise: "Enterprise analysis of quantum computing" β†’ NVIDIA NIM
220
+ - Math: "Calculate 25 Γ— 17" β†’ Advanced Math Agent
221
+ - Code: "Write Python factorial function" β†’ Advanced Coding Agent
222
+ - Research: "Find Mercedes Sosa discography" β†’ Enterprise Research Agent
223
+ - Quick: "Capital of France?" β†’ Fast Response Agent
224
 
225
+ **Setup Requirements:**
226
+ - NVIDIA_API_KEY for enterprise models (optional)
227
+ - GROQ_API_KEY for free tier models
228
+ - Other API keys optional for additional providers
 
229
  """
230
  )
231
 
 
242
  )
243
 
244
  if __name__ == "__main__":
245
+ print("\n" + "-"*30 + " Enhanced Agno Multi-LLM Agent Starting " + "-"*30)
246
+
247
+ # Display system status
248
+ if VERYFINAL_AVAILABLE:
249
+ try:
250
+ test_system = UnifiedAgnoEnhancedSystem()
251
+ info = test_system.get_system_info()
252
+ print(f"βœ… System ready with {info.get('total_models', 0)} models")
253
+ print(f"πŸ“Š Model breakdown: {len(info.get('model_breakdown', {}).get('nvidia_models', []))} NVIDIA, "
254
+ f"{len(info.get('model_breakdown', {}).get('groq_models', []))} Groq, "
255
+ f"{len(info.get('model_breakdown', {}).get('ollama_models', []))} Ollama")
256
+ except Exception as e:
257
+ print(f"⚠️ System initialization warning: {e}")
258
+ else:
259
+ print("❌ veryfinal.py not properly imported")
260
+
261
  demo.launch(debug=True, share=False)