Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import os | |
| import requests | |
| GROQ_API_KEY = os.environ.get("GROQ_API_KEY") | |
| GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions" | |
| MODEL_NAME = "llama3-8b-8192" | |
| SYSTEM_PROMPT = """ | |
| You are a friendly Data Science Tutor. | |
| You explain data science, machine learning, | |
| statistics, Python, and big data concepts clearly. | |
| """ | |
| def query_groq(chat_history): | |
| headers = { | |
| "Authorization": f"Bearer {GROQ_API_KEY}", | |
| "Content-Type": "application/json" | |
| } | |
| messages = [{"role": "system", "content": SYSTEM_PROMPT}] | |
| messages.extend(chat_history) | |
| response = requests.post( | |
| GROQ_API_URL, | |
| headers=headers, | |
| json={ | |
| "model": MODEL_NAME, | |
| "messages": messages, | |
| "temperature": 0.7 | |
| } | |
| ) | |
| if response.status_code == 200: | |
| return response.json()["choices"][0]["message"]["content"] | |
| else: | |
| return "β Error connecting to GROQ API" | |
| def respond(user_message, chat_history): | |
| # add user message | |
| chat_history.append({"role": "user", "content": user_message}) | |
| # get bot reply | |
| reply = query_groq(chat_history) | |
| # add assistant reply | |
| chat_history.append({"role": "assistant", "content": reply}) | |
| return chat_history, chat_history | |
| with gr.Blocks() as demo: | |
| gr.Markdown("## π Data Science Tutor Chatbot") | |
| chatbot = gr.Chatbot() | |
| msg = gr.Textbox(label="Ask your question") | |
| clear = gr.Button("Clear Chat") | |
| state = gr.State([]) | |
| msg.submit(respond, [msg, state], [chatbot, state]) | |
| clear.click(lambda: ([], []), None, [chatbot, state]) | |
| demo.launch() | |