Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071724 unmodified lines77787980818283848586878889909192932 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761 unmodified line17817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336410 unmodified lines37537637737837938038138238338438538638738818 unmodified lines4074084094104114124134 unmodified lines41841942042142242342442542620 unmodified lines447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481import osimport gradio as grimport requestsimport inspectimport pandas as pdfrom dotenv import load_dotenvload_dotenv()# New importsfrom duckduckgo_search import DDGSimport yt_dlpfrom PIL import Imageimport librosaimport numpy as npfrom io import BytesIOimport base64from langgraph.graph import StateGraph, ENDfrom langchain_core.runnables import RunnableLambdafrom langchain_core.messages import HumanMessage, SystemMessagefrom langchain_openai import ChatOpenAIfrom typing import TypedDict, Dict, Anyfrom langchain_core.tools import tool# --- New Tools ---from langchain_core.tools import toolfrom openai import OpenAIimport base64import requestsimport osDEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")from duckduckgo_search import DDGS# Define types for state schemaclass AgentState(TypedDict):question: stranswer: str@tooldef web_search(query: str, max_results: int = 5) -> str:"""Search the web for information about a given query using DuckDuckGo."""try:print(f"Searching the web for: {query}")results = []with DDGS() as ddgs:search_results = list(ddgs.text(query, max_results=max_results))for i, result in enumerate(search_results, 1):title = result.get('title', 'No title')body = result.get('body', 'No content')url = result.get('href', 'No URL')results.append(f"{i}. {title}\n {body}\n URL: {url}\n")if not results:return "No search results found."return "\n".join(results)except Exception as e:print(f"Error during web search: {e}")return f"Error during web search: {str(e)}"def encode_image(image_url):try:response = requests.get(image_url, stream=True, timeout=10)response.raise_for_status()4 unmodified lines@tooldef analyze_image_openai_vision(image_url: str, prompt: str) -> str:"""Analyze an image from a given URL using OpenAI Vision and answer a question about it."""if not OPENAI_API_KEY:return "OpenAI API key not found."base64_image = encode_image(image_url)if isinstance(base64_image, str) and base64_image.startswith("Error"):return base64_imageclient = OpenAI()try:response = client.chat.completions.create(model="gpt-4-vision-preview",messages=[{"role": "user","content": [2 unmodified lines],}],max_tokens=300,)return response.choices[0].message.contentexcept Exception as e:return f"Error analyzing image with OpenAI Vision: {e}"from langchain_core.tools import toolfrom openai import OpenAIimport osimport yt_dlpimport requestsOPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")def get_youtube_transcript(video_url: str) -> str | None:# (Same implementation as before)try:ydl_opts = {'writesubtitles': True,'writeautomaticsub': True,'subtitleslangs': ['en'],'skip_download': True,'outtmpl': '%(title)s.%(ext)s',}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info_dict = ydl.extract_info(video_url, download=False)if info_dict and 'subtitles' in info_dict and 'en' in info_dict['subtitles']:transcript_url = info_dict['subtitles']['en'][0]['url']response = requests.get(transcript_url, timeout=10)response.raise_for_status()transcript_text = "\n".join([line.split(' ', 1)[1] for line in response.text.splitlines() if '-->' not in line and line.strip()])return transcript_textelif info_dict and 'automatic_captions' in info_dict and 'en' in info_dict['automatic_captions']:transcript_url = info_dict['automatic_captions']['en'][0]['url']response = requests.get(transcript_url, timeout=10)response.raise_for_status()transcript_text = "\n".join([line.split(' ', 1)[1] for line in response.text.splitlines() if '-->' not in line and line.strip()])return transcript_textelse:return "No English transcript found for this YouTube video."except Exception as e:return f"Error fetching YouTube transcript: {e}"@tooldef analyze_youtube_video_openai(video_url: str, prompt: str = "Summarize the key points of this video.") -> str:"""Analyze a YouTube video by summarizing its English transcript using OpenAI."""if not OPENAI_API_KEY:return "OpenAI API key not found."transcript = get_youtube_transcript(video_url)if not transcript:return "Could not retrieve transcript for the YouTube video."client = OpenAI()try:response = client.chat.completions.create(model="gpt-4-turbo",messages=[{"role": "system", "content": "You are a helpful assistant that analyzes video transcripts."},{"role": "user", "content": f"Here is the transcript of a video: {transcript[:4000]}. {prompt}"} # Limit transcript length],max_tokens=500,)return response.choices[0].message.contentexcept Exception as e:return f"Error analyzing video transcript with OpenAI: {e}"from langchain_core.tools import toolfrom openai import OpenAIimport osimport yt_dlpimport requestsOPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")def get_youtube_transcript(video_url: str) -> str | None:# (Same implementation as before)try:ydl_opts = {'writesubtitles': True,1 unmodified line'subtitleslangs': ['en'],'skip_download': True,'outtmpl': '%(title)s.%(ext)s',}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info_dict = ydl.extract_info(video_url, download=False)if info_dict and 'subtitles' in info_dict and 'en' in info_dict['subtitles']:transcript_url = info_dict['subtitles']['en'][0]['url']response = requests.get(transcript_url, timeout=10)response.raise_for_status()transcript_text = "\n".join([line.split(' ', 1)[1] for line in response.text.splitlines() if '-->' not in line and line.strip()])return transcript_textelif info_dict and 'automatic_captions' in info_dict and 'en' in info_dict['automatic_captions']:transcript_url = info_dict['automatic_captions']['en'][0]['url']response = requests.get(transcript_url, timeout=10)response.raise_for_status()transcript_text = "\n".join([line.split(' ', 1)[1] for line in response.text.splitlines() if '-->' not in line and line.strip()])return transcript_textelse:return "No English transcript found for this YouTube video."except Exception as e:return f"Error fetching YouTube transcript: {e}"@tooldef analyze_youtube_video_openai(video_url: str, prompt: str = "Summarize the key points of this video.") -> str:"""Analyze a YouTube video by summarizing its English transcript using OpenAI."""if not OPENAI_API_KEY:return "OpenAI API key not found."transcript = get_youtube_transcript(video_url)if not transcript:return "Could not retrieve transcript for the YouTube video."client = OpenAI()try:response = client.chat.completions.create(model="gpt-4-turbo",messages=[{"role": "system", "content": "You are a helpful assistant that analyzes video transcripts."},{"role": "user", "content": f"Here is the transcript of a video: {transcript[:4000]}. {prompt}"} # Limit transcript length],max_tokens=500,)return response.choices[0].message.contentexcept Exception as e:return f"Error analyzing video transcript with OpenAI: {e}"from langchain_core.tools import toolfrom openai import OpenAIimport requestsimport os# OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")# Python REPL Toolfrom langchain_experimental.tools.python.tool import PythonREPLToolpython_repl = PythonREPLTool()@tooldef run_python_code(code: str) -> str:"""Execute a Python code snippet and return the output."""try:result = python_repl.run(code)return f"Python code executed successfully. Output: {result}"except Exception as e:return f"Error executing Python code: {e}"@tooldef transcribe_audio_openai(audio_url: str) -> str:"""Transcribe audio from a given URL using OpenAI Whisper API."""if not OPENAI_API_KEY:return "OpenAI API key not found."try:response = requests.get(audio_url, stream=True, timeout=10)response.raise_for_status()with open("temp_audio.mp3", "wb") as f:for chunk in response.iter_content(chunk_size=8192):f.write(chunk)client = OpenAI()with open("temp_audio.mp3", "rb") as audio_file:transcript = client.audio.transcriptions.create(model="whisper-1",file=audio_file)os.remove("temp_audio.mp3")return transcript.textexcept requests.exceptions.RequestException as e:return f"Error accessing audio URL {audio_url}: {e}"except Exception as e:return f"Error transcribing audio with OpenAI Whisper: {e}"@tooldef analyze_audio_transcript_openai(audio_url: str, prompt: str = "Analyze the content of this audio.") -> str:"""Transcribe audio from a URL and then analyze the transcript using OpenAI."""transcript = transcribe_audio_openai(audio_url)if isinstance(transcript, str) and transcript.startswith("Error"):return transcriptif not transcript:return "Could not transcribe the audio."client = OpenAI()try:response = client.chat.completions.create(model="gpt-4-turbo",messages=[{"role": "system", "content": "You are a helpful assistant that analyzes audio transcripts."},{"role": "user", "content": f"Here is the transcript of an audio: {transcript[:4000]}. {prompt}"} # Limit transcript length],max_tokens=500,)return response.choices[0].message.contentexcept Exception as e:return f"Error analyzing audio transcript with OpenAI: {e}"class LangGraphAgent:def __init__(self):print("LangGraphAgent initialized.")openai_key = os.environ.get("OPENAI_API_KEY")if not openai_key:openai_key = os.environ.get("OPEN_AI_KEY")if not openai_key:raise ValueError("OpenAI API key not found in environment variables")print(f"Loaded OpenAI Key: {openai_key[:3]}..." if openai_key else "No OpenAI Key found")self.llm = ChatOpenAI(model="gpt-4-turbo", temperature=0, api_key=openai_key)# Register all toolsself.tools = [web_search, analyze_image_openai_vision, analyze_youtube_video_openai, analyze_audio_transcript_openai, run_python_code]self.sys_prompt = SystemMessage(content="""You are a highly capable AI assistant with access to the following tools:- 'web_search': Use this tool to search the internet for information.- 'analyze_image_openai_vision': Use this tool to analyze images from URLs and answer questions about their content.- 'analyze_youtube_video_openai': Use this tool to analyze YouTube videos by summarizing or answering questions based on their transcripts.- 'analyze_audio_transcript_openai': Use this tool to transcribe audio from URLs and then analyze the transcript.- 'run_python_code': Use this tool to execute Python code snippets and return the output.When I ask you a question, consider if any of these tools can help you find the answer. If so, please use the most appropriate tool(s).Your final answer MUST adhere to the following format: <ANSWER> should be a number OR as few words as possible OR a comma-separated list of numbers and/or strings.Follow these conditions strictly for your final <ANSWER>:- If you are asked for a number, do not use commas to write the number and do not include units such as $ or percent signs unless specifically instructed.- If you are asked for a string, do not use articles (a, an, the), abbreviations (e.g., for cities), and write digits in plain text unless specified otherwise.- If you are asked for a comma-separated list, apply the above rules to each element in the list, depending on whether it's a number or a string.- If the question involves Python code, use the 'run_python_code' tool to execute the code and the output as part of your reasoning to arrive at the final <ANSWER>.""")def answer_fn(state: AgentState) -> Dict[str, Any]:question = state["question"]print(f"[LangGraphAgent] Received: {question[:50]}...")messages = [self.sys_prompt, HumanMessage(content=question)]# You might need to adjust this part to decide when to use which tool.# A more sophisticated approach would involve a router or a more complex LangGraph workflow.# For this basic example, the LLM will decide if and when to use the tools# based on the question and the tool descriptions.response = self.llm.invoke(messages).contentfinal_answer = self._extract_final_answer(response)return {"question": question, "answer": final_answer}workflow = StateGraph(AgentState)workflow.add_node("answer_question", answer_fn)workflow.set_entry_point("answer_question")workflow.add_edge("answer_question", END)self.graph = workflow.compile()def __call__(self, question: str) -> str:output = self.graph.invoke({"question": question, "answer": ""})return output["answer"]def _extract_final_answer(self, response: str) -> str:for line in response.strip().splitlines()[::-1]:if line.strip().lower().startswith("final answer:"):return line.split(":", 1)[1].strip()print("Warning: FINAL ANSWER not found, returning full response.")return response.strip()def run_and_submit_all(profile: gr.OAuthProfile | None):"""Fetches all questions, runs the BasicAgent/LangGraphAgent on them, submits all answers,and displays the results."""# --- Determine HF Space Runtime URL and Repo URL ---10 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agent ( modify this part to create your agent)try:# agent = BasicAgent()agent = LangGraphAgent()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)18 unmodified linesprint(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...")4 unmodified linesprint(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}"})20 unmodified linesf"({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 ---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172734 unmodified lines787980818283848586878889909192939495969798991001011021031041051061071081091102 unmodified lines1131141151161171181191201211221231241251261271281 unmodified line13013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565610 unmodified lines66766866967067167267367467567667767867968018 unmodified lines6997007017027037047054 unmodified lines71071171271371471571671771871972020 unmodified lines741742743744745746import osimport gradio as grimport requestsimport pandas as pdfrom dotenv import load_dotenvfrom duckduckgo_search import DDGSimport yt_dlpfrom openai import OpenAIimport base64from langgraph.graph import StateGraph, ENDfrom langchain_core.messages import HumanMessage, SystemMessage, AIMessage, ToolMessagefrom langchain_openai import ChatOpenAIfrom typing import TypedDict, Dict, Any, List, Optional, Annotated, Sequence, Union, Literalfrom langchain_core.tools import toolload_dotenv()# Environment setupOPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") or os.environ.get("OPEN_AI_KEY")DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"# Type definitions for state schemaclass AgentState(TypedDict):question: strmessages: List[Union[HumanMessage, AIMessage, ToolMessage, SystemMessage]]steps_remaining: intanswer: strintermediate_steps: List[Dict[str, Any]]# --------------------- IMPROVED TOOLS ---------------------@tooldef web_search(query: str, max_results: int = 10) -> str:"""Search the web for information about a given query using DuckDuckGo.Provides more comprehensive results than a standard search.Args:query: The search query string.max_results: Maximum number of search results to return (default: 10)Returns:Formatted search results as a string."""try:print(f"Searching the web for: {query}")results = []with DDGS() as ddgs:search_results = list(ddgs.text(query, max_results=max_results))for i, result in enumerate(search_results, 1):title = result.get('title', 'No title')body = result.get('body', 'No content')url = result.get('href', 'No URL')results.append(f"{i}. {title}\n {body}\n URL: {url}\n")if not results:return "No search results found."formatted_results = "\n".join(results)print(f"Web search found {len(results)} results")return formatted_resultsexcept Exception as e:print(f"Error during web search: {e}")return f"Error during web search: {str(e)}"def encode_image(image_url):"""Helper function to encode an image from URL to base64."""try:response = requests.get(image_url, stream=True, timeout=10)response.raise_for_status()4 unmodified lines@tooldef analyze_image_openai_vision(image_url: str, prompt: str) -> str:"""Analyze an image from a given URL using OpenAI Vision and answer a question about it.Provides detailed analysis of visual content.Args:image_url: URL of the image to analyzeprompt: Specific question or instruction about what to analyze in the imageReturns:Analysis of the image based on the prompt"""if not OPENAI_API_KEY:return "OpenAI API key not found."base64_image = encode_image(image_url)if isinstance(base64_image, str) and base64_image.startswith("Error"):return base64_imageclient = OpenAI()try:response = client.chat.completions.create(model="gpt-4-vision-preview",messages=[{"role": "system","content": "You are a precise image analyzer focusing on exact details and specific information. Extract only what's needed to answer the query."},{"role": "user","content": [2 unmodified lines],}],max_tokens=500,)print(f"Image analysis complete: {len(response.choices[0].message.content)} chars")return response.choices[0].message.contentexcept Exception as e:print(f"Error analyzing image with OpenAI Vision: {e}")return f"Error analyzing image with OpenAI Vision: {e}"def get_youtube_transcript(video_url: str) -> str:"""Extract transcript from a YouTube video with enhanced error handling."""try:ydl_opts = {'writesubtitles': True,1 unmodified line'subtitleslangs': ['en'],'skip_download': True,'outtmpl': '%(title)s.%(ext)s','quiet': True,}with yt_dlp.YoutubeDL(ydl_opts) as ydl:info_dict = ydl.extract_info(video_url, download=False)video_title = info_dict.get('title', 'Untitled Video')video_duration = info_dict.get('duration', 0)print(f"Video found: '{video_title}' (Duration: {video_duration}s)")# Try official subtitles firstif info_dict and 'subtitles' in info_dict and 'en' in info_dict['subtitles']:transcript_url = info_dict['subtitles']['en'][0]['url']response = requests.get(transcript_url, timeout=10)response.raise_for_status()# More robust transcript parsingtranscript_lines = []for line in response.text.splitlines():if '-->' not in line and line.strip():parts = line.split(' ', 1)if len(parts) > 1:transcript_lines.append(parts[1])return f"Video Title: {video_title}\nDuration: {video_duration} seconds\n\nTranscript:\n" + "\n".join(transcript_lines)# Fall back to automatic captionselif info_dict and 'automatic_captions' in info_dict and 'en' in info_dict['automatic_captions']:transcript_url = info_dict['automatic_captions']['en'][0]['url']response = requests.get(transcript_url, timeout=10)response.raise_for_status()transcript_lines = []for line in response.text.splitlines():if '-->' not in line and line.strip():parts = line.split(' ', 1)if len(parts) > 1:transcript_lines.append(parts[1])return f"Video Title: {video_title}\nDuration: {video_duration} seconds\n\nTranscript (Auto-generated):\n" + "\n".join(transcript_lines)else:video_info = f"Video Title: {video_title}\nDuration: {video_duration} seconds\n"return f"{video_info}\nNo English transcript found for this YouTube video."except Exception as e:print(f"Error fetching YouTube transcript: {e}")return f"Error fetching YouTube transcript: {e}"@tooldef analyze_youtube_video_openai(video_url: str, prompt: str = "Summarize the key points of this video.") -> str:"""Analyze a YouTube video by summarizing its English transcript using OpenAI.Provides comprehensive understanding of video content without watching it.Args:video_url: URL of the YouTube video to analyzeprompt: Specific question or instruction about what to analyze in the videoReturns:Analysis of the video content based on its transcript"""if not OPENAI_API_KEY:return "OpenAI API key not found."transcript = get_youtube_transcript(video_url)if not transcript or transcript.startswith("Error"):return "Could not retrieve transcript for the YouTube video."client = OpenAI()try:response = client.chat.completions.create(model="gpt-4-turbo",messages=[{"role": "system","content": "You are a video content analyzer. Extract precise information from video transcripts. Provide specific details and quantitative data when applicable."},{"role": "user","content": f"Here is the transcript of a video:\n\n{transcript[:7000]}\n\n{prompt}"}],max_tokens=750,)print(f"YouTube video analysis complete: {len(response.choices[0].message.content)} chars")return response.choices[0].message.contentexcept Exception as e:print(f"Error analyzing video transcript with OpenAI: {e}")return f"Error analyzing video transcript with OpenAI: {e}"@tooldef transcribe_audio_openai(audio_url: str) -> str:"""Transcribe audio from a given URL using OpenAI Whisper API.Provides text version of audio content for analysis.Args:audio_url: URL of the audio file to transcribeReturns:Text transcription of the audio content"""if not OPENAI_API_KEY:return "OpenAI API key not found."try:print(f"Downloading audio from {audio_url}")response = requests.get(audio_url, stream=True, timeout=15)response.raise_for_status()with open("temp_audio.mp3", "wb") as f:for chunk in response.iter_content(chunk_size=8192):f.write(chunk)client = OpenAI()print("Transcribing audio with Whisper API...")with open("temp_audio.mp3", "rb") as audio_file:transcript = client.audio.transcriptions.create(model="whisper-1",file=audio_file)os.remove("temp_audio.mp3")print(f"Audio transcription complete: {len(transcript.text)} chars")return transcript.textexcept requests.exceptions.RequestException as e:print(f"Error accessing audio URL {audio_url}: {e}")return f"Error accessing audio URL {audio_url}: {e}"except Exception as e:print(f"Error transcribing audio with OpenAI Whisper: {e}")return f"Error transcribing audio with OpenAI Whisper: {e}"@tooldef analyze_audio_transcript_openai(audio_url: str, prompt: str = "Analyze the content of this audio.") -> str:"""Transcribe audio from a URL and then analyze the transcript using OpenAI.Provides detailed understanding of audio content without listening to it.Args:audio_url: URL of the audio file to analyzeprompt: Specific question or instruction about what to analyze in the audioReturns:Analysis of the audio content based on its transcript"""transcript = transcribe_audio_openai(audio_url)if isinstance(transcript, str) and transcript.startswith("Error"):return transcriptif not transcript:return "Could not transcribe the audio."client = OpenAI()try:response = client.chat.completions.create(model="gpt-4-turbo",messages=[{"role": "system","content": "You are an audio content analyzer. Extract precise information from audio transcripts. Focus on specific details and key points."},{"role": "user","content": f"Here is the transcript of an audio:\n\n{transcript}\n\n{prompt}"}],max_tokens=750,)print(f"Audio analysis complete: {len(response.choices[0].message.content)} chars")return response.choices[0].message.contentexcept Exception as e:print(f"Error analyzing audio transcript with OpenAI: {e}")return f"Error analyzing audio transcript with OpenAI: {e}"# Improved Python REPL Toolfrom langchain_experimental.tools.python.tool import PythonREPLToolpython_repl = PythonREPLTool()@tooldef run_python_code(code: str) -> str:"""Execute a Python code snippet and return the output.Useful for calculations, data analysis, or any computational tasks.Args:code: Python code to executeReturns:Output of the executed code or error message"""print("Executing Python code...")try:# Execute the code in a sandbox environmentresult = python_repl.run(code)print(f"Python execution successful: {len(str(result))} chars")return f"{result}"except Exception as e:print(f"Error executing Python code: {e}")return f"Error executing Python code: {e}"# --------------------- IMPROVED AGENT ---------------------class ImprovedLangGraphAgent:def __init__(self):print("ImprovedLangGraphAgent initializing...")if not OPENAI_API_KEY:raise ValueError("OpenAI API key not found in environment variables")print(f"Loaded OpenAI Key: {OPENAI_API_KEY[:3]}..." if OPENAI_API_KEY else "No OpenAI Key found")# Use gpt-4-turbo for better reasoning capabilitiesself.llm = ChatOpenAI(model="gpt-4-turbo", temperature=0, api_key=OPENAI_API_KEY)# Register all toolsself.tools = [web_search,analyze_image_openai_vision,analyze_youtube_video_openai,analyze_audio_transcript_openai,run_python_code]self.tool_map = {tool.name: tool for tool in self.tools}# Improved system prompt with clearer instructions and emphasis on reasoningself.sys_prompt = SystemMessage(content="""You are a highly capable AI assistant equipped with tools to solve complex problems. Your goal is to determine the correct answer to the given question, using a step-by-step reasoning approach.AVAILABLE TOOLS:- 'web_search': Search the internet for up-to-date information.- 'analyze_image_openai_vision': Analyze images from URLs to extract visual information.- 'analyze_youtube_video_openai': Analyze YouTube videos by examining their transcripts.- 'analyze_audio_transcript_openai': Transcribe and analyze audio from URLs.- 'run_python_code': Execute Python code for calculations, data analysis, or visualization.REASONING PROCESS:1. First, understand the question thoroughly.2. Determine which tools would help gather the necessary information.3. Execute each step logically, using tools when needed.4. After collecting information, analyze it critically.5. Draw conclusions based on evidence collected.6. Formulate a precise, concise answer following the format requirements.FINAL ANSWER FORMAT:Your final answer MUST be provided in this format:<ANSWER>your concise answer here</ANSWER>ANSWER REQUIREMENTS:- For numbers: No commas, no units (like $ or %) unless explicitly requested- For strings: No articles (a, an, the), no abbreviations for places- For lists: Comma-separated values following above rulesIMPORTANT:- Ensure accuracy above all else- Be extremely precise and concise in your final answer- For coding questions, execute the code and use the output to determine the answer- Never include explanations in your final <ANSWER> tag""")# Define the various components of our graphdef setup_agent(state: AgentState) -> Dict[str, Any]:"""Initialize the agent state with the question."""question = state["question"]messages = [self.sys_prompt,HumanMessage(content=question)]print(f"[Agent] Setup with question: {question[:50]}...")return {"question": question,"messages": messages,"steps_remaining": 5, # Allow up to 5 reasoning steps"answer": "","intermediate_steps": []}def route_agent(state: AgentState) -> Literal["process_agent", "finalize_answer"]:"""Decide whether to continue reasoning or finalize the answer."""if state["steps_remaining"] <= 0:print("[Agent] Max steps reached, finalizing...")return "finalize_answer"# Check if an answer has already been determinedlast_message = state["messages"][-1]if isinstance(last_message, AIMessage) and "<ANSWER>" in last_message.content:print("[Agent] Answer found, finalizing...")return "finalize_answer"print(f"[Agent] Continuing reasoning, {state['steps_remaining']} steps remaining")return "process_agent"def process_agent(state: AgentState) -> Dict[str, Any]:"""Process the current state and decide the next action."""messages = state["messages"]# Use the LLM to decide the next stepresponse = self.llm.invoke(messages)print(f"[Agent] LLM response: {response.content[:75]}...")# Check if the response contains a tool callif "I need to use" in response.content.lower() or "let me use" in response.content.lower():# Look for tool names in the responsefor tool_name, tool_fn in self.tool_map.items():if tool_name.lower() in response.content.lower():print(f"[Agent] Using tool: {tool_name}")try:# Extract arguments from the response# This is a simple implementation - could be more sophisticatedtool_signature = f"{tool_name}("start_idx = response.content.lower().find(tool_name.lower())if start_idx == -1:continue# Find the opening and closing parenthesesopen_paren = response.content.find("(", start_idx)if open_paren == -1:continue# Extract everything between the first parenthesis and the last oneparen_count = 1close_paren = -1for i in range(open_paren + 1, len(response.content)):if response.content[i] == "(":paren_count += 1elif response.content[i] == ")":paren_count -= 1if paren_count == 0:close_paren = ibreakif close_paren == -1:continueargs_str = response.content[open_paren + 1:close_paren]# Simple parsing of arguments# This is a basic implementation - a more robust parser would be betterargs = []kwargs = {}# Split by comma, but respecting quotesin_quotes = Falsequote_char = Nonecurrent_arg = ""for char in args_str:if char in ['"', "'"]:if not in_quotes:in_quotes = Truequote_char = charelif char == quote_char:in_quotes = Falsequote_char = Nonecurrent_arg += charelif char == ',' and not in_quotes:args.append(current_arg.strip())current_arg = ""else:current_arg += charif current_arg:args.append(current_arg.strip())# Convert string arguments to actual valuesparsed_args = []for arg in args:arg = arg.strip()if arg.startswith('"') and arg.endswith('"'):parsed_args.append(arg[1:-1])elif arg.startswith("'") and arg.endswith("'"):parsed_args.append(arg[1:-1])else:# Try to parse as other typestry:parsed_args.append(eval(arg))except:parsed_args.append(arg)# Execute the tooltool_result = tool_fn(*parsed_args)print(f"[Agent] Tool result: {tool_result[:75]}...")# Update the state with the tool resultmessages.append(AIMessage(content=response.content))messages.append(ToolMessage(content=tool_result, tool_call_id=tool_name))# Record the intermediate stepstate["intermediate_steps"].append({"tool": tool_name,"args": parsed_args,"result": tool_result})# Decrement steps remainingstate["steps_remaining"] -= 1return {"question": state["question"],"messages": messages,"steps_remaining": state["steps_remaining"],"answer": state["answer"],"intermediate_steps": state["intermediate_steps"]}except Exception as e:print(f"[Agent] Error executing tool {tool_name}: {e}")messages.append(AIMessage(content=response.content))messages.append(ToolMessage(content=f"Error executing tool {tool_name}: {e}", tool_call_id=tool_name))state["steps_remaining"] -= 1return state# If no tool call identified, add the response and continuemessages.append(AIMessage(content=response.content))state["steps_remaining"] -= 1return {"question": state["question"],"messages": messages,"steps_remaining": state["steps_remaining"],"answer": state["answer"],"intermediate_steps": state["intermediate_steps"]}def finalize_answer(state: AgentState) -> Dict[str, Any]:"""Extract the final answer from the agent's reasoning."""messages = state["messages"]answer = ""# Check if the answer is already in the messagesfor message in reversed(messages):if not isinstance(message, HumanMessage) and "<ANSWER>" in message.content:# Extract the answer from between <ANSWER> tagsstart_idx = message.content.find("<ANSWER>") + len("<ANSWER>")end_idx = message.content.find("</ANSWER>", start_idx)if end_idx > start_idx:answer = message.content[start_idx:end_idx].strip()break# If no answer found, generate one final answerif not answer:print("[Agent] No answer found, generating final answer...")messages.append(HumanMessage(content="Based on all the information we've gathered, what is the final answer? Remember to format it as <ANSWER>your answer here</ANSWER>"))final_response = self.llm.invoke(messages)messages.append(final_response)# Extract the answercontent = final_response.contentif "<ANSWER>" in content:start_idx = content.find("<ANSWER>") + len("<ANSWER>")end_idx = content.find("</ANSWER>", start_idx)if end_idx > start_idx:answer = content[start_idx:end_idx].strip()else:print("[Agent] Warning: Final response didn't contain <ANSWER> tags")answer = content.strip()print(f"[Agent] Final answer: {answer}")return {"question": state["question"],"messages": messages,"steps_remaining": state["steps_remaining"],"answer": answer,"intermediate_steps": state["intermediate_steps"]}# Build the graphworkflow = StateGraph(AgentState)workflow.add_node("setup", setup_agent)workflow.add_node("process_agent", process_agent)workflow.add_node("finalize_answer", finalize_answer)# Add edgesworkflow.set_entry_point("setup")workflow.add_conditional_edges("setup",route_agent,{"process_agent": "process_agent","finalize_answer": "finalize_answer"})workflow.add_conditional_edges("process_agent",route_agent,{"process_agent": "process_agent","finalize_answer": "finalize_answer"})workflow.add_edge("finalize_answer", END)self.graph = workflow.compile()print("ImprovedLangGraphAgent initialized successfully.")def __call__(self, question: str) -> str:"""Process a question and return the answer."""print(f"[ImprovedLangGraphAgent] Processing question: {question[:75]}...")output = self.graph.invoke({"question": question,"messages": [],"steps_remaining": 5,"answer": "","intermediate_steps": []})answer = output["answer"].strip()if not answer:print("[ImprovedLangGraphAgent] Warning: Empty answer, falling back to last message content")# If answer is empty, try to extract it from the last messagelast_message = output["messages"][-1]if isinstance(last_message, AIMessage):answer = last_message.content.strip()return answer# Update the run_and_submit_all function to use our improved agentdef run_and_submit_all(profile: gr.OAuthProfile | None):"""Fetches all questions, runs the ImprovedLangGraphAgent on them, submits all answers,and displays the results."""# --- Determine HF Space Runtime URL and Repo URL ---10 unmodified linesquestions_url = f"{api_url}/questions"submit_url = f"{api_url}/submit"# 1. Instantiate Agenttry:agent = ImprovedLangGraphAgent()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 codebaseagent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"print(agent_code)18 unmodified linesprint(f"An unexpected error occurred fetching questions: {e}")return f"An unexpected error occurred fetching questions: {e}", None# 3. Run the Agentresults_log = []answers_payload = []print(f"Running agent on {len(questions_data)} questions...")4 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry:print(f"\n--- Processing Task ID: {task_id} ---")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})print(f"--- Task ID: {task_id} completed ---\n")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}"})20 unmodified linesf"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"f"Message: {result_data.get('message', 'No message received.')}")# --- Build Gradio Interface using Blocks ---
app.py+495-230