SantoshKumar1310 commited on
Commit
12df4db
·
verified ·
1 Parent(s): 06a8946

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -168
app.py CHANGED
@@ -1,177 +1,89 @@
1
- # app.py
2
- import os
3
- import gradio as gr
4
- import requests
5
- import pandas as pd
6
- from typing import Dict, List
7
-
8
- # custom imports
9
- from agents import Agent
10
- from tool import get_tools
11
- from model import get_model
12
-
13
- # --- Constants ---
14
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
15
- MODEL_ID = "vertex_ai/gemini-1.0-pro-001"
16
-
17
-
18
- # --- Async Question Processing ---
19
- async def process_question(agent, question: str, task_id: str) -> Dict:
20
- """Process a single question and return both answer AND full log entry"""
21
- try:
22
- answer = agent(question)
23
- return {
24
- "submission": {"task_id": task_id, "submitted_answer": answer},
25
- "log": {"Task ID": task_id, "Question": question, "Submitted Answer": answer}
26
- }
27
- except Exception as e:
28
- error_msg = f"ERROR: {str(e)}"
29
- return {
30
- "submission": {"task_id": task_id, "submitted_answer": error_msg},
31
- "log": {"Task ID": task_id, "Question": question, "Submitted Answer": error_msg}
32
- }
33
-
34
- async def run_questions_async(agent, questions_data: List[Dict]) -> tuple:
35
- """Process questions sequentially"""
36
- submissions = []
37
- logs = []
38
-
39
- total = len(questions_data)
40
- for idx, q in enumerate(questions_data):
41
- print(f"Processing {idx+1}/{total}: {q['question'][:80]}...")
42
- result = await process_question(agent, q["question"], q["task_id"])
43
- submissions.append(result["submission"])
44
- logs.append(result["log"])
45
-
46
- return submissions, logs
47
-
48
 
49
- async def run_and_submit_all(profile: gr.OAuthProfile | None):
50
- """
51
- Fetches all questions, runs the Agent on them, submits all answers,
52
- and displays the results.
53
- """
54
- space_id = os.getenv("SPACE_ID")
55
 
56
- if profile:
57
- username = f"{profile.username}"
58
- print(f"User logged in: {username}")
59
- else:
60
- print("User not logged in.")
61
- return "Please Login to Hugging Face with the button.", None
62
 
63
- api_url = DEFAULT_API_URL
64
- questions_url = f"{api_url}/questions"
65
- submit_url = f"{api_url}/submit"
66
 
67
- # 1. Instantiate Agent
68
- try:
69
- agent = Agent(
70
- model=get_model("LiteLLMModel", MODEL_ID),
71
- tools=get_tools()
72
- )
73
- except Exception as e:
74
- print(f"Error instantiating agent: {e}")
75
- return f"Error initializing agent: {e}", None
76
 
77
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
78
- print(f"Agent code: {agent_code}")
79
-
80
- # 2. Fetch Questions
81
- print(f"Fetching questions from: {questions_url}")
82
- try:
83
- response = requests.get(questions_url, timeout=15)
84
- response.raise_for_status()
85
- questions_data = response.json()
86
- if not questions_data:
87
- print("Fetched questions list is empty.")
88
- return "Fetched questions list is empty or invalid format.", None
89
- print(f"Fetched {len(questions_data)} questions.")
90
- # Remove this line to process all questions: questions_data = questions_data[:2]
91
- except Exception as e:
92
- print(f"Error fetching questions: {e}")
93
- return f"Error fetching questions: {e}", None
94
-
95
- # 3. Run Agent
96
- print(f"Running agent on {len(questions_data)} questions...")
97
- answers_payload, results_log = await run_questions_async(agent, questions_data)
98
-
99
- if not answers_payload:
100
- print("Agent did not produce any answers to submit.")
101
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
102
-
103
- # 4. Prepare Submission
104
- submission_data = {
105
- "username": username.strip(),
106
- "agent_code": agent_code,
107
- "answers": answers_payload
108
- }
109
- print(f"Submitting {len(answers_payload)} answers for user '{username}'...")
110
-
111
- # 5. Submit
112
- try:
113
- response = requests.post(submit_url, json=submission_data, timeout=60)
114
- response.raise_for_status()
115
- result_data = response.json()
116
- final_status = (
117
- f"✅ Submission Successful!\n\n"
118
- f"User: {result_data.get('username')}\n"
119
- f"Overall Score: {result_data.get('score', 'N/A')}% "
120
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n\n"
121
- f"Message: {result_data.get('message', 'No message received.')}\n\n"
122
- f"Leaderboard: {api_url}/leaderboard"
123
- )
124
- print("Submission successful.")
125
- results_df = pd.DataFrame(results_log)
126
- return final_status, results_df
127
- except Exception as e:
128
- status_message = f"❌ Submission Failed: {e}"
129
- print(status_message)
130
- results_df = pd.DataFrame(results_log)
131
- return status_message, results_df
132
-
133
-
134
- # --- Build Gradio Interface ---
135
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
136
- gr.Markdown("# 🤖 GAIA Agent Evaluation")
137
- gr.Markdown(
138
- """
139
- **Instructions:**
140
- 1. Log in to your Hugging Face account using the button below
141
- 2. Click 'Run Evaluation & Submit' to test your agent
142
- 3. The agent will use web search and other tools to answer questions
143
 
144
- **Current Setup:**
145
- - Model: Gemini 2.5 Flash (via LiteLLM)
146
- - Tools: Web search, Wikipedia, calculation, and more
147
- """
148
- )
149
-
150
- gr.LoginButton()
151
-
152
- run_button = gr.Button("🚀 Run Evaluation & Submit", variant="primary")
153
-
154
- status_output = gr.Textbox(label="📊 Status / Results", lines=8, interactive=False)
155
- results_table = gr.DataFrame(label="📋 Questions and Answers", wrap=True, max_height=400)
156
-
157
- run_button.click(
158
- fn=run_and_submit_all,
159
- outputs=[status_output, results_table]
160
- )
161
-
162
- if __name__ == "__main__":
163
- print("\n" + "="*70)
164
- print("🤖 GAIA Agent Starting")
165
- print("="*70)
166
 
167
- space_host = os.getenv("SPACE_HOST")
168
- space_id = os.getenv("SPACE_ID")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
169
 
170
- if space_host:
171
- print(f"✅ Runtime URL: https://{space_host}.hf.space")
172
- if space_id:
173
- print(f"✅ Repo URL: https://huggingface.co/spaces/{space_id}")
174
-
175
- print("="*70 + "\n")
176
- demo.launch(debug=True, share=False)
177
 
 
 
 
 
 
 
1
+ """Model wrapper for LiteLLM"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ import os
4
+ from typing import List, Dict, Any, Optional
 
 
 
 
5
 
6
+ try:
7
+ import litellm
8
+ except ImportError:
9
+ print("⚠️ litellm not installed. Install with: pip install litellm")
10
+ litellm = None
 
11
 
 
 
 
12
 
13
+ class LiteLLMModel:
14
+ """Wrapper for LiteLLM models"""
 
 
 
 
 
 
 
15
 
16
+ def __init__(self, model_id: str):
17
+ self.model_id = model_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
+ if "gemini" in model_id.lower():
20
+ if not os.getenv("GEMINI_API_KEY"):
21
+ print("⚠️ GEMINI_API_KEY not set in environment")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ def generate(self, messages: List[Dict], tools: Optional[List] = None) -> Dict:
24
+ if not litellm:
25
+ return {"content": "Unknown - litellm not installed"}
26
+
27
+ try:
28
+ formatted_tools = None
29
+ if tools:
30
+ formatted_tools = [
31
+ {
32
+ "type": "function",
33
+ "function": {
34
+ "name": tool.name,
35
+ "description": tool.description,
36
+ "parameters": tool.parameters
37
+ }
38
+ }
39
+ for tool in tools
40
+ ]
41
+
42
+ if "gemini" in self.model_id.lower():
43
+ api_key = os.getenv("GEMINI_API_KEY")
44
+ if not api_key:
45
+ raise RuntimeError("GEMINI_API_KEY not set in environment")
46
+
47
+ print(f"DEBUG: Using model id: {self.model_id}")
48
+
49
+ response = litellm.completion(
50
+ model=self.model_id,
51
+ api_key=api_key,
52
+ messages=messages,
53
+ tools=formatted_tools,
54
+ temperature=0.1
55
+ )
56
+ else:
57
+ response = litellm.completion(
58
+ model=self.model_id,
59
+ messages=messages,
60
+ tools=formatted_tools,
61
+ temperature=0.1
62
+ )
63
+
64
+ message = response.choices[0].message
65
+ result = {
66
+ "content": message.content or ""
67
+ }
68
+
69
+ if hasattr(message, 'tool_calls') and message.tool_calls:
70
+ result["tool_calls"] = [
71
+ {
72
+ "name": tc.function.name,
73
+ "arguments": eval(tc.function.arguments) if isinstance(tc.function.arguments, str) else tc.function.arguments
74
+ }
75
+ for tc in message.tool_calls
76
+ ]
77
+
78
+ return result
79
+
80
+ except Exception as e:
81
+ print(f"Model error: {e}")
82
+ return {"content": "Unknown"}
83
 
 
 
 
 
 
 
 
84
 
85
+ def get_model(model_type: str, model_id: str):
86
+ if model_type == "LiteLLMModel":
87
+ return LiteLLMModel(model_id)
88
+ else:
89
+ raise ValueError(f"Unknown model type: {model_type}")