Update frontend/app.py
Browse files- frontend/app.py +81 -7
frontend/app.py
CHANGED
|
@@ -1,15 +1,84 @@
|
|
|
|
|
|
|
|
| 1 |
import chainlit as cl
|
| 2 |
import httpx
|
| 3 |
|
| 4 |
# URL do nosso backend FastAPI
|
| 5 |
-
API_URL = "http://localhost:8000
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
@cl.on_chat_start
|
| 8 |
-
def start():
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
@cl.on_message
|
| 12 |
async def main(message: cl.Message):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
# Cria uma mensagem de resposta vazia para preencher com o stream
|
| 14 |
msg = cl.Message(content="")
|
| 15 |
await msg.send()
|
|
@@ -18,10 +87,11 @@ async def main(message: cl.Message):
|
|
| 18 |
# Usamos httpx para fazer uma requisição de streaming para o nosso backend
|
| 19 |
async with httpx.AsyncClient(timeout=60) as client:
|
| 20 |
# Fazemos um POST para o endpoint /chat com a mensagem do usuário
|
| 21 |
-
async with client.stream("POST",
|
| 22 |
# Se a requisição falhar, mostra um erro
|
| 23 |
if response.status_code != 200:
|
| 24 |
-
|
|
|
|
| 25 |
return
|
| 26 |
|
| 27 |
# Itera sobre os pedaços (chunks) de texto recebidos do backend
|
|
@@ -32,6 +102,10 @@ async def main(message: cl.Message):
|
|
| 32 |
await msg.update()
|
| 33 |
|
| 34 |
except httpx.ConnectError:
|
| 35 |
-
|
|
|
|
| 36 |
except Exception as e:
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#--- START OF FILE app (24).py ---
|
| 2 |
+
|
| 3 |
import chainlit as cl
|
| 4 |
import httpx
|
| 5 |
|
| 6 |
# URL do nosso backend FastAPI
|
| 7 |
+
API_URL = "http://localhost:8000"
|
| 8 |
+
UPLOAD_URL = f"{API_URL}/upload-document"
|
| 9 |
+
CHAT_URL = f"{API_URL}/chat"
|
| 10 |
+
|
| 11 |
+
# Flag para saber se o RAG está inicializado
|
| 12 |
+
RAG_INITIALIZED = False
|
| 13 |
|
| 14 |
@cl.on_chat_start
|
| 15 |
+
async def start():
|
| 16 |
+
global RAG_INITIALIZED
|
| 17 |
+
RAG_INITIALIZED = False
|
| 18 |
+
|
| 19 |
+
# Mensagem de instrução inicial
|
| 20 |
+
await cl.Message(
|
| 21 |
+
content="Olá! Para começar, por favor, **faça o upload de um arquivo PDF** para eu usar como contexto. Após o upload, poderemos conversar sobre o conteúdo do documento.",
|
| 22 |
+
author="Sistema"
|
| 23 |
+
).send()
|
| 24 |
+
|
| 25 |
+
# Pede o upload do arquivo
|
| 26 |
+
files = await cl.AskFileMessage(
|
| 27 |
+
content="Faça o upload do PDF:",
|
| 28 |
+
accept=["application/pdf"],
|
| 29 |
+
max_size_mb=20,
|
| 30 |
+
timeout=180,
|
| 31 |
+
).send()
|
| 32 |
+
|
| 33 |
+
if files:
|
| 34 |
+
file = files[0]
|
| 35 |
+
msg = cl.Message(content=f"Recebido: {file.name}. Processando...", author="Sistema")
|
| 36 |
+
await msg.send()
|
| 37 |
+
|
| 38 |
+
# Envia o arquivo para o backend
|
| 39 |
+
try:
|
| 40 |
+
async with httpx.AsyncClient(timeout=300) as client:
|
| 41 |
+
# Usamos form-data para enviar o arquivo
|
| 42 |
+
response = await client.post(
|
| 43 |
+
UPLOAD_URL,
|
| 44 |
+
files={"file": (file.name, file.content, file.mime)}
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
# Se o upload/processamento for bem-sucedido
|
| 48 |
+
if response.status_code == 200:
|
| 49 |
+
RAG_INITIALIZED = True
|
| 50 |
+
# CORREÇÃO: Uso correto do msg.update(content)
|
| 51 |
+
await msg.update(
|
| 52 |
+
f"✅ **{file.name}** processado com sucesso! Agora você pode fazer perguntas sobre o conteúdo do documento.",
|
| 53 |
+
author="Sistema"
|
| 54 |
+
)
|
| 55 |
+
else:
|
| 56 |
+
RAG_INITIALIZED = False
|
| 57 |
+
# CORREÇÃO: Uso correto do msg.update(content)
|
| 58 |
+
error_detail = response.json().get('detail', 'Erro desconhecido')
|
| 59 |
+
await msg.update(
|
| 60 |
+
f"❌ Erro ao processar o arquivo. Código: {response.status_code}. Detalhe: {error_detail}",
|
| 61 |
+
author="Sistema"
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
except httpx.ConnectError:
|
| 65 |
+
# CORREÇÃO: Uso correto do msg.update(content)
|
| 66 |
+
await msg.update("Erro de conexão: Não foi possível se conectar ao backend. Verifique se ele está rodando.", author="Sistema")
|
| 67 |
+
except Exception as e:
|
| 68 |
+
# CORREÇÃO: Uso correto do msg.update(content)
|
| 69 |
+
await msg.update(f"Ocorreu um erro: {e}", author="Sistema")
|
| 70 |
|
| 71 |
@cl.on_message
|
| 72 |
async def main(message: cl.Message):
|
| 73 |
+
global RAG_INITIALIZED
|
| 74 |
+
|
| 75 |
+
if not RAG_INITIALIZED:
|
| 76 |
+
await cl.Message(
|
| 77 |
+
content="Por favor, aguarde o processamento do arquivo ou recarregue a página para um novo upload.",
|
| 78 |
+
author="Sistema"
|
| 79 |
+
).send()
|
| 80 |
+
return
|
| 81 |
+
|
| 82 |
# Cria uma mensagem de resposta vazia para preencher com o stream
|
| 83 |
msg = cl.Message(content="")
|
| 84 |
await msg.send()
|
|
|
|
| 87 |
# Usamos httpx para fazer uma requisição de streaming para o nosso backend
|
| 88 |
async with httpx.AsyncClient(timeout=60) as client:
|
| 89 |
# Fazemos um POST para o endpoint /chat com a mensagem do usuário
|
| 90 |
+
async with client.stream("POST", CHAT_URL, json={"content": message.content}) as response:
|
| 91 |
# Se a requisição falhar, mostra um erro
|
| 92 |
if response.status_code != 200:
|
| 93 |
+
# CORREÇÃO: Uso correto do msg.update(content)
|
| 94 |
+
await msg.update(f"Erro: {response.text}")
|
| 95 |
return
|
| 96 |
|
| 97 |
# Itera sobre os pedaços (chunks) de texto recebidos do backend
|
|
|
|
| 102 |
await msg.update()
|
| 103 |
|
| 104 |
except httpx.ConnectError:
|
| 105 |
+
# CORREÇÃO: Uso correto do msg.update(content)
|
| 106 |
+
await msg.update("Erro de conexão: Não foi possível se conectar ao backend. Verifique se ele está rodando.")
|
| 107 |
except Exception as e:
|
| 108 |
+
# CORREÇÃO: Uso correto do msg.update(content)
|
| 109 |
+
await msg.update(f"Ocorreu um erro: {e}")
|
| 110 |
+
|
| 111 |
+
#--- END OF FILE app (24).py ---
|