AnshulKawarey/coding-chat-bot
0
1import os2import streamlit as st3from groq import Groq4 5st.set_page_config(6 page_title="Coding Chatbot",7 layout="centered"8)9 10GROQ_API_KEY = os.environ.get("GROQ_API_KEY")11if not GROQ_API_KEY:12 st.error("GROQ_API_KEY not found.")13 st.stop()14 15os.environ["GROQ_API_KEY"] = GROQ_API_KEY16 17client = Groq()18 19if "chat_hist" not in st.session_state:20 st.session_state.chat_hist = []21 22st.title("Coding Chatbot")23 24for msg in st.session_state.chat_hist:25 with st.chat_message(msg["role"]):26 st.markdown(msg["content"])27 28with st.form("chat_form", clear_on_submit=True):29 user_question = st.text_input("User Question", placeholder="Type your question here...")30 user_code = st.text_area("Code (optional)", placeholder="Paste your code snippet here...", height=150)31 submitted = st.form_submit_button("Send")32 33if submitted and user_question:34 if user_code.strip():35 user_content = f"**Question:** {user_question}\n\n**Code:**\n```python\n{user_code}\n```"36 else:37 user_content = f"**Question:** {user_question}"38 39 st.chat_message("User").markdown(user_content)40 st.session_state.chat_hist.append({"role": "user", "content": user_content})41 42 if user_code.strip():43 system_prompt = (44 "You are a coding assistant. The user has provided a code snippet along with their question. "45 "Analyze the code and provide necessary changes or improvements based on the question."46 )47 else:48 system_prompt = "You are a helpful assistant that provides answers to user questions."49 50 messages = [{"role": "system", "content": system_prompt}] + st.session_state.chat_hist51 52 try:53 resp = client.chat.completions.create(54 model="llama-3.1-8b-instant",55 messages=messages56 )57 assistant_resp = resp.choices[0].message.content58 except Exception as e:59 assistant_resp = f"Error calling the API: {e}"60 61 st.session_state.chat_hist.append({"role": "assistant", "content": assistant_resp})62 with st.chat_message("Assistant"):63 st.markdown(assistant_resp)64 