Create frontend/app.py
Browse files- frontend/app.py +37 -0
frontend/app.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import chainlit as cl
|
| 2 |
+
import httpx
|
| 3 |
+
|
| 4 |
+
# URL do nosso backend FastAPI
|
| 5 |
+
API_URL = "http://localhost:8000/chat"
|
| 6 |
+
|
| 7 |
+
@cl.on_chat_start
|
| 8 |
+
def start():
|
| 9 |
+
cl.user_session.set("history", [])
|
| 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()
|
| 16 |
+
|
| 17 |
+
try:
|
| 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", API_URL, json={"content": message.content}) as response:
|
| 22 |
+
# Se a requisição falhar, mostra um erro
|
| 23 |
+
if response.status_code != 200:
|
| 24 |
+
await msg.update(content=f"Erro: {response.text}")
|
| 25 |
+
return
|
| 26 |
+
|
| 27 |
+
# Itera sobre os pedaços (chunks) de texto recebidos do backend
|
| 28 |
+
async for chunk in response.aiter_text():
|
| 29 |
+
await msg.stream_token(chunk)
|
| 30 |
+
|
| 31 |
+
# Finaliza a mensagem
|
| 32 |
+
await msg.update()
|
| 33 |
+
|
| 34 |
+
except httpx.ConnectError:
|
| 35 |
+
await msg.update(content="Erro de conexão: Não foi possível se conectar ao backend. Verifique se ele está rodando.")
|
| 36 |
+
except Exception as e:
|
| 37 |
+
await msg.update(content=f"Ocorreu um erro: {e}")
|