RamiNuraliyev commited on
Commit
552bf52
·
verified ·
1 Parent(s): 81917a3

Upload 2 files

Browse files
Files changed (2) hide show
  1. agent.py +211 -0
  2. app.py +201 -195
agent.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ from langchain_google_genai import ChatGoogleGenerativeAI
3
+ from langchain_community.utilities import SerpAPIWrapper
4
+ from langchain_community.document_loaders import WikipediaLoader
5
+ from langchain_community.document_loaders import ArxivLoader
6
+ from typing import TypedDict, Annotated
7
+ from langchain_core.messages import AnyMessage
8
+ from langgraph.graph.message import add_messages
9
+ from langchain_core.messages import HumanMessage, SystemMessage
10
+ from langgraph.graph import START, StateGraph
11
+ from langgraph.prebuilt import ToolNode, tools_condition
12
+ from IPython.display import Image, display
13
+
14
+ load_dotenv('../config.env')
15
+
16
+ llm = ChatGoogleGenerativeAI(model="gemini-2.0-flash")
17
+
18
+ # load the system prompt from the file
19
+ with open('system_prompt.txt', 'r') as f:
20
+ system_prompt = f.read()
21
+ # print(system_prompt)
22
+
23
+
24
+ # --Agent tools--
25
+
26
+ # Calculation tools
27
+ def add(a: int, b: int) -> int:
28
+ """
29
+ Add two numbers
30
+
31
+ Args:
32
+ a: first int
33
+ b: second int
34
+ """
35
+ return a + b
36
+
37
+
38
+ def subtract(a: int, b: int) -> int:
39
+ """
40
+ Subtract two numbers
41
+
42
+ Args:
43
+ a: first int
44
+ b: second int
45
+ """
46
+ return a - b
47
+
48
+
49
+ def multiply(a: int, b: int) -> int:
50
+ """
51
+ Multiply two numbers
52
+
53
+ Args:
54
+ a: first int
55
+ b: second int
56
+ """
57
+ return a * b
58
+
59
+
60
+ def modulus(a: int, b: int) -> int:
61
+ """
62
+ Get the modulus (remainder) of two numbers
63
+
64
+ Args:
65
+ a: first int
66
+ b: second int
67
+ """
68
+ return a % b
69
+
70
+
71
+ def divide(a: int, b: int) -> float:
72
+ """
73
+ Divide two numbers
74
+
75
+ Args:
76
+ a: first int
77
+ b: second int
78
+
79
+ Returns:
80
+ The division result as a float
81
+ """
82
+ if b == 0:
83
+ raise ValueError("Cannot divide by zero")
84
+ return a / b
85
+
86
+
87
+
88
+ # Search tools
89
+ def web_search(query: str) -> str:
90
+ """
91
+ Searches the web using a query string. Useful for answering current events or fact-based questions.",
92
+ Args:
93
+ query: string representing the search term.
94
+
95
+ Returns:
96
+ A string containing top search results.
97
+ """
98
+
99
+ search = SerpAPIWrapper()
100
+ result = search.run(query)
101
+
102
+ return result
103
+
104
+ def wiki_search(query: str) -> str:
105
+ """
106
+ Search Wikipedia for general knowledge.
107
+
108
+ Args:
109
+ query: Wikipedia search term.
110
+
111
+ Returns:
112
+ A dict with "wiki_results" containing search results.
113
+ """
114
+ search_docs = WikipediaLoader(query=query,load_max_docs=2).load()
115
+ formatted_search_docs = "\n\n---\n\n".join(
116
+ [
117
+ f'<Document source="{doc.metadata["source"]}" page="{doc.metadata.get("page", "")}"/>\n{doc.page_content}\n</Document>'
118
+ for doc in search_docs
119
+ ])
120
+ return {"wiki_results": formatted_search_docs}
121
+
122
+ def arxiv_search(query: str) -> str:
123
+ """
124
+ Searches academic papers on arXiv based on a query.
125
+
126
+ Args:
127
+ query: The search term to query arXiv.
128
+
129
+ Returns:
130
+ A string of the top retrieved papers.
131
+ """
132
+ docs = ArxivLoader(query=query, max_results=2).load()
133
+ return "\n\n---\n\n".join(
134
+ f"Title: {doc.metadata.get('title', 'N/A')}\nContent: {doc.page_content}"
135
+ for doc in docs
136
+ )
137
+
138
+ tools = [
139
+ add,
140
+ subtract,
141
+ multiply,
142
+ divide,
143
+ modulus,
144
+ web_search,
145
+ wiki_search,
146
+ ]
147
+
148
+ llm_with_tools = llm.bind_tools(tools=tools)
149
+
150
+ def build_graph():
151
+ class AgentState(TypedDict):
152
+ messages: Annotated[list[AnyMessage], add_messages]
153
+
154
+
155
+
156
+ def assistant(state: AgentState):
157
+ # System message
158
+ sys_msg = SystemMessage(content=system_prompt)
159
+
160
+ return {"messages": [llm_with_tools.invoke([sys_msg] + state["messages"])]}
161
+
162
+
163
+
164
+ # Graph
165
+ builder = StateGraph(AgentState)
166
+
167
+ # Define nodes: these do the work
168
+ builder.add_node("assistant", assistant)
169
+ builder.add_node("tools", ToolNode(tools))
170
+
171
+ # Define edges: these determine how the control flow moves
172
+ builder.add_edge(START, "assistant")
173
+ builder.add_conditional_edges(
174
+ "assistant",
175
+ # If the latest message (result) from assistant is a tool call -> tools_condition routes to tools
176
+ # If the latest message (result) from assistant is a not a tool call -> tools_condition routes to END
177
+ tools_condition,
178
+ )
179
+ builder.add_edge("tools", "assistant")
180
+ react_graph = builder.compile()
181
+
182
+ # Show
183
+ # display(Image(react_graph.get_graph(xray=True).draw_mermaid_png()))
184
+ return react_graph
185
+
186
+ # test
187
+ if __name__ == "__main__":
188
+
189
+ react_graph = build_graph()
190
+ # Calc test
191
+ print("----Calculation tools test----")
192
+ question = "Calculate the result of 1+2*3+5 and multiply by 2"
193
+ messages = [HumanMessage(content=question)]
194
+ messages = react_graph.invoke({"messages": messages})
195
+
196
+ for m in messages['messages']:
197
+ m.pretty_print()
198
+
199
+ # Web search test
200
+ print("----Web search tools test----")
201
+ real_question = 'In April of 1977, who was the Prime Minister of the first place mentioned by name in the Book of Esther (in the New International Version)?'
202
+
203
+ messages = [HumanMessage(content=real_question)]
204
+ messages = react_graph.invoke({"messages": messages})
205
+
206
+ for m in messages['messages']:
207
+ m.pretty_print()
208
+
209
+
210
+
211
+
app.py CHANGED
@@ -1,196 +1,202 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import inspect
5
- import pandas as pd
6
-
7
- # (Keep Constants as is)
8
- # --- Constants ---
9
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
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
- def run_and_submit_all( profile: gr.OAuthProfile | None):
23
- """
24
- Fetches all questions, runs the BasicAgent on them, submits all answers,
25
- and displays the results.
26
- """
27
- # --- Determine HF Space Runtime URL and Repo URL ---
28
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
29
-
30
- if profile:
31
- username= f"{profile.username}"
32
- print(f"User logged in: {username}")
33
- else:
34
- print("User not logged in.")
35
- return "Please Login to Hugging Face with the button.", None
36
-
37
- api_url = DEFAULT_API_URL
38
- questions_url = f"{api_url}/questions"
39
- submit_url = f"{api_url}/submit"
40
-
41
- # 1. Instantiate Agent ( modify this part to create your agent)
42
- try:
43
- agent = BasicAgent()
44
- except Exception as e:
45
- print(f"Error instantiating agent: {e}")
46
- return f"Error initializing agent: {e}", None
47
- # 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)
48
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
- print(agent_code)
50
-
51
- # 2. Fetch Questions
52
- print(f"Fetching questions from: {questions_url}")
53
- try:
54
- response = requests.get(questions_url, timeout=15)
55
- response.raise_for_status()
56
- questions_data = response.json()
57
- if not questions_data:
58
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
- print(f"Fetched {len(questions_data)} questions.")
61
- except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
- except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
- except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
71
-
72
- # 3. Run your Agent
73
- results_log = []
74
- answers_payload = []
75
- print(f"Running agent on {len(questions_data)} questions...")
76
- for item in questions_data:
77
- task_id = item.get("task_id")
78
- question_text = item.get("question")
79
- if not task_id or question_text is None:
80
- print(f"Skipping item with missing task_id or question: {item}")
81
- continue
82
- try:
83
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
86
- except Exception as e:
87
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
-
90
- if not answers_payload:
91
- print("Agent did not produce any answers to submit.")
92
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
-
94
- # 4. Prepare Submission
95
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
- print(status_update)
98
-
99
- # 5. Submit
100
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
101
- try:
102
- response = requests.post(submit_url, json=submission_data, timeout=60)
103
- response.raise_for_status()
104
- result_data = response.json()
105
- final_status = (
106
- f"Submission Successful!\n"
107
- f"User: {result_data.get('username')}\n"
108
- f"Overall Score: {result_data.get('score', 'N/A')}% "
109
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
110
- f"Message: {result_data.get('message', 'No message received.')}"
111
- )
112
- print("Submission successful.")
113
- results_df = pd.DataFrame(results_log)
114
- return final_status, results_df
115
- except requests.exceptions.HTTPError as e:
116
- error_detail = f"Server responded with status {e.response.status_code}."
117
- try:
118
- error_json = e.response.json()
119
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
120
- except requests.exceptions.JSONDecodeError:
121
- error_detail += f" Response: {e.response.text[:500]}"
122
- status_message = f"Submission Failed: {error_detail}"
123
- print(status_message)
124
- results_df = pd.DataFrame(results_log)
125
- return status_message, results_df
126
- except requests.exceptions.Timeout:
127
- status_message = "Submission Failed: The request timed out."
128
- print(status_message)
129
- results_df = pd.DataFrame(results_log)
130
- return status_message, results_df
131
- except requests.exceptions.RequestException as e:
132
- status_message = f"Submission Failed: Network error - {e}"
133
- print(status_message)
134
- results_df = pd.DataFrame(results_log)
135
- return status_message, results_df
136
- except Exception as e:
137
- status_message = f"An unexpected error occurred during submission: {e}"
138
- print(status_message)
139
- results_df = pd.DataFrame(results_log)
140
- return status_message, results_df
141
-
142
-
143
- # --- Build Gradio Interface using Blocks ---
144
- with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
- gr.Markdown(
147
- """
148
- **Instructions:**
149
-
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
-
154
- ---
155
- **Disclaimers:**
156
- 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).
157
- 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.
158
- """
159
- )
160
-
161
- gr.LoginButton()
162
-
163
- run_button = gr.Button("Run Evaluation & Submit All Answers")
164
-
165
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
-
169
- run_button.click(
170
- fn=run_and_submit_all,
171
- outputs=[status_output, results_table]
172
- )
173
-
174
- if __name__ == "__main__":
175
- print("\n" + "-"*30 + " App Starting " + "-"*30)
176
- # Check for SPACE_HOST and SPACE_ID at startup for information
177
- space_host_startup = os.getenv("SPACE_HOST")
178
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
179
-
180
- if space_host_startup:
181
- print(f" SPACE_HOST found: {space_host_startup}")
182
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
183
- else:
184
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
185
-
186
- if space_id_startup: # Print repo URLs if SPACE_ID is found
187
- print(f"✅ SPACE_ID found: {space_id_startup}")
188
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
189
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
190
- else:
191
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
192
-
193
- print("-"*(60 + len(" App Starting ")) + "\n")
194
-
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
 
 
 
 
 
 
196
  demo.launch(debug=True, share=False)
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ import inspect
5
+ import pandas as pd
6
+ from agent import build_graph
7
+ from langchain_core.messages import HumanMessage
8
+
9
+ # (Keep Constants as is)
10
+ # --- Constants ---
11
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
12
+
13
+ # --- Basic Agent Definition ---
14
+ # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
15
+ class BasicAgent:
16
+ def __init__(self):
17
+ print("BasicAgent initialized.")
18
+ self.graph = build_graph()
19
+ def __call__(self, question: str) -> str:
20
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
21
+ messages = [HumanMessage(content=question)]
22
+ messages = self.graph.invoke({"messages": messages})
23
+ answer = messages['messages'][-1].content
24
+ fixed_answer = answer.replace("Final Answer: ","")
25
+ print(f"Agent returning fixed answer: {fixed_answer}")
26
+ return fixed_answer
27
+
28
+ def run_and_submit_all( profile: gr.OAuthProfile | None):
29
+ """
30
+ Fetches all questions, runs the BasicAgent on them, submits all answers,
31
+ and displays the results.
32
+ """
33
+ # --- Determine HF Space Runtime URL and Repo URL ---
34
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
35
+
36
+ if profile:
37
+ username= f"{profile.username}"
38
+ print(f"User logged in: {username}")
39
+ else:
40
+ print("User not logged in.")
41
+ return "Please Login to Hugging Face with the button.", None
42
+
43
+ api_url = DEFAULT_API_URL
44
+ questions_url = f"{api_url}/questions"
45
+ submit_url = f"{api_url}/submit"
46
+
47
+ # 1. Instantiate Agent ( modify this part to create your agent)
48
+ try:
49
+ agent = BasicAgent()
50
+ except Exception as e:
51
+ print(f"Error instantiating agent: {e}")
52
+ return f"Error initializing agent: {e}", None
53
+ # 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)
54
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
55
+ print(agent_code)
56
+
57
+ # 2. Fetch Questions
58
+ print(f"Fetching questions from: {questions_url}")
59
+ try:
60
+ response = requests.get(questions_url, timeout=15)
61
+ response.raise_for_status()
62
+ questions_data = response.json()
63
+ if not questions_data:
64
+ print("Fetched questions list is empty.")
65
+ return "Fetched questions list is empty or invalid format.", None
66
+ print(f"Fetched {len(questions_data)} questions.")
67
+ except requests.exceptions.RequestException as e:
68
+ print(f"Error fetching questions: {e}")
69
+ return f"Error fetching questions: {e}", None
70
+ except requests.exceptions.JSONDecodeError as e:
71
+ print(f"Error decoding JSON response from questions endpoint: {e}")
72
+ print(f"Response text: {response.text[:500]}")
73
+ return f"Error decoding server response for questions: {e}", None
74
+ except Exception as e:
75
+ print(f"An unexpected error occurred fetching questions: {e}")
76
+ return f"An unexpected error occurred fetching questions: {e}", None
77
+
78
+ # 3. Run your Agent
79
+ results_log = []
80
+ answers_payload = []
81
+ print(f"Running agent on {len(questions_data)} questions...")
82
+ for item in questions_data:
83
+ task_id = item.get("task_id")
84
+ question_text = item.get("question")
85
+ if not task_id or question_text is None:
86
+ print(f"Skipping item with missing task_id or question: {item}")
87
+ continue
88
+ try:
89
+ submitted_answer = agent(question_text)
90
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
91
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
92
+ except Exception as e:
93
+ print(f"Error running agent on task {task_id}: {e}")
94
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
95
+
96
+ if not answers_payload:
97
+ print("Agent did not produce any answers to submit.")
98
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
99
+
100
+ # 4. Prepare Submission
101
+ submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
102
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
103
+ print(status_update)
104
+
105
+ # 5. Submit
106
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
107
+ try:
108
+ response = requests.post(submit_url, json=submission_data, timeout=60)
109
+ response.raise_for_status()
110
+ result_data = response.json()
111
+ final_status = (
112
+ f"Submission Successful!\n"
113
+ f"User: {result_data.get('username')}\n"
114
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
115
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
116
+ f"Message: {result_data.get('message', 'No message received.')}"
117
+ )
118
+ print("Submission successful.")
119
+ results_df = pd.DataFrame(results_log)
120
+ return final_status, results_df
121
+ except requests.exceptions.HTTPError as e:
122
+ error_detail = f"Server responded with status {e.response.status_code}."
123
+ try:
124
+ error_json = e.response.json()
125
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
126
+ except requests.exceptions.JSONDecodeError:
127
+ error_detail += f" Response: {e.response.text[:500]}"
128
+ status_message = f"Submission Failed: {error_detail}"
129
+ print(status_message)
130
+ results_df = pd.DataFrame(results_log)
131
+ return status_message, results_df
132
+ except requests.exceptions.Timeout:
133
+ status_message = "Submission Failed: The request timed out."
134
+ print(status_message)
135
+ results_df = pd.DataFrame(results_log)
136
+ return status_message, results_df
137
+ except requests.exceptions.RequestException as e:
138
+ status_message = f"Submission Failed: Network error - {e}"
139
+ print(status_message)
140
+ results_df = pd.DataFrame(results_log)
141
+ return status_message, results_df
142
+ except Exception as e:
143
+ status_message = f"An unexpected error occurred during submission: {e}"
144
+ print(status_message)
145
+ results_df = pd.DataFrame(results_log)
146
+ return status_message, results_df
147
+
148
+
149
+ # --- Build Gradio Interface using Blocks ---
150
+ with gr.Blocks() as demo:
151
+ gr.Markdown("# Basic Agent Evaluation Runner")
152
+ gr.Markdown(
153
+ """
154
+ **Instructions:**
155
+
156
+ 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
157
+ 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
158
+ 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
159
+
160
+ ---
161
+ **Disclaimers:**
162
+ 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).
163
+ 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.
164
+ """
165
+ )
166
+
167
+ gr.LoginButton()
168
+
169
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
170
+
171
+ status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
172
+ # Removed max_rows=10 from DataFrame constructor
173
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
174
+
175
+ run_button.click(
176
+ fn=run_and_submit_all,
177
+ outputs=[status_output, results_table]
178
+ )
179
+
180
+ if __name__ == "__main__":
181
+ print("\n" + "-"*30 + " App Starting " + "-"*30)
182
+ # Check for SPACE_HOST and SPACE_ID at startup for information
183
+ space_host_startup = os.getenv("SPACE_HOST")
184
+ space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
185
+
186
+ if space_host_startup:
187
+ print(f"✅ SPACE_HOST found: {space_host_startup}")
188
+ print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
189
+ else:
190
+ print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
191
+
192
+ if space_id_startup: # Print repo URLs if SPACE_ID is found
193
+ print(f" SPACE_ID found: {space_id_startup}")
194
+ print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
195
+ print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
196
+ else:
197
+ print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
198
+
199
+ print("-"*(60 + len(" App Starting ")) + "\n")
200
+
201
+ print("Launching Gradio Interface for Basic Agent Evaluation...")
202
  demo.launch(debug=True, share=False)