Update app.py
Browse files4 unmodified lines567891011121314151634 unmodified lines5152535455565 unmodified lines6263646566676869707172737475767778798010 unmodified lines91929394959621 unmodified lines11811912012112212312493 unmodified lines2182192202212222232244 unmodified linesimport pandas as pdimport reimport time#from tavily import TavilyClientfrom langchain_tavily import TavilySearchfrom langgraph.prebuilt import create_react_agentfrom langgraph.graph.message import add_messagesfrom langgraph_supervisor import create_supervisor#from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFacefrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_core.tools import toolfrom langchain_core.messages import HumanMessage, SystemMessage, BaseMessage34 unmodified linesIf 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.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:- web_research_agent. Assign web research related tasks to this agent, prioritizing the use of Wikipedia sourcesAssign work to one agent at a time, do not call agents in parallel.Priorize the use of tools and another agents to help in reasoning.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."""5 unmodified linesAfter you're done with your tasks, respond to the supervisor directlyRespond ONLY with the results of your work, do NOT include ANY other text."""#TOOLSweb_search = TavilySearch(max_results=5,topic="general",)tools = [web_search]#LLMS# Create LLM classgemini_llm = ChatGoogleGenerativeAI(model= "gemini-2.0-flash-exp", # replace with "gemini-2.0-flash"temperature=1.0,max_tokens=None,timeout=None,max_retries=2,10 unmodified linesname="web_research_agent")supervisor = create_supervisor(model=gemini_llm,agents=[web_research_agent],21 unmodified lines# tools = [search_web_tool]# chat_with_tools = chat.bind_tools(tools)def __call__(self, question: str) -> str:print(f"Agent received question : {question}...")messages = {93 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:4 unmodified lines567891011121314151634 unmodified lines515253545556575 unmodified lines6364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622710 unmodified lines23823924024124224324424524624724824925021 unmodified lines27227327427527627727893 unmodified lines3723733743753763773784 unmodified linesimport pandas as pdimport reimport timeimport base64#from tavily import TavilyClientfrom langchain_tavily import TavilySearchfrom langgraph.prebuilt import create_react_agentfrom langgraph.graph.message import add_messagesfrom langgraph_supervisor import create_supervisorfrom langchain_google_genai import ChatGoogleGenerativeAIfrom langchain_core.tools import toolfrom langchain_core.messages import HumanMessage, SystemMessage, BaseMessage34 unmodified linesIf 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.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:- web_research_agent. Assign web research related tasks to this agent, prioritizing the use of Wikipedia sources- chess_position_review_agent. Assign chess position review related tasks to this agentAssign work to one agent at a time, do not call agents in parallel.Priorize the use of tools and another agents to help in reasoning.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."""5 unmodified linesAfter you're done with your tasks, respond to the supervisor directlyRespond ONLY with the results of your work, do NOT include ANY other text."""prompt_chess = """You are a chess position reviewing agent.INSTRUCTIONS:Assist ONLY with tasks related to chess position reviewing, DO NOT do any mathAfter you're done with your tasks, respond to the supervisor directlyRespond ONLY with the results of your work, do NOT include ANY other text."""#TOOLSweb_search = TavilySearch(max_results=5,topic="general",)def chess_image_to_fen_tool(task_id:str, current_player: Literal["black", "white"]) -> Dict[str,str]:"""Convert chess image to FEN (Forsyth-Edwards Notation) notation.Args:image_path: Path to the image file.current_player: Whose turn it is to play. Must be either 'black' or 'white'.Returns:JSON with FEN (Forsyth-Edwards Notation) string representing the current board position."""print(f"Image to Fen invocada com os seguintes parametros:")print(f"task_id: {task_id}")print(f"current_player: {current_player}")if current_player not in ["black", "white"]:raise ValueError("current_player must be 'black' or 'white'")base64_image = download_file_as_base64(task_id)if not base64_image:raise ValueError("Failed to encode image to base64.")base64_image_encoded = f"data:image/jpeg;base64,{base64_image}"url = CHESSVISION_TO_FEN_URLpayload = {"board_orientation": "predict","cropped": False,"current_player": "black","image": base64_image_encoded,"predict_turn": False}response = requests.post(url, json=payload)if response.status_code == 200:dados = response.json()if dados.get("success"):print(f"Retorno Chessvision {dados}")fen = dados.get("result")fen = fen.replace("_", " ") #retorna _ no lugar de espaço em brancoreturn json.dumps({"fen": fen})else:raise Exception("Requisição feita, mas falhou na predição.")else:raise Exception(f"Erro na requisição: {response.status_code}")def chess_fen_get_best_next_move_tool(fen: str, current_player: Literal["black", "white"]) -> str:"""Return the best move in algebraic notation.Args:fen: FEN (Forsyth-Edwards Notation) notation.Returns:Best move in algebraic notation."""if not fen:raise ValueError("fen must be provided.")if current_player not in ["black", "white"]:raise ValueError("current_player must be 'black' or 'white'")url = CHESS_MOVE_APIpayload = {"fen": fen,"depth": 1}print(f"Buscando melhor jogada em {CHESS_MOVE_API} - {payload}")response = requests.post(url, json=payload)if response.status_code == 200:#print(f"Retorno melhor jogada --> {response.text}")dados = response.json()move_algebric_notation = dados.get("san")move = dados.get("text")print(f"Melhor jogada segundo chess-api.com -> {move}")return move_algebric_notationelse:raise Exception(f"Erro na requisição: {response.status_code}")def download_file(task_id: str):if not fen:raise ValueError("task_id must be provided.")# Construct the URLurl = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"# Send the request to download the fileresponse = requests.get(url)if response.status_code == 200:# Get the content type from the response headers to determine the file extensioncontent_type = response.headers.get('Content-Type', '')file_extension = ''# Map content types to file extensionsif 'pdf' in content_type:file_extension = '.pdf'elif 'jpg' in content_type or 'jpeg' in content_type:file_extension = '.jpg'elif 'png' in content_type:file_extension = '.png'elif 'txt' in content_type:file_extension = '.txt'elif 'zip' in content_type:file_extension = '.zip'elif 'mp3' in content_type:file_extension = '.mp3'# Add more file types as necessary# If the extension can't be determined, default to .binif not file_extension:file_extension = '.bin'# Set the path to the Downloads folder (adjust 'YourUsername' to your actual username)save_path = os.path.join(os.path.expanduser('~'), 'Downloads', f"{task_id}_file{file_extension}")# Save the file with the appropriate extensionwith open(save_path, 'wb') as f:f.write(response.content)print(f"File successfully downloaded and saved as {save_path}")return save_pathelse:print(f"Failed to download the file. Status code: {response.status_code}")def download_file_as_base64(task_id: str) -> str:# Construct the URLurl = f"https://agents-course-unit4-scoring.hf.space/files/{task_id}"# Send the request to download the fileresponse = requests.get(url)if response.status_code == 200:# Encode the content to Base64encoded_bytes = base64.b64encode(response.content)encoded_str = encoded_bytes.decode('utf-8') # Convert bytes to stringreturn encoded_strelse:raise Exception(f"Failed to download the file. Status code: {response.status_code}")tools = [web_search]#LLMS# Create LLM classgemini_llm = ChatGoogleGenerativeAI(model= "gemini-2.0-flash-exp", # replace with "gemini-2.0-flash"temperature=0.0,max_tokens=None,timeout=None,max_retries=2,10 unmodified linesname="web_research_agent")chess_position_review_agent = create_react_agent(model=gemini_llm,tools=[chess_image_to_fen_tool,chess_fen_get_best_next_move_tool],prompt=prompt_chess,name="chess_position_review_agent")supervisor = create_supervisor(model=gemini_llm,agents=[web_research_agent],21 unmodified lines# tools = [search_web_tool]# chat_with_tools = chat.bind_tools(tools)def __call__(self, question: str, path: str) -> str:print(f"Agent received question : {question}...")messages = {93 unmodified linesprint(f"Skipping item with missing task_id or question: {item}")continuetry:submitted_answer = agent(question_text,task_id)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:
app.py+158-4