Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -765,22 +765,15 @@ def groq_with_memory(message: str, topic: str = "general", retries: int = 3) ->
|
|
| 765 |
if not messages:
|
| 766 |
messages = [{"role": "user", "content": message.strip()}]
|
| 767 |
|
| 768 |
-
#
|
| 769 |
payload = {
|
| 770 |
-
"model": "llama3-8b-8192",
|
| 771 |
"messages": [
|
| 772 |
{
|
| 773 |
"role": "system",
|
| 774 |
-
"content": "Kamu adalah asisten kreatif yang
|
| 775 |
-
seperti sahabat jenius yang selalu punya ide segar.
|
| 776 |
-
Tugasmu adalah memberikan saran atau ide-ide kreatif yang out-of-the-box,
|
| 777 |
-
singkat, tajam dan relevan saat saya stuck atau bingung mau ngapain.
|
| 778 |
-
Hindari mengulang kata-kata saya, dan berikan perspektif baru yang bikin saya semangat lagi.
|
| 779 |
-
Gunakan bahasa yang santai, ramah, tapi cerdas.
|
| 780 |
-
Saat memberikan saran dalam bentuk daftar,
|
| 781 |
-
gunakan format berikut: nomor untuk poin utama (contoh: '1. **Judul Poin**:' dengan titik dua), lalu poin-poin pendukung di bawahnya menggunakan tanda titik (contoh: '. Sub-poin satu.'). Pastikan setiap poin utama punya sub-poin yang jelas dan terstruktur."
|
| 782 |
}
|
| 783 |
-
] + messages,
|
| 784 |
"max_tokens": 300,
|
| 785 |
"temperature": 0.9,
|
| 786 |
"frequency_penalty": 0.7,
|
|
@@ -810,101 +803,8 @@ def groq_with_memory(message: str, topic: str = "general", retries: int = 3) ->
|
|
| 810 |
except Exception as e:
|
| 811 |
return f"β Error: {str(e)}", ""
|
| 812 |
|
| 813 |
-
|
| 814 |
-
def cleanup_old_messages(days: int = 30) -> str:
|
| 815 |
-
try:
|
| 816 |
-
cutoff = (datetime.now() - timedelta(days=days)).isoformat()
|
| 817 |
-
with sqlite3.connect(storage.db.db_path) as conn:
|
| 818 |
-
conn.execute('DELETE FROM messages WHERE timestamp < ?', (cutoff,))
|
| 819 |
-
conn.commit()
|
| 820 |
-
storage.chat_history = [msg for msg in storage.chat_history if msg['timestamp'] >= cutoff]
|
| 821 |
-
storage.save_history()
|
| 822 |
-
return f"β
Cleared messages older than {days} days"
|
| 823 |
-
except Exception as e:
|
| 824 |
-
return f"β Failed to clean old messages: {str(e)}"
|
| 825 |
-
|
| 826 |
-
# Helper Functions
|
| 827 |
-
def get_topics_list() -> List[str]:
|
| 828 |
-
"""Retrieve a list of unique topics from the database, ensuring 'journal' is included."""
|
| 829 |
-
try:
|
| 830 |
-
with sqlite3.connect(DATABASE_FILE) as conn:
|
| 831 |
-
cursor = conn.execute('SELECT DISTINCT topic FROM messages ORDER BY topic')
|
| 832 |
-
topics = [row[0] for row in cursor.fetchall()]
|
| 833 |
-
if not topics:
|
| 834 |
-
return ["All Topics", "journal"]
|
| 835 |
-
if "journal" not in topics:
|
| 836 |
-
topics.append("journal")
|
| 837 |
-
return ["All Topics"] + sorted(topics)
|
| 838 |
-
except sqlite3.Error as e:
|
| 839 |
-
print(f"β Error retrieving topics: {str(e)}")
|
| 840 |
-
return ["All Topics", "journal"]
|
| 841 |
-
|
| 842 |
-
def send_message(user_input: str, topic_input: str) -> Tuple[str, str, List[str]]:
|
| 843 |
-
"""Handle sending a user message, getting AI response, and updating topic list."""
|
| 844 |
-
try:
|
| 845 |
-
if not user_input.strip():
|
| 846 |
-
return "β Please enter a message", user_input, get_topics_list()
|
| 847 |
-
if not topic_input.strip():
|
| 848 |
-
return "β Please enter a topic", user_input, get_topics_list()
|
| 849 |
-
|
| 850 |
-
response, error = groq_with_memory(user_input, topic_input)
|
| 851 |
-
if error:
|
| 852 |
-
return f"β {error}", user_input, get_topics_list()
|
| 853 |
-
|
| 854 |
-
return response, "", get_topics_list()
|
| 855 |
-
except Exception as e:
|
| 856 |
-
return f"β Error processing message: {str(e)}", user_input, get_topics_list()
|
| 857 |
-
|
| 858 |
-
def show_current_context() -> str:
|
| 859 |
-
"""Show the current session's conversation context."""
|
| 860 |
-
try:
|
| 861 |
-
messages = storage.get_messages_by_session(storage.current_session_id)
|
| 862 |
-
if not messages:
|
| 863 |
-
return "No messages in the current session."
|
| 864 |
-
context = "\n".join([f"{msg['role'].capitalize()}: {msg['content']}" for msg in messages[-5:]])
|
| 865 |
-
return f"Current Session Context (Last 5 Messages):\n{context}"
|
| 866 |
-
except Exception as e:
|
| 867 |
-
return f"β Error retrieving context: {str(e)}"
|
| 868 |
-
|
| 869 |
-
def get_full_history(topic_filter: str = None) -> str:
|
| 870 |
-
"""Display the full chat history, optionally filtered by topic."""
|
| 871 |
-
try:
|
| 872 |
-
filters = {'topic': topic_filter} if topic_filter and topic_filter != "All Topics" else None
|
| 873 |
-
messages = storage.search_messages("", filters)
|
| 874 |
-
if not messages:
|
| 875 |
-
return "No messages found in the history."
|
| 876 |
-
history = "\n".join([f"[{msg['timestamp']}] {msg['role'].capitalize()} (Topic: {msg['topic']}): {msg['content']}" for msg in messages])
|
| 877 |
-
return f"Chat History:\n{history}"
|
| 878 |
-
except Exception as e:
|
| 879 |
-
return f"β Error retrieving history: {str(e)}"
|
| 880 |
|
| 881 |
-
def get_chat_summary(topic_filter: str = None) -> str:
|
| 882 |
-
"""Provide a summary of the chat history, optionally filtered by topic."""
|
| 883 |
-
try:
|
| 884 |
-
filters = {'topic': topic_filter} if topic_filter and topic_filter != "All Topics" else None
|
| 885 |
-
messages = storage.search_messages("", filters)
|
| 886 |
-
if not messages:
|
| 887 |
-
return "No messages found for summary."
|
| 888 |
-
|
| 889 |
-
total_messages = len(messages)
|
| 890 |
-
user_messages = len([msg for msg in messages if msg['role'] == 'user'])
|
| 891 |
-
assistant_messages = len([msg for msg in messages if msg['role'] == 'assistant'])
|
| 892 |
-
topics = Counter(msg['topic'] for msg in messages)
|
| 893 |
-
sessions = len(set(msg['session_id'] for msg in messages))
|
| 894 |
|
| 895 |
-
summary = (
|
| 896 |
-
f"Chat Summary:\n"
|
| 897 |
-
f"Total Messages: {total_messages}\n"
|
| 898 |
-
f"User Messages: {user_messages}\n"
|
| 899 |
-
f"Assistant Messages: {assistant_messages}\n"
|
| 900 |
-
f"Number of Sessions: {sessions}\n"
|
| 901 |
-
f"Topic Distribution:\n" +
|
| 902 |
-
"\n".join([f" - {topic}: {count}" for topic, count in topics.most_common()])
|
| 903 |
-
)
|
| 904 |
-
return summary
|
| 905 |
-
except Exception as e:
|
| 906 |
-
return f"β Error generating summary: {str(e)}"
|
| 907 |
-
|
| 908 |
def clear_all_history() -> Tuple[str, str, str]:
|
| 909 |
"""Clear all chat history and analytics data."""
|
| 910 |
try:
|
|
|
|
| 765 |
if not messages:
|
| 766 |
messages = [{"role": "user", "content": message.strip()}]
|
| 767 |
|
| 768 |
+
# Updated payload with refined system prompt
|
| 769 |
payload = {
|
| 770 |
+
"model": "llama3-8b-8192",
|
| 771 |
"messages": [
|
| 772 |
{
|
| 773 |
"role": "system",
|
| 774 |
+
"content": "Kamu adalah asisten kreatif yang memberikan ide-ide segar untuk journaling, seperti sahabat jenius yang selalu punya saran inspiratif. Tugasmu adalah memberikan 2-3 ide journaling yang out-of-the-box, singkat, dan relevan saat saya stuck atau bingung. SELALU gunakan format daftar bernomor untuk poin utama (contoh: '1. **Judul Poin**:' dengan titik dua), dengan 2-3 sub-poin di bawahnya menggunakan tanda titik (contoh: '. Sub-poin satu.'). Hindari mengulang kata-kata saya, berikan perspektif baru yang bikin semangat, dan gunakan bahasa santai, ramah, tapi cerdas. Fokus pada ide-ide spesifik untuk menulis di journal, bukan hanya motivasi umum."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 775 |
}
|
| 776 |
+
] + messages,
|
| 777 |
"max_tokens": 300,
|
| 778 |
"temperature": 0.9,
|
| 779 |
"frequency_penalty": 0.7,
|
|
|
|
| 803 |
except Exception as e:
|
| 804 |
return f"β Error: {str(e)}", ""
|
| 805 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 806 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 807 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 808 |
def clear_all_history() -> Tuple[str, str, str]:
|
| 809 |
"""Clear all chat history and analytics data."""
|
| 810 |
try:
|