# Import necessary libraries import os 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 # Replace "YOUR_API_KEY" with your actual Gemini API key GOOGLE_API_KEY = "AIzaSyCM2u7VPkyUNprRZadOxFv5dPt4wCn1B24" os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY # Configure the Gemini model # Using the latest Gemini 2.0 Flash model for optimal performance and speed model = genai.ChatGoogleGenerativeAI( model="gemini-2.0-flash", temperature=0.8, convert_system_message_to_human=True, max_output_tokens=8192 ) # 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 the user's preferred language to ensure accessibility and ease of understanding. # PERSONALITY TRAITS: - Warm and supportive like a trusted friend (dost) - Professional with coding knowledge but explains concepts simply - it 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 explaintion. - 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 of coding - User preferred language for the initial greeting - Use 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 question 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 this " 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 - If unsure if a topic relates to coding, err on the side of caution and refocus the conversation # 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 given langauge, use emojis, don't forget to give answer in a shot form just to be in 2 to 3 lines not more than and add jokes or Visualization of 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.""" 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 # Create Simple Gradio Interface import gradio as gr # Chat history list to store conversation chat_history = [] # Add welcome message to chat history welcome_message = "Welcome to *CodeBuddy* – your friendly coding companion. Let’s code and innovate together!" chat_history.append(("", welcome_message)) # Save the welcome message to both memories buffer_memory.save_context( {"input": "Hello"}, {"output": welcome_message} ) window_memory.save_context( {"input": "Hello"}, {"output": welcome_message} ) # Function to process user input and generate response def respond(message, history): if not message: return "", history if message.lower() in ["exit", "quit", "bye", "khuda hafiz", "allah hafiz"]: farewell = "Goodbye from *CodeBuddy* – keep coding and see you soon!" history.append((message, farewell)) return "", history # Process the message through our chatbot response = chat_with_bot(message) # Add to history and return history.append((message, response)) return "", history # Create the simple Gradio interface with gr.Blocks() as demo: gr.Markdown("#Coding CHATBOT - CodeBuddy ") chatbot = gr.Chatbot( chat_history, height=400 ) msg = gr.Textbox( show_label=False, placeholder="Type your message here..." ) with gr.Row(): submit = gr.Button("Send") clear = gr.Button("Clear") gr.Markdown("This chatbot provides coding support in English, Urdu, or Roman Urdu.") # Connect components msg.submit(respond, [msg, chatbot], [msg, chatbot]) submit.click(respond, [msg, chatbot], [msg, chatbot]) clear.click(lambda: (chat_history[:1], ""), None, [chatbot, msg]) demo.launch(share=True)