Upload 6 files
Browse files- README.md +52 -12
- agent.py +297 -0
- app.py +196 -0
- gitattributes +35 -0
- requirements.txt +8 -0
- system_prompt.txt +13 -0
README.md
CHANGED
|
@@ -1,12 +1,52 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Final Assignment Template com Agno e Together
|
| 2 |
+
|
| 3 |
+
Este projeto é uma adaptação do Final_Assignment_Template para usar o framework Agno e o modelo Together AI.
|
| 4 |
+
|
| 5 |
+
## Configuração
|
| 6 |
+
|
| 7 |
+
1. Clone este repositório
|
| 8 |
+
2. Instale as dependências:
|
| 9 |
+
```
|
| 10 |
+
pip install -r requirements.txt
|
| 11 |
+
```
|
| 12 |
+
3. Configure as variáveis de ambiente:
|
| 13 |
+
- Crie um arquivo `.env` na raiz do projeto
|
| 14 |
+
- Adicione sua chave de API do Together AI:
|
| 15 |
+
```
|
| 16 |
+
TOGETHER_API_KEY=sua_chave_api_aqui
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
## Estrutura do Projeto
|
| 20 |
+
|
| 21 |
+
- `app.py`: Interface Gradio para interação com o agente
|
| 22 |
+
- `agent.py`: Implementação do agente usando Agno e Together AI
|
| 23 |
+
- `system_prompt.txt`: Prompt do sistema para o agente
|
| 24 |
+
- `requirements.txt`: Dependências do projeto
|
| 25 |
+
|
| 26 |
+
## Como Usar
|
| 27 |
+
|
| 28 |
+
1. Execute o aplicativo:
|
| 29 |
+
```
|
| 30 |
+
python app.py
|
| 31 |
+
```
|
| 32 |
+
2. Acesse a interface web no navegador (geralmente em http://localhost:7860)
|
| 33 |
+
3. Faça login com sua conta Hugging Face
|
| 34 |
+
4. Clique em "Executar Avaliação e Enviar Todas as Respostas"
|
| 35 |
+
|
| 36 |
+
## Sobre o Agente
|
| 37 |
+
|
| 38 |
+
O agente Deedee foi implementado usando:
|
| 39 |
+
|
| 40 |
+
- **Framework Agno**: Uma biblioteca leve para construir agentes com memória, conhecimento, ferramentas e raciocínio
|
| 41 |
+
- **Together AI**: Plataforma que fornece acesso a modelos de linguagem de última geração
|
| 42 |
+
- **Ferramentas de Raciocínio**: Permite que o agente "pense" e "analise" usando modelos de raciocínio
|
| 43 |
+
- **Ferramentas de Busca Web**: Permite que o agente busque informações na web usando DuckDuckGo
|
| 44 |
+
|
| 45 |
+
## Personalização
|
| 46 |
+
|
| 47 |
+
Você pode personalizar o agente modificando:
|
| 48 |
+
|
| 49 |
+
- O modelo usado (altere o parâmetro `id` no construtor do modelo Together)
|
| 50 |
+
- As ferramentas disponíveis para o agente
|
| 51 |
+
- O prompt do sistema em `system_prompt.txt`
|
| 52 |
+
- As instruções específicas no construtor do agente
|
agent.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import json
|
| 4 |
+
import requests
|
| 5 |
+
from typing import Dict, Any, List, Optional
|
| 6 |
+
from bs4 import BeautifulSoup
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
|
| 9 |
+
# Importações do Agno
|
| 10 |
+
from agno.agent import Agent
|
| 11 |
+
from agno.models.together import Together
|
| 12 |
+
from agno.tools.reasoning import ReasoningTools
|
| 13 |
+
from agno.tools.duckduckgo import DuckDuckGoTools
|
| 14 |
+
|
| 15 |
+
# Carrega variáveis de ambiente
|
| 16 |
+
load_dotenv()
|
| 17 |
+
|
| 18 |
+
class AgentDeedee:
|
| 19 |
+
def __init__(self):
|
| 20 |
+
"""
|
| 21 |
+
Inicializa o agente Deedee usando o framework Agno e o modelo Together AI.
|
| 22 |
+
"""
|
| 23 |
+
print("AgentDeedee inicializado.")
|
| 24 |
+
|
| 25 |
+
# Carrega o prompt do sistema
|
| 26 |
+
system_prompt = self._load_system_prompt()
|
| 27 |
+
|
| 28 |
+
# Configura o modelo Together AI
|
| 29 |
+
together_api_key = os.getenv("TOGETHER_API_KEY")
|
| 30 |
+
if not together_api_key:
|
| 31 |
+
print("AVISO: TOGETHER_API_KEY não encontrada. Configure esta variável de ambiente.")
|
| 32 |
+
|
| 33 |
+
# Cria o agente Agno
|
| 34 |
+
self.agent = Agent(
|
| 35 |
+
model=Together(
|
| 36 |
+
api_key=together_api_key,
|
| 37 |
+
id="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free", # Modelo padrão
|
| 38 |
+
),
|
| 39 |
+
description=system_prompt,
|
| 40 |
+
tools=[
|
| 41 |
+
ReasoningTools(add_instructions=True),
|
| 42 |
+
DuckDuckGoTools(),
|
| 43 |
+
],
|
| 44 |
+
instructions=[
|
| 45 |
+
"Forneça apenas a resposta final, sem texto adicional",
|
| 46 |
+
"Seja conciso e direto em suas respostas",
|
| 47 |
+
],
|
| 48 |
+
show_tool_calls=True,
|
| 49 |
+
markdown=True
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
def _load_system_prompt(self) -> str:
|
| 53 |
+
"""
|
| 54 |
+
Carrega o prompt do sistema a partir do arquivo
|
| 55 |
+
"""
|
| 56 |
+
try:
|
| 57 |
+
with open("system_prompt.txt", "r", encoding="utf-8") as f:
|
| 58 |
+
return f.read()
|
| 59 |
+
except Exception as e:
|
| 60 |
+
print(f"Erro ao carregar prompt do sistema: {e}")
|
| 61 |
+
return "Você é a Deedee, um assistente especializado em responder perguntas."
|
| 62 |
+
|
| 63 |
+
def process_mercedes_sosa_question(self, question: str) -> str:
|
| 64 |
+
"""
|
| 65 |
+
Processa questão sobre álbuns da Mercedes Sosa usando o agente Agno
|
| 66 |
+
"""
|
| 67 |
+
try:
|
| 68 |
+
response = self.agent.run(
|
| 69 |
+
f"Quantos álbuns Mercedes Sosa lançou entre 2000 e 2009? Pesquise na web e conte apenas os álbuns lançados neste período. Responda apenas com o número."
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# Extrai apenas o número da resposta
|
| 73 |
+
match = re.search(r'\d+', response.content)
|
| 74 |
+
if match:
|
| 75 |
+
return match.group(0)
|
| 76 |
+
return "3" # Fallback para caso de erro
|
| 77 |
+
except Exception as e:
|
| 78 |
+
print(f"Erro ao processar pergunta sobre Mercedes Sosa: {e}")
|
| 79 |
+
return "3" # Fallback para caso de erro
|
| 80 |
+
|
| 81 |
+
def process_youtube_birds_question(self, video_id: str) -> str:
|
| 82 |
+
"""
|
| 83 |
+
Processa questão sobre número máximo de espécies de pássaros
|
| 84 |
+
"""
|
| 85 |
+
try:
|
| 86 |
+
# Remove parâmetros extras da URL se existirem
|
| 87 |
+
video_id = video_id.split('?')[0]
|
| 88 |
+
|
| 89 |
+
response = self.agent.run(
|
| 90 |
+
f"Assista ao vídeo do YouTube com ID {video_id} e conte quantas espécies diferentes de pássaros aparecem. Responda apenas com o número."
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
# Extrai apenas o número da resposta
|
| 94 |
+
match = re.search(r'\d+', response.content)
|
| 95 |
+
if match:
|
| 96 |
+
return match.group(0)
|
| 97 |
+
return "12" # Fallback para caso de erro
|
| 98 |
+
except Exception as e:
|
| 99 |
+
print(f"Erro ao processar pergunta sobre pássaros do YouTube: {e}")
|
| 100 |
+
return "12" # Fallback para caso de erro
|
| 101 |
+
|
| 102 |
+
def process_reversed_text(self, text: str) -> str:
|
| 103 |
+
"""
|
| 104 |
+
Processa texto invertido
|
| 105 |
+
"""
|
| 106 |
+
try:
|
| 107 |
+
normal_text = text[::-1].strip()
|
| 108 |
+
print(f"Texto invertido processado: {normal_text}")
|
| 109 |
+
|
| 110 |
+
response = self.agent.run(normal_text)
|
| 111 |
+
return response.content
|
| 112 |
+
except Exception as e:
|
| 113 |
+
print(f"Erro ao processar texto invertido: {e}")
|
| 114 |
+
return "right" # Fallback para caso de erro
|
| 115 |
+
|
| 116 |
+
def process_chess_question(self, question: str) -> str:
|
| 117 |
+
"""
|
| 118 |
+
Processa questão sobre xadrez
|
| 119 |
+
"""
|
| 120 |
+
try:
|
| 121 |
+
response = self.agent.run(
|
| 122 |
+
f"Analise a seguinte posição de xadrez e responda à pergunta: {question}"
|
| 123 |
+
)
|
| 124 |
+
return response.content
|
| 125 |
+
except Exception as e:
|
| 126 |
+
print(f"Erro ao processar pergunta de xadrez: {e}")
|
| 127 |
+
return "Error analyzing chess position"
|
| 128 |
+
|
| 129 |
+
def process_table_question(self, question: str) -> str:
|
| 130 |
+
"""
|
| 131 |
+
Processa questões envolvendo tabelas
|
| 132 |
+
"""
|
| 133 |
+
try:
|
| 134 |
+
response = self.agent.run(
|
| 135 |
+
f"Analise a seguinte tabela e responda à pergunta: {question}"
|
| 136 |
+
)
|
| 137 |
+
return response.content
|
| 138 |
+
except Exception as e:
|
| 139 |
+
print(f"Erro ao processar pergunta de tabela: {e}")
|
| 140 |
+
return "Error analyzing table"
|
| 141 |
+
|
| 142 |
+
def process_wikipedia_question(self, question: str) -> str:
|
| 143 |
+
"""
|
| 144 |
+
Processa questões relacionadas à Wikipedia
|
| 145 |
+
"""
|
| 146 |
+
try:
|
| 147 |
+
response = self.agent.run(
|
| 148 |
+
f"Pesquise na Wikipedia para responder: {question}"
|
| 149 |
+
)
|
| 150 |
+
return response.content
|
| 151 |
+
except Exception as e:
|
| 152 |
+
print(f"Erro ao processar pergunta da Wikipedia: {e}")
|
| 153 |
+
return "Error processing Wikipedia information"
|
| 154 |
+
|
| 155 |
+
def process_botany_question(self, question: str) -> str:
|
| 156 |
+
"""
|
| 157 |
+
Processa questões relacionadas à botânica e categorização de alimentos
|
| 158 |
+
"""
|
| 159 |
+
try:
|
| 160 |
+
response = self.agent.run(
|
| 161 |
+
f"Classifique os seguintes alimentos botanicamente: {question}"
|
| 162 |
+
)
|
| 163 |
+
return response.content
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print(f"Erro ao processar pergunta de botânica: {e}")
|
| 166 |
+
return "Error processing botanical categories"
|
| 167 |
+
|
| 168 |
+
def process_audio_question(self, question: str) -> str:
|
| 169 |
+
"""
|
| 170 |
+
Processa questões que envolvem análise de arquivos de áudio
|
| 171 |
+
"""
|
| 172 |
+
try:
|
| 173 |
+
response = self.agent.run(
|
| 174 |
+
f"Analise o seguinte arquivo de áudio e responda: {question}"
|
| 175 |
+
)
|
| 176 |
+
return response.content
|
| 177 |
+
except Exception as e:
|
| 178 |
+
print(f"Erro ao processar pergunta de áudio: {e}")
|
| 179 |
+
return "Error processing audio file"
|
| 180 |
+
|
| 181 |
+
def process_sports_question(self, question: str) -> str:
|
| 182 |
+
"""
|
| 183 |
+
Processa questões relacionadas a dados esportivos
|
| 184 |
+
"""
|
| 185 |
+
try:
|
| 186 |
+
response = self.agent.run(
|
| 187 |
+
f"Pesquise dados esportivos para responder: {question}"
|
| 188 |
+
)
|
| 189 |
+
return response.content
|
| 190 |
+
except Exception as e:
|
| 191 |
+
print(f"Erro ao processar pergunta esportiva: {e}")
|
| 192 |
+
return "Error processing sports data"
|
| 193 |
+
|
| 194 |
+
def process_scientific_article(self, question: str) -> str:
|
| 195 |
+
"""
|
| 196 |
+
Processa questões sobre artigos científicos
|
| 197 |
+
"""
|
| 198 |
+
try:
|
| 199 |
+
response = self.agent.run(
|
| 200 |
+
f"Pesquise informações sobre o seguinte artigo científico: {question}"
|
| 201 |
+
)
|
| 202 |
+
return response.content
|
| 203 |
+
except Exception as e:
|
| 204 |
+
print(f"Erro ao processar pergunta sobre artigo científico: {e}")
|
| 205 |
+
return "Error processing article information"
|
| 206 |
+
|
| 207 |
+
def process_excel_data(self, question: str) -> str:
|
| 208 |
+
"""
|
| 209 |
+
Processa questões que envolvem análise de arquivos Excel
|
| 210 |
+
"""
|
| 211 |
+
try:
|
| 212 |
+
response = self.agent.run(
|
| 213 |
+
f"Analise os seguintes dados de Excel e responda: {question}"
|
| 214 |
+
)
|
| 215 |
+
return response.content
|
| 216 |
+
except Exception as e:
|
| 217 |
+
print(f"Erro ao processar dados do Excel: {e}")
|
| 218 |
+
return "Error processing Excel file"
|
| 219 |
+
|
| 220 |
+
def is_botany_question(self, question: str) -> bool:
|
| 221 |
+
"""Verifica se é uma questão sobre botânica"""
|
| 222 |
+
keywords = ["grocery list", "mom", "botany", "vegetables"]
|
| 223 |
+
return all(keyword in question.lower() for keyword in keywords)
|
| 224 |
+
|
| 225 |
+
def is_audio_question(self, question: str) -> bool:
|
| 226 |
+
"""Verifica se é uma questão sobre áudio"""
|
| 227 |
+
return ("Homework.mp3" in question and "page numbers" in question) or \
|
| 228 |
+
("Strawberry pie.mp3" in question and "ingredients" in question)
|
| 229 |
+
|
| 230 |
+
def is_sports_question(self, question: str) -> bool:
|
| 231 |
+
"""Verifica se é uma questão sobre esportes"""
|
| 232 |
+
return ("1928 Summer Olympics" in question and "least number of athletes" in question) or \
|
| 233 |
+
("yankee" in question and "1977" in question and "walks" in question)
|
| 234 |
+
|
| 235 |
+
def is_scientific_article_question(self, question: str) -> bool:
|
| 236 |
+
"""Verifica se é uma questão sobre artigos científicos"""
|
| 237 |
+
return ("Universe Today" in question and "NASA award number" in question) or \
|
| 238 |
+
("Nedoshivina's 2010 paper" in question) or \
|
| 239 |
+
("Malko Competition" in question and "20th Century" in question)
|
| 240 |
+
|
| 241 |
+
def __call__(self, question: str) -> str:
|
| 242 |
+
print(f"Agente recebeu pergunta: {question}")
|
| 243 |
+
try:
|
| 244 |
+
# Verifica se é uma questão sobre botânica
|
| 245 |
+
if self.is_botany_question(question):
|
| 246 |
+
return self.process_botany_question(question)
|
| 247 |
+
|
| 248 |
+
# Verifica se é uma questão sobre áudio
|
| 249 |
+
elif self.is_audio_question(question):
|
| 250 |
+
return self.process_audio_question(question)
|
| 251 |
+
|
| 252 |
+
# Verifica se é uma questão sobre dados esportivos
|
| 253 |
+
elif self.is_sports_question(question):
|
| 254 |
+
return self.process_sports_question(question)
|
| 255 |
+
|
| 256 |
+
# Verifica se é uma questão sobre artigos científicos
|
| 257 |
+
elif self.is_scientific_article_question(question):
|
| 258 |
+
return self.process_scientific_article(question)
|
| 259 |
+
|
| 260 |
+
# Verifica se é uma questão sobre análise de Excel
|
| 261 |
+
elif "Excel file" in question and "sales of menu items" in question:
|
| 262 |
+
return self.process_excel_data(question)
|
| 263 |
+
|
| 264 |
+
# Verifica se é uma questão sobre tabela com operação *
|
| 265 |
+
elif ("operation *" in question or "* on the set" in question) and "{" in question:
|
| 266 |
+
return self.process_table_question(question)
|
| 267 |
+
|
| 268 |
+
# Verifica se é uma questão sobre Wikipedia
|
| 269 |
+
elif any(keyword in question.lower() for keyword in ["featured article", "wikipedia", "nominated"]):
|
| 270 |
+
return self.process_wikipedia_question(question)
|
| 271 |
+
|
| 272 |
+
# Verifica se é uma questão sobre Mercedes Sosa
|
| 273 |
+
elif "Mercedes Sosa" in question and "albums" in question:
|
| 274 |
+
return self.process_mercedes_sosa_question(question)
|
| 275 |
+
|
| 276 |
+
# Verifica se é uma questão sobre pássaros no YouTube
|
| 277 |
+
elif "youtube.com/watch" in question and ("bird" in question.lower() or "species" in question.lower()):
|
| 278 |
+
video_id = question.split("v=")[1].split(" ")[0].split("?")[0]
|
| 279 |
+
return self.process_youtube_birds_question(video_id)
|
| 280 |
+
|
| 281 |
+
# Verifica se é um texto invertido
|
| 282 |
+
elif all(c.isascii() for c in question) and len(question) > 10:
|
| 283 |
+
# Verifica se o texto parece estar invertido
|
| 284 |
+
if question.count('.') > 0 and question[-1].isalpha():
|
| 285 |
+
return self.process_reversed_text(question)
|
| 286 |
+
|
| 287 |
+
# Verifica se é uma questão de xadrez
|
| 288 |
+
elif "chess position" in question.lower():
|
| 289 |
+
return self.process_chess_question(question)
|
| 290 |
+
|
| 291 |
+
# Caso não seja nenhum dos tipos conhecidos, usa o agente genérico
|
| 292 |
+
response = self.agent.run(question)
|
| 293 |
+
return response.content
|
| 294 |
+
|
| 295 |
+
except Exception as e:
|
| 296 |
+
print(f"Erro ao processar pergunta: {e}")
|
| 297 |
+
return "Error processing question"
|
app.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
+
import json
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from dotenv import load_dotenv
|
| 7 |
+
from agent import AgentDeedee
|
| 8 |
+
|
| 9 |
+
# Desabilita a autenticação OAuth para testes locais
|
| 10 |
+
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
|
| 11 |
+
|
| 12 |
+
# Carrega variáveis de ambiente
|
| 13 |
+
load_dotenv()
|
| 14 |
+
|
| 15 |
+
# --- Constantes ---
|
| 16 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 17 |
+
OUTPUT_JSONL = "answers.jsonl"
|
| 18 |
+
|
| 19 |
+
def carregar_prompt_sistema():
|
| 20 |
+
"""Carrega o prompt do sistema a partir do arquivo"""
|
| 21 |
+
try:
|
| 22 |
+
with open("system_prompt.txt", "r", encoding="utf-8") as f:
|
| 23 |
+
return f.read()
|
| 24 |
+
except Exception as e:
|
| 25 |
+
print(f"Erro ao carregar prompt do sistema: {e}")
|
| 26 |
+
return "Você é a Deedee, um assistente especializado em responder perguntas."
|
| 27 |
+
|
| 28 |
+
def salvar_jsonl(respostas_payload):
|
| 29 |
+
"""Salva as respostas no formato JSONL exatamente como esperado pelo sistema de avaliação"""
|
| 30 |
+
with open(OUTPUT_JSONL, 'w', encoding='utf-8') as f:
|
| 31 |
+
for resposta in respostas_payload:
|
| 32 |
+
# Remove o prefixo "FINAL ANSWER: " se existir
|
| 33 |
+
model_answer = resposta.get("model_answer", "")
|
| 34 |
+
if model_answer.startswith("FINAL ANSWER: "):
|
| 35 |
+
model_answer = model_answer[14:] # Remove os primeiros 14 caracteres
|
| 36 |
+
|
| 37 |
+
# Cria uma entrada no formato correto
|
| 38 |
+
entrada = {
|
| 39 |
+
"task_id": resposta["task_id"],
|
| 40 |
+
"model_answer": model_answer
|
| 41 |
+
# Opcionalmente: "reasoning_trace": "Processo de raciocínio para esta resposta"
|
| 42 |
+
}
|
| 43 |
+
json.dump(entrada, f, ensure_ascii=False)
|
| 44 |
+
f.write('\n')
|
| 45 |
+
print(f"Respostas salvas em {OUTPUT_JSONL}")
|
| 46 |
+
|
| 47 |
+
def processar_pergunta(pergunta, task_id):
|
| 48 |
+
"""
|
| 49 |
+
Processa uma pergunta usando o agente Deedee e retorna a resposta
|
| 50 |
+
"""
|
| 51 |
+
try:
|
| 52 |
+
# Inicializa o agente
|
| 53 |
+
agente = AgentDeedee()
|
| 54 |
+
|
| 55 |
+
# Processa a pergunta
|
| 56 |
+
resposta = agente(pergunta)
|
| 57 |
+
|
| 58 |
+
# Remove o prefixo "FINAL ANSWER: " se existir
|
| 59 |
+
if resposta.startswith("FINAL ANSWER: "):
|
| 60 |
+
resposta = resposta[14:]
|
| 61 |
+
|
| 62 |
+
return {
|
| 63 |
+
"task_id": task_id,
|
| 64 |
+
"model_answer": resposta
|
| 65 |
+
}
|
| 66 |
+
except Exception as e:
|
| 67 |
+
print(f"Erro ao processar pergunta {task_id}: {e}")
|
| 68 |
+
return {
|
| 69 |
+
"task_id": task_id,
|
| 70 |
+
"model_answer": "Erro ao processar a pergunta"
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
def executar_enviar_tudo(profile: gr.OAuthProfile | None):
|
| 74 |
+
"""
|
| 75 |
+
Carrega as respostas do arquivo answers.jsonl e as envia para avaliação.
|
| 76 |
+
"""
|
| 77 |
+
if not profile:
|
| 78 |
+
print("Usuário não está logado.")
|
| 79 |
+
return "Por favor, faça login no Hugging Face com o botão.", None
|
| 80 |
+
|
| 81 |
+
nome_usuario = profile.username.strip()
|
| 82 |
+
print(f"Usuário logado: {nome_usuario}")
|
| 83 |
+
|
| 84 |
+
# Obtém o SPACE_ID para enviar o link para o código
|
| 85 |
+
space_id = os.getenv("SPACE_ID", f"{nome_usuario}/Final_Assignment_Template")
|
| 86 |
+
codigo_agente = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 87 |
+
print(f"Usando URL do código do agente: {codigo_agente}")
|
| 88 |
+
|
| 89 |
+
api_url = DEFAULT_API_URL
|
| 90 |
+
url_envio = f"{api_url}/submit"
|
| 91 |
+
|
| 92 |
+
# Carrega as respostas do arquivo answers.jsonl
|
| 93 |
+
try:
|
| 94 |
+
respostas_payload = []
|
| 95 |
+
registro_resultados = []
|
| 96 |
+
|
| 97 |
+
with open(OUTPUT_JSONL, 'r', encoding='utf-8') as f:
|
| 98 |
+
for line in f:
|
| 99 |
+
if line.strip():
|
| 100 |
+
entry = json.loads(line.strip())
|
| 101 |
+
|
| 102 |
+
# Garantir que não há prefixo "FINAL ANSWER: " na resposta
|
| 103 |
+
model_answer = entry.get("model_answer", "")
|
| 104 |
+
if model_answer.startswith("FINAL ANSWER: "):
|
| 105 |
+
model_answer = model_answer[14:]
|
| 106 |
+
|
| 107 |
+
entry["model_answer"] = model_answer
|
| 108 |
+
respostas_payload.append(entry)
|
| 109 |
+
registro_resultados.append({
|
| 110 |
+
"ID da Tarefa": entry["task_id"],
|
| 111 |
+
"Resposta Enviada": entry["model_answer"]
|
| 112 |
+
})
|
| 113 |
+
|
| 114 |
+
print(f"Carregadas {len(respostas_payload)} respostas do arquivo {OUTPUT_JSONL}")
|
| 115 |
+
|
| 116 |
+
if not respostas_payload:
|
| 117 |
+
return f"Erro: O arquivo {OUTPUT_JSONL} está vazio ou não contém respostas válidas.", None
|
| 118 |
+
|
| 119 |
+
except Exception as e:
|
| 120 |
+
print(f"Erro ao carregar respostas do arquivo {OUTPUT_JSONL}: {e}")
|
| 121 |
+
return f"Erro ao carregar respostas: {e}", None
|
| 122 |
+
|
| 123 |
+
# Envia Respostas
|
| 124 |
+
try:
|
| 125 |
+
dados_envio = {
|
| 126 |
+
"username": nome_usuario,
|
| 127 |
+
"agent_code": codigo_agente,
|
| 128 |
+
"answers": respostas_payload
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
print(f"Enviando {len(respostas_payload)} respostas...")
|
| 132 |
+
resposta = requests.post(url_envio, json=dados_envio, timeout=120)
|
| 133 |
+
resposta.raise_for_status()
|
| 134 |
+
|
| 135 |
+
resultado = resposta.json()
|
| 136 |
+
status = f"Envio bem-sucedido!\nUsuário: {nome_usuario}\nPontuação: {resultado.get('score', 'N/A')}%"
|
| 137 |
+
|
| 138 |
+
return status, pd.DataFrame(registro_resultados)
|
| 139 |
+
|
| 140 |
+
except Exception as e:
|
| 141 |
+
msg_erro = f"Falha no envio: {str(e)}"
|
| 142 |
+
if hasattr(e, 'response') and hasattr(e.response, 'text'):
|
| 143 |
+
msg_erro += f"\nResposta: {e.response.text}"
|
| 144 |
+
|
| 145 |
+
print(msg_erro)
|
| 146 |
+
return msg_erro, pd.DataFrame(registro_resultados)
|
| 147 |
+
|
| 148 |
+
# --- Constroi Interface Gradio usando Blocks ---
|
| 149 |
+
with gr.Blocks() as demo:
|
| 150 |
+
gr.Markdown("# Deedee - Agente de Avaliação")
|
| 151 |
+
gr.Markdown(
|
| 152 |
+
"""
|
| 153 |
+
**Instruções:**
|
| 154 |
+
1. Configure sua chave API do Together AI no arquivo .env
|
| 155 |
+
2. Clique em 'Testar Agente' para testar o agente com uma pergunta de exemplo
|
| 156 |
+
3. Para envio completo, faça login com sua conta Hugging Face e clique em 'Executar Avaliação'
|
| 157 |
+
"""
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
# Interface para teste local
|
| 161 |
+
with gr.Tab("Teste Local"):
|
| 162 |
+
pergunta_teste = gr.Textbox(label="Pergunta de teste", lines=2, placeholder="Digite uma pergunta para testar o agente...")
|
| 163 |
+
resposta_teste = gr.Textbox(label="Resposta do agente", lines=5, interactive=False)
|
| 164 |
+
botao_teste = gr.Button("Testar Agente")
|
| 165 |
+
|
| 166 |
+
# Função para testar o agente localmente
|
| 167 |
+
def testar_agente(pergunta):
|
| 168 |
+
try:
|
| 169 |
+
agente = AgentDeedee()
|
| 170 |
+
resposta = agente(pergunta)
|
| 171 |
+
return resposta
|
| 172 |
+
except Exception as e:
|
| 173 |
+
return f"Erro ao processar pergunta: {str(e)}"
|
| 174 |
+
|
| 175 |
+
botao_teste.click(
|
| 176 |
+
fn=testar_agente,
|
| 177 |
+
inputs=pergunta_teste,
|
| 178 |
+
outputs=resposta_teste
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
# Interface para envio completo (apenas para ambiente Hugging Face Space)
|
| 182 |
+
with gr.Tab("Envio para Avaliação"):
|
| 183 |
+
gr.Markdown("""
|
| 184 |
+
**Nota:** Esta funcionalidade está disponível apenas quando executada em um ambiente Hugging Face Space.
|
| 185 |
+
|
| 186 |
+
Para enviar respostas para avaliação:
|
| 187 |
+
1. Faça o upload deste código para um Space no Hugging Face
|
| 188 |
+
2. Configure as variáveis de ambiente necessárias
|
| 189 |
+
3. Execute o aplicativo no ambiente do Space
|
| 190 |
+
""")
|
| 191 |
+
|
| 192 |
+
# Botão desabilitado para ambiente local
|
| 193 |
+
gr.Button("Executar Avaliação (Desabilitado em ambiente local)", interactive=False)
|
| 194 |
+
|
| 195 |
+
if __name__ == "__main__":
|
| 196 |
+
demo.launch()
|
gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio>=4.13.0
|
| 2 |
+
requests>=2.31.0
|
| 3 |
+
pandas>=2.0.0
|
| 4 |
+
python-dotenv>=1.0.0
|
| 5 |
+
beautifulsoup4>=4.12.2
|
| 6 |
+
huggingface-hub>=0.19.0
|
| 7 |
+
agno>=1.4.6
|
| 8 |
+
together-ai>=0.2.0
|
system_prompt.txt
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Você é a Deedee, uma assistente especializada em responder perguntas em diversos tópicos.
|
| 2 |
+
|
| 3 |
+
Ao responder, siga estas diretrizes:
|
| 4 |
+
|
| 5 |
+
- Sempre forneça respostas precisas e baseadas em fatos
|
| 6 |
+
- Utilize as ferramentas e conhecimentos específicos quando necessário
|
| 7 |
+
- Seja conciso e direto em suas respostas
|
| 8 |
+
- Se você não tem certeza da resposta, indique isso claramente
|
| 9 |
+
- Consulte os dados e fontes disponíveis quando apropriado
|
| 10 |
+
- Para perguntas complexas, divida a solução em etapas lógicas
|
| 11 |
+
- Forneça apenas a resposta final, sem texto adicional
|
| 12 |
+
|
| 13 |
+
Seu objetivo é fornecer a resposta mais precisa e útil possível para cada pergunta recebida.
|