Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211import os # 导入操作系统模块import gradio as gr # 导入Gradio库用于创建Web界面import requests # 导入请求库用于API调用import inspect # 导入检查模块用于函数检查import pandas as pd # 导入pandas用于数据处理from smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel, WikipediaSearchTool # 从smolagents导入所需组件# (Keep Constants as is) # 保持常量不变# --- Constants --- # 常量部分DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"deepseek_api_key = "sk-04da63f756c9468182d278f52e33ad15"deepseek_api_base_url = "https://api.deepseek.com"# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):# model = OpenAIServerModel(model_id="gpt-4o")# 已经直接设置了 API Key,不需要再检查环境变量model = OpenAIServerModel(model_id="deepseek-chat",api_base=deepseek_api_base_url,api_headers={"Authorization": f"Bearer {deepseek_api_key}", "Content-Type": "application/json"})search_tool = DuckDuckGoSearchTool()wiki_search = WikipediaSearchTool()self.agent = CodeAgent( # 初始化代码代理model = model, # 设置模型tools=[ # 设置可用工具列表search_tool, # 搜索工具wiki_search # 维基百科工具])def __call__(self, question: str) -> str: # 定义调用方法,使对象可直接调用return self.agent.run(question) # type: ignore # 运行代理并返回结果def run_and_submit_all( profile: gr.OAuthProfile | None): # 运行并提交所有回答的函数"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results."""# --- Determine HF Space Runtime URL and Repo URL ---space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code # 获取SPACE_ID用于发送代码链接if profile: # 如果用户已登录username= f"{profile.username}" # 获取用户名print(f"User logged in: {username}") # 打印已登录的用户名else: # 如果用户未登录print("User not logged in.") # 打印用户未登录return "Please Login to Hugging Face with the button.", None # 返回请求登录的消息api_url = DEFAULT_API_URL # 设置API URLquestions_url = f"{api_url}/questions" # 构建获取问题的URLsubmit_url = f"{api_url}/submit" # 构建提交答案的URL# 1. Instantiate Agent ( modify this part to create your agent) # 1. 实例化代理(修改此部分来创建你的代理)try: # 尝试agent = BasicAgent() # 创建基本代理实例except Exception as e: # 捕获异常print(f"Error instantiating agent: {e}") # 打印代理实例化错误return f"Error initializing agent: {e}", None # 返回初始化错误信息# 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空间运行时,此链接指向你的代码库(对其他人有用,请保持公开)agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main" # 构建代码库URLprint(agent_code) # 打印代码库URL# 2. Fetch Questions # 2. 获取问题print(f"Fetching questions from: {questions_url}") # 打印正在从哪个URL获取问题try: # 尝试response = requests.get(questions_url, timeout=15) # 发送GET请求获取问题,超时设置为15秒response.raise_for_status() # 检查HTTP错误questions_data = response.json() # 解析JSON响应if not questions_data: # 如果问题列表为空print("Fetched questions list is empty.") # 打印问题列表为空return "Fetched questions list is empty or invalid format.", None # 返回问题列表为空或格式无效的消息print(f"Fetched {len(questions_data)} questions.") # 打印获取到的问题数量except requests.exceptions.RequestException as e: # 捕获请求异常print(f"Error fetching questions: {e}") # 打印获取问题错误return f"Error fetching questions: {e}", None # 返回获取问题错误except requests.exceptions.JSONDecodeError as e: # 捕获JSON解码错误print(f"Error decoding JSON response from questions endpoint: {e}") # 打印JSON解码错误print(f"Response text: {response.text[:500]}") # 打印响应文本(前500个字符)return f"Error decoding server response for questions: {e}", None # 返回服务器响应解码错误except Exception as e: # 捕获其他异常print(f"An unexpected error occurred fetching questions: {e}") # 打印获取问题时发生意外错误return f"An unexpected error occurred fetching questions: {e}", None # 返回获取问题时发生意外错误# 3. Run your Agent # 3. 运行你的代理results_log = [] # 初始化结果日志列表answers_payload = [] # 初始化答案载荷列表print(f"Running agent on {len(questions_data)} questions...") # 打印正在多少个问题上运行代理for item in questions_data: # 遍历每个问题数据项task_id = item.get("task_id") # 获取任务IDquestion_text = item.get("question") # 获取问题文本if not task_id or question_text is None: # 如果任务ID或问题文本缺失print(f"Skipping item with missing task_id or question: {item}") # 打印跳过缺少任务ID或问题的项continue # 继续下一个循环try: # 尝试submitted_answer = agent(question_text) # 使用代理回答问题answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer}) # 将答案添加到载荷中results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer}) # 将结果添加到日志中except Exception as e: # 捕获异常print(f"Error running agent on task {task_id}: {e}") # 打印在任务上运行代理时出错results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"}) # 将错误添加到结果日志中if not answers_payload: # 如果答案载荷为空print("Agent did not produce any answers to submit.") # 打印代理没有产生任何答案可提交return "Agent did not produce any answers to submit.", pd.DataFrame(results_log) # 返回代理没有产生任何答案可提交# 4. Prepare Submission # 4. 准备提交submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload} # 准备提交数据status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..." # 构建状态更新消息print(status_update) # 打印状态更新# 5. Submit # 5. 提交print(f"Submitting {len(answers_payload)} answers to: {submit_url}") # 打印正在将多少个答案提交到哪个URLtry: # 尝试response = requests.post(submit_url, json=submission_data, timeout=60) # 发送POST请求提交数据,超时设置为60秒response.raise_for_status() # 检查HTTP错误result_data = response.json() # 解析JSON响应final_status = ( # 构建最终状态消息f"Submission Successful!\n" # 提交成功f"User: {result_data.get('username')}\n" # 用户名f"Overall Score: {result_data.get('score', 'N/A')}% " # 总分f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n" # 正确数/总尝试数f"Message: {result_data.get('message', 'No message received.')}" # 消息)print("Submission successful.") # 打印提交成功results_df = pd.DataFrame(results_log) # 创建结果数据框return final_status, results_df # 返回最终状态和结果数据框except requests.exceptions.HTTPError as e: # 捕获HTTP错误error_detail = f"Server responded with status {e.response.status_code}." # 服务器响应状态try: # 尝试error_json = e.response.json() # 解析错误响应的JSONerror_detail += f" Detail: {error_json.get('detail', e.response.text)}" # 添加错误详情except requests.exceptions.JSONDecodeError: # 捕获JSON解码错误error_detail += f" Response: {e.response.text[:500]}" # 添加原始响应文本status_message = f"Submission Failed: {error_detail}" # 构建提交失败消息print(status_message) # 打印状态消息results_df = pd.DataFrame(results_log) # 创建结果数据框return status_message, results_df # 返回状态消息和结果数据框except requests.exceptions.Timeout: # 捕获超时异常status_message = "Submission Failed: The request timed out." # 构建请求超时消息print(status_message) # 打印状态消息results_df = pd.DataFrame(results_log) # 创建结果数据框return status_message, results_df # 返回状态消息和结果数据框except requests.exceptions.RequestException as e: # 捕获请求异常status_message = f"Submission Failed: Network error - {e}" # 构建网络错误消息print(status_message) # 打印状态消息results_df = pd.DataFrame(results_log) # 创建结果数据框return status_message, results_df # 返回状态消息和结果数据框except Exception as e: # 捕获其他异常status_message = f"An unexpected error occurred during submission: {e}" # 构建意外错误消息print(status_message) # 打印状态消息results_df = pd.DataFrame(results_log) # ���建结果数据框return status_message, results_df # 返回状态消息和结果数据框# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo: # 创建Gradio Blocks界面gr.Markdown("# Basic Agent Evaluation Runner") # 添加标题gr.Markdown( # 添加说明文本"""Modified by niku.... # 由niku修改**Instructions:** # 指示1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ... # 请克隆此空间,然后修改代码以定义代理逻辑、工具和必要的包等2. Log in to your Hugging Face account using the button below. This uses your HF username for submission. # 使用下面的按钮登录您的Hugging Face账户。这将使用您的HF用户名进行提交3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score. # 点击"运行评估并提交所有答案"以获取问题,运行您的代理,提交答案,并查看分数---**Disclaimers:** # 免责声明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). # 点击"提交"按钮后,可能需要相当长的时间(这是代理回答所有问题所需的时间)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. # 此空间提供了一个基本设置,故意设计成不是最优的,以鼓励您开发自己的更强大的解决方案。例如,对于提交按钮的延迟过程,一个解决方案可能是缓存答案并在单独的操作中提交,或者甚至异步回答问题""")gr.LoginButton() # 添加登录按钮run_button = gr.Button("Run Evaluation & Submit All Answers") # 添加运行评估按钮status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False) # 添加状态输出文本框# Removed max_rows=10 from DataFrame constructor # 从DataFrame构造函数中移除了max_rows=10results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True) # 添加结果表格run_button.click( # 设置按钮点击事件fn=run_and_submit_all, # 点击时运行的函数outputs=[status_output, results_table] # 输出组件)if __name__ == "__main__": # 如果这个脚本作为主程序运行print("\n" + "-"*30 + " App Starting " + "-"*30) # 打印应用启动分隔线# Check for SPACE_HOST and SPACE_ID at startup for information # 启动时检查SPACE_HOST和SPACE_ID信息space_host_startup = os.getenv("SPACE_HOST") # 获取SPACE_HOST环境变量space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup # 获取SPACE_ID环境变量if space_host_startup: # 如果找到SPACE_HOSTprint(f"✅ SPACE_HOST found: {space_host_startup}") # 打印找到SPACE_HOSTprint(f" Runtime URL should be: https://{space_host_startup}.hf.space") # 打印运行时URLelse: # 如果没找到SPACE_HOSTprint("ℹ️ SPACE_HOST environment variable not found (running locally?).") # 打印SPACE_HOST环境变量未找到if space_id_startup: # Print repo URLs if SPACE_ID is found # 如果找到SPACE_ID,打印代码库URLprint(f"✅ SPACE_ID found: {space_id_startup}") # 打印找到SPACE_IDprint(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}") # 打印代码库URLprint(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main") # 打印代码库树URLelse: # 如果没找到SPACE_IDprint("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.") # 打印SPACE_ID环境变量未找到print("-"*(60 + len(" App Starting ")) + "\n") # 打印结束分隔线print("Launching Gradio Interface for Basic Agent Evaluation...") # 打印正在启动Gradio界面demo.launch(debug=True, share=False) # 启动Gradio演示,启用调试模式,不共享123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207import osimport gradio as grimport requestsimport inspectimport pandas as pdfrom smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel, WikipediaSearchTool# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------class BasicAgent:def __init__(self):model = OpenAIServerModel(model_id="deepseek-chat",api_key="sk-04da63f756c9468182d278f52e33ad15", api_base="https://api.deepseek.com")search_tool = DuckDuckGoSearchTool()wiki_search = WikipediaSearchTool()self.agent = CodeAgent(model = model,tools=[search_tool,])def __call__(self, question: str) -> str:return self.agent.run(question) # type: ignoredef run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results."""# --- Determine HF Space Runtime URL and Repo URL ---space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the codeif profile:username= f"{profile.username}"print(f"User logged in: {username}")else:print("User not logged in.")return "Please Login to Hugging Face with the button.", Noneapi_url = DEFAULT_API_URLquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent()except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None# 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)agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)# 2. Fetch Questionsprint(f"Fetching questions from: {questions_url}")try:response = requests.get(questions_url, timeout=15)response.raise_for_status()questions_data = response.json()if not questions_data:print("Fetched questions list is empty.")return "Fetched questions list is empty or invalid format.", Noneprint(f"Fetched {len(questions_data)} questions.")except requests.exceptions.RequestException as e:print(f"Error fetching questions: {e}")return f"Error fetching questions: {e}", Noneexcept requests.exceptions.JSONDecodeError as e:print(f"Error decoding JSON response from questions endpoint: {e}")print(f"Response text: {response.text[:500]}")return f"Error decoding server response for questions: {e}", Noneexcept Exception as e:print(f"An unexpected error occurred fetching questions: {e}")return f"An unexpected error occurred fetching questions: {e}", None# 3. Run your Agentresults_log = []answers_payload = []print(f"Running agent on {len(questions_data)} questions...")for item in questions_data:task_id = item.get("task_id")question_text = item.get("question")if not task_id or question_text is None:print(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = agent(question_text)answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})except Exception as e:print(f"Error running agent on task {task_id}: {e}")results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})if not answers_payload:print("Agent did not produce any answers to submit.")return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)# 4. Prepare Submissionsubmission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."print(status_update)# 5. Submitprint(f"Submitting {len(answers_payload)} answers to: {submit_url}")try:response = requests.post(submit_url, json=submission_data, timeout=60)response.raise_for_status()result_data = response.json()final_status = (f"Submission Successful!\n"f"User: {result_data.get('username')}\n"f"Overall Score: {result_data.get('score', 'N/A')}% "f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"f"Message: {result_data.get('message', 'No message received.')}")print("Submission successful.")results_df = pd.DataFrame(results_log)return final_status, results_dfexcept requests.exceptions.HTTPError as e:error_detail = f"Server responded with status {e.response.status_code}."try:error_json = e.response.json()error_detail += f" Detail: {error_json.get('detail', e.response.text)}"except requests.exceptions.JSONDecodeError:error_detail += f" Response: {e.response.text[:500]}"status_message = f"Submission Failed: {error_detail}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept requests.exceptions.Timeout:status_message = "Submission Failed: The request timed out."print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept requests.exceptions.RequestException as e:status_message = f"Submission Failed: Network error - {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_dfexcept Exception as e:status_message = f"An unexpected error occurred during submission: {e}"print(status_message)results_df = pd.DataFrame(results_log)return status_message, results_df# --- Build Gradio Interface using Blocks ---with gr.Blocks() as demo:gr.Markdown("# Basic Agent Evaluation Runner")gr.Markdown("""**Instructions:**1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.---**Disclaimers:**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).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.Please note that this version requires an OpenAI Key to run.""")gr.LoginButton()run_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)# Removed max_rows=10 from DataFrame constructorresults_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(fn=run_and_submit_all,outputs=[status_output, results_table])if __name__ == "__main__":print("\n" + "-"*30 + " App Starting " + "-"*30)# Check for SPACE_HOST and SPACE_ID at startup for informationspace_host_startup = os.getenv("SPACE_HOST")space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startupif space_host_startup:print(f"✅ SPACE_HOST found: {space_host_startup}")print(f" Runtime URL should be: https://{space_host_startup}.hf.space")else:print("ℹ️ SPACE_HOST environment variable not found (running locally?).")if space_id_startup: # Print repo URLs if SPACE_ID is foundprint(f"✅ SPACE_ID found: {space_id_startup}")print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")else:print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")print("-"*(60 + len(" App Starting ")) + "\n")print("Launching Gradio Interface for Basic Agent Evaluation...")demo.launch(debug=True, share=False)
app.py+189-193