NitinBot001 commited on
Commit
2216c04
·
verified ·
1 Parent(s): c4be6e7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -170
app.py CHANGED
@@ -350,171 +350,7 @@ Rules:
350
  Returns:
351
  List of messages with their IDs
352
  """
353
- return self.manager.get_history(chat_id, user_id).tool_calls
354
- ]
355
- })
356
-
357
- # Execute all tool calls
358
- for tool_call in message.tool_calls:
359
- function_name = tool_call.function.name
360
- function_args = json.loads(tool_call.function.arguments)
361
-
362
- logger.info(f"Calling function: {function_name} with args: {function_args}")
363
-
364
- # Call the function
365
- function_result = self.call_function(function_name, function_args)
366
-
367
- # Add function result to messages
368
- messages.append({
369
- "role": "tool",
370
- "tool_call_id": tool_call.id,
371
- "content": json.dumps(function_result)
372
- })
373
-
374
- # Add final system prompt for generating response
375
- messages.append({
376
- "role": "system",
377
- "content": self.final_system
378
- })
379
-
380
- # Get final response
381
- final_response = self.client.chat.completions.create(
382
- model=self.config.model_name,
383
- messages=messages,
384
- temperature=self.config.temperature
385
- )
386
- response_content = final_response.choices[0].message.content
387
- else:
388
- response_content = message.content
389
-
390
- # Add messages to conversation history with unique IDs
391
- user_msg = self.manager.add_message(chat_id, user_id, "user", user_message, image_url)
392
- assistant_msg = self.manager.add_message(chat_id, user_id, "assistant", response_content)
393
-
394
- return {
395
- "response": response_content,
396
- "chat_id": chat_id,
397
- "is_new_chat": is_new_chat,
398
- "user_message_id": user_msg.get("message_id"),
399
- "assistant_message_id": assistant_msg.get("message_id"),
400
- "total_messages": len(self.manager.get_history(chat_id, user_id))
401
- }
402
-
403
- except Exception as e:
404
- logger.error(f"Error processing query for chat {chat_id}, user {user_id}: {e}")
405
- return {
406
- "error": f"I apologize, but I encountered an error: {str(e)}. Please try again or rephrase your question.",
407
- "chat_id": chat_id or self.manager.generate_chat_id(user_id) if user_id else None,
408
- "is_new_chat": True,
409
- "user_message_id": None,
410
- "assistant_message_id": None,
411
- "total_messages": 0
412
- }.tool_calls
413
- ]
414
- })
415
-
416
- # Execute all tool calls
417
- for tool_call in message.tool_calls:
418
- function_name = tool_call.function.name
419
- function_args = json.loads(tool_call.function.arguments)
420
-
421
- logger.info(f"Calling function: {function_name} with args: {function_args}")
422
-
423
- # Call the function
424
- function_result = self.call_function(function_name, function_args)
425
-
426
- # Add function result to messages
427
- messages.append({
428
- "role": "tool",
429
- "tool_call_id": tool_call.id,
430
- "content": json.dumps(function_result)
431
- })
432
-
433
- # Add final system prompt for generating response
434
- messages.append({
435
- "role": "system",
436
- "content": self.final_system
437
- })
438
-
439
- # Get final response
440
- final_response = self.client.chat.completions.create(
441
- model=self.config.model_name,
442
- messages=messages,
443
- temperature=self.config.temperature
444
- )
445
- response_content = final_response.choices[0].message.content
446
- else:
447
- response_content = message.content
448
-
449
- # Add messages to conversation history with unique IDs
450
- user_msg = self.manager.add_message(chat_id, "user", user_message, image_url)
451
- assistant_msg = self.manager.add_message(chat_id, "assistant", response_content)
452
-
453
- return {
454
- "response": response_content,
455
- "chat_id": chat_id,
456
- "is_new_chat": is_new_chat,
457
- "user_message_id": user_msg.get("message_id"),
458
- "assistant_message_id": assistant_msg.get("message_id"),
459
- "total_messages": len(self.manager.get_history(chat_id))
460
- }
461
-
462
- except Exception as e:
463
- logger.error(f"Error processing query for chat {chat_id}: {e}")
464
- return {
465
- "error": f"I apologize, but I encountered an error: {str(e)}. Please try again or rephrase your question.",
466
- "chat_id": chat_id or self.manager.generate_chat_id(),
467
- "is_new_chat": True,
468
- "user_message_id": None,
469
- "assistant_message_id": None,
470
- "total_messages": 0
471
- }
472
-
473
- def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
474
- """
475
- Get information about a specific chat
476
-
477
- Args:
478
- chat_id: The chat ID to get information for
479
-
480
- Returns:
481
- Dictionary with chat information
482
- """
483
- return self.manager.get_chat_info(chat_id)
484
-
485
- def get_all_chats(self) -> List[Dict[str, Any]]:
486
- """
487
- Get all chat sessions
488
-
489
- Returns:
490
- List of chat session information
491
- """
492
- return self.manager.get_all_chat_sessions()
493
-
494
- def clear_history(self, chat_id: str) -> bool:
495
- """
496
- Clear conversation history for a specific chat
497
-
498
- Args:
499
- chat_id: The ID of the chat to clear
500
-
501
- Returns:
502
- True if deletion was successful, False otherwise
503
- """
504
- logger.info(f"Clearing history for chat: {chat_id}")
505
- return self.manager.delete_history(chat_id)
506
-
507
- def get_messages(self, chat_id: str) -> List[Dict[str, Any]]:
508
- """
509
- Get all messages for a specific chat
510
-
511
- Args:
512
- chat_id: The chat ID to get messages for
513
-
514
- Returns:
515
- List of messages with their IDs
516
- """
517
- return self.manager.get_history(chat_id)
518
 
519
 
520
  # Utility class for generating example queries (can be used for testing)
@@ -571,7 +407,7 @@ def test_conversation_management():
571
 
572
  # Test 1: New conversation
573
  print("\n=== Test 1: New Conversation ===")
574
- result1 = assistant.process_query("Hello, I need help with farming")
575
  print(f"Chat ID: {result1['chat_id']}")
576
  print(f"Is new chat: {result1['is_new_chat']}")
577
  print(f"User message ID: {result1['user_message_id']}")
@@ -581,7 +417,7 @@ def test_conversation_management():
581
  # Test 2: Continue conversation
582
  print("\n=== Test 2: Continue Conversation ===")
583
  chat_id = result1['chat_id']
584
- result2 = assistant.process_query("What crops grow well in sandy soil?", chat_id=chat_id)
585
  print(f"Chat ID: {result2['chat_id']}")
586
  print(f"Is new chat: {result2['is_new_chat']}")
587
  print(f"User message ID: {result2['user_message_id']}")
@@ -590,20 +426,20 @@ def test_conversation_management():
590
 
591
  # Test 3: Get messages
592
  print(f"\n=== Test 3: Messages in chat {chat_id} ===")
593
- messages = assistant.get_messages(chat_id)
594
  for msg in messages:
595
  print(f" Message {msg.get('message_id')}: {msg.get('role')} - {msg.get('content')[:50]}...")
596
 
597
  # Test 4: User-defined chat ID
598
  print("\n=== Test 4: User-defined Chat ID ===")
599
  custom_chat_id = "my_farming_chat_2024"
600
- result3 = assistant.process_query("Tell me about wheat farming", chat_id=custom_chat_id)
601
  print(f"Custom chat ID: {result3['chat_id']}")
602
  print(f"Is new chat: {result3['is_new_chat']}")
603
 
604
  # Test 5: Get all chats
605
  print("\n=== Test 5: All Chats ===")
606
- all_chats = assistant.get_all_chats()
607
  for chat in all_chats[:3]: # Show first 3
608
  print(f" {chat.get('session_id')}: {chat.get('title')} ({chat.get('message_count')} messages)")
609
 
 
350
  Returns:
351
  List of messages with their IDs
352
  """
353
+ return self.manager.get_history(chat_id, user_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
 
355
 
356
  # Utility class for generating example queries (can be used for testing)
 
407
 
408
  # Test 1: New conversation
409
  print("\n=== Test 1: New Conversation ===")
410
+ result1 = assistant.process_query("Hello, I need help with farming", "test_user_123")
411
  print(f"Chat ID: {result1['chat_id']}")
412
  print(f"Is new chat: {result1['is_new_chat']}")
413
  print(f"User message ID: {result1['user_message_id']}")
 
417
  # Test 2: Continue conversation
418
  print("\n=== Test 2: Continue Conversation ===")
419
  chat_id = result1['chat_id']
420
+ result2 = assistant.process_query("What crops grow well in sandy soil?", "test_user_123", chat_id=chat_id)
421
  print(f"Chat ID: {result2['chat_id']}")
422
  print(f"Is new chat: {result2['is_new_chat']}")
423
  print(f"User message ID: {result2['user_message_id']}")
 
426
 
427
  # Test 3: Get messages
428
  print(f"\n=== Test 3: Messages in chat {chat_id} ===")
429
+ messages = assistant.get_messages(chat_id, "test_user_123")
430
  for msg in messages:
431
  print(f" Message {msg.get('message_id')}: {msg.get('role')} - {msg.get('content')[:50]}...")
432
 
433
  # Test 4: User-defined chat ID
434
  print("\n=== Test 4: User-defined Chat ID ===")
435
  custom_chat_id = "my_farming_chat_2024"
436
+ result3 = assistant.process_query("Tell me about wheat farming", "test_user_123", chat_id=custom_chat_id)
437
  print(f"Custom chat ID: {result3['chat_id']}")
438
  print(f"Is new chat: {result3['is_new_chat']}")
439
 
440
  # Test 5: Get all chats
441
  print("\n=== Test 5: All Chats ===")
442
+ all_chats = assistant.get_all_chats("test_user_123")
443
  for chat in all_chats[:3]: # Show first 3
444
  print(f" {chat.get('session_id')}: {chat.get('title')} ({chat.get('message_count')} messages)")
445