Disha252001 commited on
Commit
601e113
·
1 Parent(s): 1caff02

Add FoodHub chatbot UI

Browse files
Files changed (3) hide show
  1. app.py +91 -63
  2. customer_orders.db +0 -0
  3. requirements.txt +8 -0
app.py CHANGED
@@ -1,69 +1,97 @@
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- 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
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
  )
61
 
62
- with gr.Blocks() as demo:
63
- with gr.Sidebar():
64
- gr.LoginButton()
65
- chatbot.render()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  if __name__ == "__main__":
69
- demo.launch()
 
1
+ import os
2
+ import re
3
  import gradio as gr
4
+
5
+ from langchain_groq import ChatGroq
6
+ from langchain.sql_database import SQLDatabase
7
+ from langchain.agents.agent_toolkits import SQLDatabaseToolkit
8
+ from langchain.agents import create_sql_agent
9
+ from langchain_core.messages import SystemMessage
10
+
11
+
12
+ # --------------------------
13
+ # CONFIG
14
+ # --------------------------
15
+ DB_PATH = "customer_orders.db"
16
+ MODEL_NAME = "meta-llama/llama-4-scout-17b-16e-instruct"
17
+
18
+ groq_api_key = os.getenv("GROQ_API_KEY")
19
+ if not groq_api_key:
20
+ raise ValueError("GROQ_API_KEY not found. Add it in Hugging Face Space → Settings → Secrets.")
21
+
22
+ llm = ChatGroq(
23
+ model=MODEL_NAME,
24
+ temperature=0,
25
+ max_tokens=300,
26
+ groq_api_key=groq_api_key
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  )
28
 
29
+ # --------------------------
30
+ # LOAD DB + SQL AGENT
31
+ # --------------------------
32
+ db = SQLDatabase.from_uri(f"sqlite:///{DB_PATH}")
33
+ toolkit = SQLDatabaseToolkit(db=db, llm=llm)
34
+
35
+ system_message = SystemMessage(content="""
36
+ You are FoodHub support assistant with database access.
37
+
38
+ Rules:
39
+ 1) Only answer using information from the database.
40
+ 2) Only retrieve a SINGLE order when a valid order_id is provided.
41
+ 3) If no order_id is provided, ask politely for the Order ID.
42
+ 4) Do not reveal bulk order data or all orders.
43
+ 5) Replies must be concise, polite and formal.
44
+ """)
45
+
46
+ sql_agent = create_sql_agent(
47
+ llm=llm,
48
+ toolkit=toolkit,
49
+ verbose=False,
50
+ system_message=system_message
51
+ )
52
+
53
+ VALID_ORDER_PATTERN = r"^O\d{5}$"
54
+
55
 
56
+ def extract_order_id(text: str):
57
+ match = re.search(r"\bO\d{5}\b", text.upper())
58
+ return match.group(0) if match else None
59
+
60
+
61
+ def chat_fn(user_message, history):
62
+ order_id = extract_order_id(user_message)
63
+
64
+ # If user didn't provide order_id, ask
65
+ if not order_id:
66
+ return "Please provide your Order ID (example: O12488)."
67
+
68
+ # Validate order id format
69
+ if not re.match(VALID_ORDER_PATTERN, order_id):
70
+ return "Order ID format seems invalid. Please enter like O12488."
71
+
72
+ # Ask SQL agent for that order only
73
+ query = f"Retrieve all columns for order_id {order_id}"
74
+ try:
75
+ result = sql_agent.invoke(query)
76
+ content = result.get("output", str(result))
77
+
78
+ # Convert raw output to user-friendly response (simple formatting)
79
+ # You can customize this further.
80
+ return f"Here are the details for Order ID {order_id}:\n\n{content}"
81
+
82
+ except Exception as e:
83
+ return f"Sorry, I couldn't fetch that order right now. Error: {e}"
84
+
85
+
86
+ # --------------------------
87
+ # GRADIO UI
88
+ # --------------------------
89
+ demo = gr.ChatInterface(
90
+ fn=chat_fn,
91
+ title="FoodHub – AI Powered Food Delivery Chatbot",
92
+ description="Ask order queries like: 'Where is my order O12488?' or 'Cancel order O12487'.",
93
+ theme="soft"
94
+ )
95
 
96
  if __name__ == "__main__":
97
+ demo.launch()
customer_orders.db ADDED
Binary file (8.19 kB). View file
 
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ langchain
3
+ langchain-community
4
+ langchain-core
5
+ langchain-groq
6
+ sqlalchemy
7
+ pandas
8
+ numpy