gemini_chatBot / chat-streamlit-app.py
Rhodham96's picture
change to gemini
0f6bf6d
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()