Spaces:
Sleeping
Sleeping
Update app.py
Browse files2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514 unmodified lines160161162163164165166101 unmodified lines2682692702712722732742752762772782792802812822832842852862872882892902912 unmodified linesimport requestsimport inspectimport pandas as pdfrom smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel, VisitWebpageTool, Tool, HfApiModel, ToolCallingAgentimport io# (Keep Constants as is)# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"class AttachmentDownloadTool(Tool):name = "attachment-downloader"description = "Downloads the file associated with the given task_id. If it does not exist, return None. input: task_id。output: attachment files or None"inputs = {"task_id": {"type": "str","description": "task_id that needs to download attachment files."}}output_type = io.BytesIOdef forward(self, task_id):download_url = f"{api_url}/files/"try:response = requests.get(download_url + task_id, stream=True, timeout=15)if response.status_code != 200:return Nonefile_obj = io.BytesIO(response.content)file_obj.seek(0)return file_objexcept Exception as e:return Noneclass ImageCaptionTool(Tool):name = "image-captioner"description = "Identify the content of the input image and describe it in natural language. Input: image. Output: description text."inputs = {"image": {"type": "image","description": "Images that need to be identified and described"}}output_type = strdef setup(self):self.model = OpenAIServerModel(model_id="Qwen/Qwen2.5-VL-32B-Instruct",api_base="https://api.siliconflow.cn/v1/",api_key=os.getenv('MODEL_TOKEN'),)def forward(self, image):prompt = "Please describe the content of this picture in detail."return self.model(prompt, images=[image])class AudioToTextTool(Tool):name = "audio-to-text"description = "Convert the input audio content to text. Input: audio. Output: text."inputs = {"audio": {"type": "audio","description": "The audio file that needs to be transcribed"}}output_type = strdef setup(self):# 使用 HuggingFace Hub 上的 Whisper 大模型self.model = HfApiModel(model_id="openai/whisper-large-v3") # 或其他支持音频转写的模型def forward(self, audio):prompt = "Please transcribe this audio content into text."return self.model(prompt, audios=[audio])# --- Basic Agent Definition ---# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------# class BasicAgent:# def __init__(self):# print("BasicAgent initialized.")# def __call__(self, question: str) -> str:# print(f"Agent received question (first 50 chars): {question[:50]}...")# fixed_answer = "This is a default answer."# print(f"Agent returning fixed answer: {fixed_answer}")# return fixed_answerclass BasicAgent:def __init__(self):self.think_model = OpenAIServerModel(model_id="THUDM/GLM-Z1-32B-0414",api_base="https://api.siliconflow.cn/v1/",api_key=os.getenv('MODEL_TOKEN'),)self.base_model = OpenAIServerModel(model_id="THUDM/GLM-4-32B-0414",api_base="https://api.siliconflow.cn/v1/",api_key=os.getenv('MODEL_TOKEN'),)# self.vision_model = OpenAIServerModel(# model_id="Qwen/Qwen2.5-VL-32B-Instruct",# api_base="https://api.siliconflow.cn/v1/",# api_key=os.getenv('MODEL_TOKEN'),# )self.tools = [AttachmentDownloadTool, ImageCaptionTool, AudioToTextTool]web_agent = ToolCallingAgent(tools=[DuckDuckGoSearchTool(), VisitWebpageTool()],model=self.base_model,max_steps=10,name="web_search_agent",description="Runs web searches for you.",)self.agent = CodeAgent(tools=self.tools,model=self.think_model,managed_agents=[web_agent,],additional_authorized_imports=["time", "numpy", "pandas"],max_steps=20)print("BasicAgent initialized.")def __call__(self, question: str, images=None) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")try:if images is not None:result = self.agent.run(question, images=images)else:result = self.agent.run(question)print(f"Agent returning answer: {result}")return resultexcept Exception as e:print(f"Agent error: {e}")return f"AGENT ERROR: {e}"def run_and_submit_all( profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results.14 unmodified lines# 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}", None101 unmodified lines**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.""")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])2 unmodified lines34567891011121314151617181920212223242526272829303132333435363714 unmodified lines52535455565758101 unmodified lines1601611621631641651661671681691701711721731741751761771781791801811821831841851862 unmodified linesimport requestsimport inspectimport pandas as pdfrom smolagents import CodeAgent, DuckDuckGoSearchTool, OpenAIServerModel# (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, openai_key):self.openai_key = openai_keyprint("BasicAgent initialized.")# Initialize the model#model = HfApiModel()model = OpenAIServerModel(model_id="gpt-4.1", api_key=self.openai_key)# Initialize the search toolsearch_tool = DuckDuckGoSearchTool()# Initialize Agentself.agent = CodeAgent(model = model,tools=[search_tool])def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")fixed_answer =self.agent.run(question)print(f"Agent returning fixed answer: {fixed_answer}")return fixed_answerdef run_and_submit_all(profile: gr.OAuthProfile | None, openai_key: str):"""Fetches all questions, runs the BasicAgent on them, submits all answers,and displays the results.14 unmodified lines# 1. Instantiate Agent ( modify this part to create your agent)try:agent = BasicAgent(openai_key)except Exception as e:print(f"Error instantiating agent: {e}")return f"Error initializing agent: {e}", None101 unmodified lines**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. Enter your OpenAI key below (if required by your agent).4. 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 separate action or even to answer the questions in async.""")gr.LoginButton()openai_key_box = gr.Textbox(label="OpenAI API Key", type="password", placeholder="sk-...", lines=1)run_button = gr.Button("Run Evaluation & Submit All Answers")status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)run_button.click(fn=run_and_submit_all,inputs=[openai_key_box],outputs=[status_output, results_table])
app.py+25-130