Search code examples
pythonmachine-learningartificial-intelligencechatbot

Type Error when trying to make a LLM chatbot using Gemini-Pro


Here is the code

import os 

import streamlit as st 
from dotenv import load_dotenv 
import google.generativeai as gen_ai  

load_dotenv() 

st.set_page_config(
    page_title="Chat with Gemini Pro",
    page_icon=":brain:",
    layout="centered" 
)

GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") 
gen_ai.configure(api_key=GOOGLE_API_KEY) 
model = gen_ai.GenerativeModel("gemini-pro") 

def translate_role_for_streamlit(user_role): 
  if user_role == "model": 
    return "assistant" 
  else: 
    return user_role 

if "chat_session" not in st.session_state:
  st.session_state.chat_session = model.start_chat(history=[])
st.title("CAIE Bot") 

for message in st.session_state.chat_session.history:
  with st.chat_message(translate_role_for_streamlit(message.role)): 
    st.markdown(message.parts[0].text) 

user_prompt = st.chat_input("Ask CAIE bot...") 
if user_prompt: 
  st.chat_message("user").markdown(user_prompt) 
  gemini_response = st.session_state.chat_session.send_message(user_prompt) 
  with st.chat_message("assistant"): 
    st.markdown(gemini_response.text)  

!streamlit run main.py

I'm getting error in line

if "chat_session" not in st.session_state:

I wanted to check if user had an active chat with the bot and if it did, then the bot would save it previous conversation history for the next conversation. And after a session is over, history would then reset


Solution

  • The type error is because you are using in on a class that does not store values. in only works on sets, lists, and other data structures that contain values.

    If you want to see whether something has the chat_session attribute, you can try hasattr(st.session_state, "chat_session").

    See also: