Spaces:
Runtime error
Runtime error
Commit ·
a0d7e0d
1
Parent(s): 8140fce
Passes tests
Browse filesFiles changed (2)
- app.py+83-9
- requirements.txt+2-1
6 unmodified lines789101112136 unmodified lines20212223242526272829301 unmodified line32333435363738394041424351 unmodified lines95969798991001011021031041051061071081091101111121131146 unmodified linesimport dotenvdotenv.load_dotenv()from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, AzureOpenAIServerModelMODEL = AzureOpenAIServerModel(model_id=os.environ.get("AZURE_OPENAI_DEPLOYMENT"),6 unmodified lines# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"class BasicAgent:def __init__(self):print("BasicAgent initialized.")def __call__(self, question: str) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")# Initialize the search toolsearch_tool = DuckDuckGoSearchTool(max_results=20)1 unmodified lineagent = CodeAgent(model=MODEL,tools=[search_tool, web_tool])response = agent.run(question)print(f"Agent returning fixed answer: {response}")return response51 unmodified lines# 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.")6 unmodified lines78910111213146 unmodified lines212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465661 unmodified line68697071727374757677787980818251 unmodified lines1341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871886 unmodified linesimport dotenvdotenv.load_dotenv()import tempfilefrom smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool, AzureOpenAIServerModel, toolMODEL = AzureOpenAIServerModel(model_id=os.environ.get("AZURE_OPENAI_DEPLOYMENT"),6 unmodified lines# --- Constants ---DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"@tooldef file_reader_tool(file_path: str) -> str:"""Reads and returns the content of a local file.Args:file_path: Path to the local file."""try:with open(file_path, 'r', errors='ignore') as f:return f.read()except Exception as e:return f"Error reading file: {e}"@tooldef youtube_transcript_tool(video_url: str) -> str:"""Fetches and returns the transcript of a YouTube video.Args:video_url: URL of the YouTube video."""from youtube_transcript_api import YouTubeTranscriptApiimport rematch = re.search(r"(?:v=|youtu\\.be/)([A-Za-z0-9_-]+)", video_url)if not match:return "Invalid YouTube URL."video_id = match.group(1)try:transcript_list = YouTubeTranscriptApi.get_transcript(video_id)return " ".join([seg["text"] for seg in transcript_list])except Exception as e:return f"Error fetching transcript: {e}"class BasicAgent:def __init__(self):print("BasicAgent initialized.")def __call__(self, question: str, file_path: str = None) -> str:print(f"Agent received question (first 50 chars): {question[:50]}...")if file_path:print(f"Agent received file path: {file_path}")# Initialize the search toolsearch_tool = DuckDuckGoSearchTool(max_results=20)1 unmodified lineagent = CodeAgent(model=MODEL,tools=[search_tool, web_tool, file_reader_tool, youtube_transcript_tool])# Enhance the question with file path information if availableenhanced_question = questionif file_path:enhanced_question += f"\n\nNote: There is a file available at path: {file_path}. You can use the 'file_reader_tool' to read its contents if needed for answering this question."response = agent.run(enhanced_question)print(f"Agent returning fixed answer: {response}")return response51 unmodified lines# 3. Run your Agentresults_log = []answers_payload = []# Prepare temp folder for downloading collateral filestemp_dir = os.path.join(tempfile.gettempdir(), "hf_agent_files")os.makedirs(temp_dir, exist_ok=True)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")file_name = item.get("file_name", "")if not task_id or question_text is None:print(f"Skipping item with missing task_id or question: {item}")continue# Download collateral file if anylocal_file = Noneif file_name:file_url = f"{api_url}/files/{task_id}"local_file = os.path.join(temp_dir, file_name)try:r = requests.get(file_url, timeout=30, stream=True)r.raise_for_status()with open(local_file, "wb") as f:for chunk in r.iter_content(chunk_size=8192):f.write(chunk)print(f"Downloaded file for task {task_id} to {local_file}")except Exception as e:print(f"Error downloading file for task {task_id}: {e}")local_file = Nonetry:# Enrich the question with hints for tool usageinput_question = question_text# Hint for YouTube transcriptionif "youtube.com" in question_text or "youtu.be" in question_text:input_question += ("\nYou can use the 'youtube_transcript_tool' ""to fetch the video's transcript by providing the URL.")# Call agent with both question and file pathsubmitted_answer = agent(input_question, local_file)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.")
1 unmodified line23451 unmodified linerequestssmolagents[openai]duckduckgo-searchmarkdownify1 unmodified line234561 unmodified linerequestssmolagents[openai]duckduckgo-searchmarkdownifyyoutube-transcript-api
app.py+83-9
requirements.txt+2-1