Spaces:
Sleeping
Sleeping
import os | |
import gradio as gr | |
from langchain_core.prompts import ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder | |
from langchain_groq import ChatGroq | |
from langchain_core.runnables import RunnablePassthrough | |
from langchain_core.output_parsers import StrOutputParser | |
from dotenv import load_dotenv | |
# Load environment variables | |
load_dotenv() | |
# Set up the model | |
groq_api_key = os.getenv("GROQ_API_KEY") | |
if not groq_api_key: | |
raise ValueError("GROQ_API_KEY not found in environment variables") | |
model = ChatGroq(api_key=groq_api_key, model="llama-3.1-8b-instant") | |
# Define a custom system message and prompt | |
system_message = "You are a chatbot that helps convert normal English conversation into brain-rot language like the new generation of kids. You will generate 2 responses, one in brain-rot language and one in normal English. The first response should be in brain-rot language and in brackets the normal English version of the same sentence in the next line." | |
# Create the chat prompt template | |
prompt = ChatPromptTemplate.from_messages([ | |
SystemMessagePromptTemplate.from_template(system_message), | |
MessagesPlaceholder(variable_name="history"), | |
HumanMessagePromptTemplate.from_template("{input}") | |
]) | |
# Set up the conversation chain | |
chain = ( | |
RunnablePassthrough.assign(history=lambda x: x["history"]) | |
| prompt | |
| model | |
| StrOutputParser() | |
) | |
# Define a function to interact with the model and update history | |
def chat_function(user_input, history): | |
messages = [ | |
{"role": "human", "content": msg[0]} | |
| {"role": "ai", "content": msg[1]} | |
for msg in history | |
] | |
response = chain.invoke({"input": user_input, "history": messages}) | |
response = response.strip() | |
formatted_input = f"Normal English: {user_input}" | |
formatted_response = f"Skibbidi: {response}" | |
history.append((formatted_input, formatted_response)) | |
return history | |
# Set up Gradio interface | |
with gr.Blocks() as demo: | |
chatbot = gr.Chatbot(label="Conversation History") | |
with gr.Row(): | |
user_input = gr.Textbox(label="Your message", placeholder="Type your message here...", scale=4) | |
submit_button = gr.Button("Submit", scale=1) | |
# Enable submitting with Enter key and button | |
for trigger in [user_input.submit, submit_button.click]: | |
trigger(chat_function, inputs=[user_input, chatbot], outputs=[chatbot]) | |
trigger(lambda: "", outputs=[user_input]) | |
if __name__ == "__main__": | |
try: | |
print("Launching Gradio interface...") | |
demo.launch() | |
print("Gradio interface launched successfully!") | |
except Exception as e: | |
print(f"An error occurred: {e}") | |