gdms commited on
Commit
f15d6bc
·
1 Parent(s): 696f644

Preparar para executar!!

Browse files
Files changed (6) hide show
  1. .gitignore +1 -0
  2. agent.py +29 -12
  3. app.py +11 -2
  4. constantes.py +9 -1
  5. file_util.py +22 -13
  6. tmp/teste.txt +0 -0
.gitignore CHANGED
@@ -3,3 +3,4 @@ get-pip.py
3
  *.m4a
4
  *.mp4
5
  audio_analysis_output/
 
 
3
  *.m4a
4
  *.mp4
5
  audio_analysis_output/
6
+ files/
agent.py CHANGED
@@ -1,4 +1,6 @@
 
1
  from langgraph.prebuilt import create_react_agent
 
2
  from prompts import *
3
  from tools import *
4
  from langgraph_supervisor import create_supervisor
@@ -38,18 +40,33 @@ class Agent:
38
  output_mode="full_history",
39
  ).compile()
40
 
41
- print("Agent initialized.")
42
 
43
- def _exist_file_with_task_id(task_id: str) -> str:
44
- padrao = os.path.join(AGENTS_FILES_PATH, f"{task_id}.*")
45
- arquivos_encontrados = glob.glob(padrao)
46
- return arquivos_encontrados[0] if arquivos_encontrados else None
47
 
 
 
 
 
 
48
 
49
- def __call__(self, question: str, task_id: str) -> str:
50
- print(f"Agent received question (first 50 chars): {question[:50]}...")
51
- file = self._exist_file_with_task_id(task_id)
52
-
53
- fixed_answer = "This is a default answer."
54
- print(f"Agent returning fixed answer: {fixed_answer}")
55
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
  from langgraph.prebuilt import create_react_agent
3
+ from agent_util import Agent_Util
4
  from prompts import *
5
  from tools import *
6
  from langgraph_supervisor import create_supervisor
 
40
  output_mode="full_history",
41
  ).compile()
42
 
43
+ print("Agent initialized.")
44
 
45
+
46
+
47
+ def __call__(self, question: str, task_id: str, task_file_name: str) -> str:
48
+ print(f"Agent received question({task_id}) (first 50 chars): {question[:50]}...")
49
 
50
+ file_prefix = ""
51
+ if task_file_name:
52
+ print(f"Task com arquivo {task_file_name}")
53
+ File_Util.baixa_arquivo_task(task_file_name)
54
+ file_prefix = f"File: {task_file_name} . "
55
 
56
+ for chunk in self.supervisor.stream(
57
+ {
58
+ "messages": [
59
+ {
60
+ "role": "user",
61
+ "content": f"{file_prefix}{question}",
62
+ }
63
+ ]
64
+ },
65
+ ):
66
+ Agent_Util.pretty_print_messages(chunk, last_message=True)
67
+
68
+ agent_answer = chunk["supervisor"]["messages"]
69
+
70
+ final_answer = re.sub(r"^FINAL ANSWER:\s*", "", agent_answer, flags=re.IGNORECASE)
71
+ print(f"Agent returning answer for task {task_id}: {final_answer}")
72
+ return final_answer
app.py CHANGED
@@ -59,6 +59,9 @@ import mimetypes
59
  from urllib.parse import urlparse, unquote
60
  import google.generativeai as genai
61
 
 
 
 
62
  # (Keep Constants as is)
63
  # --- Constants ---
64
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
@@ -95,7 +98,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
95
 
96
  # 1. Instantiate Agent ( modify this part to create your agent)
97
  try:
98
- agent = BasicAgent()
99
  except Exception as e:
100
  print(f"Error instantiating agent: {e}")
101
  return f"Error initializing agent: {e}", None
@@ -131,11 +134,17 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
131
  for item in questions_data:
132
  task_id = item.get("task_id")
133
  question_text = item.get("question")
 
 
 
 
 
 
134
  if not task_id or question_text is None:
135
  print(f"Skipping item with missing task_id or question: {item}")
136
  continue
137
  try:
138
- submitted_answer = agent(question_text)
139
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
140
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
141
  except Exception as e:
 
59
  from urllib.parse import urlparse, unquote
60
  import google.generativeai as genai
61
 
62
+ from agent import Agent
63
+ from constantes import LISTA_TASKS_PROCESSAR
64
+
65
  # (Keep Constants as is)
66
  # --- Constants ---
67
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
98
 
99
  # 1. Instantiate Agent ( modify this part to create your agent)
100
  try:
101
+ agent = Agent()
102
  except Exception as e:
103
  print(f"Error instantiating agent: {e}")
104
  return f"Error initializing agent: {e}", None
 
134
  for item in questions_data:
135
  task_id = item.get("task_id")
136
  question_text = item.get("question")
137
+ question_file_name = item.get("file_name")
138
+
139
+ if not task_id in LISTA_TASKS_PROCESSAR:
140
+ print(f"Task {"task_id"} não está na lista de execução")
141
+ continue
142
+
143
  if not task_id or question_text is None:
144
  print(f"Skipping item with missing task_id or question: {item}")
145
  continue
146
  try:
147
+ submitted_answer = agent(question_text, task_id, question_file_name)
148
  answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
149
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
150
  except Exception as e:
constantes.py CHANGED
@@ -27,4 +27,12 @@ GEMINI_MODEL = "gemini-2.0-flash"
27
  CHESSVISION_TO_FEN_URL = "http://app.chessvision.ai/predict"
28
  CHESS_MOVE_API = "https://chess-api.com/v1"
29
 
30
- AGENTS_FILES_PATH = "./files"
 
 
 
 
 
 
 
 
 
27
  CHESSVISION_TO_FEN_URL = "http://app.chessvision.ai/predict"
28
  CHESS_MOVE_API = "https://chess-api.com/v1"
29
 
30
+ AGENTS_FILES_PATH = "./tmp"
31
+ HUGGINGFACE_DATASET_URL_TEMPLATE = (
32
+ "https://huggingface.co/datasets/gdms/gaia/resolve/main/{filename}"
33
+ )
34
+
35
+ LISTA_TASKS_PROCESSAR = [
36
+ "8e867cd7-cff9-4e6c-867a-ff5ddc2550be",
37
+
38
+ ]
file_util.py CHANGED
@@ -3,7 +3,9 @@ import re
3
  import shutil
4
  from typing import List
5
 
6
- from constantes import AGENTS_FILES_PATH
 
 
7
 
8
 
9
 
@@ -56,25 +58,32 @@ class File_Util:
56
 
57
 
58
  @staticmethod
59
- def tratar_arquivo_local(caminho_entrada: str) -> str:
60
  """
61
- Verifica se o arquivo existe no caminho informado.
62
- Se não existir, adiciona o path padrão do sistema.
63
 
64
  Parâmetros:
65
- - caminho_entrada (str): Caminho completo ou nome do arquivo.
66
 
67
  Retorna:
68
  - str: Caminho válido para o arquivo, ou None se não encontrado.
69
  """
70
  # Verifica se o arquivo já existe no caminho informado
71
- if os.path.isfile(caminho_entrada):
72
- return caminho_entrada
 
 
 
 
 
 
 
 
73
 
74
- # Tenta procurar no diretório padrão, se fornecido
75
- novo_caminho = os.path.join(AGENTS_FILES_PATH, os.path.basename(caminho_entrada))
76
- if os.path.isfile(novo_caminho):
77
- return novo_caminho
78
 
79
- # Arquivo não encontrado
80
- return None
 
 
 
3
  import shutil
4
  from typing import List
5
 
6
+ import requests
7
+
8
+ from constantes import AGENTS_FILES_PATH, HUGGINGFACE_DATASET_URL_TEMPLATE
9
 
10
 
11
 
 
58
 
59
 
60
  @staticmethod
61
+ def baixa_arquivo_task(task_file_name: str) -> str:
62
  """
63
+ Baixa o arquivo da task para o diretório temporario local
 
64
 
65
  Parâmetros:
66
+ - task_file_name (str): Caminho completo ou nome do arquivo.
67
 
68
  Retorna:
69
  - str: Caminho válido para o arquivo, ou None se não encontrado.
70
  """
71
  # Verifica se o arquivo já existe no caminho informado
72
+ task_file_path= os.path.join(AGENTS_FILES_PATH, task_file_name)
73
+ if os.path.isfile(task_file_path):
74
+ return task_file_path
75
+
76
+ #Tenta baixar do dataset
77
+ url = HUGGINGFACE_DATASET_URL_TEMPLATE.format(filename=task_file_name)
78
+
79
+ try:
80
+ response = requests.get(url)
81
+ response.raise_for_status()
82
 
83
+ with open(task_file_path, "wb") as f:
84
+ f.write(response.content)
 
 
85
 
86
+ return task_file_path
87
+ except Exception as e:
88
+ print(f"[ERRO] Problemas ao baixar arquivo {task_file_name}")
89
+ return None
tmp/teste.txt ADDED
File without changes