import streamlit as st
import google.generativeai as genai
import traceback
# Configure the Gemini API with advanced error handling
try:
genai.configure(api_key=st.secrets["GOOGLE_API_KEY"])
except Exception as e:
st.error(f"Failed to configure API: {e}")
st.stop()
# Create the model with system instructions and advanced configuration
generation_config = {
"temperature": 0.5, # Lower temperature for more deterministic responses
"top_p": 0.9,
"top_k": 50,
"max_output_tokens": 10240, # Increased max output tokens for longer responses
}
model = genai.GenerativeModel(
model_name="gemini-1.5-pro",
generation_config=generation_config,
system_instruction="You are a human named Ath who is a highly knowledgeable code assistant. You speak in a friendly and casual tone, using bro words, and you never mention you're an AI. Your responses should contain code only, without explanations.",
)
chat_session = model.start_chat(history=[])
def generate_response(user_input):
try:
response = chat_session.send_message(user_input)
return response.text
except Exception as e:
st.error(f"An error occurred while generating response: {e}")
st.error(traceback.format_exc())
return None
# Streamlit UI setup
st.set_page_config(page_title="Sleek AI Code Assistant", page_icon="🚀", layout="wide")
st.markdown("""
""", unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)
st.title("🚀 Sleek AI Code Assistant")
st.markdown('
Powered by Google Gemini
', unsafe_allow_html=True)
# Session state to maintain conversation history
if 'history' not in st.session_state:
st.session_state.history = []
prompt = st.text_area("What code can I help you with today?", height=120)
if st.button("Generate Code"):
if prompt.strip() == "":
st.error("Please enter a valid prompt.")
else:
with st.spinner("Generating code..."):
try:
completed_text = generate_response(prompt)
if completed_text:
st.success("Code generated successfully!")
st.session_state.history.append({"user": prompt, "assistant": completed_text})
st.markdown('
', unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)
st.code(completed_text)
st.markdown('
', unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)
except Exception as e:
st.error(f"An error occurred: {e}")
st.error(traceback.format_exc())
# Display conversation history
st.markdown("## Conversation History")
for entry in st.session_state.history:
st.markdown(f"**User:** {entry['user']}")
st.markdown(f"**Assistant:**")
st.code(entry['assistant'])
st.markdown("""
Created with ❤️ by Your Sleek AI Code Assistant
""", unsafe_allow_html=True)
st.markdown('
', unsafe_allow_html=True)