kamil1300 commited on
Commit
0ea7d6c
·
verified ·
1 Parent(s): f12c823

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +207 -60
app.py CHANGED
@@ -1,64 +1,211 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
  import gradio as gr
3
+ import requests
4
+ import pandas as pd
5
+ from agent.agent import chat_with_agent
6
+ # (Keep Constants as is)
7
+ # --- Constants ---
8
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
 
11
+ # --- Basic Agent Definition ---
12
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
+ # class BasicAgent:
14
+ # def __init__(self):
15
+ # print("BasicAgent initialized.")
16
+ # def __call__(self, question: str) -> str:
17
+ # print(f"Agent received question (first 50 chars): {question[:50]}...")
18
+ # fixed_answer = "This is a default answer."
19
+ # print(f"Agent returning fixed answer: {fixed_answer}")
20
+ # return fixed_answer
21
+
22
+ class BasicAgent:
23
+ def __init__(self):
24
+ print("DeepSeekAgent initialized.")
25
+
26
+ def __call__(self, question: str) -> str:
27
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
28
+ try:
29
+ answer = chat_with_agent(question)
30
+ print(f"Agent returning answer: {answer[:100]}...")
31
+ return answer
32
+ except Exception as e:
33
+ print(f"Agent failed to answer: {e}")
34
+ return f"Error: {e}"
35
+
36
+
37
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
38
+ """
39
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
40
+ and displays the results.
41
+ """
42
+ # --- Determine HF Space Runtime URL and Repo URL ---
43
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
44
+
45
+ if profile:
46
+ username= f"{profile.username}"
47
+ print(f"User logged in: {username}")
48
+ else:
49
+ print("User not logged in.")
50
+ return "Please Login to Hugging Face with the button.", None
51
+
52
+ api_url = DEFAULT_API_URL
53
+ questions_url = f"{api_url}/questions"
54
+ submit_url = f"{api_url}/submit"
55
+
56
+ # 1. Instantiate Agent ( modify this part to create your agent)
57
+ try:
58
+ agent = BasicAgent()
59
+ except Exception as e:
60
+ print(f"Error instantiating agent: {e}")
61
+ return f"Error initializing agent: {e}", None
62
+ # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
63
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
64
+ print(agent_code)
65
+
66
+ # 2. Fetch Questions
67
+ print(f"Fetching questions from: {questions_url}")
68
+ try:
69
+ response = requests.get(questions_url, timeout=15)
70
+ response.raise_for_status()
71
+ questions_data = response.json()
72
+ if not questions_data:
73
+ print("Fetched questions list is empty.")
74
+ return "Fetched questions list is empty or invalid format.", None
75
+ print(f"Fetched {len(questions_data)} questions.")
76
+ except requests.exceptions.RequestException as e:
77
+ print(f"Error fetching questions: {e}")
78
+ return f"Error fetching questions: {e}", None
79
+ except requests.exceptions.JSONDecodeError as e:
80
+ print(f"Error decoding JSON response from questions endpoint: {e}")
81
+ print(f"Response text: {response.text[:500]}")
82
+ return f"Error decoding server response for questions: {e}", None
83
+ except Exception as e:
84
+ print(f"An unexpected error occurred fetching questions: {e}")
85
+ return f"An unexpected error occurred fetching questions: {e}", None
86
+
87
+ # 3. Run your Agent
88
+ results_log = []
89
+ answers_payload = []
90
+ print(f"Running agent on {len(questions_data)} questions...")
91
+ for item in questions_data:
92
+ task_id = item.get("task_id")
93
+ question_text = item.get("question")
94
+ if not task_id or question_text is None:
95
+ print(f"Skipping item with missing task_id or question: {item}")
96
+ continue
97
+ try:
98
+ submitted_answer = agent(question_text)
99
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
100
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
101
+ except Exception as e:
102
+ print(f"Error running agent on task {task_id}: {e}")
103
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
104
+
105
+ if not answers_payload:
106
+ print("Agent did not produce any answers to submit.")
107
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
108
+
109
+ # 4. Prepare Submission
110
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
111
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
112
+ print(status_update)
113
+
114
+ # 5. Submit
115
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
116
+ try:
117
+ response = requests.post(submit_url, json=submission_data, timeout=60)
118
+ response.raise_for_status()
119
+ result_data = response.json()
120
+ final_status = (
121
+ f"Submission Successful!\n"
122
+ f"User: {result_data.get('username')}\n"
123
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
124
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
125
+ f"Message: {result_data.get('message', 'No message received.')}"
126
+ )
127
+ print("Submission successful.")
128
+ results_df = pd.DataFrame(results_log)
129
+ return final_status, results_df
130
+ except requests.exceptions.HTTPError as e:
131
+ error_detail = f"Server responded with status {e.response.status_code}."
132
+ try:
133
+ error_json = e.response.json()
134
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
135
+ except requests.exceptions.JSONDecodeError:
136
+ error_detail += f" Response: {e.response.text[:500]}"
137
+ status_message = f"Submission Failed: {error_detail}"
138
+ print(status_message)
139
+ results_df = pd.DataFrame(results_log)
140
+ return status_message, results_df
141
+ except requests.exceptions.Timeout:
142
+ status_message = "Submission Failed: The request timed out."
143
+ print(status_message)
144
+ results_df = pd.DataFrame(results_log)
145
+ return status_message, results_df
146
+ except requests.exceptions.RequestException as e:
147
+ status_message = f"Submission Failed: Network error - {e}"
148
+ print(status_message)
149
+ results_df = pd.DataFrame(results_log)
150
+ return status_message, results_df
151
+ except Exception as e:
152
+ status_message = f"An unexpected error occurred during submission: {e}"
153
+ print(status_message)
154
+ results_df = pd.DataFrame(results_log)
155
+ return status_message, results_df
156
+
157
+
158
+ # --- Build Gradio Interface using Blocks ---
159
+ with gr.Blocks() as demo:
160
+ gr.Markdown("# Basic Agent Evaluation Runner")
161
+ gr.Markdown(
162
+ """
163
+ **Instructions:**
164
+
165
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
166
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
167
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
168
+
169
+ ---
170
+ **Disclaimers:**
171
+ Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
172
+ This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
173
+ """
174
+ )
175
+
176
+ # gr.LoginButton()
177
+
178
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
179
+
180
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
181
+ # Removed max_rows=10 from DataFrame constructor
182
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
183
+
184
+ run_button.click(
185
+ fn=run_and_submit_all,
186
+ outputs=[status_output, results_table]
187
+ )
188
+
189
  if __name__ == "__main__":
190
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
191
+ # Check for SPACE_HOST and SPACE_ID at startup for information
192
+ space_host_startup = os.getenv("SPACE_HOST")
193
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
194
+
195
+ if space_host_startup:
196
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
197
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
198
+ else:
199
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
200
+
201
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
202
+ print(f"✅ SPACE_ID found: {space_id_startup}")
203
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
204
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
205
+ else:
206
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
207
+
208
+ print("-"*(60 + len(" App Starting ")) + "\n")
209
+
210
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
211
+ demo.launch(debug=True, share=False)