File size: 5,267 Bytes
9f54a3b
877a721
2506825
 
1311090
 
9f54a3b
1311090
2506825
9f54a3b
1311090
2506825
 
6307698
2506825
01d4f3f
6e2a9c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dac4be
6e2a9c8
 
 
 
 
fadd816
 
6e2a9c8
 
1311090
6e2a9c8
 
 
bc9d32e
6e2a9c8
1b110d7
1311090
6e2a9c8
 
9f54a3b
1311090
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6307698
c7d20e2
 
6307698
c7d20e2
121058e
1311090
 
 
 
9e4c880
4700e8c
 
1311090
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e8f8a5f
4f4ef99
8ccf576
ab1a8b0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import streamlit as st
import requests
import os
from dotenv import load_dotenv
from requests.exceptions import RequestException, HTTPError, ConnectionError, Timeout, TooManyRedirects, JSONDecodeError
from textblob import TextBlob

# Load environment variables
load_dotenv()

# Function to reset conversation
def reset_conversation():
    st.session_state.messages = []
    st.session_state.ask_intervention = False
    return None

# Function to interact with the selected model via the Together API
def interact_with_together_api(messages, model_link):
    all_messages = []

    if not any("role" in msg for msg in messages):
        all_messages.append({"role": "system", "content": model_pre_instructions[selected_model]})
    else:
        all_messages.append({"role": "system", "content": f"Switched to model: {selected_model}"})

    for human, assistant in messages:
        all_messages.append({"role": "user", "content": human})
        all_messages.append({"role": "assistant", "content": assistant})

    all_messages.append({"role": "user", "content": messages[-1][1]})

    url = "https://api.together.xyz/v1/chat/completions"
    payload = {
        "model": model_link,
        "temperature": 1.05,
        "top_p": 0.9,
        "top_k": 50,
        "repetition_penalty": 1,
        "n": 1,
        "messages": all_messages,
    }

    TOGETHER_API_KEY = os.getenv('TOGETHER_API_KEY')
    headers = {
        "accept": "application/json",
        "content-type": "application/json",
        "Authorization": f"Bearer {TOGETHER_API_KEY}",
    }

    try:
        response = requests.post(url, json=payload, headers=headers)
        response.raise_for_status()

        response_data = response.json()
        assistant_response = response_data["choices"][0]["message"]["content"]

        return assistant_response

    except (HTTPError, ConnectionError, Timeout, TooManyRedirects) as e:
        st.error(f"Error communicating with the API: {e}")
        return None

    except JSONDecodeError as e:
        st.error(f"Error decoding JSON response: {e}")
        return None

    except RequestException as e:
        st.error(f"RequestException: {e}")
        return None

# Function to perform sentiment analysis on the conversation
def analyze_sentiment(messages):
    sentiments = []
    for _, message in messages:
        blob = TextBlob(message)
        sentiment_score = blob.sentiment.polarity
        sentiments.append(sentiment_score)
    
    # Calculate average sentiment score
    average_sentiment = sum(sentiments) / len(sentiments)
    return average_sentiment

# Initialize chat history and session state attributes
if "messages" not in st.session_state:
    st.session_state.messages = []
    st.session_state.ask_intervention = False

# Create sidebar with model selection dropdown and reset button
model_links = {
    "Addiction recovery AI": "NousResearch/Nous-Hermes-2-Yi-34B",
    "Mental health AI": "NousResearch/Nous-Hermes-2-Yi-34B"
}
selected_model = st.sidebar.selectbox("Select Model", list(model_links.keys()))
reset_button = st.sidebar.button('Reset Chat', on_click=reset_conversation)

# Accept user input with input validation
max_input_length = 100  # Maximum allowed character limit for user input
if prompt := st.chat_input(f"Hi, I'm {selected_model}, let's chat (Max {max_input_length} characters)"):
    if len(prompt) > max_input_length:
        st.error(f"Maximum input length exceeded. Please limit your input to {max_input_length} characters.")
    else:
        with st.chat_message("user"):
            st.markdown(prompt)
        st.session_state.messages.append(("user", prompt))

        # Interact with the selected model
        assistant_response = interact_with_together_api(st.session_state.messages, model_links[selected_model])

        if assistant_response is not None:
            with st.empty():
                st.markdown("AI is typing...")
                st.empty()
                st.markdown(assistant_response)

                if any(keyword in prompt.lower() for keyword in ["human", "therapist", "someone", "died", "death", "help", "suicide", "suffering", "crisis", "emergency", "support", "depressed", "anxiety", "lonely", "desperate", "struggling", "counseling", "distressed", "hurt", "pain", "grief", "trauma", "abuse", "danger", "risk", "urgent", "need assistance"]):
                    if not st.session_state.ask_intervention:
                        if st.button("After the analyzing our session you may need some extra help, so you can reach out to a certified therapist at +25493609747 Name: Ogega feel free to talk"):
                            st.write("You can reach out to a certified therapist at +25493609747.")

            st.session_state.messages.append(("assistant", assistant_response))

# Display conversation insights
st.sidebar.subheader("Conversation Insights")
average_sentiment = analyze_sentiment(st.session_state.messages)
st.sidebar.write(f"Average Sentiment: {average_sentiment}")

# Add logo and text to the sidebar
st.sidebar.image("https://assets.isu.pub/document-structure/221118065013-a6029cf3d563afaf9b946bb9497d45d4/v1/2841525b232adaef7bd0efe1da81a4c5.jpeg", width=200)
st.sidebar.write("A product proudly developed by Kisii University")