Spaces:
Build error
Build error
Added file support
Browse files- agents.py +36 -5
- app.py +11 -3
- questions_data/questions.json +2 -2
- requirements.txt +2 -1
- run-local.py +2 -4
- tools.py +77 -6
agents.py
CHANGED
|
@@ -1,6 +1,9 @@
|
|
| 1 |
from typing import TypedDict, Annotated, List, Union, Optional
|
| 2 |
import json
|
| 3 |
import re
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
from langgraph.graph import StateGraph, add_messages
|
| 6 |
from langchain_openai import ChatOpenAI
|
|
@@ -8,6 +11,7 @@ from langchain_core.messages import SystemMessage, HumanMessage, AIMessage, Tool
|
|
| 8 |
from langgraph.prebuilt import ToolNode, tools_condition
|
| 9 |
|
| 10 |
from tools import tools
|
|
|
|
| 11 |
|
| 12 |
# Define the system prompt for the thinking agent
|
| 13 |
THINKER_SYSTEM_PROMPT = """
|
|
@@ -17,9 +21,10 @@ You will also provide a final answer at the end of your reasoning.
|
|
| 17 |
|
| 18 |
Your job is to:
|
| 19 |
- Understand what the task is asking.
|
| 20 |
-
- Decide what information you need to solve it. Think step by step and think ahead about what you will need to do.
|
|
|
|
| 21 |
- Use the available tools to obtain the required information or if you are 100% sure about the answer use your knowledge.
|
| 22 |
-
- If you need to use a tool, call it with the required arguments. You are encouraged to use multiple tools in a single turn for a quicker resolution if they don't depend on each other. For example search for multiple terms in Google or Wikipedia at once.
|
| 23 |
- You can use the tools in any order you like. You can also use the same tool multiple times. However if the tool returns an error don't use it again with the same arguments.
|
| 24 |
- After the tools are called control will return to you and you will decide what to do next, whether to use another tool or provide a final answer.
|
| 25 |
- When you think you have all the information to solve the task, present all the facts that led you to the final answer in a clear and concise summary, showing your reasoning.
|
|
@@ -33,7 +38,7 @@ MAX_TURNS = 10
|
|
| 33 |
|
| 34 |
# Initialize the LLM
|
| 35 |
# llm = ChatOpenAI(model="o4-mini")
|
| 36 |
-
llm = ChatOpenAI(model="gpt-
|
| 37 |
|
| 38 |
|
| 39 |
class AgentState(TypedDict):
|
|
@@ -136,7 +141,7 @@ class ThinkerAgent:
|
|
| 136 |
def __init__(self):
|
| 137 |
self.graph = build_graph()
|
| 138 |
|
| 139 |
-
def __call__(self, task: str) -> AgentState:
|
| 140 |
print("====== Running task ======")
|
| 141 |
print(task)
|
| 142 |
print("==========================")
|
|
@@ -144,10 +149,36 @@ class ThinkerAgent:
|
|
| 144 |
initial_state: AgentState = {
|
| 145 |
"messages": [
|
| 146 |
SystemMessage(content=THINKER_SYSTEM_PROMPT),
|
| 147 |
-
HumanMessage(content=task),
|
| 148 |
],
|
| 149 |
"final_answer": None,
|
| 150 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
# Run the graph with the initial state
|
| 153 |
final_state = self.graph.invoke(initial_state)
|
|
|
|
| 1 |
from typing import TypedDict, Annotated, List, Union, Optional
|
| 2 |
import json
|
| 3 |
import re
|
| 4 |
+
import base64
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import magic
|
| 7 |
|
| 8 |
from langgraph.graph import StateGraph, add_messages
|
| 9 |
from langchain_openai import ChatOpenAI
|
|
|
|
| 11 |
from langgraph.prebuilt import ToolNode, tools_condition
|
| 12 |
|
| 13 |
from tools import tools
|
| 14 |
+
from markitdown import MarkItDown
|
| 15 |
|
| 16 |
# Define the system prompt for the thinking agent
|
| 17 |
THINKER_SYSTEM_PROMPT = """
|
|
|
|
| 21 |
|
| 22 |
Your job is to:
|
| 23 |
- Understand what the task is asking.
|
| 24 |
+
- Decide what information you need to solve it. Think step by step and think ahead about what you will need to do.
|
| 25 |
+
- Always print your thoughts in every step and the next steps you will take.
|
| 26 |
- Use the available tools to obtain the required information or if you are 100% sure about the answer use your knowledge.
|
| 27 |
+
- If you need to use a tool, call it with the required arguments. You are encouraged to use multiple tools in a single turn for a quicker resolution if they don't depend on each other. For example search for multiple terms in Google or Wikipedia at once. Google results include the URLs of the pages and you are encouraged to visit them to get more information.
|
| 28 |
- You can use the tools in any order you like. You can also use the same tool multiple times. However if the tool returns an error don't use it again with the same arguments.
|
| 29 |
- After the tools are called control will return to you and you will decide what to do next, whether to use another tool or provide a final answer.
|
| 30 |
- When you think you have all the information to solve the task, present all the facts that led you to the final answer in a clear and concise summary, showing your reasoning.
|
|
|
|
| 38 |
|
| 39 |
# Initialize the LLM
|
| 40 |
# llm = ChatOpenAI(model="o4-mini")
|
| 41 |
+
llm = ChatOpenAI(model="gpt-4o", temperature=0)
|
| 42 |
|
| 43 |
|
| 44 |
class AgentState(TypedDict):
|
|
|
|
| 141 |
def __init__(self):
|
| 142 |
self.graph = build_graph()
|
| 143 |
|
| 144 |
+
def __call__(self, task: str, file_io: BytesIO = None) -> AgentState:
|
| 145 |
print("====== Running task ======")
|
| 146 |
print(task)
|
| 147 |
print("==========================")
|
|
|
|
| 149 |
initial_state: AgentState = {
|
| 150 |
"messages": [
|
| 151 |
SystemMessage(content=THINKER_SYSTEM_PROMPT),
|
|
|
|
| 152 |
],
|
| 153 |
"final_answer": None,
|
| 154 |
}
|
| 155 |
+
human_message_content = [
|
| 156 |
+
{"type": "text", "text": task},
|
| 157 |
+
]
|
| 158 |
+
if file_io:
|
| 159 |
+
# Figure out the file type using python-magic
|
| 160 |
+
file_content = file_io.read()
|
| 161 |
+
file_io.seek(0) # Reset the file pointer to the beginning
|
| 162 |
+
file_mime_type = magic.from_buffer(file_content, mime=True)
|
| 163 |
+
print(f"File MIME type: {file_mime_type}")
|
| 164 |
+
|
| 165 |
+
if file_mime_type.startswith("image/"):
|
| 166 |
+
base64_file = base64.b64encode(file_content).decode("utf-8")
|
| 167 |
+
human_message_content.append({
|
| 168 |
+
"type": "image_url",
|
| 169 |
+
"image_url": {
|
| 170 |
+
"url": f"data:{file_mime_type};base64,{base64_file}"
|
| 171 |
+
}
|
| 172 |
+
})
|
| 173 |
+
else:
|
| 174 |
+
# Convert the file to markdown
|
| 175 |
+
md = MarkItDown()
|
| 176 |
+
markdown_result = md.convert(file_io)
|
| 177 |
+
human_message_content.append({
|
| 178 |
+
"type": "text",
|
| 179 |
+
"text": markdown_result.markdown
|
| 180 |
+
})
|
| 181 |
+
initial_state["messages"].append(HumanMessage(content=human_message_content))
|
| 182 |
|
| 183 |
# Run the graph with the initial state
|
| 184 |
final_state = self.graph.invoke(initial_state)
|
app.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
# import inspect
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
from agents import ThinkerAgent # Assuming ThinkerAgent is defined in agents.py
|
|
@@ -63,7 +62,7 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 63 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 64 |
|
| 65 |
# 2.5 Filter out questions with files (for now)
|
| 66 |
-
questions_data = [item for item in questions_data if not item.get("file_name")]
|
| 67 |
|
| 68 |
# 3. Run your Agent
|
| 69 |
results_log = []
|
|
@@ -72,11 +71,20 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 72 |
for item in questions_data:
|
| 73 |
task_id = item.get("task_id")
|
| 74 |
question_text = item.get("question")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
if not task_id or question_text is None:
|
| 76 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 77 |
continue
|
| 78 |
try:
|
| 79 |
-
final_answer, _ = agent(question_text)
|
| 80 |
submitted_answer = str(final_answer).strip()
|
| 81 |
if not submitted_answer:
|
| 82 |
print(f"Agent did not produce a valid answer for task {task_id}.")
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
|
| 6 |
from agents import ThinkerAgent # Assuming ThinkerAgent is defined in agents.py
|
|
|
|
| 62 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 63 |
|
| 64 |
# 2.5 Filter out questions with files (for now)
|
| 65 |
+
# questions_data = [item for item in questions_data if not item.get("file_name")]
|
| 66 |
|
| 67 |
# 3. Run your Agent
|
| 68 |
results_log = []
|
|
|
|
| 71 |
for item in questions_data:
|
| 72 |
task_id = item.get("task_id")
|
| 73 |
question_text = item.get("question")
|
| 74 |
+
if item.get("file_name"):
|
| 75 |
+
try:
|
| 76 |
+
response = requests.get(f"{DEFAULT_API_URL}/files/{item['task_id']", timeout=15)
|
| 77 |
+
response.raise_for_status()
|
| 78 |
+
file_io = response.content
|
| 79 |
+
except requests.exceptions.RequestException as e:
|
| 80 |
+
print(f"Error fetching file for task {task_id}: {e}")
|
| 81 |
+
else
|
| 82 |
+
file_io = None
|
| 83 |
if not task_id or question_text is None:
|
| 84 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 85 |
continue
|
| 86 |
try:
|
| 87 |
+
final_answer, _ = agent(question_text, file_io)
|
| 88 |
submitted_answer = str(final_answer).strip()
|
| 89 |
if not submitted_answer:
|
| 90 |
print(f"Agent did not produce a valid answer for task {task_id}.")
|
questions_data/questions.json
CHANGED
|
@@ -25,7 +25,7 @@
|
|
| 25 |
"question": "Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.",
|
| 26 |
"Level": "1",
|
| 27 |
"file_name": "cca530fc-4052-43b2-b130-b30968d8aa44.png",
|
| 28 |
-
"answer": "
|
| 29 |
},
|
| 30 |
{
|
| 31 |
"task_id": "4fc2f1ae-8625-45b5-ab34-ad4433bc21f8",
|
|
@@ -95,7 +95,7 @@
|
|
| 95 |
"question": "Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",
|
| 96 |
"Level": "1",
|
| 97 |
"file_name": "1f975693-876d-457b-a649-393859e79bf3.mp3",
|
| 98 |
-
"answer":
|
| 99 |
},
|
| 100 |
{
|
| 101 |
"task_id": "840bfca7-4f7b-481a-8794-c560c340185d",
|
|
|
|
| 25 |
"question": "Review the chess position provided in the image. It is black's turn. Provide the correct next move for black which guarantees a win. Please provide your response in algebraic notation.",
|
| 26 |
"Level": "1",
|
| 27 |
"file_name": "cca530fc-4052-43b2-b130-b30968d8aa44.png",
|
| 28 |
+
"answer": "Qd1+"
|
| 29 |
},
|
| 30 |
{
|
| 31 |
"task_id": "4fc2f1ae-8625-45b5-ab34-ad4433bc21f8",
|
|
|
|
| 95 |
"question": "Hi, I was out sick from my classes on Friday, so I'm trying to figure out what I need to study for my Calculus mid-term next week. My friend from class sent me an audio recording of Professor Willowbrook giving out the recommended reading for the test, but my headphones are broken :(\n\nCould you please listen to the recording for me and tell me the page numbers I'm supposed to go over? I've attached a file called Homework.mp3 that has the recording. Please provide just the page numbers as a comma-delimited list. And please provide the list in ascending order.",
|
| 96 |
"Level": "1",
|
| 97 |
"file_name": "1f975693-876d-457b-a649-393859e79bf3.mp3",
|
| 98 |
+
"answer": "132, 133, 134, 197, 245"
|
| 99 |
},
|
| 100 |
{
|
| 101 |
"task_id": "840bfca7-4f7b-481a-8794-c560c340185d",
|
requirements.txt
CHANGED
|
@@ -12,5 +12,6 @@ langgraph
|
|
| 12 |
langchain-community
|
| 13 |
pyowm
|
| 14 |
wikipedia
|
| 15 |
-
|
|
|
|
| 16 |
markitdown[all]
|
|
|
|
| 12 |
langchain-community
|
| 13 |
pyowm
|
| 14 |
wikipedia
|
| 15 |
+
google-search-results
|
| 16 |
+
python-magic
|
| 17 |
markitdown[all]
|
run-local.py
CHANGED
|
@@ -20,15 +20,13 @@ if __name__ == "__main__":
|
|
| 20 |
agent = ThinkerAgent()
|
| 21 |
questions = Questions()
|
| 22 |
|
| 23 |
-
print(sys.argv)
|
| 24 |
for question in questions.get_questions(sys.argv[1:]):
|
| 25 |
-
if question.get("file"):
|
| 26 |
-
continue # Skip questions with files
|
| 27 |
print(f"====== Question: {question['task_id']} ======")
|
| 28 |
# Run the agent with a sample task
|
| 29 |
task = question["question"]
|
|
|
|
| 30 |
provided_answer = question.get("answer")
|
| 31 |
-
final_answer, final_state = agent(task)
|
| 32 |
print(f"Final Answer: {final_answer}")
|
| 33 |
print(f"Provided Answer: {provided_answer}")
|
| 34 |
|
|
|
|
| 20 |
agent = ThinkerAgent()
|
| 21 |
questions = Questions()
|
| 22 |
|
|
|
|
| 23 |
for question in questions.get_questions(sys.argv[1:]):
|
|
|
|
|
|
|
| 24 |
print(f"====== Question: {question['task_id']} ======")
|
| 25 |
# Run the agent with a sample task
|
| 26 |
task = question["question"]
|
| 27 |
+
file = question.get("file")
|
| 28 |
provided_answer = question.get("answer")
|
| 29 |
+
final_answer, final_state = agent(task, file)
|
| 30 |
print(f"Final Answer: {final_answer}")
|
| 31 |
print(f"Provided Answer: {provided_answer}")
|
| 32 |
|
tools.py
CHANGED
|
@@ -1,8 +1,9 @@
|
|
| 1 |
from io import BytesIO
|
|
|
|
| 2 |
from langchain_core.tools import tool
|
| 3 |
# from langchain_core.messages import SystemMessage, HumanMessage
|
| 4 |
# from langchain_openai import ChatOpenAI
|
| 5 |
-
from langchain_community.utilities import OpenWeatherMapAPIWrapper
|
| 6 |
# from langchain_community.retrievers import WikipediaRetriever
|
| 7 |
import wikipedia
|
| 8 |
from markitdown import MarkItDown
|
|
@@ -150,27 +151,97 @@ def youtube_video_tool(url: str) -> str:
|
|
| 150 |
|
| 151 |
|
| 152 |
@tool
|
| 153 |
-
def audio_transcript_tool(
|
| 154 |
"""
|
| 155 |
Get a transcript of an audio file.
|
| 156 |
|
| 157 |
Args:
|
| 158 |
-
|
| 159 |
|
| 160 |
Returns:
|
| 161 |
str: The transcript of the audio file.
|
| 162 |
"""
|
| 163 |
print(f"audio_transcript_tool called with: {url}")
|
| 164 |
md = MarkItDown()
|
| 165 |
-
markdown_result = md.
|
| 166 |
return markdown_result.markdown
|
| 167 |
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
# List of tools to be used
|
| 170 |
tools = [
|
| 171 |
# simple_answer_function,
|
| 172 |
-
weather_tool,
|
| 173 |
-
unit_converter_tool,
|
|
|
|
|
|
|
| 174 |
wikipedia_tool,
|
| 175 |
youtube_video_tool,
|
| 176 |
]
|
|
|
|
| 1 |
from io import BytesIO
|
| 2 |
+
import requests
|
| 3 |
from langchain_core.tools import tool
|
| 4 |
# from langchain_core.messages import SystemMessage, HumanMessage
|
| 5 |
# from langchain_openai import ChatOpenAI
|
| 6 |
+
from langchain_community.utilities import OpenWeatherMapAPIWrapper, SerpAPIWrapper
|
| 7 |
# from langchain_community.retrievers import WikipediaRetriever
|
| 8 |
import wikipedia
|
| 9 |
from markitdown import MarkItDown
|
|
|
|
| 151 |
|
| 152 |
|
| 153 |
@tool
|
| 154 |
+
def audio_transcript_tool(url: str) -> str:
|
| 155 |
"""
|
| 156 |
Get a transcript of an audio file.
|
| 157 |
|
| 158 |
Args:
|
| 159 |
+
url (str): The URL of the audio file.
|
| 160 |
|
| 161 |
Returns:
|
| 162 |
str: The transcript of the audio file.
|
| 163 |
"""
|
| 164 |
print(f"audio_transcript_tool called with: {url}")
|
| 165 |
md = MarkItDown()
|
| 166 |
+
markdown_result = md.convert_url(url)
|
| 167 |
return markdown_result.markdown
|
| 168 |
|
| 169 |
|
| 170 |
+
@tool
|
| 171 |
+
def google_search_tool(query: str) -> str:
|
| 172 |
+
"""
|
| 173 |
+
Perform a Google search for a specific query.
|
| 174 |
+
|
| 175 |
+
Args:
|
| 176 |
+
query (str): The query to search for on Google.
|
| 177 |
+
|
| 178 |
+
Returns:
|
| 179 |
+
str: The search results from Google.
|
| 180 |
+
"""
|
| 181 |
+
print(f"google_search_tool called with: {query}")
|
| 182 |
+
try:
|
| 183 |
+
# Create the Google API wrapper
|
| 184 |
+
google_api = SerpAPIWrapper()
|
| 185 |
+
# Perform the search
|
| 186 |
+
search_results = google_api.results(query)
|
| 187 |
+
print(f"google_search_tool response: {search_results['organic_results']}")
|
| 188 |
+
return search_results['organic_results']
|
| 189 |
+
except Exception as e:
|
| 190 |
+
error = f"Error performing Google search: {e}"
|
| 191 |
+
print(error)
|
| 192 |
+
return error
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
@tool
|
| 196 |
+
def visit_url_tool(url: str) -> str:
|
| 197 |
+
"""
|
| 198 |
+
Visit the URL and retrieve the webpage or file content.
|
| 199 |
+
This function checks the content type of the file and converts it to markdown if necessary.
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
url (str): The URL of the file to be downloaded.
|
| 203 |
+
|
| 204 |
+
Returns:
|
| 205 |
+
str: The content of the downloaded file.
|
| 206 |
+
"""
|
| 207 |
+
print(f"download_url_tool called with: {url}")
|
| 208 |
+
try:
|
| 209 |
+
# Download the file
|
| 210 |
+
response = requests.get(url)
|
| 211 |
+
response.raise_for_status()
|
| 212 |
+
|
| 213 |
+
# Check content type and if it's not a text file, convert it to markdown
|
| 214 |
+
content_type = response.headers.get("Content-Type", "")
|
| 215 |
+
if content_type in ["text/plain", "application/json"]:
|
| 216 |
+
print(f"download_url_tool response: {response.content[:100]}...")
|
| 217 |
+
return response.content
|
| 218 |
+
|
| 219 |
+
# Convert the file to markdown
|
| 220 |
+
print(f"download_url_tool converting to markdown: {content_type}")
|
| 221 |
+
md = MarkItDown()
|
| 222 |
+
try:
|
| 223 |
+
content_io = BytesIO(response.content)
|
| 224 |
+
markdown_result = md.convert(content_io)
|
| 225 |
+
print(f"download_url_tool response: {markdown_result.markdown[:100]}...")
|
| 226 |
+
return markdown_result.markdown
|
| 227 |
+
except Exception as e:
|
| 228 |
+
error = f"Error converting {content_type} file to markdown: {e}"
|
| 229 |
+
print(error)
|
| 230 |
+
return error
|
| 231 |
+
|
| 232 |
+
except Exception as e:
|
| 233 |
+
error = f"Error downloading file from URL: {e}"
|
| 234 |
+
print(error)
|
| 235 |
+
return error
|
| 236 |
+
|
| 237 |
+
|
| 238 |
# List of tools to be used
|
| 239 |
tools = [
|
| 240 |
# simple_answer_function,
|
| 241 |
+
# weather_tool,
|
| 242 |
+
# unit_converter_tool,
|
| 243 |
+
google_search_tool,
|
| 244 |
+
visit_url_tool,
|
| 245 |
wikipedia_tool,
|
| 246 |
youtube_video_tool,
|
| 247 |
]
|