VincentA2K's picture
Product Recommendation RestAPI
480e694
import os
import gradio as gr
from huggingface_hub import InferenceClient
from huggingface_hub.utils import HfHubHTTPError
from dotenv import load_dotenv
# Load environment variables from .env file in parent directory
env_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), '.env')
load_dotenv(dotenv_path=env_path)
api_token = os.getenv("HUGGINGFACE_API_TOKEN")
if not api_token:
raise ValueError("HUGGINGFACE_API_TOKEN environment variable not set. Please check your .env file.")
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta", token=api_token)
def respond(message, history, system_message, max_tokens, temperature, top_p):
messages = [{"role": "system", "content": system_message}]
for val in history:
if val[0]:
messages.append({"role": "user", "content": val[0]})
if val[1]:
messages.append({"role": "assistant", "content": val[1]})
messages.append({"role": "user", "content": message})
response = ""
try:
for message in client.chat_completion(
messages,
max_tokens=max_tokens,
stream=True,
temperature=temperature,
top_p=top_p,
):
if hasattr(message.choices[0], 'delta') and hasattr(message.choices[0].delta, 'content'):
token = message.choices[0].delta.content
response += token
yield response
except Exception as e:
yield f"Error: {str(e)}"
# Create the Gradio interface
demo = gr.ChatInterface(
fn=respond,
title="E-commerce Chatbot",
description="Ask me anything about products!",
examples=["Tell me about gaming laptops", "What are the best smartphones?"],
additional_inputs=[
gr.Textbox(value="You are a friendly E-commerce assistant.", label="System message"),
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p")
]
)
if __name__ == "__main__":
try:
demo.launch(server_name="0.0.0.0", server_port=8000, share=True)
except Exception as e:
print(f"Error launching the demo: {e}")