wakeupmh commited on
Commit
24405fe
·
1 Parent(s): fc964f0

feat: agentic approach

Browse files
app.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import logging
3
+ from services.model_handler import ModelHandler
4
+
5
+ # Configure logging
6
+ logging.basicConfig(
7
+ level=logging.INFO,
8
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
9
+ )
10
+
11
+ class AutismResearchApp:
12
+ def __init__(self):
13
+ """Initialize the application components"""
14
+ self.model_handler = ModelHandler()
15
+
16
+ def _setup_streamlit(self):
17
+ """Setup Streamlit UI components"""
18
+ st.image("https://images.unsplash.com/photo-1642370324000-f204b23aafe0?q=80&w=4072&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D")
19
+ st.title("🧩 Além do Espectro 🧠✨")
20
+ st.subheader("Tudo o que você precisa saber além dos rotulos e explorando a riqueza das neurodivergências")
21
+ st.markdown("""
22
+ Pergunte o que quiser e eu vou analisar os últimos artigos científicos e fornecer uma resposta baseada em evidências.
23
+ """)
24
+
25
+ def run(self):
26
+ """Run the main application loop"""
27
+ self._setup_streamlit()
28
+
29
+ # Initialize session state for papers
30
+ if 'papers' not in st.session_state:
31
+ st.session_state.papers = []
32
+
33
+ # Get user query
34
+ col1, col2 = st.columns(2, vertical_alignment="bottom", gap="small")
35
+
36
+ query = col1.text_input("O que você precisa saber?")
37
+ if col2.button("Enviar"):
38
+ # Show status while processing
39
+ with st.status("Processando sua Pergunta...") as status:
40
+ status.write("🔍 Buscando papers de pesquisa relevantes...")
41
+ status.write("📚 Analisando papers de pesquisa...")
42
+ status.write("✍️ Gerando resposta...")
43
+ answer = self.model_handler.generate_answer(query)
44
+
45
+ status.write("✨ Resposta gerada! Exibindo resultados...")
46
+
47
+ st.success("✅ Resposta gerada com base nos artigos de pesquisa encontrados.")
48
+
49
+
50
+ st.markdown("### Resposta")
51
+ st.markdown(answer)
52
+
53
+ def main():
54
+ app = AutismResearchApp()
55
+ app.run()
56
+
57
+ if __name__ == "__main__":
58
+ main()
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ transformers>=4.36.2
2
+ streamlit>=1.29.0
3
+ --extra-index-url https://download.pytorch.org/whl/cpu
4
+ accelerate>=0.26.0
5
+ arxiv>=1.4.7
6
+ python-dotenv>=1.0.0
7
+ agno==1.0.6
8
+ ollama>=0.4.7
9
+ pypdf>=3.11.1
10
+ watchdog>=2.3.1
services/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
services/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (179 Bytes). View file
 
services/__pycache__/model_handler.cpython-311.pyc ADDED
Binary file (6.53 kB). View file
 
services/__pycache__/research_fetcher.cpython-311.pyc ADDED
Binary file (17.9 kB). View file
 
services/model_handler.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import streamlit as st
4
+ from agno.agent import Agent
5
+ from agno.models.ollama import Ollama
6
+ from agno.tools.arxiv import ArxivTools
7
+ from agno.tools.pubmed import PubmedTools
8
+
9
+ MODEL_PATH = "meta-llama/Llama-3.2-1B"
10
+
11
+ class ModelHandler:
12
+ def __init__(self):
13
+ """Initialize the model handler"""
14
+ self.model = None
15
+ self.tokenizer = None
16
+ self.translator = None
17
+ self.researcher = None
18
+ self.summarizer = None
19
+ self.presenter = None
20
+ self._initialize_model()
21
+
22
+ def _initialize_model(self):
23
+ """Initialize model and tokenizer"""
24
+ self.model, self.tokenizer = self._load_model()
25
+ self.translator = Agent(
26
+ name="Translator",
27
+ role="You will translate the query to English",
28
+ model=Ollama(id="llama3.2:1b"),
29
+ goal="Translate to English",
30
+ instructions=[
31
+ "Translate the query to English"
32
+ ]
33
+ )
34
+
35
+ self.researcher = Agent(
36
+ name="Researcher",
37
+ role="You are a research scholar who specializes in autism research.",
38
+ model=Ollama(id="llama3.2:1b"),
39
+ tools=[ArxivTools(), PubmedTools()],
40
+ instructions=[
41
+ "You need to understand the context of the question to provide the best answer based on your tools."
42
+ "Be precise and provide just enough information to be useful",
43
+ "You must cite the sources used in your answer."
44
+ "You must create an accessible summary.",
45
+ "The content must be for people without autism knowledge.",
46
+ "Focus in the main findings of the paper taking in consideration the question.",
47
+ "The answer must be brief."
48
+ ],
49
+ show_tool_calls=True,
50
+ )
51
+ self.summarizer = Agent(
52
+ name="Summarizer",
53
+ role="You are a specialist in summarizing research papers for people without autism knowledge.",
54
+ model=Ollama(id="llama3.2:1b"),
55
+ instructions=[
56
+ "You must provide just enough information to be useful",
57
+ "You must cite the sources used in your answer.",
58
+ "You must be clear and concise.",
59
+ "You must create an accessible summary.",
60
+ "The content must be for people without autism knowledge.",
61
+ "Focus in the main findings of the paper taking in consideration the question.",
62
+ "The answer must be brief."
63
+ "Remove everything related to the run itself like: 'Running: transfer_', just use plain text",
64
+ "You must use the language provided by the user to present the results.",
65
+ "Add references to the sources used in the answer.",
66
+ "Add emojis to make the presentation more interactive."
67
+ "Translaste the answer to Portuguese."
68
+ ],
69
+ show_tool_calls=True,
70
+ markdown=True,
71
+ add_references=True,
72
+ )
73
+
74
+ self.presenter = Agent(
75
+ name="Presenter",
76
+ role="You are a professional researcher who presents the results of the research.",
77
+ model=Ollama(id="llama3.2:1b"),
78
+ instructions=[
79
+ "You are multilingual",
80
+ "You must present the results in a clear and concise manner.",
81
+ "Clenaup the presentation to make it more readable.",
82
+ "Remove unnecessary information.",
83
+ "Remove everything related to the run itself like: 'Running: transfer_', just use plain text",
84
+ "You must use the language provided by the user to present the results.",
85
+ "Add references to the sources used in the answer.",
86
+ "Add emojis to make the presentation more interactive."
87
+ "Translaste the answer to Portuguese."
88
+ ],
89
+ add_references=True,
90
+ )
91
+
92
+
93
+ @staticmethod
94
+ @st.cache_resource
95
+ @st.cache_data
96
+ def _load_model():
97
+ try:
98
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH)
99
+ model = AutoModelForCausalLM.from_pretrained(MODEL_PATH)
100
+ return model, tokenizer
101
+ except Exception as e:
102
+ logging.error(f"Error loading model: {str(e)}")
103
+ return None, None
104
+
105
+ def generate_answer(self, query: str) -> str:
106
+ try:
107
+ translator = self.translator.run(query, stream=False)
108
+ logging.info(f"Translated query")
109
+ research = self.researcher.run(translator.content, stream=False)
110
+ logging.info(f"Generated research")
111
+ summary = self.summarizer.run(research.content, stream=False)
112
+ logging.info(f"Generated summary")
113
+ presentation = self.presenter.run(summary.content, stream=False)
114
+ logging.info(f"Generated presentation")
115
+
116
+ if not presentation.content:
117
+ return self._get_fallback_response()
118
+ return presentation.content
119
+ except Exception as e:
120
+ logging.error(f"Error generating answer: {str(e)}")
121
+ return self._get_fallback_response()
122
+
123
+ @staticmethod
124
+ def _get_fallback_response() -> str:
125
+ """Provide a friendly, helpful fallback response"""
126
+ return """
127
+ Peço descula, mas encontrei um erro ao gerar a resposta. Tente novamente ou refaça a sua pergunta.
128
+ """