Disha252001 commited on
Commit
807d6fe
Β·
1 Parent(s): 1d85e16

Fix LangChain imports and pin versions

Browse files
Files changed (2) hide show
  1. app.py +70 -53
  2. requirements.txt +6 -8
app.py CHANGED
@@ -3,94 +3,111 @@ import re
3
  import gradio as gr
4
 
5
  from langchain_groq import ChatGroq
 
 
 
6
  from langchain_community.utilities import SQLDatabase
7
  from langchain_community.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__":
 
3
  import gradio as gr
4
 
5
  from langchain_groq import ChatGroq
6
+ from langchain_core.messages import SystemMessage
7
+
8
+ # βœ… Correct imports for SQLDatabase + Toolkit (HF-safe)
9
  from langchain_community.utilities import SQLDatabase
10
  from langchain_community.agent_toolkits import SQLDatabaseToolkit
11
+
12
+ # βœ… Correct import path for create_sql_agent (NOT langchain.agents)
13
+ from langchain_community.agent_toolkits.sql.base import create_sql_agent
14
 
15
 
16
+ # -----------------------------
17
+ # Config
18
+ # -----------------------------
19
+ MODEL_NAME = os.getenv("GROQ_MODEL", "meta-llama/llama-3.1-8b-instant")
20
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
21
 
22
+ if not GROQ_API_KEY:
23
+ raise ValueError(
24
+ "❌ GROQ_API_KEY not found. Add it in Hugging Face: Settings β†’ Secrets β†’ GROQ_API_KEY"
25
+ )
26
 
27
+ DB_PATH = "customer_orders.db" # must be in same Space repo
28
+ DB_URI = f"sqlite:///{DB_PATH}"
29
+
30
+ if not os.path.exists(DB_PATH):
31
+ raise FileNotFoundError(
32
+ f"❌ Database file '{DB_PATH}' not found. Make sure customer_orders.db is committed to the Space repo."
33
+ )
34
+
35
+ # -----------------------------
36
+ # LLM
37
+ # -----------------------------
38
  llm = ChatGroq(
39
  model=MODEL_NAME,
40
+ temperature=0, # deterministic
41
  max_tokens=300,
42
+ groq_api_key=GROQ_API_KEY
43
  )
44
 
45
+ # -----------------------------
46
+ # Database + SQL Agent
47
+ # -----------------------------
48
+ db = SQLDatabase.from_uri(DB_URI)
49
  toolkit = SQLDatabaseToolkit(db=db, llm=llm)
50
 
51
+ system_message = SystemMessage(content=
52
+ "You are FoodHub customer support. "
53
+ "You can query the database safely using SQL tools. "
54
+ "Rules: (1) Never return bulk data. (2) Only answer for a single order_id. "
55
+ "(3) If order_id missing, ask for it. (4) Keep replies short and professional."
56
+ )
 
 
 
 
57
 
58
  sql_agent = create_sql_agent(
59
  llm=llm,
60
  toolkit=toolkit,
61
+ verbose=False, # set True only if you want logs
62
  system_message=system_message
63
  )
64
 
65
+ ORDER_ID_PATTERN = re.compile(r"\bO\d{5}\b", re.IGNORECASE)
 
66
 
67
  def extract_order_id(text: str):
68
+ m = ORDER_ID_PATTERN.search(text or "")
69
+ return m.group(0).upper() if m else None
70
 
71
 
72
+ # -----------------------------
73
+ # Chatbot logic
74
+ # -----------------------------
75
+ def respond(user_message, history):
76
+ user_message = (user_message or "").strip()
77
 
78
+ # 1) If order id not provided, ask for it
79
+ order_id = extract_order_id(user_message)
80
  if not order_id:
81
  return "Please provide your Order ID (example: O12488)."
82
 
83
+ # 2) Ask SQL agent for that one order only (safe query)
84
+ # Keep query explicit to avoid the agent doing broad selects
85
+ agent_query = (
86
+ f"Retrieve all columns for order_id '{order_id}' from the orders table. "
87
+ f"Then summarize the order status and payment status in 2-3 short sentences."
88
+ )
89
 
 
 
90
  try:
91
+ result = sql_agent.invoke({"input": agent_query})
92
+ # result is usually dict with "output"
93
+ output_text = result.get("output", str(result))
94
+ return output_text
 
 
 
95
  except Exception as e:
96
+ return f"Sorry β€” I couldn’t fetch that order right now. Please try again. (Error: {type(e).__name__})"
97
 
98
 
99
+ # -----------------------------
100
+ # Gradio UI
101
+ # -----------------------------
102
  demo = gr.ChatInterface(
103
+ fn=respond,
104
  title="FoodHub – AI Powered Food Delivery Chatbot",
105
+ description="Ask order-related questions. Include your Order ID like O12488.",
106
+ examples=[
107
+ "Where is my order? O12488",
108
+ "What is the payment status of order O12488?",
109
+ "I want to cancel my order O12487"
110
+ ],
111
  )
112
 
113
  if __name__ == "__main__":
requirements.txt CHANGED
@@ -1,8 +1,6 @@
1
- gradio
2
- langchain
3
- langchain-community
4
- langchain-core
5
- langchain-groq
6
- sqlalchemy
7
- pandas
8
- numpy
 
1
+ gradio==4.44.1
2
+ langchain==0.2.17
3
+ langchain-core==0.2.43
4
+ langchain-community==0.2.19
5
+ langchain-groq==0.1.9
6
+ sqlalchemy==2.0.32git add app.py requirements.txt customer_orders.db