Update app.py
Browse files
app.py
CHANGED
|
@@ -1,222 +1,212 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel
|
| 8 |
-
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
#
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
#model = HfApiModel()
|
| 22 |
-
if not DEEPSEEK_API_KEY: # 添加一个检查,确保密钥已设置
|
| 23 |
-
raise ValueError("DEEPSEEK_API_KEY environment variable not set. Please set it before running.")
|
| 24 |
-
|
| 25 |
-
openai.api_key = DEEPSEEK_API_KEY # <--- 步骤 2: 全局设置 API 密钥
|
| 26 |
-
|
| 27 |
-
# 为 openai 库设置基础 URL
|
| 28 |
-
openai.api_base = DEEPSEEK_API_BASE
|
| 29 |
-
|
| 30 |
model = OpenAIServerModel(
|
| 31 |
-
model_id="deepseek-chat",
|
| 32 |
-
|
|
|
|
| 33 |
)
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
self.agent = CodeAgent(
|
| 38 |
-
model = model,
|
| 39 |
-
tools=[
|
|
|
|
|
|
|
|
|
|
| 40 |
)
|
| 41 |
-
def __call__(self, question: str) -> str:
|
| 42 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 43 |
-
fixed_answer =self.agent.run(question)
|
| 44 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 45 |
-
return fixed_answer
|
| 46 |
|
| 47 |
-
def
|
|
|
|
|
|
|
|
|
|
| 48 |
"""
|
| 49 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 50 |
and displays the results.
|
| 51 |
-
"""
|
| 52 |
-
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 53 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 54 |
-
|
| 55 |
-
if profile:
|
| 56 |
-
username= f"{profile.username}"
|
| 57 |
-
print(f"User logged in: {username}")
|
| 58 |
-
else:
|
| 59 |
-
print("User not logged in.")
|
| 60 |
-
return "Please Login to Hugging Face with the button.", None
|
| 61 |
-
|
| 62 |
-
api_url = DEFAULT_API_URL
|
| 63 |
-
questions_url = f"{api_url}/questions"
|
| 64 |
-
submit_url = f"{api_url}/submit"
|
| 65 |
-
|
| 66 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 67 |
-
try:
|
| 68 |
-
agent = BasicAgent()
|
| 69 |
-
except Exception as e:
|
| 70 |
-
print(f"Error instantiating agent: {e}")
|
| 71 |
-
return f"Error initializing agent: {e}", None
|
| 72 |
-
# 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)
|
| 73 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 74 |
-
print(agent_code)
|
| 75 |
-
|
| 76 |
-
# 2. Fetch Questions
|
| 77 |
-
print(f"Fetching questions from: {questions_url}")
|
| 78 |
-
try:
|
| 79 |
-
response = requests.get(questions_url, timeout=15)
|
| 80 |
-
response.raise_for_status()
|
| 81 |
-
questions_data = response.json()
|
| 82 |
-
if not questions_data:
|
| 83 |
-
print("Fetched questions list is empty.")
|
| 84 |
-
return "Fetched questions list is empty or invalid format.", None
|
| 85 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 86 |
-
except requests.exceptions.RequestException as e:
|
| 87 |
-
print(f"Error fetching questions: {e}")
|
| 88 |
-
return f"Error fetching questions: {e}", None
|
| 89 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 90 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 91 |
-
print(f"Response text: {response.text[:500]}")
|
| 92 |
-
return f"Error decoding server response for questions: {e}", None
|
| 93 |
-
except Exception as e:
|
| 94 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 95 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 96 |
-
|
| 97 |
-
# 3. Run your Agent
|
| 98 |
-
results_log = []
|
| 99 |
-
answers_payload = []
|
| 100 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 101 |
-
for item in questions_data:
|
| 102 |
-
task_id = item.get("task_id")
|
| 103 |
-
question_text = item.get("question")
|
| 104 |
-
if not task_id or question_text is None:
|
| 105 |
-
print(f"Skipping item with missing task_id or question: {item}")
|
| 106 |
-
continue
|
| 107 |
-
try:
|
| 108 |
-
submitted_answer = agent(question_text)
|
| 109 |
-
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 110 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 111 |
-
except Exception as e:
|
| 112 |
-
print(f"Error running agent on task {task_id}: {e}")
|
| 113 |
-
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 114 |
-
|
| 115 |
-
if not answers_payload:
|
| 116 |
-
print("Agent did not produce any answers to submit.")
|
| 117 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 118 |
-
|
| 119 |
-
# 4. Prepare Submission
|
| 120 |
-
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 121 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 122 |
-
print(status_update)
|
| 123 |
-
|
| 124 |
-
# 5. Submit
|
| 125 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 126 |
-
try:
|
| 127 |
-
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 128 |
-
response.raise_for_status()
|
| 129 |
-
result_data = response.json()
|
| 130 |
-
final_status = (
|
| 131 |
-
f"Submission Successful!\n"
|
| 132 |
-
f"User: {result_data.get('username')}\n"
|
| 133 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 134 |
-
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 135 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 136 |
)
|
| 137 |
-
print("Submission successful.")
|
| 138 |
-
results_df = pd.DataFrame(results_log)
|
| 139 |
-
return final_status, results_df
|
| 140 |
-
except requests.exceptions.HTTPError as e:
|
| 141 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 142 |
-
try:
|
| 143 |
-
error_json = e.response.json()
|
| 144 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 145 |
-
except requests.exceptions.JSONDecodeError:
|
| 146 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 147 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 148 |
-
print(status_message)
|
| 149 |
-
results_df = pd.DataFrame(results_log)
|
| 150 |
-
return status_message, results_df
|
| 151 |
-
except requests.exceptions.Timeout:
|
| 152 |
-
status_message = "Submission Failed: The request timed out."
|
| 153 |
-
print(status_message)
|
| 154 |
-
results_df = pd.DataFrame(results_log)
|
| 155 |
-
return status_message, results_df
|
| 156 |
-
except requests.exceptions.RequestException as e:
|
| 157 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 158 |
-
print(status_message)
|
| 159 |
-
results_df = pd.DataFrame(results_log)
|
| 160 |
-
return status_message, results_df
|
| 161 |
-
except Exception as e:
|
| 162 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
| 163 |
-
print(status_message)
|
| 164 |
-
results_df = pd.DataFrame(results_log)
|
| 165 |
-
return status_message, results_df
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
gr.Markdown(
|
| 171 |
-
gr.Markdown(
|
| 172 |
"""
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 176 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 177 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 178 |
-
|
| 179 |
---
|
| 180 |
-
**Disclaimers:**
|
| 181 |
-
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).
|
| 182 |
-
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.
|
| 183 |
-
Please note that this version requires an OpenAI Key to run.
|
| 184 |
"""
|
| 185 |
)
|
| 186 |
|
| 187 |
-
gr.LoginButton()
|
| 188 |
|
| 189 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 190 |
|
| 191 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 192 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 193 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 194 |
|
| 195 |
-
run_button.click(
|
| 196 |
-
fn=run_and_submit_all,
|
| 197 |
-
outputs=[status_output, results_table]
|
| 198 |
)
|
| 199 |
|
| 200 |
-
if __name__ == "__main__":
|
| 201 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 202 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 203 |
-
space_host_startup = os.getenv("SPACE_HOST")
|
| 204 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 205 |
-
|
| 206 |
-
if space_host_startup:
|
| 207 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 208 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 209 |
-
else:
|
| 210 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 211 |
-
|
| 212 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 213 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 214 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 215 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 216 |
-
else:
|
| 217 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 218 |
-
|
| 219 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 220 |
-
|
| 221 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 222 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
+
import os # 导入操作系统模块
|
| 2 |
+
import gradio as gr # 导入Gradio库用于创建Web界面
|
| 3 |
+
import requests # 导入请求库用于API调用
|
| 4 |
+
import inspect # 导入检查模块用于函数检查
|
| 5 |
+
import pandas as pd # 导入pandas用于数据处理
|
| 6 |
+
|
| 7 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel, WikipediaSearchTool # 从smolagents导入所需组件
|
| 8 |
+
|
| 9 |
+
# (Keep Constants as is) # 保持常量不变
|
| 10 |
+
# --- Constants --- # 常量部分
|
| 11 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
+
deepseek_api_key = os.environ.get("DEEPSEEK_API_KEY") # 从环境变量中获取 DeepSeek API Key
|
| 13 |
+
deepseek_api_base_url = "https://api.deepseek.com"
|
| 14 |
+
# --- Basic Agent Definition ---
|
| 15 |
+
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 16 |
+
class BasicAgent:
|
| 17 |
+
def __init__(self):
|
| 18 |
+
# model = OpenAIServerModel(model_id="gpt-4o")
|
| 19 |
+
if not deepseek_api_key:
|
| 20 |
+
raise ValueError("DeepSeek API Key not found in environment variables.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
model = OpenAIServerModel(
|
| 22 |
+
model_id="deepseek-chat",
|
| 23 |
+
api_base=deepseek_api_base_url,
|
| 24 |
+
api_headers={"Authorization": f"Bearer {deepseek_api_key}", "Content-Type": "application/json"}
|
| 25 |
)
|
| 26 |
+
search_tool = DuckDuckGoSearchTool()
|
| 27 |
+
wiki_search = WikipediaSearchTool()
|
| 28 |
+
|
| 29 |
+
self.agent = CodeAgent( # 初始化代码代理
|
| 30 |
+
model = model, # 设置模型
|
| 31 |
+
tools=[ # 设置可用工具列表
|
| 32 |
+
search_tool, # 搜索工具
|
| 33 |
+
wiki_search # 维基百科工具
|
| 34 |
+
]
|
| 35 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
def __call__(self, question: str) -> str: # 定义调用方法,使对象可直接调用
|
| 38 |
+
return self.agent.run(question) # type: ignore # 运行代理并返回结果
|
| 39 |
+
|
| 40 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None): # 运行并提交所有回答的函数
|
| 41 |
"""
|
| 42 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 43 |
and displays the results.
|
| 44 |
+
"""
|
| 45 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 46 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code # 获取SPACE_ID用于发送代码链接
|
| 47 |
+
|
| 48 |
+
if profile: # 如果用户已登录
|
| 49 |
+
username= f"{profile.username}" # 获取用户名
|
| 50 |
+
print(f"User logged in: {username}") # 打印已登录的用户名
|
| 51 |
+
else: # 如果用户未登录
|
| 52 |
+
print("User not logged in.") # 打印用户未登录
|
| 53 |
+
return "Please Login to Hugging Face with the button.", None # 返回请求登录的消息
|
| 54 |
+
|
| 55 |
+
api_url = DEFAULT_API_URL # 设置API URL
|
| 56 |
+
questions_url = f"{api_url}/questions" # 构建获取问题的URL
|
| 57 |
+
submit_url = f"{api_url}/submit" # 构建提交答案的URL
|
| 58 |
+
|
| 59 |
+
# 1. Instantiate Agent ( modify this part to create your agent) # 1. 实例化代理(修改此部分来创建你的代理)
|
| 60 |
+
try: # 尝试
|
| 61 |
+
agent = BasicAgent() # 创建基本代理实例
|
| 62 |
+
except Exception as e: # 捕获异常
|
| 63 |
+
print(f"Error instantiating agent: {e}") # 打印代理实例化错误
|
| 64 |
+
return f"Error initializing agent: {e}", None # 返回初始化错误信息
|
| 65 |
+
# 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) # 当应用程序作为Hugging Face空间运行时,此链接指向你的代码库(对其他人有用,请保持公开)
|
| 66 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" # 构建代码库URL
|
| 67 |
+
print(agent_code) # 打印代码库URL
|
| 68 |
+
|
| 69 |
+
# 2. Fetch Questions # 2. 获取问题
|
| 70 |
+
print(f"Fetching questions from: {questions_url}") # 打印正在从哪个URL获取问题
|
| 71 |
+
try: # 尝试
|
| 72 |
+
response = requests.get(questions_url, timeout=15) # 发送GET请求获取问题,超时设置为15秒
|
| 73 |
+
response.raise_for_status() # 检查HTTP错误
|
| 74 |
+
questions_data = response.json() # 解析JSON响应
|
| 75 |
+
if not questions_data: # 如果问题列表为空
|
| 76 |
+
print("Fetched questions list is empty.") # 打印问题列表为空
|
| 77 |
+
return "Fetched questions list is empty or invalid format.", None # 返回问题列表为空或格式无效的消息
|
| 78 |
+
print(f"Fetched {len(questions_data)} questions.") # 打印获取到的问题数量
|
| 79 |
+
except requests.exceptions.RequestException as e: # 捕获请求异常
|
| 80 |
+
print(f"Error fetching questions: {e}") # 打印获取问题错误
|
| 81 |
+
return f"Error fetching questions: {e}", None # 返回获取问题错误
|
| 82 |
+
except requests.exceptions.JSONDecodeError as e: # 捕获JSON解码错误
|
| 83 |
+
print(f"Error decoding JSON response from questions endpoint: {e}") # 打印JSON解码错误
|
| 84 |
+
print(f"Response text: {response.text[:500]}") # 打印响应文本(前500个字符)
|
| 85 |
+
return f"Error decoding server response for questions: {e}", None # 返回服务器响应解码错误
|
| 86 |
+
except Exception as e: # 捕获其他异常
|
| 87 |
+
print(f"An unexpected error occurred fetching questions: {e}") # 打印获取问题时发生意外错误
|
| 88 |
+
return f"An unexpected error occurred fetching questions: {e}", None # 返回获取问题时发生意外错误
|
| 89 |
+
|
| 90 |
+
# 3. Run your Agent # 3. 运行你的代理
|
| 91 |
+
results_log = [] # 初始化结果日志列表
|
| 92 |
+
answers_payload = [] # 初始化答案载荷列表
|
| 93 |
+
print(f"Running agent on {len(questions_data)} questions...") # 打印正在多少个问题上运行代理
|
| 94 |
+
for item in questions_data: # 遍历每个问题数据项
|
| 95 |
+
task_id = item.get("task_id") # 获取任务ID
|
| 96 |
+
question_text = item.get("question") # 获取问题文本
|
| 97 |
+
if not task_id or question_text is None: # 如果任务ID或问题文本缺失
|
| 98 |
+
print(f"Skipping item with missing task_id or question: {item}") # 打印跳过缺少任务ID或问题的项
|
| 99 |
+
continue # 继续下一个循环
|
| 100 |
+
try: # 尝试
|
| 101 |
+
submitted_answer = agent(question_text) # 使用代理回答问题
|
| 102 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer}) # 将答案添加到载荷中
|
| 103 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer}) # 将结果添加到日志中
|
| 104 |
+
except Exception as e: # 捕获异常
|
| 105 |
+
print(f"Error running agent on task {task_id}: {e}") # 打印在任务上运行代理时出错
|
| 106 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"}) # 将错误添加到结果日志中
|
| 107 |
+
|
| 108 |
+
if not answers_payload: # 如果答案载荷为空
|
| 109 |
+
print("Agent did not produce any answers to submit.") # 打印代理没有产生任何答案可提交
|
| 110 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log) # 返回代理没有产生任何答案可提交
|
| 111 |
+
|
| 112 |
+
# 4. Prepare Submission # 4. 准备提交
|
| 113 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} # 准备提交数据
|
| 114 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..." # 构建状态更新消息
|
| 115 |
+
print(status_update) # 打印状态更新
|
| 116 |
+
|
| 117 |
+
# 5. Submit # 5. 提交
|
| 118 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}") # 打印正在将多少个答案提交到哪个URL
|
| 119 |
+
try: # 尝试
|
| 120 |
+
response = requests.post(submit_url, json=submission_data, timeout=60) # 发送POST请求提交数据,超时设置为60秒
|
| 121 |
+
response.raise_for_status() # 检查HTTP错误
|
| 122 |
+
result_data = response.json() # 解析JSON响应
|
| 123 |
+
final_status = ( # 构建最终状态消息
|
| 124 |
+
f"Submission Successful!\n" # 提交成功
|
| 125 |
+
f"User: {result_data.get('username')}\n" # 用户名
|
| 126 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% " # 总分
|
| 127 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n" # 正确数/总尝试数
|
| 128 |
+
f"Message: {result_data.get('message', 'No message received.')}" # 消息
|
| 129 |
)
|
| 130 |
+
print("Submission successful.") # 打印提交成功
|
| 131 |
+
results_df = pd.DataFrame(results_log) # 创建结果数据框
|
| 132 |
+
return final_status, results_df # 返回最终状态和结果数据框
|
| 133 |
+
except requests.exceptions.HTTPError as e: # 捕获HTTP错误
|
| 134 |
+
error_detail = f"Server responded with status {e.response.status_code}." # 服务器响应状态
|
| 135 |
+
try: # 尝试
|
| 136 |
+
error_json = e.response.json() # 解析错误响应的JSON
|
| 137 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}" # 添加错误详情
|
| 138 |
+
except requests.exceptions.JSONDecodeError: # 捕获JSON解码错误
|
| 139 |
+
error_detail += f" Response: {e.response.text[:500]}" # 添加原始响应文本
|
| 140 |
+
status_message = f"Submission Failed: {error_detail}" # 构建提交失败消息
|
| 141 |
+
print(status_message) # 打印状态消息
|
| 142 |
+
results_df = pd.DataFrame(results_log) # 创建结果数据框
|
| 143 |
+
return status_message, results_df # 返回状态消息和结果数据框
|
| 144 |
+
except requests.exceptions.Timeout: # 捕获超时异常
|
| 145 |
+
status_message = "Submission Failed: The request timed out." # 构建请求超时消息
|
| 146 |
+
print(status_message) # 打印状态消息
|
| 147 |
+
results_df = pd.DataFrame(results_log) # 创建结果数据框
|
| 148 |
+
return status_message, results_df # 返回状态消息和结果数据框
|
| 149 |
+
except requests.exceptions.RequestException as e: # 捕获请求异常
|
| 150 |
+
status_message = f"Submission Failed: Network error - {e}" # 构建网络错误消息
|
| 151 |
+
print(status_message) # 打印状态消息
|
| 152 |
+
results_df = pd.DataFrame(results_log) # 创建结果数据框
|
| 153 |
+
return status_message, results_df # 返回状态消息和结果数据框
|
| 154 |
+
except Exception as e: # 捕获其他异常
|
| 155 |
+
status_message = f"An unexpected error occurred during submission: {e}" # 构建意外错误消息
|
| 156 |
+
print(status_message) # 打印状态消息
|
| 157 |
+
results_df = pd.DataFrame(results_log) # 创建结果数据框
|
| 158 |
+
return status_message, results_df # 返回状态消息和结果数据框
|
| 159 |
+
|
| 160 |
+
# --- Build Gradio Interface using Blocks ---
|
| 161 |
+
with gr.Blocks() as demo: # 创建Gradio Blocks界面
|
| 162 |
+
gr.Markdown("# Basic Agent Evaluation Runner") # 添加标题
|
| 163 |
+
gr.Markdown( # 添加说明文本
|
|
|
|
| 164 |
"""
|
| 165 |
+
Modified by niku.... # 由niku修改
|
| 166 |
+
**Instructions:** # 指示
|
| 167 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ... # 请克隆此空间,然后修改代码以定义代理逻辑、工具和必要的包等
|
| 168 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission. # 使用下面的按钮登录您的Hugging Face账户。这将使用您的HF用户名进行提交
|
| 169 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score. # 点击"运行评估并提交所有答案"以获取问题,运行您的代理,提交答案,并查看分数
|
|
|
|
| 170 |
---
|
| 171 |
+
**Disclaimers:** # 免责声明
|
| 172 |
+
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). # 点击"提交"按钮后,可能需要相当长的时间(这是代理回答所有问题所需的时间)
|
| 173 |
+
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. # 此空间提供了一个基本设置,故意设计成不是最优的,以鼓励您开发自��的更强大的解决方案。例如,对于提交按钮的延迟过程,一个解决方案可能是缓存答案并在单独的操作中提交,或者甚至异步回答问题
|
|
|
|
| 174 |
"""
|
| 175 |
)
|
| 176 |
|
| 177 |
+
gr.LoginButton() # 添加登录按钮
|
| 178 |
|
| 179 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers") # 添加运行评估按钮
|
| 180 |
|
| 181 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False) # 添加状态输出文本框
|
| 182 |
+
# Removed max_rows=10 from DataFrame constructor # 从DataFrame构造函数中移除了max_rows=10
|
| 183 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) # 添加结果表格
|
| 184 |
|
| 185 |
+
run_button.click( # 设置按钮点击事件
|
| 186 |
+
fn=run_and_submit_all, # 点击时运行的函数
|
| 187 |
+
outputs=[status_output, results_table] # 输出组件
|
| 188 |
)
|
| 189 |
|
| 190 |
+
if __name__ == "__main__": # 如果这个脚本作为主程序运行
|
| 191 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30) # 打印应用启动分隔线
|
| 192 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information # 启动时检查SPACE_HOST和SPACE_ID信息
|
| 193 |
+
space_host_startup = os.getenv("SPACE_HOST") # 获取SPACE_HOST环境变量
|
| 194 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup # 获取SPACE_ID环境变量
|
| 195 |
+
|
| 196 |
+
if space_host_startup: # 如果找到SPACE_HOST
|
| 197 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}") # 打印找到SPACE_HOST
|
| 198 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space") # 打印运行时URL
|
| 199 |
+
else: # 如果没找到SPACE_HOST
|
| 200 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).") # 打印SPACE_HOST环境变量未找到
|
| 201 |
+
|
| 202 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found # 如果找到SPACE_ID,打印代码库URL
|
| 203 |
+
print(f"✅ SPACE_ID found: {space_id_startup}") # 打印找到SPACE_ID
|
| 204 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}") # 打印代码库URL
|
| 205 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main") # 打印代码库树URL
|
| 206 |
+
else: # 如果没找到SPACE_ID
|
| 207 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.") # 打印SPACE_ID环境变量未找到
|
| 208 |
+
|
| 209 |
+
print("-"*(60 + len(" App Starting ")) + "\n") # 打印结束分隔线
|
| 210 |
+
|
| 211 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...") # 打印正在启动Gradio界面
|
| 212 |
+
demo.launch(debug=True, share=False) # 启动Gradio演示,启用调试模式,不共享
|