Spaces:
Sleeping
Sleeping
lucas-wa
commited on
Commit
·
6558cd8
1
Parent(s):
6250002
Refactoring server
Browse files- .gitignore +4 -0
- server/app.py +2 -398
- server/data/load_data.py +63 -0
- server/inference.py +31 -0
- server/llm/gemini.py +82 -0
- server/requirements.txt +9 -4
- server/utils.py +0 -0
- server/utils/__init__.py +0 -0
- server/utils/questions_parser.py +22 -0
.gitignore
CHANGED
@@ -25,3 +25,7 @@ dist-ssr
|
|
25 |
*.njsproj
|
26 |
*.sln
|
27 |
*.sw?
|
|
|
|
|
|
|
|
|
|
25 |
*.njsproj
|
26 |
*.sln
|
27 |
*.sw?
|
28 |
+
|
29 |
+
*.env
|
30 |
+
*chroma_db
|
31 |
+
databases
|
server/app.py
CHANGED
@@ -1,402 +1,6 @@
|
|
1 |
-
import
|
2 |
-
import re
|
3 |
-
import time
|
4 |
-
from langchain_core.documents import Document
|
5 |
-
from langchain_community.document_loaders import TextLoader
|
6 |
-
from langchain.vectorstores import Chroma
|
7 |
-
from langchain_text_splitters import CharacterTextSplitter
|
8 |
-
from langchain import PromptTemplate, LLMChain
|
9 |
-
from langchain.schema.runnable import RunnablePassthrough
|
10 |
-
from langchain.schema import StrOutputParser
|
11 |
-
from langchain_google_genai import ChatGoogleGenerativeAI
|
12 |
-
from langchain_google_genai import GoogleGenerativeAIEmbeddings
|
13 |
-
from langchain.chains.query_constructor.base import AttributeInfo
|
14 |
-
from langchain.retrievers.self_query.base import SelfQueryRetriever
|
15 |
-
from langchain.output_parsers import ResponseSchema, StructuredOutputParser
|
16 |
-
from langchain.prompts import ChatPromptTemplate
|
17 |
-
from langchain_core.runnables import RunnableLambda
|
18 |
-
|
19 |
-
GOOGLE_API_KEY=""
|
20 |
-
|
21 |
-
if "GOOGLE_API_KEY" not in os.environ:
|
22 |
-
os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
|
23 |
-
|
24 |
-
loader = TextLoader("/content/banco_de_questoes_v3.txt").load()
|
25 |
-
|
26 |
-
gemini_embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
|
27 |
-
|
28 |
-
|
29 |
-
# db = Chroma.from_documents(documents, gemini_embeddings)
|
30 |
-
# vectorstore = Chroma.from_documents(
|
31 |
-
# documents=documents,
|
32 |
-
# embedding=gemini_embeddings,
|
33 |
-
# persist_directory="./chroma_db"
|
34 |
-
# )
|
35 |
-
# vectorstore_disk = Chroma(
|
36 |
-
# persist_directory="./chroma_db",
|
37 |
-
# embedding_function=gemini_embeddings
|
38 |
-
# )
|
39 |
-
# retriever = vectorstore_disk.as_retriever(search_kwargs={"k": 10})
|
40 |
-
|
41 |
-
questions = list(map(lambda x: "##Questão" + x, loader[0].page_content.split("##Questão")))
|
42 |
-
|
43 |
-
def parse_question(question_str):
|
44 |
-
# Extract content
|
45 |
-
content_start = question_str.find('"""') + 3
|
46 |
-
content_end = question_str.rfind('"""', content_start)
|
47 |
-
content = question_str[content_start:content_end].strip()
|
48 |
-
|
49 |
-
# Extract correct option
|
50 |
-
correct_option_start = question_str.find('opcao_correta=') + 15
|
51 |
-
correct_option_end = correct_option_start + 1
|
52 |
-
correct_option = question_str[correct_option_start:correct_option_end]
|
53 |
-
|
54 |
-
# Extract metadata
|
55 |
-
metadata_start = question_str.find("metadados=") + 10
|
56 |
-
metadata_end = question_str.find("}", metadata_start) + 1
|
57 |
-
metadata_str = question_str[metadata_start:metadata_end]
|
58 |
-
metadata = eval(metadata_str)
|
59 |
-
|
60 |
-
topico, assunto, dificuldade, tipo = metadata.values()
|
61 |
-
|
62 |
-
return Document(page_content="##Questão\n" + content, metadata={"correct_option":correct_option, "topico":topico, "assunto":assunto, "dificuldade":dificuldade, "tipo":tipo})
|
63 |
-
|
64 |
-
# Lista para armazenar os documentos
|
65 |
-
docs = []
|
66 |
-
|
67 |
-
for question in questions:
|
68 |
-
try:
|
69 |
-
docs.append(parse_question(question))
|
70 |
-
except Exception as e:
|
71 |
-
print(e, question)
|
72 |
-
|
73 |
-
docs[0]
|
74 |
-
|
75 |
-
|
76 |
-
db = Chroma.from_documents(docs, gemini_embeddings)
|
77 |
-
vectorstore = Chroma.from_documents(
|
78 |
-
documents=docs,
|
79 |
-
embedding=gemini_embeddings,
|
80 |
-
persist_directory="./chroma_db"
|
81 |
-
)
|
82 |
-
vectorstore_disk = Chroma(
|
83 |
-
persist_directory="./chroma_db",
|
84 |
-
embedding_function=gemini_embeddings
|
85 |
-
)
|
86 |
-
metadata_field_info = [
|
87 |
-
AttributeInfo(
|
88 |
-
name="topico",
|
89 |
-
description="A materia escolar da qual a questão pertence.",
|
90 |
-
type="string",
|
91 |
-
),
|
92 |
-
AttributeInfo(
|
93 |
-
name="assunto",
|
94 |
-
description="O assunto da materia fornecida anteriormente.",
|
95 |
-
type="string",
|
96 |
-
),
|
97 |
-
AttributeInfo(
|
98 |
-
name="dificuldade",
|
99 |
-
description="O nivel de dificuldade para resolver a questao.",
|
100 |
-
type="string",
|
101 |
-
),
|
102 |
-
AttributeInfo(
|
103 |
-
name="tipo",
|
104 |
-
description="O tipo da questao. Pode ser ou Multipla Escolha ou Justificativa",
|
105 |
-
type="string",
|
106 |
-
),
|
107 |
-
]
|
108 |
-
document_content_description = "Questões de biologia"
|
109 |
-
llm = ChatGoogleGenerativeAI(model="gemini-pro",
|
110 |
-
temperature=0.7, top_p=1)
|
111 |
-
retriever = SelfQueryRetriever.from_llm(
|
112 |
-
llm, vectorstore, document_content_description, metadata_field_info, verbose=True
|
113 |
-
)
|
114 |
-
|
115 |
-
print(len(retriever.get_relevant_documents("MMLU")))
|
116 |
-
|
117 |
-
llm_prompt_template = """Olá, sou uma IA treinada para gerar conteúdo educacional. Por favor, gere cinco questões de múltipla escolha sobre o seguinte tema:
|
118 |
-
Instruções para cada questão:
|
119 |
-
- Crie uma questão clara e relevante para o tema.
|
120 |
-
- Forneça cinco opções de resposta, rotuladas de A) a E).
|
121 |
-
- Apenas uma das opções de resposta deve ser correta.
|
122 |
-
- Indique a resposta correta ao final de cada questão.
|
123 |
-
|
124 |
-
Exemplo de uma questão:
|
125 |
-
Tema: Fotossíntese
|
126 |
-
|
127 |
-
Questão:
|
128 |
-
Qual é o pigmento primário responsável pela fotossíntese nas plantas?
|
129 |
-
|
130 |
-
Opções de Resposta:
|
131 |
-
A) Clorofila
|
132 |
-
B) Hemoglobina
|
133 |
-
C) Mioglobina
|
134 |
-
D) Citocromo
|
135 |
-
E) Queratina
|
136 |
-
|
137 |
-
Resposta Correta:
|
138 |
-
A) Clorofila
|
139 |
-
|
140 |
-
Context: {context}
|
141 |
-
Question: {question}
|
142 |
-
Answer:
|
143 |
-
|
144 |
-
|
145 |
-
{format_questions_instructions}
|
146 |
-
GIVE ME THE FIVE QUESTIONS SEPARATED IN AN ARRAY
|
147 |
-
"""
|
148 |
-
|
149 |
-
llm_prompt = PromptTemplate.from_template(llm_prompt_template)
|
150 |
-
|
151 |
-
print(llm_prompt)
|
152 |
-
|
153 |
-
|
154 |
-
questions_template = ChatPromptTemplate.from_template(template=llm_prompt_template)
|
155 |
-
|
156 |
-
questions_chain = LLMChain(llm=llm, prompt=questions_template)
|
157 |
-
|
158 |
-
questions_schema = ResponseSchema(
|
159 |
-
name="questions",
|
160 |
-
description="""Give the questions in json as an array""",
|
161 |
-
)
|
162 |
-
|
163 |
-
questions_schemas = [questions_schema]
|
164 |
-
|
165 |
-
questions_parser = StructuredOutputParser.from_response_schemas(questions_schemas)
|
166 |
-
format_questions_instructions = questions_parser.get_format_instructions()
|
167 |
-
|
168 |
-
print(format_questions_instructions)
|
169 |
-
|
170 |
-
def get_questions(_dict):
|
171 |
-
question = _dict["question"]
|
172 |
-
context = _dict["context"]
|
173 |
-
messages = questions_template.format_messages(
|
174 |
-
context=context,
|
175 |
-
question=question,
|
176 |
-
format_questions_instructions=format_questions_instructions,
|
177 |
-
)
|
178 |
-
|
179 |
-
chat = ChatGoogleGenerativeAI(model="gemini-pro")
|
180 |
-
response = chat.invoke(messages)
|
181 |
-
return questions_parser.parse(response.content)
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
def format_docs(docs):
|
186 |
-
return "\n\n".join(doc.page_content for doc in docs)
|
187 |
-
|
188 |
-
|
189 |
-
# llm = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.7, top_p=1)
|
190 |
-
rag_chain = (
|
191 |
-
{"context": retriever | RunnableLambda(format_docs),
|
192 |
-
"question": RunnablePassthrough()}
|
193 |
-
| RunnableLambda(get_questions)
|
194 |
-
)
|
195 |
-
|
196 |
-
retriever
|
197 |
-
|
198 |
-
start_time = time.time()
|
199 |
-
assunto = "Bioquimica e Biofisica"
|
200 |
-
query = f"Quero que você gere questões de biologia, sendo do assunto: {assunto}."
|
201 |
-
print(rag_chain.invoke(f"""{query}"""))
|
202 |
-
end_time = time.time()
|
203 |
-
execution_time = end_time - start_time
|
204 |
-
print(f"Tempo de execução: {execution_time:.2f} segundos.")
|
205 |
|
206 |
assunto = "Bioquimica e Biofisica"
|
207 |
query = f"Quero que você gere questões de biologia, sendo do assunto: {assunto}."
|
208 |
res = rag_chain.invoke(f"""{query}""")
|
209 |
-
|
210 |
-
res["questions"][0]
|
211 |
-
|
212 |
-
docs = retriever.invoke(f"{query}")
|
213 |
-
for doc in docs:
|
214 |
-
print(doc)
|
215 |
-
print()
|
216 |
-
|
217 |
-
"""###PIPELINE 2
|
218 |
-
|
219 |
-
"""
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
class Document:
|
225 |
-
def __init__(self, page_content, metadata):
|
226 |
-
self.page_content = page_content
|
227 |
-
self.metadata = metadata
|
228 |
-
|
229 |
-
def parse_document(text):
|
230 |
-
regex = r"Document\(\n\s+conteudo=\n\"{3}([^`]+?)\"{3}\n,\n\s+opcao_correta=\"(\w+)\"\,\n\s+metadados=\{([^}]+)\}\n\)"
|
231 |
-
matches = re.finditer(regex, text, re.DOTALL)
|
232 |
-
documents = []
|
233 |
-
for match in matches:
|
234 |
-
page_content = match.group(1).strip()
|
235 |
-
metadata_text = match.group(3).strip()
|
236 |
-
metadata = {}
|
237 |
-
metadata_entries = metadata_text.split(', ')
|
238 |
-
for entry in metadata_entries:
|
239 |
-
key, value = entry.split(': ')
|
240 |
-
metadata[key.strip("'")] = value.strip("'")
|
241 |
-
|
242 |
-
document = Document(page_content, metadata)
|
243 |
-
documents.append(document)
|
244 |
-
|
245 |
-
return documents
|
246 |
-
|
247 |
-
with open('/content/banco_de_questoes_v2.txt', 'r', encoding='utf-8') as file:
|
248 |
-
txt_data = file.read()
|
249 |
-
|
250 |
-
docs = parse_document(txt_data)
|
251 |
-
|
252 |
-
gemini_embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
|
253 |
-
|
254 |
-
db = Chroma.from_documents(docs, gemini_embeddings)
|
255 |
-
vectorstore = Chroma.from_documents(
|
256 |
-
documents=docs,
|
257 |
-
embedding=gemini_embeddings,
|
258 |
-
persist_directory="./chroma_db"
|
259 |
-
)
|
260 |
-
vectorstore_disk = Chroma(
|
261 |
-
persist_directory="./chroma_db",
|
262 |
-
embedding_function=gemini_embeddings
|
263 |
-
)
|
264 |
-
|
265 |
-
metadata_field_info = [
|
266 |
-
AttributeInfo(
|
267 |
-
name="topico",
|
268 |
-
description="A materia escolar da qual a questão pertence.",
|
269 |
-
type="string",
|
270 |
-
),
|
271 |
-
AttributeInfo(
|
272 |
-
name="assunto",
|
273 |
-
description="O assunto da materia fornecida anteriormente.",
|
274 |
-
type="string",
|
275 |
-
),
|
276 |
-
AttributeInfo(
|
277 |
-
name="dificuldade",
|
278 |
-
description="O nivel de dificuldade para resolver a questao.",
|
279 |
-
type="string",
|
280 |
-
),
|
281 |
-
AttributeInfo(
|
282 |
-
name="tipo",
|
283 |
-
description="O tipo da questao. Pode ser ou Multipla Escolha ou Justificativa",
|
284 |
-
type="string",
|
285 |
-
),
|
286 |
-
]
|
287 |
-
document_content_description = "Questões de biologia"
|
288 |
-
llm = ChatGoogleGenerativeAI(model="gemini-pro",
|
289 |
-
temperature=0.7, top_p=1)
|
290 |
-
retriever = SelfQueryRetriever.from_llm(
|
291 |
-
llm, vectorstore, document_content_description, metadata_field_info, verbose=True
|
292 |
-
)
|
293 |
-
retriever.invoke("Qual é a importância das células")
|
294 |
-
|
295 |
-
"""###PIPELINE 3
|
296 |
-
|
297 |
-
"""
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
loader = TextLoader("/content/banco_de_questoes_v2.txt").load()
|
302 |
-
|
303 |
-
gemini_embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
|
304 |
-
|
305 |
-
text_splitter = CharacterTextSplitter(chunk_size=1024, chunk_overlap=0)
|
306 |
-
documents = text_splitter.split_documents(loader)
|
307 |
-
db = Chroma.from_documents(documents, gemini_embeddings)
|
308 |
-
vectorstore = Chroma.from_documents(
|
309 |
-
documents=documents,
|
310 |
-
embedding=gemini_embeddings,
|
311 |
-
persist_directory="./chroma_db"
|
312 |
-
)
|
313 |
-
vectorstore_disk = Chroma(
|
314 |
-
persist_directory="./chroma_db",
|
315 |
-
embedding_function=gemini_embeddings
|
316 |
-
)
|
317 |
-
metadata_field_info = [
|
318 |
-
AttributeInfo(
|
319 |
-
name="topico",
|
320 |
-
description="A materia escolar da qual a questão pertence.",
|
321 |
-
type="string",
|
322 |
-
),
|
323 |
-
AttributeInfo(
|
324 |
-
name="assunto",
|
325 |
-
description="O assunto da materia fornecida anteriormente.",
|
326 |
-
type="string",
|
327 |
-
),
|
328 |
-
AttributeInfo(
|
329 |
-
name="dificuldade",
|
330 |
-
description="O nivel de dificuldade para resolver a questao.",
|
331 |
-
type="string",
|
332 |
-
),
|
333 |
-
AttributeInfo(
|
334 |
-
name="tipo",
|
335 |
-
description="O tipo da questao. Pode ser ou Multipla Escolha ou Justificativa",
|
336 |
-
type="string",
|
337 |
-
),
|
338 |
-
]
|
339 |
-
document_content_description = "Questões de biologia"
|
340 |
-
llm = ChatGoogleGenerativeAI(model="gemini-pro",
|
341 |
-
temperature=0.7, top_p=1)
|
342 |
-
retriever = SelfQueryRetriever.from_llm(
|
343 |
-
llm, vectorstore, document_content_description, metadata_field_info, verbose=True
|
344 |
-
)
|
345 |
-
|
346 |
-
print(len(retriever.get_relevant_documents("MMLU")))
|
347 |
-
|
348 |
-
llm_prompt_template = """Olá, sou uma IA treinada para gerar conteúdo educacional. Por favor, gere cinco questões de múltipla escolha sobre o seguinte tema:
|
349 |
-
Instruções para cada questão:
|
350 |
-
- Crie uma questão clara e relevante para o tema.
|
351 |
-
- Forneça cinco opções de resposta, rotuladas de A) a E).
|
352 |
-
- Apenas uma das opções de resposta deve ser correta.
|
353 |
-
- Indique a resposta correta ao final de cada questão.
|
354 |
-
|
355 |
-
Exemplo de uma questão:
|
356 |
-
Tema: Fotossíntese
|
357 |
-
|
358 |
-
Questão:
|
359 |
-
Qual é o pigmento primário responsável pela fotossíntese nas plantas?
|
360 |
-
|
361 |
-
Opções de Resposta:
|
362 |
-
A) Clorofila
|
363 |
-
B) Hemoglobina
|
364 |
-
C) Mioglobina
|
365 |
-
D) Citocromo
|
366 |
-
E) Queratina
|
367 |
-
|
368 |
-
Resposta Correta:
|
369 |
-
A) Clorofila
|
370 |
-
|
371 |
-
Context: {context}
|
372 |
-
Question: {question}
|
373 |
-
Answer:
|
374 |
-
"""
|
375 |
-
|
376 |
-
llm_prompt = PromptTemplate.from_template(llm_prompt_template)
|
377 |
-
|
378 |
-
print(llm_prompt)
|
379 |
-
|
380 |
-
def format_docs(docs):
|
381 |
-
return "\n\n".join(doc.page_content for doc in docs)
|
382 |
-
llm = ChatGoogleGenerativeAI(model="gemini-pro",
|
383 |
-
temperature=0.7, top_p=1)
|
384 |
-
rag_chain = (
|
385 |
-
{"context": retriever | format_docs, "question": RunnablePassthrough()}
|
386 |
-
| llm_prompt
|
387 |
-
| llm
|
388 |
-
| StrOutputParser()
|
389 |
-
)
|
390 |
-
|
391 |
-
start_time = time.time()
|
392 |
-
assunto = "citologia"
|
393 |
-
query = f"Preciso de cinco questões de biologia, sendo do assunto: {assunto}."
|
394 |
-
print(rag_chain.invoke(f"""
|
395 |
-
{query}
|
396 |
-
"""))
|
397 |
-
end_time = time.time()
|
398 |
-
execution_time = end_time - start_time
|
399 |
-
print(f"Tempo de execução: {execution_time:.2f} segundos.")
|
400 |
-
docs = retriever.invoke(f"{query}")
|
401 |
-
len(docs)
|
402 |
-
print(docs)
|
|
|
1 |
+
from inference import rag_chain
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
assunto = "Bioquimica e Biofisica"
|
4 |
query = f"Quero que você gere questões de biologia, sendo do assunto: {assunto}."
|
5 |
res = rag_chain.invoke(f"""{query}""")
|
6 |
+
print(res)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
server/data/load_data.py
ADDED
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from langchain_community.document_loaders import TextLoader
|
3 |
+
from langchain.vectorstores import Chroma
|
4 |
+
from langchain.chains.query_constructor.base import AttributeInfo
|
5 |
+
from langchain.retrievers.self_query.base import SelfQueryRetriever
|
6 |
+
from llm.gemini import gemini_embeddings, llm
|
7 |
+
from utils.questions_parser import parse_question
|
8 |
+
|
9 |
+
if "DATA_PATH" not in os.environ:
|
10 |
+
raise ValueError("DATA_PATH environment variable is not set")
|
11 |
+
|
12 |
+
DATA_PATH = os.environ["DATA_PATH"]
|
13 |
+
|
14 |
+
data_loader = TextLoader(DATA_PATH, encoding = 'UTF-8').load()
|
15 |
+
|
16 |
+
questions = list(
|
17 |
+
map(lambda x: "##Questão" + x, data_loader[0].page_content.split("##Questão"))
|
18 |
+
)
|
19 |
+
|
20 |
+
docs = []
|
21 |
+
|
22 |
+
for question in questions:
|
23 |
+
try:
|
24 |
+
docs.append(parse_question(question))
|
25 |
+
except Exception as e:
|
26 |
+
print(e, question)
|
27 |
+
|
28 |
+
db = Chroma.from_documents(docs, gemini_embeddings)
|
29 |
+
vectorstore = Chroma.from_documents(
|
30 |
+
documents=docs, embedding=gemini_embeddings, persist_directory="./chroma_db"
|
31 |
+
)
|
32 |
+
|
33 |
+
vectorstore_disk = Chroma(
|
34 |
+
persist_directory="./chroma_db", embedding_function=gemini_embeddings
|
35 |
+
)
|
36 |
+
metadata_field_info = [
|
37 |
+
AttributeInfo(
|
38 |
+
name="topico",
|
39 |
+
description="A materia escolar da qual a questão pertence.",
|
40 |
+
type="string",
|
41 |
+
),
|
42 |
+
AttributeInfo(
|
43 |
+
name="assunto",
|
44 |
+
description="O assunto da materia fornecida anteriormente.",
|
45 |
+
type="string",
|
46 |
+
),
|
47 |
+
AttributeInfo(
|
48 |
+
name="dificuldade",
|
49 |
+
description="O nivel de dificuldade para resolver a questao.",
|
50 |
+
type="string",
|
51 |
+
),
|
52 |
+
AttributeInfo(
|
53 |
+
name="tipo",
|
54 |
+
description="O tipo da questao. Pode ser ou Multipla Escolha ou Justificativa",
|
55 |
+
type="string",
|
56 |
+
),
|
57 |
+
]
|
58 |
+
|
59 |
+
document_content_description = "Questões de biologia"
|
60 |
+
|
61 |
+
retriever = SelfQueryRetriever.from_llm(
|
62 |
+
llm, vectorstore, document_content_description, metadata_field_info, verbose=True
|
63 |
+
)
|
server/inference.py
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain.schema.runnable import RunnablePassthrough
|
2 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
3 |
+
from langchain_core.runnables import RunnableLambda
|
4 |
+
|
5 |
+
from llm.gemini import questions_template, format_questions_instructions, questions_parser
|
6 |
+
from data.load_data import retriever
|
7 |
+
|
8 |
+
def get_questions(_dict):
|
9 |
+
question = _dict["question"]
|
10 |
+
context = _dict["context"]
|
11 |
+
messages = questions_template.format_messages(
|
12 |
+
context=context,
|
13 |
+
question=question,
|
14 |
+
format_questions_instructions=format_questions_instructions,
|
15 |
+
)
|
16 |
+
|
17 |
+
chat = ChatGoogleGenerativeAI(model="gemini-pro")
|
18 |
+
response = chat.invoke(messages)
|
19 |
+
return questions_parser.parse(response.content)
|
20 |
+
|
21 |
+
|
22 |
+
def format_docs(docs):
|
23 |
+
return "\n\n".join(doc.page_content for doc in docs)
|
24 |
+
|
25 |
+
|
26 |
+
rag_chain = {
|
27 |
+
"context": retriever | RunnableLambda(format_docs),
|
28 |
+
"question": RunnablePassthrough(),
|
29 |
+
} | RunnableLambda(get_questions)
|
30 |
+
|
31 |
+
|
server/llm/gemini.py
ADDED
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
3 |
+
from langchain_google_genai import GoogleGenerativeAIEmbeddings
|
4 |
+
from langchain import PromptTemplate, LLMChain
|
5 |
+
from langchain.output_parsers import ResponseSchema, StructuredOutputParser
|
6 |
+
from langchain.prompts import ChatPromptTemplate
|
7 |
+
|
8 |
+
if "GOOGLE_API_KEY" not in os.environ:
|
9 |
+
raise ValueError("GOOGLE_API_KEY environment variable is not set")
|
10 |
+
|
11 |
+
llm_prompt_template = """Olá, sou uma IA treinada para gerar conteúdo educacional. Por favor, gere cinco questões de múltipla escolha sobre o seguinte tema:
|
12 |
+
Instruções para cada questão:
|
13 |
+
- Crie uma questão clara e relevante para o tema.
|
14 |
+
- Forneça cinco opções de resposta, rotuladas de A) a E).
|
15 |
+
- Apenas uma das opções de resposta deve ser correta.
|
16 |
+
- Indique a resposta correta ao final de cada questão.
|
17 |
+
|
18 |
+
Exemplo de uma questão:
|
19 |
+
Tema: Fotossíntese
|
20 |
+
|
21 |
+
Questão:
|
22 |
+
Qual é o pigmento primário responsável pela fotossíntese nas plantas?
|
23 |
+
|
24 |
+
Opções de Resposta:
|
25 |
+
A) Clorofila
|
26 |
+
B) Hemoglobina
|
27 |
+
C) Mioglobina
|
28 |
+
D) Citocromo
|
29 |
+
E) Queratina
|
30 |
+
|
31 |
+
Resposta Correta:
|
32 |
+
A) Clorofila
|
33 |
+
|
34 |
+
Context: {context}
|
35 |
+
Question: {question}
|
36 |
+
Answer:
|
37 |
+
|
38 |
+
|
39 |
+
{format_questions_instructions}
|
40 |
+
"""
|
41 |
+
|
42 |
+
llm_prompt = PromptTemplate.from_template(llm_prompt_template)
|
43 |
+
|
44 |
+
gemini_embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
|
45 |
+
|
46 |
+
llm = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.7, top_p=1)
|
47 |
+
|
48 |
+
questions_template = ChatPromptTemplate.from_template(template=llm_prompt_template)
|
49 |
+
|
50 |
+
questions_chain = LLMChain(llm=llm, prompt=questions_template)
|
51 |
+
|
52 |
+
questions_schema = ResponseSchema(
|
53 |
+
name="questions",
|
54 |
+
description="""Give the questions in json as an array""",
|
55 |
+
)
|
56 |
+
|
57 |
+
questions_schemas = [questions_schema]
|
58 |
+
|
59 |
+
questions_parser = StructuredOutputParser.from_response_schemas(questions_schemas)
|
60 |
+
format_questions_instructions = questions_parser.get_format_instructions()
|
61 |
+
format_questions_instructions = """
|
62 |
+
The output should be a markdown code snippet formatted in the following schema, including the leading and trailing "```json" and "```":
|
63 |
+
```json
|
64 |
+
{
|
65 |
+
"questions": [
|
66 |
+
{
|
67 |
+
question: "Qual é o pigmento primário responsável pela fotossíntese nas plantas?",
|
68 |
+
options: ["A) Clorofila",
|
69 |
+
"B) Hemoglobina",
|
70 |
+
"C) Mioglobina",
|
71 |
+
"D) Citocromo",
|
72 |
+
"E) Queratina"],
|
73 |
+
answer: "A"
|
74 |
+
}
|
75 |
+
]
|
76 |
+
```
|
77 |
+
}"""
|
78 |
+
|
79 |
+
|
80 |
+
|
81 |
+
|
82 |
+
|
server/requirements.txt
CHANGED
@@ -1,5 +1,10 @@
|
|
1 |
langchain==0.1.6
|
2 |
-
|
3 |
-
|
4 |
-
|
5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
1 |
langchain==0.1.6
|
2 |
+
chromadb==0.5.0
|
3 |
+
lark==1.1.9
|
4 |
+
langchain-google-genai==1.0.1
|
5 |
+
# langchain-text-splitters==0.0.1
|
6 |
+
langchain-core==0.1.22
|
7 |
+
langchain-community==0.0.20
|
8 |
+
langsmith==0.0.87
|
9 |
+
python-daemon==2.1.2
|
10 |
+
localstack==0.12.0
|
server/utils.py
ADDED
File without changes
|
server/utils/__init__.py
ADDED
File without changes
|
server/utils/questions_parser.py
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain_core.documents import Document
|
2 |
+
|
3 |
+
def parse_question(question_str):
|
4 |
+
# Extract content
|
5 |
+
content_start = question_str.find('"""') + 3
|
6 |
+
content_end = question_str.rfind('"""', content_start)
|
7 |
+
content = question_str[content_start:content_end].strip()
|
8 |
+
|
9 |
+
# Extract correct option
|
10 |
+
correct_option_start = question_str.find('opcao_correta=') + 15
|
11 |
+
correct_option_end = correct_option_start + 1
|
12 |
+
correct_option = question_str[correct_option_start:correct_option_end]
|
13 |
+
|
14 |
+
# Extract metadata
|
15 |
+
metadata_start = question_str.find("metadados=") + 10
|
16 |
+
metadata_end = question_str.find("}", metadata_start) + 1
|
17 |
+
metadata_str = question_str[metadata_start:metadata_end]
|
18 |
+
metadata = eval(metadata_str)
|
19 |
+
|
20 |
+
topico, assunto, dificuldade, tipo = metadata.values()
|
21 |
+
|
22 |
+
return Document(page_content="##Questão\n" + content, metadata={"correct_option":correct_option, "topico":topico, "assunto":assunto, "dificuldade":dificuldade, "tipo":tipo})
|