File size: 2,498 Bytes
84f5e0b
0f6bf6d
d27dbb4
0f6bf6d
 
84f5e0b
 
0f6bf6d
 
 
 
 
 
 
 
 
 
 
 
 
 
84f5e0b
 
0f6bf6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84f5e0b
0f6bf6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84f5e0b
 
0f6bf6d
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
import streamlit as st
import google.generativeai as genai

# Initialize session state variable for messages
if "messages" not in st.session_state:
    st.session_state.messages = []

def create_sidebar():
    """Creates the sidebar for the app."""
    with st.sidebar:
        st.title("πŸ€– Gemini Chatbot")
        api_key = st.text_input("Google API Key:", type="password", help="Get your API key from Google Cloud")
        st.markdown("""
        ### What is this?
        A simple chatbot powered by the Gemini language model.
        
        ### How to use
        1.  Enter your Google API key in the sidebar.
        2.  Start chatting!
        """)
        return api_key

def main():
    """Main function to run the chatbot app."""
    st.set_page_config(page_title="Gemini Chatbot")
    api_key = create_sidebar()  # Get the API key from the sidebar
    st.title("πŸ’¬ Gemini Chatbot")

    if not api_key:
        st.warning("πŸ‘† Please enter your Google API key in the sidebar to start.")
        return

    # Initialize Gemini model
    genai.configure(api_key=api_key)
    model = genai.GenerativeModel("gemini-2.0-flash")  # Use gemini-pro for chat

    # Display chat history
    st.markdown("### πŸ’­ Chat")
    for message in st.session_state.messages:
        with st.chat_message(message["role"]):
            st.markdown(message["content"])

    # Get user input and generate response
    if prompt := st.chat_input("Say something..."):
        st.session_state.messages.append({"role": "user", "content": prompt})
        with st.chat_message("user"):
            st.markdown(prompt)

        with st.chat_message("assistant"):
            with st.spinner("Thinking..."):
                try:
                    response = model.generate_content(prompt)
                    if response.text:
                        st.markdown(response.text)
                        st.session_state.messages.append({"role": "assistant", "content": response.text})
                    else:
                        st.markdown("Sorry, I couldn't get a response.") # error message
                        st.session_state.messages.append({"role": "assistant", "content": "Sorry, I couldn't get a response."})
                except Exception as e:
                    st.error(f"An error occurred: {e}") # show the error to the user
                    st.session_state.messages.append({"role": "assistant", "content": f"An error occurred: {e}"})

if __name__ == "__main__":
    main()