Spaces:
Runtime error
Runtime error
import streamlit as st | |
import pandas as pd | |
import numpy as np | |
import google.generativeai as genai | |
# API key | |
genai.configure(api_key="AIzaSyC70u1sN87IkoxOoIj4XCAPw97ae2LwNM") | |
# Model settings | |
generation_config = { | |
"temperature": 0.9, | |
"max_output_tokens": 2048 | |
} | |
safety_settings = [ | |
{ | |
"category": "HARM_CATEGORY_HARASSMENT", | |
"threshold": "BLOCK_MEDIUM_AND_ABOVE" | |
}, | |
{ | |
"category": "HARM_CATEGORY_HATE_SPEECH", | |
"threshold": "BLOCK_MEDIUM_AND_ABOVE" | |
}, | |
{ | |
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", | |
"threshold": "BLOCK_MEDIUM_AND_ABOVE" | |
}, | |
{ | |
"category": "HARM_CATEGORY_DANGEROUS_CONTENT", | |
"threshold": "BLOCK_MEDIUM_AND_ABOVE" | |
} | |
] | |
model = genai.GenerativeModel( | |
model_name="gemini-pro", | |
generation_config=generation_config, | |
safety_settings=safety_settings | |
) | |
# Chatbot interface | |
st.title("Gemini API Chatbot") | |
chat_history = st.session_state.get("chat_history", []) | |
chat_container = st.container() | |
for message in chat_history: | |
# Display message | |
if message.parts: | |
role = "assistant" if message.role == "system" else "user" | |
text = message.parts[0].text | |
else: | |
role = message.role | |
text = message.content | |
chat_container.markdown(f"**{role}:** {text}") | |
# Input | |
user_input = st.text_input("You") | |
if user_input: | |
# Create message | |
user_message = genai.GenerativeContent( | |
parts=[genai.Part(text=user_input)], # Wrap in a list | |
role=genai.Role.USER | |
) | |
# Append message | |
chat_history.append(user_message) | |
# Display message | |
chat_container.markdown(f"**user:** {user_input}") | |
# Get response | |
with st.spinner("Thinking..."): | |
convo = model.start_chat(chat_history) | |
response = convo.last | |
# Extract response text | |
response_text = response.parts[0].text | |
# Create response message | |
assistant_message = genai.GenerativeContent( | |
parts=[genai.Part(text=response_text)], # Wrap in a list | |
role=genai.Role.ASSISTANT | |
) | |
# Append response | |
chat_history.append(assistant_message) | |
# Display response | |
chat_container.markdown(f"**assistant:** {response_text}") | |
# Update session state | |
st.session_state["chat_history"] = chat_history |