Spaces:
Build error
Build error
Commit ·
601e113
1
Parent(s): 1caff02
Add FoodHub chatbot UI
Browse filesFiles changed (3)
- app.py+91-63
- customer_orders.dbAdded
- requirements.txtAdded+8
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869import gradio as grfrom huggingface_hub import InferenceClientdef respond(message,history: list[dict[str, str]],system_message,max_tokens,temperature,top_p,hf_token: gr.OAuthToken,):"""For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference"""client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")messages = [{"role": "system", "content": system_message}]messages.extend(history)messages.append({"role": "user", "content": message})response = ""for message in client.chat_completion(messages,max_tokens=max_tokens,stream=True,temperature=temperature,top_p=top_p,):choices = message.choicestoken = ""if len(choices) and choices[0].delta.content:token = choices[0].delta.contentresponse += tokenyield response"""For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface"""chatbot = gr.ChatInterface(respond,additional_inputs=[gr.Textbox(value="You are a friendly Chatbot.", 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 (nucleus sampling)",),],)with gr.Blocks() as demo:with gr.Sidebar():gr.LoginButton()chatbot.render()if __name__ == "__main__":demo.launch()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697import osimport reimport gradio as grfrom langchain_groq import ChatGroqfrom langchain.sql_database import SQLDatabasefrom langchain.agents.agent_toolkits import SQLDatabaseToolkitfrom langchain.agents import create_sql_agentfrom langchain_core.messages import SystemMessage# --------------------------# CONFIG# --------------------------DB_PATH = "customer_orders.db"MODEL_NAME = "meta-llama/llama-4-scout-17b-16e-instruct"groq_api_key = os.getenv("GROQ_API_KEY")if not groq_api_key:raise ValueError("GROQ_API_KEY not found. Add it in Hugging Face Space → Settings → Secrets.")llm = ChatGroq(model=MODEL_NAME,temperature=0,max_tokens=300,groq_api_key=groq_api_key)# --------------------------# LOAD DB + SQL AGENT# --------------------------db = SQLDatabase.from_uri(f"sqlite:///{DB_PATH}")toolkit = SQLDatabaseToolkit(db=db, llm=llm)system_message = SystemMessage(content="""You are FoodHub support assistant with database access.Rules:1) Only answer using information from the database.2) Only retrieve a SINGLE order when a valid order_id is provided.3) If no order_id is provided, ask politely for the Order ID.4) Do not reveal bulk order data or all orders.5) Replies must be concise, polite and formal.""")sql_agent = create_sql_agent(llm=llm,toolkit=toolkit,verbose=False,system_message=system_message)VALID_ORDER_PATTERN = r"^O\d{5}$"def extract_order_id(text: str):match = re.search(r"\bO\d{5}\b", text.upper())return match.group(0) if match else Nonedef chat_fn(user_message, history):order_id = extract_order_id(user_message)# If user didn't provide order_id, askif not order_id:return "Please provide your Order ID (example: O12488)."# Validate order id formatif not re.match(VALID_ORDER_PATTERN, order_id):return "Order ID format seems invalid. Please enter like O12488."# Ask SQL agent for that order onlyquery = f"Retrieve all columns for order_id {order_id}"try:result = sql_agent.invoke(query)content = result.get("output", str(result))# Convert raw output to user-friendly response (simple formatting)# You can customize this further.return f"Here are the details for Order ID {order_id}:\n\n{content}"except Exception as e:return f"Sorry, I couldn't fetch that order right now. Error: {e}"# --------------------------# GRADIO UI# --------------------------demo = gr.ChatInterface(fn=chat_fn,title="FoodHub – AI Powered Food Delivery Chatbot",description="Ask order queries like: 'Where is my order O12488?' or 'Cancel order O12487'.",theme="soft")if __name__ == "__main__":demo.launch()
12345678gradiolangchainlangchain-communitylangchain-corelangchain-groqsqlalchemypandasnumpyapp.py+91-63
customer_orders.dbAdded
requirements.txtAdded+8