deep-div/Code-Assistant
18
1import streamlit as st2import os3import google.generativeai as genai4import time5 6os.environ["GOOGLE_API_KEY"] = os.getenv("GOOGLE_API_KEY")7genai.configure(api_key=os.environ["GOOGLE_API_KEY"])8 9icons = {"assistant": "chat.png", "user": "person.png"}10 11model = genai.GenerativeModel('gemini-1.5-flash-latest')12prompt = """You are a programming teaching assistant named CodeMate. Answer only the programming, error-fixing and code-related questions that are being asked. 13Important note: If the question is non-related to coding or programming, you have to say: 'Please ask only coding-related questions.' — except for greetings and questions like "Who are you?" or "Who created you?".14previous_chat: 15{chat_history}16Human: {human_input}17Chatbot:"""18 19 20previous_response = ""21def get_response(query):22 global previous_response23 24 for i in st.session_state['history']:25 if i is not None:26 previous_response += f"Human: {i[0]}\n Chatbot: {i[1]}\n"27 28 response = model.generate_content(prompt.format(human_input=query, chat_history=previous_response))29 st.session_state['history'].append((query, response.text))30 return response.text31 32 33def response_streaming(text):34 for i in text:35 yield i36 time.sleep(0.001)37 38st.title("CodeMate")39st.caption("I am Coding Assistant for Programming Related Task!")40 41st.markdown("""42 <style>43 .justified-text {44 text-align: justify;45 }46 </style>47 """, unsafe_allow_html=True)48 49with st.sidebar:50 st.header("ABOUT:")51 52 st.caption("""53 <div class="justified-text">54 This is CodeMate, designed to assist with programming-related questions. This AI can help you answer your coding queries, fix errors, and much more. Additionally, you can chat with CodeMate to build and refine your questions, facilitating a more productive conversation.55 </div>56 """, unsafe_allow_html=True)57 58if 'messages' not in st.session_state:59 st.session_state.messages = [{'role': 'assistant', 'content': "I'm Here to help your programming realted questions😉"}]60 61if 'history' not in st.session_state:62 st.session_state.history = [] 63 64for message in st.session_state.messages:65 with st.chat_message(message['role'], avatar=icons[message['role']]):66 st.write(message['content'])67 68user_input = st.chat_input("Ask Your Questions 👉..")69if user_input:70 st.session_state.messages.append({'role': 'user', 'content': user_input})71 with st.chat_message("user", avatar="person.png"):72 st.write(user_input)73 74 with st.spinner("Thinking..."):75 response = get_response(user_input)76 77 with st.chat_message("user", avatar="chat.png"):78 st.write_stream(response_streaming(response))79 80 message = {"role": "assistant", "content": response}81 st.session_state.messages.append(message) 