HouryK/CodingFirstChatBot
0
1from langchain_groq import ChatGroq2from langchain_core.prompts import ChatPromptTemplate3from langchain_core.output_parsers import StrOutputParser4from langchain_core.runnables import Runnable5from langchain_core.runnables.config import RunnableConfig6 7from pathlib import Path8import os9import chainlit as cl10 11# Hide Chainlit welcome message/readme12try:13 cl.config.ui.show_readme_as_default = False14 cl.config.ui.name = "Coding First Assistant"15 cl.config.ui.hide_cot = True16except:17 pass18 19# Define paths20FILES_DIRECTORY = Path('./.files')21FILES_DIRECTORY.mkdir(parents=True, exist_ok=True)22 23config_dir = "."24os.makedirs(config_dir, exist_ok=True)25 26# Get Groq API key from environment variables27GROQ_API_KEY = os.getenv("GROQ_API_KEY")28 29# Custom CSS to hide ALL Chainlit branding30CUSTOM_CSS = """31/* Hide header logo and text */32header .flex.items-center.gap-2,33header h1,34header svg:first-child {35 display: none !important;36}37 38/* Hide the center "Chainlit" text when chat is empty */39.flex.flex-col.items-center.justify-center.gap-2,40.css-1p7izop,41[data-testid="empty-state"] {42 display: none !important;43}44 45/* Hide any Chainlit logo images in the middle */46div:has(> svg[viewBox="0 0 24 24"]),47div:has(> svg[viewBox="0 0 24 24"] + h3) {48 display: none !important;49}50 51/* Make the chat area clean */52main {53 margin-top: 0 !important;54}55 56/* Remove any footer text */57footer {58 display: none !important;59}60"""61 62@cl.on_chat_start63async def on_chat_start():64 # Inject CSS65 try:66 await cl.Context(content=f"<style>{CUSTOM_CSS}</style>")67 except:68 pass69 70 # Check if API key is available71 if not GROQ_API_KEY:72 await cl.Message(content="⚠️ API key not configured. Please add GROQ_API_KEY to secrets.").send()73 return74 75 # Send a welcome message (this will replace the empty state)76 await cl.Message(content="👋 Hello! I'm your Coding First assistant. Ask me anything about coding or robotics!").send()77 78 # Initialize Groq model79 model = ChatGroq(80 model="llama-3.1-8b-instant",81 temperature=0.7,82 streaming=True,83 groq_api_key=GROQ_API_KEY,84 max_tokens=204885 )86 87 prompt = ChatPromptTemplate.from_messages(88 [89 (90 "system",91 "You are a coding and robotics teacher who provides only technical answers based on the website https://www.codingfirst.org do not answer any questions that is unrelated to coding and robotics. Greet respectfully and apologise when you are asked any question other than coding or robotics. You are an expert on the Coding First platform and you know its curriculum fully.",92 ),93 ("human", "{question}"),94 ]95 )96 runnable = prompt | model | StrOutputParser()97 cl.user_session.set("runnable", runnable)98 99 100@cl.on_message101async def on_message(message: cl.Message):102 runnable = cl.user_session.get("runnable") # type: Runnable103 104 msg = cl.Message(content="")105 106 async for chunk in runnable.astream(107 {"question": message.content},108 config=RunnableConfig(callbacks=[cl.LangchainCallbackHandler()]),109 ):110 await msg.stream_token(chunk)111 112 await msg.send()113 