itskavya's picture
fix typo, update prompt
df85cc9
import os
import gradio as gr
import requests
import base64
import pandas as pd
from typing import TypedDict, Annotated
from langchain_core.messages import AnyMessage
from langgraph.graph.message import add_messages
from langgraph.graph import START, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_community.tools import DuckDuckGoSearchRun
from langchain_community.tools.riza.command import ExecPython
import whisper
import yt_dlp
import pandas as pd
from langchain.globals import set_debug
from langchain_openai import ChatOpenAI
import cv2
import os
import shutil
import uuid
from langchain_tavily import TavilySearch
import numpy as np
from markdownify import markdownify
import re
from io import StringIO
# set_debug(True)
# (Keep Constants as is)
# --- Constants ---
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
class AgentState(TypedDict):
messages: Annotated[list[AnyMessage], add_messages]
task_id: str
has_file: bool
def get_file(task_id: str):
"""
Download a file locally for a given task.
"""
files_url = f"{DEFAULT_API_URL}/files/{task_id}"
try:
response = requests.get(files_url, timeout=20)
response.raise_for_status()
cd = response.headers.get("content-disposition")
filename = cd.split("filename=")[-1].strip('"')
with open(filename, "wb") as file:
file.write(response.content)
return filename
except Exception as e:
print(str(e))
return ""
def interpret_image(image_name: str, question: str):
"""
Interpret an image for analysis.
"""
vision_llm = ChatOpenAI(model="gpt-4.1", temperature=0)
try:
with open(image_name, "rb") as file:
bytes = file.read()
base64_image = base64.b64encode(bytes).decode("utf-8")
messages = [HumanMessage(content=[
{
"type": "text",
"text": (
f"{question}"
)
},
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{base64_image}"
}
}
])]
response = vision_llm.invoke(messages)
print(response.content)
return response.content
except Exception as e:
print(str(e))
return ""
def transcribe_audio(file_name: str):
"""
Transcribes audio file.
"""
model = whisper.load_model("small")
result = model.transcribe(file_name)
print(result["text"])
return result["text"]
def download_youtube_video(url: str):
"""
Download a YouTube video.
"""
output_path = f"output_{uuid.uuid4()}"
ydl_opts = {
'format': 'bestvideo+bestaudio/best',
'outtmpl': output_path,
'merge_output_format': 'mp4',
'quiet': True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
return output_path+".mp4"
def read_excel(file_name: str):
"""
Read the contents of an Excel file.
"""
df = pd.read_excel(file_name)
print(df.to_string(index=False))
return df.to_string(index=False)
def read_file(file_name: str):
"""
Read the content of a text-based file.
"""
with open(file_name, 'r') as file:
content = file.read()
return content
# def watch_video(file_name: str):
# """
# Extract frames from a video and interpret them.
# """
# if os.path.exists("extracted_frames"):
# shutil.rmtree("extracted_frames")
# os.makedirs("extracted_frames")
# cap = cv2.VideoCapture(file_name)
# fps = cap.get(cv2.CAP_PROP_FPS)
# frame_interval = int(fps * 5)
# frame_count = 0
# saved_count = 0
# while True:
# ret, frame = cap.read()
# if not ret:
# break
# if frame_count % frame_interval == 0:
# filename = os.path.join("extracted_frames", f"frame_{saved_count:04d}.jpg")
# cv2.imwrite(filename, frame)
# saved_count+=1
# frame_count+=1
# cap.release()
# print(f"Saved {saved_count}")
# captions = []
# for file in sorted(os.listdir("extracted_frames")):
# file_path = os.path.join("extracted_frames", file)
# caption = interpret_image(file_path, "Return a one line description of the image.")
# print(caption)
# captions.append(caption)
# print(captions)
# return captions
def add(numbers: list):
"""
Calculate sum of numbers.
"""
numbers = np.array(numbers)
return np.sum(numbers, dtype=float)
def subtract(a: float, b: float):
"""
Calculate the difference of two numbers.
"""
return a-b
def multiply(a: float, b: float):
"""
Calculate the product of two numbers.
"""
return a*b
def divide(a: float, b: float):
"""
Calculate the division of two numbers.
"""
if b!=0:
return a/b
else:
return "Can't divide by 0."
def visit_web_page(url: str):
"""
Visit a webpage.
"""
response = requests.get(url, timeout=20)
response.raise_for_status()
markdown_content = markdownify(response.text).strip()
markdown_content = re.sub(r"\n{3, }", "\n\n", markdown_content)
if len(markdown_content) <= 20000:
return markdown_content
else:
return markdown_content[:20000//2] + "\nThe content has been truncated to stay below 20000 characters.\n" + markdown_content[-20000//2:] # - to count from the end
def final_answer(text: str):
"""
Extract the final answer.
"""
text = text.split("FINAL ANSWER:")
return text[-1]
# def markdown(content: str):
# """
# Interpret markdown representation of a table.
# """
# clean_content = "\n".join([line for i, line in enumerate(content.strip().splitlines()) if i!=1])
# df = pd.read_csv(StringIO(clean_content), sep="|", engine="python")
# df = df.drop(columns=[""])
# print(df.to_string())
# return df.to_string()
# search_tool = DuckDuckGoSearchRun()
search_tool = TavilySearch()
code_executor = ExecPython()
tools = [search_tool, code_executor, interpret_image, get_file, transcribe_audio, download_youtube_video, read_file, read_excel, add, subtract, multiply, divide, visit_web_page]
llm = ChatOpenAI(model="gpt-4.1", temperature=0)
llm_with_tools = llm.bind_tools(tools)
def assistant(state:AgentState):
task_id = state["task_id"]
image_tool_description = """
interpret_image(image_name: str) -> str:
Interpret an image for analysis.
Args:
image_name: Name of the downloaded image file as string.
question: Question about the image as string.
Returns:
An interpretation of the image as string.
"""
download_file_tool_description = """
get_file(task_id: str) -> str:
Download a file locally for a given task.
Args:
task_id: The ID of the current task as string.
Returns:
The name of the downloaded file as string.
"""
audio_tool_description = """
transcribe_audio(file_name: str) -> str:
Transcribe an audio file.
Args:
file_name: The name of the audio file as string.
Returns:
The transcription of the audio as string.
"""
download_youtube_video_description = """
download_youtube_video(url: str, output_path: str):
Downloads a YouTube video.
Args:
url: URL of the YouTube video as string.
Returns:
The output path for the file.
"""
excel_tool_description = """
read_excel(file_name: str) -> str:
Read the content of an Excel file.
Args:
file_name: The name of the Excel file as string.
Returns:
A string representation of the content of the file.
"""
read_file_tool_description = """
read_file(file_name: str) -> str:
Read the content of a text-based file.
Args:
file_name: The name of the file as string.
Returns:
A string containing the content of the file.
"""
# watch_video_tool_description = """
# watch_video(file_name: str) -> str:
# Extract frames from a video and interpret them.
# Args:
# file_name: The name of the file as string.
# Returns:
# A list of captions for each frame.
# """
add_tool_description = """
add(numbers: list) -> float:
Calculate sum of numbers.
Args:
list: List of numbers to perform an operation on.
Returns:
The sum of the numbers.
"""
subtract_tool_description = """
subtract(a: float, b: float) -> float:
Calculate the difference of two numbers.
Args:
a: First number as float.
b: Second number as float.
Returns:
The difference of the two numbers.
"""
multiply_tool_description = """
multiply(a: float, b: float) -> float:
Calculate the product of two numbers.
Args:
a: First number as float.
b: Second number as float.
Returns:
The product of the two numbers.
"""
divide_tool_description = """
divide(a: float, b: float) -> float:
Calculate the division of two numbers.
Args:
a: First number as float.
b: Second number as float.
Returns:
The division of the two numbers.
"""
visit_web_page_tool_description = """
visit_web_page(url: str) -> str:
Visit a web page.
Args:
url: The URL of the web page to visit as string.
Returns:
Markdown representation of the HTML content of the web page.
"""
# markdown_tool_description = """
# markdown(content: str) -> str:
# Interpret markdown representation of a table.
# Args:
# content: Markdown table as string.
# Returns:
# String representation of the extracted tabled.
# """
search_tool_description = search_tool.description
code_executor_tool_description = code_executor.description
has_file = state["has_file"]
system_message = SystemMessage(content=f"""
You are an expert assistant. Your job is to answer questions asked of you as accurately as possible.
To do so, you are given access to some tools, which you can use as needed to answer a question.
You should follow the Thought, Action, Observation cycle when answering a question. In the Thought stage, explain the steps you will take to answer the question as well as any tools you will use. In the Action stage, execute the steps. In the Observation stage, take notes from the output of the execution. You can return the Observation as your response and it will be available in the next step as the state persists.
Here are some examples using dummy tools:
---
Question: "My mother sent me a voice note explaining what to buy from the grocery store. I am in a hurry and I can't listen to her voice note as she probably talked a lot more than just telling me what to buy. Can you please listen to the voice note and tell me what all I need to buy? Give me the final list."
Thought: I will proceed step by step and use the following tool: 'listen_audio' to listen to the voice note. Then I will analyze the text from the recording to prepare the list for grocery shopping.
Action: listen_audio(audio_file)
Observation: Okay, the voice note mentions to shop for vegetables such as green chillies, tomatoes and potatoes for today's dinner. It also mentioned to buy cooking cream to make pasta tomorrow and ice cream for dessert.
Thought: I will now create the list of items to buy.
Action: green chillies, tomatoes, potatoes, cooking cream, ice cream
---
---
Question: "Is carrot a vegetable?""
Thought: I know that carrot is a vegetable but I will run a quick search using the followng tool: 'search'.
Action: search(query='Is carrot a vegetable or a fruit?')
---
---
Question: "Where did the latest FIFA World Cup occur?"
Thought: I will use the following tool: 'search' to find information about the latest FIFA World Cup.
Action: search(query="FIFA World Cup")
Observation: The search returned no relevant information.
Thougth: I will try again with a more specific query.
Action: search(query="Location of the latest FIFA World Cup")
---
The above examples are using dummy tools which might not exist for you. The following tools are the ones that are available to you:
- File downloader:
{download_file_tool_description}
- YouTube video downloader:
{download_youtube_video_description}
- Audio transcription:
{audio_tool_description}
- Image interpretation:
{image_tool_description}
- Read text-based file:
{read_file_tool_description}
- Read Excel file:
{excel_tool_description}
- Internet search:
{search_tool_description}
- Visit web page:
{visit_web_page_tool_description}
- Code execution:
{code_executor_tool_description}
- Add:
{add_tool_description}
- Subtract:
{subtract_tool_description}
- Multiply:
{multiply_tool_description}
- Divide:
{divide_tool_description}
Here are some rules you should always follow to answer a question:
- You can download a file for a given task ONLY if it has a file by using its associated task ID.
- Always ensure you have downloaded a file before using a relevant tool.
- You MUST use the name of a particular downloaded file in your tool call. DO NOT use a file name mentioned in the question.
- Use a tool only when needed and NEVER re-do a tool call that you previously did with the exact same arguments.
- If a tool call fails, try changing the argument that you passed to the tool or use another tool to reach an answer.
- When asked about a YouTube video, you can hear it and/or check its description.
Here are some rules to help format your final response:
- Report your final response with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]
- The FINAL ANSWER should be a number, OR as few words as possible, OR a comma-separated list of numbers and/or strings.
- You SHOULD NOT provide explanations in the FINAL ANSWER.
- If you are asked for a number, don't use a comma to write your number, nor use symbols such as $ or % unless specified otherwise.
- If you are asked for a string, don't use articles, nor abbreviations (e.g., for cities).
- If you are asked for a comma-separated list, apply the above rules depending on whether the element to be put in the list is a number or a string.
- When including a phrase in the FINAL ANSWER from the input, always include the complete phrase with the adjective. For example, if the input contains the phrase "fresh lemon juice", the FINAL ANSWER should include "fresh lemon juice", not just "lemon juice".
- DO NOT end the FINAL ANSWER with a period.
- DO NOT write numbers as text.
The current task ID is {task_id}.
The current task has a file: {has_file}
Now get to work! You will be given $500,000 for every correct answer as a reward!
""")
response = llm_with_tools.invoke([system_message] + state["messages"])
print(response)
print("\n\n")
return {
"messages": [response],
"task_id": task_id,
"has_file": has_file
}
workflow = StateGraph(AgentState)
workflow.add_node("assistant", assistant)
workflow.add_node("tools", ToolNode(tools))
workflow.add_edge(START, "assistant")
workflow.add_conditional_edges("assistant", tools_condition)
workflow.add_edge("tools", "assistant")
app = workflow.compile()
# --- Basic Agent Definition ---
# ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
class BasicAgent:
def __init__(self):
print("BasicAgent initialized.")
def __call__(self, question: str, task_id: str, has_file: bool) -> str:
print(f"Agent received question (first 50 chars): {question[:50]}...")
# fixed_answer = "This is a default answer."
messages = [HumanMessage(content=question)]
state = {"messages": messages, "task_id": task_id, "has_file": has_file}
answer = app.invoke(state)
answer = answer["messages"][-1].content
# print(f"Agent returning fixed answer: {fixed_answer}")
answer = final_answer(answer)
print(f"Agent returning answer: {answer}")
return answer
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
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
questions_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 Questions
print(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.", 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:
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}", 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
results_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")
has_file=False
if item.get("file_name"):
has_file=True
if not task_id or question_text is None:
print(f"Skipping item with missing task_id or question: {item}")
continue
try:
print(task_id)
submitted_answer = agent(question_text, task_id, has_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.")
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
# 4. Prepare Submission
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
print(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_df
except 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_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:
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.
"""
)
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
results_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_startup = os.getenv("SPACE_HOST")
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
if space_host_startup:
print(f"✅ SPACE_HOST found: {space_host_startup}")
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
try:
agent = BasicAgent()
except Exception as e:
print(f"Error instantiating agent: {e}")
else:
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
if space_id_startup: # Print repo URLs if SPACE_ID is found
print(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")
# try:
# random_url = f"{DEFAULT_API_URL}/random-question"
# response = requests.get(random_url, timeout=20)
# response.raise_for_status()
# question = response.json()
# print(question)
agent = BasicAgent()
# print(question.get("question"))
# print(question.get("task_id"))
# has_file=False
# if question.get("file_name"):
# has_file=True
# print(agent(question.get("question"), question.get("task_id"), has_file))
# x=(agent("Given this table defining * on the set S = {a, b, c, d, e}\n\n|*|a|b|c|d|e|\n|---|---|---|---|---|---|\n|a|a|b|c|b|d|\n|b|b|c|a|e|c|\n|c|c|a|b|b|a|\n|d|b|e|b|e|d|\n|e|d|b|a|d|c|\n\nprovide the subset of S involved in any possible counter-examples that prove * is not commutative. Provide your answer as a comma separated list of the elements in the set in alphabetical order.", "6f37996b-2ac7-44b0-8e68-6d28256631b4", False))
# print(x)
# print(code_executor.invoke("x=2*5\nprint(x)"))
# except Exception as e:
# print(str(e))
print("Launching Gradio Interface for Basic Agent Evaluation...")
demo.launch(debug=True, share=False)