@@ -279,37 +279,41 @@ def create_chat_histories(
279
279
return chat_histories
280
280
281
281
282
- async def get_analytics (email : str ):
282
+ async def get_analytics (chatbot_id : str ):
283
283
with Session () as session :
284
284
chat_histories = []
285
285
286
- # Step 1: Get chatbot_ids associated with the given email
287
- chatbot_ids = session .query (Chatbot .id ).filter (Chatbot .email == email ).all ()
288
-
289
- if chatbot_ids :
290
- chatbot_ids = [chatbot_id [0 ] for chatbot_id in chatbot_ids ]
291
-
292
- # Step 2: Get analytics data in a single query
293
- analytics_data = (
294
- session .query (
295
- func .sum (func .cast (ChatHistory .api_called , Integer )).label ("api_called_count" ),
296
- func .sum (func .cast (ChatHistory .knowledgebase_called , Integer )).label ("knowledgebase_called_count" ),
297
- func .count ().label ("total" ),
298
- func .sum (func .cast (
299
- ~ ChatHistory .api_called & ~ ChatHistory .knowledgebase_called , Integer )).label ("other_count" )
300
- )
301
- .filter (ChatHistory .chatbot_id .in_ (chatbot_ids ))
302
- .one ()
286
+ # Step 2: Get analytics data in a single query
287
+ analytics_data = (
288
+ session .query (
289
+ func .sum (func .cast (ChatHistory .api_called , Integer )).label (
290
+ "api_called_count"
291
+ ),
292
+ func .sum (func .cast (ChatHistory .knowledgebase_called , Integer )).label (
293
+ "knowledgebase_called_count"
294
+ ),
295
+ func .count ().label ("total" ),
296
+ func .sum (
297
+ func .cast (
298
+ ~ ChatHistory .api_called & ~ ChatHistory .knowledgebase_called ,
299
+ Integer ,
300
+ )
301
+ ).label ("other_count" ),
303
302
)
303
+ .filter (ChatHistory .chatbot_id == chatbot_id )
304
+ .one ()
305
+ )
304
306
305
- # Append the results to chat_histories
306
- chat_histories .append (
307
- {
308
- "api_called_count" : analytics_data .api_called_count or 0 ,
309
- "knowledgebase_called_count" : analytics_data .knowledgebase_called_count or 0 ,
310
- "total" : analytics_data .total or 0 ,
311
- "other_count" : analytics_data .other_count or 0 ,
312
- }
313
- )
307
+ # Append the results to chat_histories
308
+ chat_histories .append (
309
+ {
310
+ "api_called_count" : int (analytics_data .api_called_count or 0 ),
311
+ "knowledgebase_called_count" : int (
312
+ analytics_data .knowledgebase_called_count or 0
313
+ ),
314
+ "total" : int (analytics_data .total or 0 ),
315
+ "other_count" : int (analytics_data .other_count or 0 ),
316
+ }
317
+ )
314
318
315
319
return chat_histories
0 commit comments