Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -106,6 +106,8 @@ from chainlit.auth import create_jwt
|
|
| 106 |
from dotenv import load_dotenv
|
| 107 |
import chainlit as cl
|
| 108 |
import uvicorn
|
|
|
|
|
|
|
| 109 |
# Load environment variables from .env file
|
| 110 |
load_dotenv()
|
| 111 |
|
|
@@ -172,14 +174,26 @@ async def on_message(message: cl.Message):
|
|
| 172 |
msg = cl.Message(content="")
|
| 173 |
await msg.send()
|
| 174 |
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
message_history.append({"role": "assistant", "content": msg.content})
|
| 184 |
await msg.update()
|
| 185 |
logger.info("Message processed and response sent.")
|
|
|
|
|
|
| 106 |
from dotenv import load_dotenv
|
| 107 |
import chainlit as cl
|
| 108 |
import uvicorn
|
| 109 |
+
import asyncio
|
| 110 |
+
from socket import gaierror
|
| 111 |
# Load environment variables from .env file
|
| 112 |
load_dotenv()
|
| 113 |
|
|
|
|
| 174 |
msg = cl.Message(content="")
|
| 175 |
await msg.send()
|
| 176 |
|
| 177 |
+
try:
|
| 178 |
+
stream = await client.chat.completions.create(
|
| 179 |
+
messages=message_history, stream=True, **settings
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
async for part in stream:
|
| 183 |
+
if token := part.choices[0].delta.content or "":
|
| 184 |
+
await msg.stream_token(token)
|
| 185 |
+
|
| 186 |
+
except gaierror as e:
|
| 187 |
+
logger.error(f"Network error during OpenAI API call: {e}")
|
| 188 |
+
await msg.update(content="Sorry, there was a network error.")
|
| 189 |
+
except asyncio.TimeoutError:
|
| 190 |
+
logger.error("Timeout error during OpenAI API call.")
|
| 191 |
+
await msg.update(content="Sorry, the request timed out.")
|
| 192 |
+
except Exception as e:
|
| 193 |
+
logger.error(f"Unexpected error during OpenAI API call: {e}")
|
| 194 |
+
await msg.update(content="Sorry, an unexpected error occurred.")
|
| 195 |
|
| 196 |
message_history.append({"role": "assistant", "content": msg.content})
|
| 197 |
await msg.update()
|
| 198 |
logger.info("Message processed and response sent.")
|
| 199 |
+
|