ghanemfaouri commited on
Commit
b0f2a92
Β·
verified Β·
1 Parent(s): 9932b07

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -0
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import pandas as pd
5
+ from smolagents import CodeAgent, DuckDuckGoSearchTool
6
+
7
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
8
+
9
+ class HfApiModel:
10
+ def __init__(self, model_name="tiiuae/falcon-7b-instruct", api_key=None):
11
+ self.model_name = model_name
12
+ self.api_key = api_key or os.getenv("HF_TOKEN")
13
+ if not self.api_key:
14
+ raise ValueError("HF_TOKEN environment variable is missing.")
15
+
16
+ def __call__(self, prompt):
17
+ # Safely flatten and convert to string
18
+ if hasattr(prompt, "content"):
19
+ prompt = prompt.content
20
+ elif isinstance(prompt, list):
21
+ flat_parts = []
22
+ for m in prompt:
23
+ if isinstance(m, list):
24
+ flat_parts.extend(str(sub) for sub in m)
25
+ elif hasattr(m, "content"):
26
+ flat_parts.append(str(m.content))
27
+ else:
28
+ flat_parts.append(str(m))
29
+ prompt = " ".join(flat_parts)
30
+ else:
31
+ prompt = str(prompt)
32
+
33
+ url = f"https://api-inference.huggingface.co/models/{self.model_name}"
34
+ headers = {"Authorization": f"Bearer {self.api_key}"}
35
+ payload = {
36
+ "inputs": prompt,
37
+ "options": {"wait_for_model": True}
38
+ }
39
+
40
+ response = requests.post(url, headers=headers, json=payload, timeout=60)
41
+ response.raise_for_status()
42
+ output = response.json()
43
+
44
+ try:
45
+ return output[0]["generated_text"]
46
+ except Exception:
47
+ return f"ERROR: {output}"
48
+
49
+ def generate(self, prompt, **kwargs):
50
+ return self.__call__(prompt)
51
+
52
+ class BasicAgent:
53
+ def __init__(self):
54
+ print("βœ… BasicAgent initialized.")
55
+ self.agent = CodeAgent(
56
+ tools=[DuckDuckGoSearchTool()],
57
+ model=HfApiModel(model_name="tiiuae/falcon-7b-instruct")
58
+ )
59
+
60
+ SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and
61
+ finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER].
62
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated
63
+ list of numbers and/or strings.
64
+ If you are asked for a number, don't use comma to write your number neither use units such as $ or
65
+ percent sign unless specified otherwise.
66
+ If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the
67
+ digits in plain text unless specified otherwise.
68
+ If you are asked for a comma separated list, apply the above rules depending of whether the element
69
+ to be put in the list is a number or a string.
70
+ """
71
+ self.agent.prompt_templates["system_prompt"] += SYSTEM_PROMPT
72
+
73
+ def __call__(self, question: str) -> str:
74
+ print(f"πŸ“₯ Agent received question: {question[:60]}...")
75
+ final_answer = self.agent.run(question)
76
+ print(f"πŸ“€ Agent returning answer: {final_answer}")
77
+ return final_answer
78
+
79
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
80
+ space_id = os.getenv("SPACE_ID")
81
+
82
+ if profile:
83
+ username = profile.username
84
+ print(f"πŸ” Logged in as: {username}")
85
+ else:
86
+ return "⚠️ Please login with Hugging Face to continue.", None
87
+
88
+ questions_url = f"{DEFAULT_API_URL}/questions"
89
+ submit_url = f"{DEFAULT_API_URL}/submit"
90
+
91
+ try:
92
+ agent = BasicAgent()
93
+ except Exception as e:
94
+ return f"❌ Agent initialization failed: {e}", None
95
+
96
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" if space_id else "Unknown"
97
+
98
+ try:
99
+ response = requests.get(questions_url, timeout=15)
100
+ response.raise_for_status()
101
+ questions_data = response.json()
102
+ if not questions_data:
103
+ return "❌ No questions received from the server.", None
104
+ except Exception as e:
105
+ return f"❌ Failed to fetch questions: {e}", None
106
+
107
+ answers_payload = []
108
+ results_log = []
109
+
110
+ for item in questions_data:
111
+ task_id = item.get("task_id")
112
+ question_text = item.get("question")
113
+ if not task_id or question_text is None:
114
+ continue
115
+ try:
116
+ submitted_answer = agent(question_text)
117
+ except Exception as e:
118
+ submitted_answer = f"AGENT ERROR: {e}"
119
+ answers_payload.append({
120
+ "task_id": task_id,
121
+ "submitted_answer": submitted_answer
122
+ })
123
+ results_log.append({
124
+ "Task ID": task_id,
125
+ "Question": question_text,
126
+ "Submitted Answer": submitted_answer
127
+ })
128
+
129
+ if not answers_payload:
130
+ return "⚠️ Agent failed to generate any answers.", pd.DataFrame(results_log)
131
+
132
+ submission_data = {
133
+ "username": username.strip(),
134
+ "agent_code": agent_code,
135
+ "answers": answers_payload
136
+ }
137
+
138
+ try:
139
+ response = requests.post(submit_url, json=submission_data, timeout=60)
140
+ response.raise_for_status()
141
+ result_data = response.json()
142
+ status = (
143
+ f"βœ… Submission Successful!\n"
144
+ f"User: {result_data.get('username')}\n"
145
+ f"Score: {result_data.get('score', '?')}% "
146
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')})\n"
147
+ f"Message: {result_data.get('message', 'No message.')}"
148
+ )
149
+ return status, pd.DataFrame(results_log)
150
+ except Exception as e:
151
+ return f"❌ Submission failed: {e}", pd.DataFrame(results_log)
152
+
153
+ # Gradio UI
154
+ with gr.Blocks() as demo:
155
+ gr.Markdown("# πŸ€– Basic Agent Evaluation Runner")
156
+ gr.Markdown("Clone this space, log in, and run your agent on the questions. Modify `BasicAgent` logic if needed.")
157
+
158
+ gr.LoginButton()
159
+ run_button = gr.Button("▢️ Run Evaluation & Submit All Answers")
160
+ status_output = gr.Textbox(label="πŸ“ Run Status", lines=5, interactive=False)
161
+ results_table = gr.DataFrame(label="πŸ“‹ Results", wrap=True)
162
+
163
+ run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
164
+
165
+ if __name__ == "__main__":
166
+ print("πŸš€ Launching Gradio app...")
167
+ demo.launch(debug=True, share=False)