Update app.py
Browse files
app.py
CHANGED
|
@@ -5,12 +5,12 @@ import inspect
|
|
| 5 |
import pandas as pd
|
| 6 |
import re
|
| 7 |
import time
|
|
|
|
| 8 |
#from tavily import TavilyClient
|
| 9 |
from langchain_tavily import TavilySearch
|
| 10 |
from langgraph.prebuilt import create_react_agent
|
| 11 |
from langgraph.graph.message import add_messages
|
| 12 |
from langgraph_supervisor import create_supervisor
|
| 13 |
-
#from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
|
| 14 |
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 15 |
from langchain_core.tools import tool
|
| 16 |
from langchain_core.messages import HumanMessage, SystemMessage, BaseMessage
|
|
@@ -51,6 +51,7 @@ prompt_recomendado = """You are a general AI assistant. I will ask you a questio
|
|
| 51 |
If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
| 52 |
To assist in your task, you can supervise other agents who perform specific tasks that could not be handled by tools, since they require the processing of another LLM. Below, I will inform you about your assistants:
|
| 53 |
- web_research_agent. Assign web research related tasks to this agent, prioritizing the use of Wikipedia sources
|
|
|
|
| 54 |
Assign work to one agent at a time, do not call agents in parallel.
|
| 55 |
Priorize the use of tools and another agents to help in reasoning.
|
| 56 |
When a file or URL is entered at the prompt, use it in tools or other agents, both are prepared to handle files and URLs."""
|
|
@@ -62,19 +63,165 @@ prompt_search = """You are a web research agent.
|
|
| 62 |
After you're done with your tasks, respond to the supervisor directly
|
| 63 |
Respond ONLY with the results of your work, do NOT include ANY other text."""
|
| 64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
#TOOLS
|
| 66 |
web_search = TavilySearch(
|
| 67 |
max_results=5,
|
| 68 |
topic="general",
|
| 69 |
)
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
tools = [web_search]
|
| 72 |
|
| 73 |
#LLMS
|
| 74 |
# Create LLM class
|
| 75 |
gemini_llm = ChatGoogleGenerativeAI(
|
| 76 |
model= "gemini-2.0-flash-exp", # replace with "gemini-2.0-flash"
|
| 77 |
-
temperature=
|
| 78 |
max_tokens=None,
|
| 79 |
timeout=None,
|
| 80 |
max_retries=2,
|
|
@@ -91,6 +238,13 @@ web_research_agent = create_react_agent(
|
|
| 91 |
name="web_research_agent"
|
| 92 |
)
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
supervisor = create_supervisor(
|
| 95 |
model=gemini_llm,
|
| 96 |
agents=[web_research_agent],
|
|
@@ -118,7 +272,7 @@ class BasicAgent:
|
|
| 118 |
# tools = [search_web_tool]
|
| 119 |
# chat_with_tools = chat.bind_tools(tools)
|
| 120 |
|
| 121 |
-
def __call__(self, question: str) -> str:
|
| 122 |
print(f"Agent received question : {question}...")
|
| 123 |
|
| 124 |
messages = {
|
|
@@ -218,7 +372,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 218 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 219 |
continue
|
| 220 |
try:
|
| 221 |
-
submitted_answer = agent(question_text)
|
| 222 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 223 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 224 |
except Exception as e:
|
|
|
|
| 5 |
import pandas as pd
|
| 6 |
import re
|
| 7 |
import time
|
| 8 |
+
import base64
|
| 9 |
#from tavily import TavilyClient
|
| 10 |
from langchain_tavily import TavilySearch
|
| 11 |
from langgraph.prebuilt import create_react_agent
|
| 12 |
from langgraph.graph.message import add_messages
|
| 13 |
from langgraph_supervisor import create_supervisor
|
|
|
|
| 14 |
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 15 |
from langchain_core.tools import tool
|
| 16 |
from langchain_core.messages import HumanMessage, SystemMessage, BaseMessage
|
|
|
|
| 51 |
If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
|
| 52 |
To assist in your task, you can supervise other agents who perform specific tasks that could not be handled by tools, since they require the processing of another LLM. Below, I will inform you about your assistants:
|
| 53 |
- web_research_agent. Assign web research related tasks to this agent, prioritizing the use of Wikipedia sources
|
| 54 |
+
- chess_position_review_agent. Assign chess position review related tasks to this agent
|
| 55 |
Assign work to one agent at a time, do not call agents in parallel.
|
| 56 |
Priorize the use of tools and another agents to help in reasoning.
|
| 57 |
When a file or URL is entered at the prompt, use it in tools or other agents, both are prepared to handle files and URLs."""
|
|
|
|
| 63 |
After you're done with your tasks, respond to the supervisor directly
|
| 64 |
Respond ONLY with the results of your work, do NOT include ANY other text."""
|
| 65 |
|
| 66 |
+
prompt_chess = """You are a chess position reviewing agent.
|
| 67 |
+
INSTRUCTIONS:
|
| 68 |
+
Assist ONLY with tasks related to chess position reviewing, DO NOT do any math
|
| 69 |
+
After you're done with your tasks, respond to the supervisor directly
|
| 70 |
+
Respond ONLY with the results of your work, do NOT include ANY other text."""
|
| 71 |
+
|
| 72 |
#TOOLS
|
| 73 |
web_search = TavilySearch(
|
| 74 |
max_results=5,
|
| 75 |
topic="general",
|
| 76 |
)
|
| 77 |
|
| 78 |
+
def chess_image_to_fen_tool(task_id:str, current_player: Literal["black", "white"]) -> Dict[str,str]:
|
| 79 |
+
"""
|
| 80 |
+
Convert chess image to FEN (Forsyth-Edwards Notation) notation.
|
| 81 |
+
Args:
|
| 82 |
+
image_path: Path to the image file.
|
| 83 |
+
current_player: Whose turn it is to play. Must be either 'black' or 'white'.
|
| 84 |
+
Returns:
|
| 85 |
+
JSON with FEN (Forsyth-Edwards Notation) string representing the current board position.
|
| 86 |
+
"""
|
| 87 |
+
print(f"Image to Fen invocada com os seguintes parametros:")
|
| 88 |
+
print(f"task_id: {task_id}")
|
| 89 |
+
print(f"current_player: {current_player}")
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
if current_player not in ["black", "white"]:
|
| 93 |
+
raise ValueError("current_player must be 'black' or 'white'")
|
| 94 |
+
|
| 95 |
+
base64_image = download_file_as_base64(task_id)
|
| 96 |
+
if not base64_image:
|
| 97 |
+
raise ValueError("Failed to encode image to base64.")
|
| 98 |
+
base64_image_encoded = f"data:image/jpeg;base64,{base64_image}"
|
| 99 |
+
url = CHESSVISION_TO_FEN_URL
|
| 100 |
+
payload = {
|
| 101 |
+
"board_orientation": "predict",
|
| 102 |
+
"cropped": False,
|
| 103 |
+
"current_player": "black",
|
| 104 |
+
"image": base64_image_encoded,
|
| 105 |
+
"predict_turn": False
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
response = requests.post(url, json=payload)
|
| 109 |
+
if response.status_code == 200:
|
| 110 |
+
dados = response.json()
|
| 111 |
+
if dados.get("success"):
|
| 112 |
+
print(f"Retorno Chessvision {dados}")
|
| 113 |
+
fen = dados.get("result")
|
| 114 |
+
fen = fen.replace("_", " ") #retorna _ no lugar de espaço em branco
|
| 115 |
+
return json.dumps({"fen": fen})
|
| 116 |
+
else:
|
| 117 |
+
raise Exception("Requisição feita, mas falhou na predição.")
|
| 118 |
+
else:
|
| 119 |
+
raise Exception(f"Erro na requisição: {response.status_code}")
|
| 120 |
+
|
| 121 |
+
def chess_fen_get_best_next_move_tool(fen: str, current_player: Literal["black", "white"]) -> str:
|
| 122 |
+
"""
|
| 123 |
+
Return the best move in algebraic notation.
|
| 124 |
+
Args:
|
| 125 |
+
fen: FEN (Forsyth-Edwards Notation) notation.
|
| 126 |
+
Returns:
|
| 127 |
+
Best move in algebraic notation.
|
| 128 |
+
"""
|
| 129 |
+
if not fen:
|
| 130 |
+
raise ValueError("fen must be provided.")
|
| 131 |
+
if current_player not in ["black", "white"]:
|
| 132 |
+
raise ValueError("current_player must be 'black' or 'white'")
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
url = CHESS_MOVE_API
|
| 136 |
+
payload = {
|
| 137 |
+
"fen": fen,
|
| 138 |
+
"depth": 1
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
print(f"Buscando melhor jogada em {CHESS_MOVE_API} - {payload}")
|
| 142 |
+
|
| 143 |
+
response = requests.post(url, json=payload)
|
| 144 |
+
if response.status_code == 200:
|
| 145 |
+
#print(f"Retorno melhor jogada --> {response.text}")
|
| 146 |
+
dados = response.json()
|
| 147 |
+
move_algebric_notation = dados.get("san")
|
| 148 |
+
move = dados.get("text")
|
| 149 |
+
print(f"Melhor jogada segundo chess-api.com -> {move}")
|
| 150 |
+
|
| 151 |
+
return move_algebric_notation
|
| 152 |
+
|
| 153 |
+
else:
|
| 154 |
+
raise Exception(f"Erro na requisição: {response.status_code}")
|
| 155 |
+
|
| 156 |
+
def download_file(task_id: str):
|
| 157 |
+
if not fen:
|
| 158 |
+
raise ValueError("task_id must be provided.")
|
| 159 |
+
# Construct the URL
|
| 160 |
+
url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
|
| 161 |
+
|
| 162 |
+
# Send the request to download the file
|
| 163 |
+
response = requests.get(url)
|
| 164 |
+
|
| 165 |
+
if response.status_code == 200:
|
| 166 |
+
# Get the content type from the response headers to determine the file extension
|
| 167 |
+
content_type = response.headers.get('Content-Type', '')
|
| 168 |
+
file_extension = ''
|
| 169 |
+
|
| 170 |
+
# Map content types to file extensions
|
| 171 |
+
if 'pdf' in content_type:
|
| 172 |
+
file_extension = '.pdf'
|
| 173 |
+
elif 'jpg' in content_type or 'jpeg' in content_type:
|
| 174 |
+
file_extension = '.jpg'
|
| 175 |
+
elif 'png' in content_type:
|
| 176 |
+
file_extension = '.png'
|
| 177 |
+
elif 'txt' in content_type:
|
| 178 |
+
file_extension = '.txt'
|
| 179 |
+
elif 'zip' in content_type:
|
| 180 |
+
file_extension = '.zip'
|
| 181 |
+
elif 'mp3' in content_type:
|
| 182 |
+
file_extension = '.mp3'
|
| 183 |
+
# Add more file types as necessary
|
| 184 |
+
|
| 185 |
+
# If the extension can't be determined, default to .bin
|
| 186 |
+
if not file_extension:
|
| 187 |
+
file_extension = '.bin'
|
| 188 |
+
|
| 189 |
+
# Set the path to the Downloads folder (adjust 'YourUsername' to your actual username)
|
| 190 |
+
save_path = os.path.join(os.path.expanduser('~'), 'Downloads', f"{task_id}_file{file_extension}")
|
| 191 |
+
|
| 192 |
+
# Save the file with the appropriate extension
|
| 193 |
+
with open(save_path, 'wb') as f:
|
| 194 |
+
f.write(response.content)
|
| 195 |
+
print(f"File successfully downloaded and saved as {save_path}")
|
| 196 |
+
|
| 197 |
+
return save_path
|
| 198 |
+
else:
|
| 199 |
+
print(f"Failed to download the file. Status code: {response.status_code}")
|
| 200 |
+
|
| 201 |
+
def download_file_as_base64(task_id: str) -> str:
|
| 202 |
+
# Construct the URL
|
| 203 |
+
url = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"
|
| 204 |
+
|
| 205 |
+
# Send the request to download the file
|
| 206 |
+
response = requests.get(url)
|
| 207 |
+
|
| 208 |
+
if response.status_code == 200:
|
| 209 |
+
# Encode the content to Base64
|
| 210 |
+
encoded_bytes = base64.b64encode(response.content)
|
| 211 |
+
encoded_str = encoded_bytes.decode('utf-8') # Convert bytes to string
|
| 212 |
+
return encoded_str
|
| 213 |
+
else:
|
| 214 |
+
raise Exception(f"Failed to download the file. Status code: {response.status_code}")
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
|
| 218 |
tools = [web_search]
|
| 219 |
|
| 220 |
#LLMS
|
| 221 |
# Create LLM class
|
| 222 |
gemini_llm = ChatGoogleGenerativeAI(
|
| 223 |
model= "gemini-2.0-flash-exp", # replace with "gemini-2.0-flash"
|
| 224 |
+
temperature=0.0,
|
| 225 |
max_tokens=None,
|
| 226 |
timeout=None,
|
| 227 |
max_retries=2,
|
|
|
|
| 238 |
name="web_research_agent"
|
| 239 |
)
|
| 240 |
|
| 241 |
+
chess_position_review_agent = create_react_agent(
|
| 242 |
+
model=gemini_llm,
|
| 243 |
+
tools=[chess_image_to_fen_tool,chess_fen_get_best_next_move_tool],
|
| 244 |
+
prompt=prompt_chess,
|
| 245 |
+
name="chess_position_review_agent"
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
supervisor = create_supervisor(
|
| 249 |
model=gemini_llm,
|
| 250 |
agents=[web_research_agent],
|
|
|
|
| 272 |
# tools = [search_web_tool]
|
| 273 |
# chat_with_tools = chat.bind_tools(tools)
|
| 274 |
|
| 275 |
+
def __call__(self, question: str, path: str) -> str:
|
| 276 |
print(f"Agent received question : {question}...")
|
| 277 |
|
| 278 |
messages = {
|
|
|
|
| 372 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 373 |
continue
|
| 374 |
try:
|
| 375 |
+
submitted_answer = agent(question_text,task_id)
|
| 376 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 377 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 378 |
except Exception as e:
|