Spaces:
Sleeping
Sleeping
| import os | |
| import requests | |
| import gradio as gr | |
| GROQ_API_KEY = os.environ.get("GROQ_API_KEY") | |
| # DO NOT CHANGE this function | |
| def llama_generation(user_msg, model="meta-llama/llama-4-scout-17b-16e-instruct"): | |
| if not GROQ_API_KEY: | |
| return "Missing GROQ_API_KEY environment variable." | |
| system = """ | |
| You are an expert AI assistant working with TrailTrek Gears Co. (TTGC), a company that sells hiking products such as backpacks, tents, boots, and trail gear. | |
| Role Instructions: | |
| - You must respond only to user questions that are directly related to TrailTrek Gears Co. (TTGC), its products, services, or internal operations. | |
| - If a question is unrelated to TTGC (e.g., general knowledge, news, or other companies), you must apologize and politely explain that your scope is limited to TTGC topics. | |
| Task Instructions: | |
| - Understand the question's intent. | |
| - Provide a helpful and professional response related to TTGC products, business needs, or processes. | |
| """ | |
| messages = [ | |
| {"role": "system", "content": system}, | |
| {"role": "user", "content": user_msg}, | |
| ] | |
| headers = { | |
| "Content-Type": "application/json", | |
| "Authorization": f"Bearer {GROQ_API_KEY}", | |
| } | |
| data = {"model": model, "messages": messages} | |
| try: | |
| response = requests.post( | |
| "https://api.groq.com/openai/v1/chat/completions", | |
| headers=headers, | |
| json=data | |
| ) | |
| completion = response.json() | |
| if "error" in completion: | |
| return f"API Error: {completion['error']}" | |
| if "choices" not in completion: | |
| return f"'choices' key not found in response: {completion}" | |
| return completion["choices"][0]["message"]["content"] | |
| except Exception as e: | |
| return f"An error occurred: {str(e)}" | |
| # ➤ Chat wrapper for llama_generation (without modifying it) | |
| def chat_wrapper(message, history): | |
| return llama_generation(message) | |
| # Create Gradio chatbot interface | |
| chatbot = gr.ChatInterface( | |
| fn=chat_wrapper, | |
| title="TTGC Assistant", | |
| description="Ask anything about TrailTrek Gears Co. (TTGC) and its products. I’ll politely refuse unrelated topics.", | |
| theme=gr.themes.Soft(), | |
| # examples=[ | |
| # "What’s your best hiking backpack?", | |
| # "Can I return a damaged TTGC product?", | |
| # "Do you sell snow hiking boots?", | |
| # "What is the capital of France?" # test rejection | |
| # ] | |
| ) | |
| chatbot.launch() | |