Spaces:
Sleeping
Sleeping
| import os | |
| import gradio as gr | |
| from groq import Groq | |
| from datasets import load_dataset | |
| GROQ_MODEL = "llama3-70b-8192" | |
| DATASET_NAME = "embedding-data/Amazon-QA" | |
| def load_shopify_context(): | |
| dataset = load_dataset(DATASET_NAME) | |
| samples = dataset['train'].select(range(3)) | |
| examples = [] | |
| for sample in samples: | |
| question = sample['query'] | |
| if isinstance(question, list): | |
| question = question[0] if len(question) > 0 else "No question" | |
| question = str(question).replace('\\', '/') | |
| answer = sample.get('pos', sample.get('answer', ["No answer"])) | |
| if isinstance(answer, list): | |
| answer = answer[0] if len(answer) > 0 else "No answer" | |
| answer = str(answer).replace('\\', '/') | |
| examples.append(f"Q: {question}\nA: {answer}") | |
| return '\n'.join(examples) | |
| def generate_response(message, history): | |
| api_key = os.getenv("Mujtaba_shopify_chatbot_key") | |
| if not api_key: | |
| return "Error: GROQ_API_KEY not set. Please add it as a secret in your Space." | |
| client = Groq(api_key=api_key) | |
| context = load_shopify_context() | |
| conversation = [] | |
| for user_msg, bot_msg in history: | |
| safe_user = str(user_msg).replace('\\', '/') | |
| safe_bot = str(bot_msg).replace('\\', '/') | |
| conversation.extend([f"User: {safe_user}", f"Assistant: {safe_bot}"]) | |
| safe_message = str(message).replace('\\', '/') | |
| prompt = f"You are an expert Shopify support agent. Context examples:\n{context}\n{chr(10).join(conversation)}\nUser: {safe_message}\nAssistant:" | |
| try: | |
| response = client.chat.completions.create( | |
| messages=[{"role": "user", "content": prompt}], | |
| model=GROQ_MODEL, | |
| temperature=0.7, | |
| max_tokens=256, | |
| top_p=0.9, | |
| stop=["<|endoftext|>"] | |
| ) | |
| return response.choices[0].message.content | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| with gr.Blocks() as app: | |
| gr.Markdown("## Shopify Q&A Assistant (Groq-powered)") | |
| gr.ChatInterface( | |
| fn=generate_response, | |
| examples=[ | |
| "What's your return policy?", | |
| "Do you ship internationally?", | |
| "Is this compatible with iPhone 15?" | |
| ] | |
| ) | |
| app.launch() | |