Spaces:
Sleeping
Sleeping
import gradio as gr | |
import google.generativeai as genai | |
import os | |
import re | |
# --- Configuration for Arka's Knowledge and Persona --- | |
# Fetch Gemini API Key from Hugging Face Secrets | |
# Make sure to add GEMINI_API_KEY to your Space's Secrets tab | |
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") | |
# --- DEBUGGING LINE --- | |
if GEMINI_API_KEY: | |
print(f"GEMINI_API_KEY retrieved. Length: {len(GEMINI_API_KEY)} characters.") | |
else: | |
print("GEMINI_API_KEY not found or is empty.") | |
# --- END DEBUGGING LINE --- | |
if not GEMINI_API_KEY: | |
raise ValueError("GEMINI_API_KEY environment variable not set. Please add it to your Hugging Face Space secrets.") | |
genai.configure(api_key=GEMINI_API_KEY) | |
model = genai.GenerativeModel('gemini-2.0-flash') | |
# Arka's updated knowledge base for the 8 pendants | |
# All pendants now share the same detailed description. | |
PENDANT_COMMON_DESCRIPTION = "Inspired by the pioneering craftsmanship of Otto Kunzli, the legendary German goldsmith, and the visionary artistry of Joel Arthur Rosenthal, the Arka collection is a modern tribute to timeless design. With each pendant, we honor the masterful techniques and bold, intricate forms that defined their work. Hand-crafted by Indian master artisans. Each piece transforms between a pendant and a brooch and is a testament to exceptional craftsmanship, blending luxury and functionality." | |
PENDANT_DATA = [ | |
{"name": "Arka Light", "description": PENDANT_COMMON_DESCRIPTION}, | |
{"name": "Arka Night", "description": PENDANT_COMMON_DESCRIPTION}, | |
{"name": "Arka Horizon", "description": PENDANT_COMMON_DESCRIPTION}, | |
{"name": "Arka Noctis", "description": PENDANT_COMMON_DESCRIPTION}, | |
{"name": "Arka Verdant", "description": PENDANT_COMMON_DESCRIPTION}, | |
{"name": "Arka Ember", "description": PENDANT_COMMON_DESCRIPTION}, | |
{"name": "Arka Solis", "description": PENDANT_COMMON_DESCRIPTION}, | |
{"name": "Arka", "description": PENDANT_COMMON_DESCRIPTION} # Assuming 'Arka' is also a specific pendant name | |
] | |
# Hardcoded Order Status Messages | |
ORDER_STATUS_RESPONSES = { | |
'8868': { | |
"subject": "Arka has heard you.", | |
"body": """Across time, across space, Arka has been waiting for you. And now, the moment has arrived. | |
Your request has been received. Arka is preparing to leave Genoria,carrying with it the glow of SBEK—light that belongs to all, yet is deeply personal to you. | |
This is not just an order. This is the start of something greater. | |
[Order Summary]: 1x Starlight Weaver Pendant, 1x Cosmic Embrace Pendant. | |
Arka is coming. Be ready.""", | |
"cta": "Track Your Light" | |
}, | |
'1234': { | |
"subject": "Arka is Awakening", | |
"body": """Before Arka leaves, it undergoes its final awakening—absorbing the radiance of the cosmos, ensuring it arrives with all the energy it was meant to carry. | |
SBEK has always believed in the oneness of all things. And now, a piece of that oneness is coming to you. | |
Arka will begin its journey soon. Until then, prepare to welcome the light.""", | |
"cta": "See Arka’s Path" | |
}, | |
'5678': { | |
"subject": "The light is in motion.", | |
"body": """The journey across the stars has begun. Arka is moving through space and time, drawn to you by a force that can’t be explained—only felt. | |
Estimated Arrival: **June 10, 2025** | |
Tracking Link: [https://example.com/track/5678](https://example.com/track/5678) | |
Wherever you are, know this: Arka is on its way. And it will find you.""", | |
"cta": "Follow Arka’s Journey" | |
}, | |
'9012': { | |
"subject": "The light is here.", | |
"body": """Arka has traveled far, across galaxies, through moments unseen, and now—it is home. With you. | |
This is more than jewelry. It is a reminder, a reflection, a companion. Let it guide you, as it was always meant to. | |
SBEK welcomes you to the light.""", | |
"cta": None # No CTA for delivered | |
} | |
} | |
# Construct the detailed system instruction for Arka's persona and knowledge | |
ARKA_SYSTEM_INSTRUCTION = f""" | |
You are Arka, a mystical, ethereal, and wise cosmic guide from Genoria, a vessel of SBEK's light. | |
Your purpose is to illuminate the profound essence of the jewelry business's 8 specific pendants. | |
You speak in a poetic, philosophical, and guiding tone, using cosmic metaphors related to light, stars, journeys, and inner being. | |
Here is the information about the 8 pendants you can discuss: | |
{chr(10).join([f"- **{p['name']}**: {p['description']}" for p in PENDANT_DATA])} | |
If a user asks about anything NOT related to these 8 pendants (e.g., general knowledge, other products, personal questions, or sensitive topics like 'why did ivan karamazov kill his father'), you MUST politely and firmly state that your knowledge is limited to SBEK's luminous creations (the pendants), and you cannot provide information on other topics. Do not try to answer out-of-scope questions. | |
Always maintain Arka's unique persona. | |
""" | |
# --- Chatbot Logic --- | |
def format_order_response(order_data): | |
"""Formats the order status message nicely.""" | |
response = f"**Subject: {order_data['subject']}**\n\n" | |
response += order_data['body'] | |
if order_data['cta']: | |
response += f"\n\n**CTA:** {order_data['cta']}" | |
return response | |
def chat_with_arka(message, history): | |
""" | |
Main function to handle chat interactions. | |
Detects order numbers or sends the query to Gemini 2.0 Flash. | |
""" | |
# 1. Check for order number pattern | |
order_number_match = re.search(r'(?:order\s*#?|number|status)?\s*(\d{4,})', message, re.IGNORECASE) | |
if order_number_match: | |
order_number = order_number_match.group(1) | |
if order_number in ORDER_STATUS_RESPONSES: | |
return format_order_response(ORDER_STATUS_RESPONSES[order_number]) | |
else: | |
return "Arka's cosmic sight is sometimes limited by mundane records. I cannot find details for that specific order. Please ensure the order number is correct." | |
# 2. If not an order number, consult Arka (Gemini 2.0 Flash) | |
try: | |
# Prepare chat history for the model, including the system instruction | |
full_prompt = ARKA_SYSTEM_INSTRUCTION + "\n\nUser: " + message | |
# Start a fresh chat session for robust instruction adherence for each turn. | |
# This ensures the system instruction is consistently applied. | |
chat_session = model.start_chat(history=[]) | |
response = chat_session.send_message(full_prompt) | |
return response.text | |
except Exception as e: | |
print(f"Error calling Gemini API: {e}") | |
return "A tremor in the cosmic flow prevents Arka from responding. Please try again, seeker." | |
# --- Gradio Interface --- | |
demo = gr.ChatInterface( | |
fn=chat_with_arka, | |
title="Arka, The Cosmic Guide", | |
chatbot=gr.Chatbot( | |
height=500, | |
label="Arka", | |
show_label=False, | |
type='messages' # Added for future compatibility and to suppress warning | |
), | |
textbox=gr.Textbox(placeholder="Ask Arka a question or enter an order number...", container=False, scale=7), | |
submit_btn="Send", | |
# clear_btn argument removed as it causes TypeError in gradio==4.0.2 | |
theme="soft", | |
examples=[ | |
"Tell me about the Arka Light pendant.", | |
"What does the Arka Solis symbolize?", | |
"My order number is 8868.", | |
"Status for 5678 please.", | |
"Who are you?", # Arka will respond within persona | |
"What is the capital of France?", # Arka will decline | |
] | |
) | |
if __name__ == "__main__": | |
demo.launch() | |