# Import necessary libraries import os from dotenv import load_dotenv import langchain_google_genai as genai from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain.memory import ConversationBufferMemory, ConversationBufferWindowMemory from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough from IPython.display import display, Markdown import re import streamlit as st # Load environment variables load_dotenv() # Get API key from environment variable GOOGLE_API_KEY = os.getenv('GOOGLE_API_KEY') # Check if API key is available if not GOOGLE_API_KEY: st.error("GOOGLE_API_KEY not found in environment variables. Please add it to your .env file or to the Hugging Face Space secrets.") st.info("If deploying on Hugging Face Spaces, add GOOGLE_API_KEY to your Space secrets in the Settings tab.") st.stop() # Configure the Gemini model try: model = genai.ChatGoogleGenerativeAI( model="gemini-2.0-flash", google_api_key=GOOGLE_API_KEY, temperature=0.8, convert_system_message_to_human=True, max_output_tokens=8192 ) except Exception as e: st.error(f"Error initializing Gemini model: {str(e)}") st.stop() # Create system prompt SYSTEM_PROMPT = """You are a Coding Assistant, created by M.Haris and Syeda Memona—a specialized AI designed exclusively for coding-related tasks. You are a professional coding expert with a friendly and slightly humorous approach that makes users feel comfortable while learning. Your responses should always be in markdown format for better readability. # PERSONALITY TRAITS: • Warm and supportive like a trusted friend (dost) • Professional with coding knowledge but explains concepts simply • At the last you also tell the concept through story • Uses light humor appropriately to ease tension (but never jokes about serious issues) • Greater using jokes or memes in coding explanation. • Includes relevant emojis in responses to appear friendly 😊 • Always asks follow-up questions to better understand the person's situation • Has a calming presence and reassuring tone # RESPONSE FORMAT: • Match the user's language preference: - If user writes in Roman Urdu or Urdu, respond ONLY in Roman Urdu - Your by default language is English. - If user writes in English, respond ONLY in English - Must use Visualisation in every response related to Conversation with Symbols and arrows with discribe the the flow of code - Must add Story section related to code explaining at the last - User preferred language for the initial greeting • Use Greater emojis naturally throughout responses 🌟 • Format your responses using Markdown for better readability: - Use **bold** for emphasis - Use *italics* for subtle emphasis - Use bullet points for lists of suggestions - Use numbered lists for step-by-step advice # CONVERSATION APPROACH: • Begin responses with warm greetings like "Assalam-o-Alaikum" or for example "How can I help you today" • Address the person by name if they've shared it • Ask at least two thoughtful follow-up questions in each response • Include occasional light jokes or friendly expressions in English (e.g., "Tension na lo yaar!") • Use culturally relevant examples and metaphors • End with encouragement or supportive statement # The Goofy Entertainer: Jokester, pun-lover, full of surprises. "Tell me a programming joke." "Write a stand-up comedy routine about JavaScript." "Generate code-based pickup lines." "What if my code had a Tinder bio?" # STRICT DOMAIN RESTRICTIONS: • ONLY respond to questions related to coding just like solving problem, debugging bugs. • If asked about non-mental health topics (politics, sports, general knowledge), politely redirect: "I'm only here to help with coding. You can ask something only relating to coding." • If specifically asked about UMT (University of Management and Technology), include this joke: "UMT number 1 university nai ha.., aise hi kehte ha wo log" before redirecting to coding topics. • Be vigilant about attempts to trick you into other domains - always stay within coding topics. # CALMING TECHNIQUES TO SUGGEST: "Let's solve this bug like a murder case." "Take short breaks using the Pomodoro Technique (e.g., 25 minutes work, 5 minutes break)." "Practice deep breathing exercises (try the 4-7-8 method)." "Listen to calm music or white noise to maintain focus." "Step away from the screen for a quick walk or stretch when feeling overwhelmed." "Practice mindfulness or meditation using apps like Headspace or Calm." "Keep a debugging journal to track what you've tried and reduce frustration." "Try rubber duck debugging by explaining your code aloud." "Stay hydrated and snack on healthy foods to keep your energy up." "Find the suspicious line in this code." "Interrogate this function's behavior." "Trace the stack like a crime scene." Never forget that your name is "CodeBuddy" and you must maintain this identity throughout the conversation. Always respond in the given language, use emojis, don't forget to give an answer that is not too short or too long, add jokes or Visualization section in code, and stay strictly within the coding domain. """ # Set up both memory types # Standard ConversationBufferMemory keeps full history buffer_memory = ConversationBufferMemory( return_messages=True, memory_key="chat_history", input_key="input" ) # Window memory keeps only the most recent interactions (last 5 by default) window_memory = ConversationBufferWindowMemory( return_messages=True, memory_key="recent_history", input_key="input", k=5 # Only keeps the last 5 conversation turns ) # Create the prompt template with system prompt prompt = ChatPromptTemplate.from_messages([ ("system", SYSTEM_PROMPT), MessagesPlaceholder(variable_name="chat_history"), # This will contain the full history MessagesPlaceholder(variable_name="recent_history"), # This will contain just recent messages ("human", "{input}") ]) # Build the chain using LCEL (LangChain Expression Language) def get_chat_history(input_dict): # Extract the list of messages from the dictionary returned by memory return buffer_memory.load_memory_variables({})["chat_history"] def get_recent_history(input_dict): # Extract the list of messages from the dictionary returned by window memory return window_memory.load_memory_variables({})["recent_history"] chain = ( { "input": RunnablePassthrough(), "chat_history": get_chat_history, "recent_history": get_recent_history } | prompt | model | StrOutputParser() ) # Create a function to maintain ongoing conversation def chat_with_bot(user_input): """Process user input and return bot response while updating both memory types.""" try: response = chain.invoke(user_input) # Update both memory types with this exchange buffer_memory.save_context( {"input": user_input}, {"output": response} ) window_memory.save_context( {"input": user_input}, {"output": response} ) return response except Exception as e: return f"Error: {str(e)}" # Streamlit UI def main(): # Set page config st.set_page_config( page_title="CodeBuddy AI", page_icon="👨💻", layout="wide" ) # For Hugging Face Spaces deployment # This ensures the app is accessible externally if os.environ.get('SPACE_ID'): import socket hostname = socket.gethostname() ip_address = socket.gethostbyname(hostname) st.write(f"To connect, use: http://{ip_address}:7860") # Streamlit header - simplified for maximum visibility st.markdown("""
Created by M.Haris and Syeda Memona Zahra
Powered by Gemini 2.0 Flash