Spaces:
Runtime error
Runtime error
Commit
·
6318a31
1
Parent(s):
81917a3
Updated agent
Browse files- .gitignore +3 -0
- app.py +219 -7
.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.venv
|
| 2 |
+
.env
|
| 3 |
+
.gitattributes
|
app.py
CHANGED
|
@@ -3,21 +3,232 @@ import gradio as gr
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# (Keep Constants as is)
|
| 8 |
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
# --- Basic Agent Definition ---
|
| 12 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
|
@@ -76,11 +287,12 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 76 |
for item in questions_data:
|
| 77 |
task_id = item.get("task_id")
|
| 78 |
question_text = item.get("question")
|
|
|
|
| 79 |
if not task_id or question_text is None:
|
| 80 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 81 |
continue
|
| 82 |
try:
|
| 83 |
-
submitted_answer = agent(question_text)
|
| 84 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 85 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 86 |
except Exception as e:
|
|
|
|
| 3 |
import requests
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
+
from langgraph.graph import StateGraph, START, END
|
| 7 |
+
from typing_extensions import TypedDict
|
| 8 |
+
from typing import List, TypedDict, Annotated, Optional
|
| 9 |
+
from langchain_core.messages import AnyMessage, SystemMessage, HumanMessage
|
| 10 |
+
from langgraph.graph.message import add_messages
|
| 11 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
| 12 |
+
from langgraph.prebuilt import ToolNode, tools_condition
|
| 13 |
+
from PIL import Image
|
| 14 |
+
import requests
|
| 15 |
+
from io import BytesIO
|
| 16 |
+
import PyPDF2
|
| 17 |
+
import base64
|
| 18 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 19 |
+
from langchain_core.tools import tool
|
| 20 |
+
from dotenv import load_dotenv
|
| 21 |
+
import time
|
| 22 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
| 23 |
+
from langchain_community.utilities.duckduckgo_search import DuckDuckGoSearchAPIWrapper
|
| 24 |
+
from langchain_community.tools import BraveSearch
|
| 25 |
+
|
| 26 |
+
load_dotenv(".env", override=True)
|
| 27 |
+
BRAVE_API_KEY = os.getenv("BRAVE_API")
|
| 28 |
+
|
| 29 |
+
class State(TypedDict):
|
| 30 |
+
file_path : str
|
| 31 |
+
file: Optional[str]
|
| 32 |
+
parsed_file: Optional[str]
|
| 33 |
+
messages: Annotated[list[AnyMessage], add_messages]
|
| 34 |
+
parsed_file_message: dict
|
| 35 |
|
| 36 |
# (Keep Constants as is)
|
| 37 |
# --- Constants ---
|
| 38 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 39 |
|
| 40 |
# --- Basic Agent Definition ---
|
|
|
|
| 41 |
class BasicAgent:
|
| 42 |
def __init__(self):
|
| 43 |
+
|
| 44 |
+
# tools initialization
|
| 45 |
+
#internet_search = DuckDuckGoSearchRun()
|
| 46 |
+
|
| 47 |
+
tools = [BasicAgent.search_tool, BasicAgent.revert_string, BasicAgent.download_file_tool, BasicAgent.answer_question_tool_from_file]
|
| 48 |
+
|
| 49 |
+
#llm = ChatOllama(model="llama3.2", temperature=0)
|
| 50 |
+
llm = ChatGoogleGenerativeAI(
|
| 51 |
+
model="gemini-2.0-flash",
|
| 52 |
+
temperature=0)
|
| 53 |
+
self.llm_with_tools = llm.bind_tools(tools)
|
| 54 |
+
|
| 55 |
+
builder = StateGraph(State)
|
| 56 |
+
|
| 57 |
+
builder.add_node("assistant", self.assistant)
|
| 58 |
+
builder.add_node("tools", ToolNode(tools))
|
| 59 |
+
#builder.add_node("download_file", BasicAgent.download_file_node)
|
| 60 |
+
#builder.add_node("parse_img", BasicAgent.parse_image)
|
| 61 |
+
#builder.add_node("parse_pdf", BasicAgent.parse_pdf)
|
| 62 |
+
#builder.add_node("parse_audio", BasicAgent.parse_audio)
|
| 63 |
+
#builder.add_node("extract_data", BasicAgent.extract_data_from_file)
|
| 64 |
+
|
| 65 |
+
builder.add_edge(START, "assistant")
|
| 66 |
+
#builder.add_conditional_edges("download_file", BasicAgent.determine_file_type,
|
| 67 |
+
# {"img": "parse_img", "pdf": "parse_pdf", "audio": "parse_audio", "end": END})
|
| 68 |
+
#builder.add_edge("parse_img", "assistant")
|
| 69 |
+
#builder.add_edge("parse_pdf", "assistant")
|
| 70 |
+
#builder.add_edge("parse_audio", "assistant")
|
| 71 |
+
builder.add_conditional_edges("assistant", tools_condition)
|
| 72 |
+
builder.add_edge("tools", "assistant")
|
| 73 |
+
|
| 74 |
+
self.react_graph = builder.compile()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def __call__(self, question: str, file_name: Optional[str]) -> str:
|
| 78 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 79 |
+
|
| 80 |
+
messages = [HumanMessage(question)]
|
| 81 |
+
messages = self.react_graph.invoke({"messages": messages, "file_path": file_name})
|
| 82 |
+
|
| 83 |
+
for m in messages['messages']:
|
| 84 |
+
m.pretty_print()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
final_answer = messages["messages"][-1].content
|
| 88 |
+
print(f"Final answer is {final_answer}")
|
| 89 |
+
return final_answer
|
| 90 |
+
|
| 91 |
+
def search_tool(query: str):
|
| 92 |
+
"""
|
| 93 |
+
This function looks for the provided query online and gives you information about it.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
search_tool = BraveSearch.from_api_key(api_key=BRAVE_API_KEY, search_kwargs={"count": 3})
|
| 97 |
+
res = search_tool.run(query)
|
| 98 |
+
|
| 99 |
+
return res
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def assistant(self, state: State):
|
| 103 |
+
if state["file_path"]:
|
| 104 |
+
file_name = state["file_path"].split(".")[0]
|
| 105 |
+
file_extension = state["file_path"].split(".")[1]
|
| 106 |
+
else:
|
| 107 |
+
file_extension = None
|
| 108 |
+
|
| 109 |
+
prompt = f"""
|
| 110 |
+
You are a helpful assistant.
|
| 111 |
+
You have access to some optional documents. The file name of the file you have access is: {file_name} and it is a {file_extension} file. The DEFAULT_API_URL to fetch this file is {DEFAULT_API_URL}.
|
| 112 |
+
If you need to fetch a file, call the download_file tool with exactly the filename in the format {DEFAULT_API_URL}/files/file_name or URL. Once you have the bytes back (and the Base64), continue.
|
| 113 |
+
You need to answer the given question EXACTLY in the SPECIFIC WAY it is asked in the user question. DO NOT ADD ANYTHING NOT NEEDED IN THE ANSWER.")
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
sys_msg = SystemMessage(content=prompt)
|
| 117 |
+
|
| 118 |
+
time.sleep(5)
|
| 119 |
+
return {"messages": [self.llm_with_tools.invoke([sys_msg] + state["messages"])]}
|
| 120 |
+
|
| 121 |
+
def file_to_download_exists(state: State) -> ["download", "apply_tools"]:
|
| 122 |
+
"""
|
| 123 |
+
This function checks whether there is a file that needs to be downloaded
|
| 124 |
+
"""
|
| 125 |
+
return state["file_path"] != ""
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def download_file_tool(file_url: str) -> dict:
|
| 129 |
+
"""
|
| 130 |
+
This tool downloads a file (image, pdf, etc.) given the name of the file. The url for the request will be composed in the function so ONLY the name of the file should be passed in.
|
| 131 |
+
|
| 132 |
+
You may have to download a file in 2 different scenarios:
|
| 133 |
+
- A file given already as part of the task. In this case the format of the url must be: {DEFAULT_API_URL}/files/{file_name} THE EXTENSION OF THE FILE MUST NOT(!!) BE INCLUDED!
|
| 134 |
+
- A url retrieved from the internet in the format https://some_url. In that case, you simply need to provide the url of the file that needs to be retrieved.
|
| 135 |
+
|
| 136 |
+
Args:
|
| 137 |
+
file_name: the name of the file to be retrieved
|
| 138 |
+
|
| 139 |
+
Output:
|
| 140 |
+
A tuple made of:
|
| 141 |
+
1) The file in bytes
|
| 142 |
+
2) The file in Base64 encoding
|
| 143 |
+
3) The result of the call
|
| 144 |
+
"""
|
| 145 |
+
#task_id = file_.split(".")[0]
|
| 146 |
+
#print("Downloading the file")
|
| 147 |
+
|
| 148 |
+
response = requests.get(file_url)
|
| 149 |
+
if response.status_code == 200:
|
| 150 |
+
msg = "File downloaded successfully!!"
|
| 151 |
+
print(msg)
|
| 152 |
+
file = response.content
|
| 153 |
+
b64_file = base64.b64encode(state["file"]).decode("utf-8")
|
| 154 |
+
else:
|
| 155 |
+
msg = "There was an error downloading the file."
|
| 156 |
+
print(msg)
|
| 157 |
+
file = None
|
| 158 |
+
b64_file = None
|
| 159 |
+
|
| 160 |
+
return {
|
| 161 |
+
"bytes": file,
|
| 162 |
+
"base64": b64_file,
|
| 163 |
+
"status": response.status_code,
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
def determine_file_type(state: State) -> ["pdf", "img", "audio", "end"]:
|
| 167 |
+
if state["file"] is None:
|
| 168 |
+
return "end"
|
| 169 |
+
|
| 170 |
+
file_extension = state["file_path"].split(".")[1]
|
| 171 |
+
if file_extension in ["png", "jpg"]:
|
| 172 |
+
return "img"
|
| 173 |
+
elif file_extension == "pdf":
|
| 174 |
+
return "pdf"
|
| 175 |
+
elif file_extension in ["mp3", "wav"]:
|
| 176 |
+
return "audio"
|
| 177 |
+
|
| 178 |
+
return "end"
|
| 179 |
+
|
| 180 |
+
def answer_question_tool_from_file(question: str, encoded_file: str, file_extension: str) -> str:
|
| 181 |
+
"""
|
| 182 |
+
This tool allows you to answer a question taking into account information that were provided inside a file.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
The question that needs to be answered.
|
| 186 |
+
The file from which you want to get some information.
|
| 187 |
+
The file extension of the file that is being processed.
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
if file_extension in ["png", "jpg"]:
|
| 191 |
+
message = {"type": "image_url", "image_url": f"data:image/png;base64,{encoded_file}"}
|
| 192 |
+
elif file_extension == "pdf":
|
| 193 |
+
message = {"type": "image_url", # Assuming the LLM accepts PDF under this key, you might need to verify this
|
| 194 |
+
"image_url": f"data:application/pdf;base64,{encoded_file}"
|
| 195 |
+
}
|
| 196 |
+
elif file_extension in ["mp3", "wav"]:
|
| 197 |
+
message = {"type": "media", "data": encoded_file, # Use base64 string directly
|
| 198 |
+
"mime_type": "audio/mpeg",
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
message_local = HumanMessage(
|
| 202 |
+
content=[
|
| 203 |
+
{"type": "text", "text": question},
|
| 204 |
+
message,
|
| 205 |
+
]
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
llm = ChatGoogleGenerativeAI(
|
| 209 |
+
model="gemini-2.0-flash",
|
| 210 |
+
temperature=0)
|
| 211 |
+
|
| 212 |
+
response = llm.invoke(message_local)
|
| 213 |
+
|
| 214 |
+
return response
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def revert_string(input_str: str) -> str:
|
| 218 |
+
"""
|
| 219 |
+
This function inverst the order of the characters within a sentence. It is particularly useful if you can't understand the content
|
| 220 |
+
in any language.
|
| 221 |
+
|
| 222 |
+
Args:
|
| 223 |
+
input_str: the string to invert
|
| 224 |
+
|
| 225 |
+
Returns:
|
| 226 |
+
The inverted string
|
| 227 |
+
"""
|
| 228 |
+
|
| 229 |
+
return input_str[::-1]
|
| 230 |
+
|
| 231 |
+
|
| 232 |
|
| 233 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 234 |
"""
|
|
|
|
| 287 |
for item in questions_data:
|
| 288 |
task_id = item.get("task_id")
|
| 289 |
question_text = item.get("question")
|
| 290 |
+
file_name = item.get("file_name")
|
| 291 |
if not task_id or question_text is None:
|
| 292 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 293 |
continue
|
| 294 |
try:
|
| 295 |
+
submitted_answer = agent(question_text, file_name)
|
| 296 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 297 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 298 |
except Exception as e:
|