Spaces:
Sleeping
Sleeping
Commit
·
dcc08e1
1
Parent(s):
c7397e8
Correções e evoluções
Browse files
app.py
CHANGED
|
@@ -7,6 +7,7 @@ import time
|
|
| 7 |
import os
|
| 8 |
import uuid
|
| 9 |
import threading
|
|
|
|
| 10 |
|
| 11 |
# Importações do LangChain
|
| 12 |
from langchain.prompts import PromptTemplate
|
|
@@ -65,11 +66,9 @@ def process():
|
|
| 65 |
rag_context = get_relevant_context(file_paths, solicitacao_usuario)
|
| 66 |
|
| 67 |
if processing_mode == 'atomic':
|
| 68 |
-
# --- LÓGICA ATÔMICA (PARALELA) CORRIGIDA ---
|
| 69 |
results = {}
|
| 70 |
threads = []
|
| 71 |
|
| 72 |
-
# --- FUNÇÃO ATUALIZADA COM TIMEOUT ---
|
| 73 |
def run_chain_with_timeout(chain, inputs, key, timeout=300):
|
| 74 |
def task():
|
| 75 |
return chain.invoke(inputs)['text']
|
|
@@ -93,7 +92,6 @@ def process():
|
|
| 93 |
|
| 94 |
for name, llm in models.items():
|
| 95 |
chain = LLMChain(llm=llm, prompt=prompt)
|
| 96 |
-
# A thread agora chama a função com timeout
|
| 97 |
thread = threading.Thread(target=run_chain_with_timeout, args=(chain, {"solicitacao_usuario": solicitacao_usuario, "rag_context": rag_context}, name))
|
| 98 |
threads.append(thread)
|
| 99 |
thread.start()
|
|
@@ -101,15 +99,11 @@ def process():
|
|
| 101 |
for thread in threads:
|
| 102 |
thread.join()
|
| 103 |
|
| 104 |
-
# --- NOVA VALIDAÇÃO APÓS A CONCLUSÃO DAS THREADS ---
|
| 105 |
for key, result in results.items():
|
| 106 |
-
if result == "Error:EmptyResponse":
|
| 107 |
-
error_msg = f"Falha no serviço {key.upper()}: Sem resposta."
|
| 108 |
yield f"data: {json.dumps({'error': error_msg})}\n\n"
|
| 109 |
-
return
|
| 110 |
-
elif isinstance(result, str) and result.startswith("Erro ao processar"):
|
| 111 |
-
yield f"data: {json.dumps({'error': result})}\n\n"
|
| 112 |
-
return # Interrompe o processo
|
| 113 |
|
| 114 |
yield f"data: {json.dumps({'progress': 80, 'message': 'Todos os modelos responderam. Formatando saída...'})}\n\n"
|
| 115 |
|
|
@@ -132,7 +126,7 @@ def process():
|
|
| 132 |
yield f"data: {json.dumps({'progress': 33, 'message': 'Agora, o Claude Sonnet está aprofundando o texto...', 'partial_result': {'id': 'grok-output', 'content': grok_html}})}\n\n"
|
| 133 |
|
| 134 |
prompt_sonnet = PromptTemplate(template=PROMPT_HIERARQUICO_SONNET, input_variables=["solicitacao_usuario", "texto_para_analise"])
|
| 135 |
-
claude_with_max_tokens = claude_llm.bind(max_tokens=
|
| 136 |
chain_sonnet = LLMChain(llm=claude_with_max_tokens, prompt=prompt_sonnet)
|
| 137 |
resposta_sonnet = chain_sonnet.invoke({"solicitacao_usuario": solicitacao_usuario, "texto_para_analise": resposta_grok})['text']
|
| 138 |
if not resposta_sonnet or not resposta_sonnet.strip(): raise ValueError("Falha no serviço Claude Sonnet: Sem resposta.")
|
|
@@ -145,13 +139,14 @@ def process():
|
|
| 145 |
if not resposta_gemini or not resposta_gemini.strip(): raise ValueError("Falha no serviço Gemini: Sem resposta.")
|
| 146 |
gemini_html = markdown2.markdown(resposta_gemini, extras=["fenced-code-blocks", "tables"])
|
| 147 |
yield f"data: {json.dumps({'progress': 100, 'message': 'Processamento concluído!', 'partial_result': {'id': 'gemini-output', 'content': gemini_html}, 'done': True, 'mode': 'hierarchical'})}\n\n"
|
|
|
|
| 148 |
except Exception as e:
|
| 149 |
print(f"Ocorreu um erro durante o processamento: {e}")
|
| 150 |
yield f"data: {json.dumps({'error': f'Ocorreu um erro inesperado na aplicação: {e}'})}\n\n"
|
| 151 |
|
| 152 |
return Response(generate_stream(mode, form_data, temp_file_paths), mimetype='text/event-stream')
|
| 153 |
|
| 154 |
-
# --- ROTA
|
| 155 |
@app.route('/merge', methods=['POST'])
|
| 156 |
def merge():
|
| 157 |
data = request.get_json()
|
|
@@ -162,7 +157,6 @@ def merge():
|
|
| 162 |
|
| 163 |
prompt_merge = PromptTemplate(template=PROMPT_ATOMICO_MERGE, input_variables=["solicitacao_usuario", "texto_para_analise_grok", "texto_para_analise_sonnet", "texto_para_analise_gemini"])
|
| 164 |
|
| 165 |
-
# ATUALIZAÇÃO: O merge agora será feito pelo GROK
|
| 166 |
chain_merge = LLMChain(llm=grok_llm, prompt=prompt_merge)
|
| 167 |
|
| 168 |
yield f"data: {json.dumps({'progress': 50, 'message': 'Enviando textos para o GROK para consolidação...'})}\n\n"
|
|
@@ -177,11 +171,9 @@ def merge():
|
|
| 177 |
if not resposta_merge or not resposta_merge.strip():
|
| 178 |
raise ValueError("Falha no serviço de Merge (GROK): Sem resposta.")
|
| 179 |
|
| 180 |
-
# --- NOVA LÓGICA: CALCULAR PALAVRAS ---
|
| 181 |
word_count = len(resposta_merge.split())
|
| 182 |
merge_html = markdown2.markdown(resposta_merge, extras=["fenced-code-blocks", "tables"])
|
| 183 |
|
| 184 |
-
# Envia o resultado final junto com a contagem de palavras
|
| 185 |
yield f"data: {json.dumps({'progress': 100, 'message': 'Merge concluído!', 'final_result': {'content': merge_html, 'word_count': word_count}, 'done': True})}\n\n"
|
| 186 |
|
| 187 |
except Exception as e:
|
|
|
|
| 7 |
import os
|
| 8 |
import uuid
|
| 9 |
import threading
|
| 10 |
+
import concurrent.futures # Nova importação para timeout
|
| 11 |
|
| 12 |
# Importações do LangChain
|
| 13 |
from langchain.prompts import PromptTemplate
|
|
|
|
| 66 |
rag_context = get_relevant_context(file_paths, solicitacao_usuario)
|
| 67 |
|
| 68 |
if processing_mode == 'atomic':
|
|
|
|
| 69 |
results = {}
|
| 70 |
threads = []
|
| 71 |
|
|
|
|
| 72 |
def run_chain_with_timeout(chain, inputs, key, timeout=300):
|
| 73 |
def task():
|
| 74 |
return chain.invoke(inputs)['text']
|
|
|
|
| 92 |
|
| 93 |
for name, llm in models.items():
|
| 94 |
chain = LLMChain(llm=llm, prompt=prompt)
|
|
|
|
| 95 |
thread = threading.Thread(target=run_chain_with_timeout, args=(chain, {"solicitacao_usuario": solicitacao_usuario, "rag_context": rag_context}, name))
|
| 96 |
threads.append(thread)
|
| 97 |
thread.start()
|
|
|
|
| 99 |
for thread in threads:
|
| 100 |
thread.join()
|
| 101 |
|
|
|
|
| 102 |
for key, result in results.items():
|
| 103 |
+
if result == "Error:EmptyResponse" or "Erro ao processar" in result:
|
| 104 |
+
error_msg = result if "Erro ao processar" in result else f"Falha no serviço {key.upper()}: Sem resposta."
|
| 105 |
yield f"data: {json.dumps({'error': error_msg})}\n\n"
|
| 106 |
+
return
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
yield f"data: {json.dumps({'progress': 80, 'message': 'Todos os modelos responderam. Formatando saída...'})}\n\n"
|
| 109 |
|
|
|
|
| 126 |
yield f"data: {json.dumps({'progress': 33, 'message': 'Agora, o Claude Sonnet está aprofundando o texto...', 'partial_result': {'id': 'grok-output', 'content': grok_html}})}\n\n"
|
| 127 |
|
| 128 |
prompt_sonnet = PromptTemplate(template=PROMPT_HIERARQUICO_SONNET, input_variables=["solicitacao_usuario", "texto_para_analise"])
|
| 129 |
+
claude_with_max_tokens = claude_llm.bind(max_tokens=8000)
|
| 130 |
chain_sonnet = LLMChain(llm=claude_with_max_tokens, prompt=prompt_sonnet)
|
| 131 |
resposta_sonnet = chain_sonnet.invoke({"solicitacao_usuario": solicitacao_usuario, "texto_para_analise": resposta_grok})['text']
|
| 132 |
if not resposta_sonnet or not resposta_sonnet.strip(): raise ValueError("Falha no serviço Claude Sonnet: Sem resposta.")
|
|
|
|
| 139 |
if not resposta_gemini or not resposta_gemini.strip(): raise ValueError("Falha no serviço Gemini: Sem resposta.")
|
| 140 |
gemini_html = markdown2.markdown(resposta_gemini, extras=["fenced-code-blocks", "tables"])
|
| 141 |
yield f"data: {json.dumps({'progress': 100, 'message': 'Processamento concluído!', 'partial_result': {'id': 'gemini-output', 'content': gemini_html}, 'done': True, 'mode': 'hierarchical'})}\n\n"
|
| 142 |
+
|
| 143 |
except Exception as e:
|
| 144 |
print(f"Ocorreu um erro durante o processamento: {e}")
|
| 145 |
yield f"data: {json.dumps({'error': f'Ocorreu um erro inesperado na aplicação: {e}'})}\n\n"
|
| 146 |
|
| 147 |
return Response(generate_stream(mode, form_data, temp_file_paths), mimetype='text/event-stream')
|
| 148 |
|
| 149 |
+
# --- ROTA PARA O MERGE ---
|
| 150 |
@app.route('/merge', methods=['POST'])
|
| 151 |
def merge():
|
| 152 |
data = request.get_json()
|
|
|
|
| 157 |
|
| 158 |
prompt_merge = PromptTemplate(template=PROMPT_ATOMICO_MERGE, input_variables=["solicitacao_usuario", "texto_para_analise_grok", "texto_para_analise_sonnet", "texto_para_analise_gemini"])
|
| 159 |
|
|
|
|
| 160 |
chain_merge = LLMChain(llm=grok_llm, prompt=prompt_merge)
|
| 161 |
|
| 162 |
yield f"data: {json.dumps({'progress': 50, 'message': 'Enviando textos para o GROK para consolidação...'})}\n\n"
|
|
|
|
| 171 |
if not resposta_merge or not resposta_merge.strip():
|
| 172 |
raise ValueError("Falha no serviço de Merge (GROK): Sem resposta.")
|
| 173 |
|
|
|
|
| 174 |
word_count = len(resposta_merge.split())
|
| 175 |
merge_html = markdown2.markdown(resposta_merge, extras=["fenced-code-blocks", "tables"])
|
| 176 |
|
|
|
|
| 177 |
yield f"data: {json.dumps({'progress': 100, 'message': 'Merge concluído!', 'final_result': {'content': merge_html, 'word_count': word_count}, 'done': True})}\n\n"
|
| 178 |
|
| 179 |
except Exception as e:
|