import streamlit as st import requests import os # --- Page Configuration --- st.set_page_config( page_title="potential 🧑‍💻", page_icon="🤖", layout="wide", initial_sidebar_state="expanded", ) # --- Custom CSS for a Polished Look (Optional) --- st.markdown(""" """, unsafe_allow_html=True) # --- API Key and Model Configuration --- st.sidebar.title("🔧 Configuration") # API Key Handling # Option 1: Use Streamlit Secrets (recommended for deployed apps) # Create a secrets.toml file in .streamlit folder with: # GROQ_API_KEY = "your_actual_api_key" # api_key_from_secrets = st.secrets.get("GROQ_API_KEY") # Option 2: Allow user to input API key (good for local dev or if secrets not set) # Fallback to environment variable if set during deployment api_key_env = os.environ.get('GROQ_API_KEY') groq_api_key = st.sidebar.text_input( "Groq API Key", type="password", value=api_key_env if api_key_env else "", # Pre-fill if env var exists placeholder="sk-...", help="Get your API key from https://console.groq.com/keys" ) if not groq_api_key: st.sidebar.warning("Please enter your Groq API Key to use the chatbot.", icon="⚠️") # Model Selection available_models = { "Gemma2 9B (Meta)": "gemma2-9b-it", "Llama3 70B (Meta)": "llama3-70b-8192", "Llama3 8B (Meta)": "llama3-8b-8192", "Mixtral 8x7B (Mistral)": "mixtral-8x7b-32768", "Gemma 7B (Google)": "gemma-7b-it", } selected_model_name = st.sidebar.selectbox( "Select Model", options=list(available_models.keys()), index=0 # Default to Gemma2 ) model_id = available_models[selected_model_name] # Advanced Settings st.sidebar.subheader("⚙️ Advanced Settings") system_prompt_default = "You are a helpful AI assistant that writes high-quality, efficient, and well-documented code. You always try to provide explanations for your code. Prefer Python if language is not specified." system_prompt = st.sidebar.text_area( "System Prompt", value=system_prompt_default, height=150 ) temperature = st.sidebar.slider( "Temperature", min_value=0.0, max_value=1.0, value=0.7, step=0.05, help="Controls randomness. Lower values make the model more deterministic." ) max_tokens = st.sidebar.number_input( "Max Tokens", min_value=50, max_value=8000, value=1500, step=100, # Adjusted max_tokens as per Groq limits help="Maximum number of tokens to generate in the response." ) # --- Groq API Call Function --- def call_groq_api(messages_history, model, temp, max_tok, sys_prompt): if not groq_api_key: return "Error: Groq API Key not provided." url = 'https://api.groq.com/openai/v1/chat/completions' headers = { 'Authorization': f'Bearer {groq_api_key}', 'Content-Type': 'application/json' } # Construct payload with the current system prompt and message history payload_messages = [{"role": "system", "content": sys_prompt}] + messages_history parameters = { 'model': model, 'messages': payload_messages, 'temperature': temp, 'max_tokens': max_tok } try: response = requests.post(url, headers=headers, json=parameters, timeout=30) # Added timeout response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) return response.json()['choices'][0]['message']['content'] except requests.exceptions.RequestException as e: return f"Error calling Groq API: {e}" except KeyError: return f"Error: Unexpected response format from Groq API. Response: {response.text}" except Exception as e: return f"An unexpected error occurred: {e}" # --- Chat Application Logic --- st.title("🧑‍💻 Groq Code Artisan") st.caption(f"Powered by Groq & Streamlit | Model: {selected_model_name}") # Initialize chat history in session state if "messages" not in st.session_state: st.session_state.messages = [] if "groq_api_key_valid" not in st.session_state: # To avoid re-prompting if already entered st.session_state.groq_api_key_valid = bool(groq_api_key) # Display past messages for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"]) # Use markdown to render code blocks properly # Main chat input if prompt := st.chat_input("Ask me to write or explain code..."): if not groq_api_key: st.error("Please enter your Groq API Key in the sidebar to start chatting.", icon="🔑") st.stop() st.session_state.groq_api_key_valid = True # Assume valid if user proceeds # Add user message to history and display it st.session_state.messages.append({"role": "user", "content": prompt}) with st.chat_message("user"): st.markdown(prompt) # Get assistant response with st.chat_message("assistant"): message_placeholder = st.empty() # For streaming-like effect or loading with st.spinner("Groq is thinking... 🤔"): # Prepare only the relevant message history for the API call api_messages_history = [ {"role": msg["role"], "content": msg["content"]} for msg in st.session_state.messages ] assistant_response = call_groq_api( api_messages_history, model_id, temperature, max_tokens, system_prompt ) message_placeholder.markdown(assistant_response) # Add assistant response to history st.session_state.messages.append({"role": "assistant", "content": assistant_response}) # "Clear Chat" button in the sidebar if st.sidebar.button("Clear Chat History", use_container_width=True): st.session_state.messages = [] st.rerun() # Rerun to clear the displayed messages # --- Footer or additional info (optional) --- st.sidebar.markdown("---") st.sidebar.markdown("Made with ❤️ by a Streamlit enthusiast.") st.sidebar.markdown(f"Groq Model ID: `{model_id}`")