Skip to content

Commit e4ef675

Browse files
Merge pull request #75 from MervinPraison/develop
Adding Log to PraisonAI chat
2 parents 46f8724 + df5d2bc commit e4ef675

File tree

1 file changed

+35
-7
lines changed

1 file changed

+35
-7
lines changed

praisonai/ui/chat.py

Lines changed: 35 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,22 @@
1111
import chainlit.data as cl_data
1212
from chainlit.step import StepDict
1313
from literalai.helper import utc_now
14+
import logging
15+
16+
# Set up logging
17+
logger = logging.getLogger(__name__)
18+
log_level = os.getenv("LOGLEVEL", "INFO").upper()
19+
logger.handlers = []
20+
21+
# Set up logging to console
22+
console_handler = logging.StreamHandler()
23+
console_handler.setLevel(log_level)
24+
console_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
25+
console_handler.setFormatter(console_formatter)
26+
logger.addHandler(console_handler)
27+
28+
# Set the logging level for the logger
29+
logger.setLevel(log_level)
1430

1531
now = utc_now()
1632

@@ -57,7 +73,7 @@ def save_thread_to_db(thread):
5773
# No steps to save as steps are empty in the provided thread data
5874
conn.commit()
5975
conn.close()
60-
print("saved")
76+
logger.debug("Thread saved to DB")
6177

6278
def update_thread_in_db(thread):
6379
conn = sqlite3.connect(DB_PATH)
@@ -70,7 +86,7 @@ def update_thread_in_db(thread):
7086
''', (thread['id'], thread['name'], thread['createdAt'], thread['userId'], thread['userIdentifier']))
7187

7288
# Fetch message_history from metadata
73-
message_history = thread['metadata']['message_history']
89+
message_history = cl.user_session.get("message_history", [])
7490

7591
# Ensure user messages come first followed by assistant messages
7692
user_messages = [msg for msg in message_history if msg['role'] == 'user']
@@ -102,6 +118,7 @@ def update_thread_in_db(thread):
102118

103119
conn.commit()
104120
conn.close()
121+
logger.debug("Thread updated in DB")
105122

106123
def load_threads_from_db():
107124
conn = sqlite3.connect(DB_PATH)
@@ -131,6 +148,7 @@ def load_threads_from_db():
131148
"steps": steps
132149
})
133150
conn.close()
151+
logger.debug("Threads loaded from DB")
134152
return threads
135153

136154
# Initialize the database
@@ -141,9 +159,11 @@ def load_threads_from_db():
141159

142160
class TestDataLayer(cl_data.BaseDataLayer):
143161
async def get_user(self, identifier: str):
162+
logger.debug(f"Getting user: {identifier}")
144163
return cl.PersistedUser(id="test", createdAt=now, identifier=identifier)
145164

146165
async def create_user(self, user: cl.User):
166+
logger.debug(f"Creating user: {user.identifier}")
147167
return cl.PersistedUser(id="test", createdAt=now, identifier=user.identifier)
148168

149169
async def update_thread(
@@ -154,6 +174,7 @@ async def update_thread(
154174
metadata: Optional[Dict] = None,
155175
tags: Optional[List[str]] = None,
156176
):
177+
logger.debug(f"Updating thread: {thread_id}")
157178
thread = next((t for t in thread_history if t["id"] == thread_id), None)
158179
if thread:
159180
if name:
@@ -162,10 +183,11 @@ async def update_thread(
162183
thread["metadata"] = metadata
163184
if tags:
164185
thread["tags"] = tags
165-
update_thread_in_db(thread)
186+
166187
cl.user_session.set("message_history", thread['metadata']['message_history'])
167188
cl.user_session.set("thread_id", thread["id"])
168-
print("Updated")
189+
update_thread_in_db(thread)
190+
logger.debug(f"Thread updated: {thread_id}")
169191

170192
else:
171193
thread_history.append(
@@ -191,6 +213,7 @@ async def update_thread(
191213
"steps": [],
192214
}
193215
save_thread_to_db(thread)
216+
logger.debug(f"Thread created: {thread_id}")
194217

195218
@cl_data.queue_until_user_message()
196219
async def create_step(self, step_dict: StepDict):
@@ -204,11 +227,13 @@ async def create_step(self, step_dict: StepDict):
204227
thread["steps"].append(step_dict)
205228

206229
async def get_thread_author(self, thread_id: str):
230+
logger.debug(f"Getting thread author: {thread_id}")
207231
return "admin"
208232

209233
async def list_threads(
210234
self, pagination: cl_data.Pagination, filters: cl_data.ThreadFilter
211235
) -> cl_data.PaginatedResponse[cl_data.ThreadDict]:
236+
logger.debug(f"Listing threads")
212237
return cl_data.PaginatedResponse(
213238
data=[t for t in thread_history if t["id"] not in deleted_thread_ids],
214239
pageInfo=cl_data.PageInfo(
@@ -217,10 +242,12 @@ async def list_threads(
217242
)
218243

219244
async def get_thread(self, thread_id: str):
245+
logger.debug(f"Getting thread: {thread_id}")
220246
thread_history = load_threads_from_db()
221247
return next((t for t in thread_history if t["id"] == thread_id), None)
222248

223249
async def delete_thread(self, thread_id: str):
250+
logger.debug(f"Deleting thread: {thread_id}")
224251
deleted_thread_ids.append(thread_id)
225252

226253
cl_data._data_layer = TestDataLayer()
@@ -266,9 +293,9 @@ async def main(message: cl.Message):
266293
if token := part['choices'][0]['delta']['content']:
267294
await msg.stream_token(token)
268295
full_response += token
269-
print(full_response)
296+
logger.debug(f"Full response: {full_response}")
270297
message_history.append({"role": "assistant", "content": full_response})
271-
print(message_history)
298+
logger.debug(f"Message history: {message_history}")
272299
cl.user_session.set("message_history", message_history)
273300
await msg.update()
274301

@@ -291,6 +318,7 @@ async def send_count():
291318

292319
@cl.on_chat_resume
293320
async def on_chat_resume(thread: cl_data.ThreadDict):
321+
logger.info(f"Resuming chat: {thread['id']}")
294322
thread_id = thread["id"]
295323
cl.user_session.set("thread_id", thread["id"])
296324
message_history = cl.user_session.get("message_history", [])
@@ -303,6 +331,6 @@ async def on_chat_resume(thread: cl_data.ThreadDict):
303331
elif msg_type == "assistant_message":
304332
message_history.append({"role": "assistant", "content": message.get("output", "")})
305333
else:
306-
print(f"Message without type: {message}")
334+
logger.warning(f"Message without type: {message}")
307335

308336
cl.user_session.set("message_history", message_history)

0 commit comments

Comments
 (0)