Spaces:
Build error
Build error
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -7,6 +7,7 @@ import pandas as pd
|
|
| 7 |
from datetime import datetime
|
| 8 |
import sqlite3
|
| 9 |
import weave
|
|
|
|
| 10 |
|
| 11 |
from langchain_community.embeddings.sentence_transformer import SentenceTransformerEmbeddings
|
| 12 |
from langchain_community.vectorstores import Chroma
|
|
@@ -16,26 +17,32 @@ from langchain_community.utilities.sql_database import SQLDatabase
|
|
| 16 |
from langchain_community.agent_toolkits import create_sql_agent
|
| 17 |
from langchain.agents import create_tool_calling_agent, AgentExecutor
|
| 18 |
from langchain_core.tools import tool
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
from
|
| 22 |
-
from langchain.chat_models import AzureChatOpenAI # NEW
|
| 23 |
-
AzureChatOpenAI.model_rebuild(_types_namespace={'BaseCache': BaseCache, 'Callbacks': Callbacks})
|
| 24 |
|
| 25 |
from huggingface_hub import CommitScheduler
|
| 26 |
from pathlib import Path
|
| 27 |
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
#====================================SETUP=====================================#
|
| 30 |
# Fetch secrets from Hugging Face Spaces
|
|
|
|
| 31 |
|
|
|
|
| 32 |
|
| 33 |
# Extract the OpenAI key and endpoint from the configuration
|
| 34 |
-
|
| 35 |
-
api_key =
|
| 36 |
-
|
| 37 |
-
api_version =
|
| 38 |
-
|
| 39 |
|
| 40 |
# Define the location of the SQLite database
|
| 41 |
db_loc = 'ecomm.db'
|
|
@@ -49,7 +56,7 @@ database_schema = db.get_table_info()
|
|
| 49 |
|
| 50 |
# Let's initiate w&b weave with a project name - this will automatically save all the llm calls made using openai or gemini
|
| 51 |
# Make sure to save your w&b api key in secrets as WANDB_API_KEY
|
| 52 |
-
|
| 53 |
|
| 54 |
|
| 55 |
#=================================Setup Logging=====================================#
|
|
@@ -105,21 +112,17 @@ full_prompt = ChatPromptTemplate.from_messages(
|
|
| 105 |
MessagesPlaceholder("agent_scratchpad")
|
| 106 |
]
|
| 107 |
)
|
| 108 |
-
|
| 109 |
# Initialize the ChatOpenAI model with the extracted configuration
|
| 110 |
-
|
| 111 |
-
# openai_api_base=endpoint,
|
| 112 |
-
# openai_api_key=api_key,
|
| 113 |
-
# model="gpt-4o-mini",
|
| 114 |
-
# streaming=False # Explicitly disabling streaming
|
| 115 |
-
#)
|
| 116 |
-
llm = AzureChatOpenAI(
|
| 117 |
model_name=model_name,
|
| 118 |
api_key=api_key,
|
| 119 |
-
azure_endpoint=
|
| 120 |
api_version=api_version,
|
| 121 |
-
temperature=0
|
|
|
|
| 122 |
)
|
|
|
|
| 123 |
|
| 124 |
# Create the SQL agent using the ChatOpenAI model, database, and prompt template
|
| 125 |
sqlite_agent = create_sql_agent(
|
|
@@ -191,7 +194,7 @@ Here are some documents and their source that may be relevant to the question me
|
|
| 191 |
{question}
|
| 192 |
"""
|
| 193 |
# Load the persisted DB
|
| 194 |
-
persisted_vectordb_location = 'policy_docs
|
| 195 |
#Create a Colelction Name
|
| 196 |
collection_name = 'policy_docs'
|
| 197 |
|
|
@@ -209,16 +212,13 @@ retriever = vector_store.as_retriever(
|
|
| 209 |
search_kwargs={'k': 5}
|
| 210 |
)
|
| 211 |
|
| 212 |
-
|
| 213 |
-
#client =
|
| 214 |
-
#
|
| 215 |
-
#
|
| 216 |
-
#
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
azure_endpoint=endpoint,
|
| 220 |
-
api_version=api_version
|
| 221 |
-
)
|
| 222 |
|
| 223 |
@tool
|
| 224 |
def rag(user_input: str) -> str:
|
|
@@ -245,12 +245,9 @@ def rag(user_input: str) -> str:
|
|
| 245 |
}
|
| 246 |
]
|
| 247 |
try:
|
| 248 |
-
response =
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
)
|
| 252 |
-
|
| 253 |
-
prediction = response.choices[0].message.content
|
| 254 |
except Exception as e:
|
| 255 |
prediction = f'Sorry, I encountered the following error: \n {e}'
|
| 256 |
|
|
@@ -354,16 +351,12 @@ def days_since(delivered_date: str) ->str:
|
|
| 354 |
def build_prompt(df):
|
| 355 |
|
| 356 |
system_message = f"""
|
| 357 |
-
|
| 358 |
You are an intelligent e-commerce chatbot designed to assist users with pre-order and post-order queries. Your job is to
|
| 359 |
-
|
| 360 |
Gather necessary information from the user to help them with their query.
|
| 361 |
If at any point you cannot determine the next steps - defer to human. you do not have clearance to go beyond the scope the following flow.
|
| 362 |
Do not provide sql inputs to the sql tool - you only need to ask in natural language what information you need.
|
| 363 |
You are only allowed to provide information relevant to the particular customer and the customer information is provided below. you can provide information of this customer only. Following is the information about the customer from the last 2 weeks:
|
| 364 |
-
|
| 365 |
{df}
|
| 366 |
-
|
| 367 |
If this information is not enough to answer question, identify the customer from data above and fetch necessary information usign the sql_tool or rag tool - do not fetch information of other customers.
|
| 368 |
use the details provided in the above file to fetch information from sql tool - like customer id, email and phone. Refrain from asking customers details unless necessary.
|
| 369 |
If customer asks about a product, you should act as a sales representative and help them understand the product as much as possible and provide all the necessary information for them. You should also provide them the link to the product which you can get from the source of the information.
|
|
@@ -375,7 +368,6 @@ def build_prompt(df):
|
|
| 375 |
1. Ask for their feedback and rating out of 5.
|
| 376 |
2. then, Use the `register_feedback` tool to log it. - you MUST ask customer feedback along with asking customer what else they need help with.
|
| 377 |
3. After receving customer feedback exit the chat by responding with 'Bye'.
|
| 378 |
-
|
| 379 |
---
|
| 380 |
### **Handling Out-of-Scope Queries:**
|
| 381 |
If the user's query, at any point is not covered by the workflows above:
|
|
@@ -500,29 +492,19 @@ def chatbot_interface():
|
|
| 500 |
if 'conversation_history' not in st.session_state:
|
| 501 |
st.session_state.conversation_history = [{"role": "assistant", "content": "welcome! I am Raha, how can I help you on this beautiful day?"}]
|
| 502 |
|
| 503 |
-
|
| 504 |
details = fetch_details(st.session_state.email)
|
| 505 |
-
# st.write(details)
|
| 506 |
prompt = build_prompt(details)
|
| 507 |
-
tools = [sql_tool,defer_to_human, rag, register_feedback, days_since]
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
#chatbot = ChatOpenAI(
|
| 511 |
-
#openai_api_base=endpoint,
|
| 512 |
-
#openai_api_key=api_key,
|
| 513 |
-
#model="gpt-4o-mini",
|
| 514 |
-
#streaming=False, # Explicitly disabling streaming
|
| 515 |
-
#temperature=0
|
| 516 |
-
#)
|
| 517 |
-
|
| 518 |
-
chatbot = AzureChatOpenAI(
|
| 519 |
model_name=model_name,
|
| 520 |
api_key=api_key,
|
| 521 |
-
azure_endpoint=
|
| 522 |
api_version=api_version,
|
| 523 |
-
temperature=0
|
|
|
|
| 524 |
)
|
| 525 |
-
|
| 526 |
|
| 527 |
agent = create_tool_calling_agent(chatbot, tools, prompt)
|
| 528 |
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
|
|
@@ -534,11 +516,8 @@ def chatbot_interface():
|
|
| 534 |
|
| 535 |
# React to user input
|
| 536 |
if user_input := st.chat_input("You: ", key="chat_input"):
|
| 537 |
-
# Display user message in chat message container
|
| 538 |
st.chat_message("user").markdown(user_input)
|
| 539 |
with st.spinner("Processing..."):
|
| 540 |
-
|
| 541 |
-
# Add user message to conversation history
|
| 542 |
st.session_state.conversation_history.append({"role": "user", "content": user_input})
|
| 543 |
|
| 544 |
conversation_input = "\n".join(
|
|
@@ -546,22 +525,19 @@ def chatbot_interface():
|
|
| 546 |
)
|
| 547 |
|
| 548 |
try:
|
| 549 |
-
# Pass the history to the agent
|
| 550 |
response = agent_executor.invoke({"input": conversation_input})
|
| 551 |
|
| 552 |
-
# Add the chatbot's response to the history
|
| 553 |
chatbot_response = response['output']
|
| 554 |
st.session_state.conversation_history.append({"role": "assistant", "content": chatbot_response})
|
| 555 |
-
|
| 556 |
if "bye" in chatbot_response.lower():
|
| 557 |
-
log_history(st.session_state.email,st.session_state.conversation_history)
|
| 558 |
|
| 559 |
-
# Display the chatbot's response
|
| 560 |
with st.chat_message("assistant"):
|
| 561 |
st.markdown(chatbot_response)
|
| 562 |
|
| 563 |
except Exception as e:
|
| 564 |
-
st.write("Blocked by content policy \n", e
|
| 565 |
|
| 566 |
def main():
|
| 567 |
# Check if the user is logged in
|
|
|
|
| 7 |
from datetime import datetime
|
| 8 |
import sqlite3
|
| 9 |
import weave
|
| 10 |
+
import wandb
|
| 11 |
|
| 12 |
from langchain_community.embeddings.sentence_transformer import SentenceTransformerEmbeddings
|
| 13 |
from langchain_community.vectorstores import Chroma
|
|
|
|
| 17 |
from langchain_community.agent_toolkits import create_sql_agent
|
| 18 |
from langchain.agents import create_tool_calling_agent, AgentExecutor
|
| 19 |
from langchain_core.tools import tool
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
from langchain_openai import AzureChatOpenAI
|
|
|
|
|
|
|
| 23 |
|
| 24 |
from huggingface_hub import CommitScheduler
|
| 25 |
from pathlib import Path
|
| 26 |
|
| 27 |
+
from langchain_openai import AzureChatOpenAI
|
| 28 |
+
from typing import Union
|
| 29 |
+
class NonStreamingAzureChatOpenAI(AzureChatOpenAI):
|
| 30 |
+
def stream(self, input, config=None, **kwargs):
|
| 31 |
+
# Emulate streaming by calling invoke and yielding once
|
| 32 |
+
result = self.invoke(input, config=config, **kwargs)
|
| 33 |
+
yield result
|
| 34 |
#====================================SETUP=====================================#
|
| 35 |
# Fetch secrets from Hugging Face Spaces
|
| 36 |
+
wandb.login(key=st.secrets["WANDB_API_KEY"])
|
| 37 |
|
| 38 |
+
model_name = st.secrets["CHATGPT_MODEL"]
|
| 39 |
|
| 40 |
# Extract the OpenAI key and endpoint from the configuration
|
| 41 |
+
|
| 42 |
+
api_key = st.secrets["AZURE_OPENAI_KEY"]
|
| 43 |
+
azure_endpoint = st.secrets["AZURE_OPENAI_ENDPOINT"]
|
| 44 |
+
api_version = st.secrets["AZURE_OPENAI_APIVERSION"]
|
| 45 |
+
|
| 46 |
|
| 47 |
# Define the location of the SQLite database
|
| 48 |
db_loc = 'ecomm.db'
|
|
|
|
| 56 |
|
| 57 |
# Let's initiate w&b weave with a project name - this will automatically save all the llm calls made using openai or gemini
|
| 58 |
# Make sure to save your w&b api key in secrets as WANDB_API_KEY
|
| 59 |
+
weave.init('ecomm_support')
|
| 60 |
|
| 61 |
|
| 62 |
#=================================Setup Logging=====================================#
|
|
|
|
| 112 |
MessagesPlaceholder("agent_scratchpad")
|
| 113 |
]
|
| 114 |
)
|
| 115 |
+
|
| 116 |
# Initialize the ChatOpenAI model with the extracted configuration
|
| 117 |
+
llm = NonStreamingAzureChatOpenAI(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
model_name=model_name,
|
| 119 |
api_key=api_key,
|
| 120 |
+
azure_endpoint=azure_endpoint,
|
| 121 |
api_version=api_version,
|
| 122 |
+
temperature=0,
|
| 123 |
+
streaming=False
|
| 124 |
)
|
| 125 |
+
print("Streaming enabled?", llm.streaming)
|
| 126 |
|
| 127 |
# Create the SQL agent using the ChatOpenAI model, database, and prompt template
|
| 128 |
sqlite_agent = create_sql_agent(
|
|
|
|
| 194 |
{question}
|
| 195 |
"""
|
| 196 |
# Load the persisted DB
|
| 197 |
+
persisted_vectordb_location = 'policy_docs'
|
| 198 |
#Create a Colelction Name
|
| 199 |
collection_name = 'policy_docs'
|
| 200 |
|
|
|
|
| 212 |
search_kwargs={'k': 5}
|
| 213 |
)
|
| 214 |
|
| 215 |
+
|
| 216 |
+
# client = AzureOpenAI(
|
| 217 |
+
# azure_endpoint=creds["AZURE_OPENAI_ENDPOINT"],
|
| 218 |
+
# api_key=creds["AZURE_OPENAI_KEY"],
|
| 219 |
+
# api_version=creds["AZURE_OPENAI_APIVERSION"]
|
| 220 |
+
# )
|
| 221 |
+
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
@tool
|
| 224 |
def rag(user_input: str) -> str:
|
|
|
|
| 245 |
}
|
| 246 |
]
|
| 247 |
try:
|
| 248 |
+
response = llm.invoke(prompt)
|
| 249 |
+
prediction = response.content
|
| 250 |
+
# prediction = response.choices[0].message.content
|
|
|
|
|
|
|
|
|
|
| 251 |
except Exception as e:
|
| 252 |
prediction = f'Sorry, I encountered the following error: \n {e}'
|
| 253 |
|
|
|
|
| 351 |
def build_prompt(df):
|
| 352 |
|
| 353 |
system_message = f"""
|
|
|
|
| 354 |
You are an intelligent e-commerce chatbot designed to assist users with pre-order and post-order queries. Your job is to
|
|
|
|
| 355 |
Gather necessary information from the user to help them with their query.
|
| 356 |
If at any point you cannot determine the next steps - defer to human. you do not have clearance to go beyond the scope the following flow.
|
| 357 |
Do not provide sql inputs to the sql tool - you only need to ask in natural language what information you need.
|
| 358 |
You are only allowed to provide information relevant to the particular customer and the customer information is provided below. you can provide information of this customer only. Following is the information about the customer from the last 2 weeks:
|
|
|
|
| 359 |
{df}
|
|
|
|
| 360 |
If this information is not enough to answer question, identify the customer from data above and fetch necessary information usign the sql_tool or rag tool - do not fetch information of other customers.
|
| 361 |
use the details provided in the above file to fetch information from sql tool - like customer id, email and phone. Refrain from asking customers details unless necessary.
|
| 362 |
If customer asks about a product, you should act as a sales representative and help them understand the product as much as possible and provide all the necessary information for them. You should also provide them the link to the product which you can get from the source of the information.
|
|
|
|
| 368 |
1. Ask for their feedback and rating out of 5.
|
| 369 |
2. then, Use the `register_feedback` tool to log it. - you MUST ask customer feedback along with asking customer what else they need help with.
|
| 370 |
3. After receving customer feedback exit the chat by responding with 'Bye'.
|
|
|
|
| 371 |
---
|
| 372 |
### **Handling Out-of-Scope Queries:**
|
| 373 |
If the user's query, at any point is not covered by the workflows above:
|
|
|
|
| 492 |
if 'conversation_history' not in st.session_state:
|
| 493 |
st.session_state.conversation_history = [{"role": "assistant", "content": "welcome! I am Raha, how can I help you on this beautiful day?"}]
|
| 494 |
|
|
|
|
| 495 |
details = fetch_details(st.session_state.email)
|
|
|
|
| 496 |
prompt = build_prompt(details)
|
| 497 |
+
tools = [sql_tool, defer_to_human, rag, register_feedback, days_since]
|
| 498 |
+
|
| 499 |
+
chatbot = NonStreamingAzureChatOpenAI(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
model_name=model_name,
|
| 501 |
api_key=api_key,
|
| 502 |
+
azure_endpoint=azure_endpoint,
|
| 503 |
api_version=api_version,
|
| 504 |
+
temperature=0,
|
| 505 |
+
streaming=False
|
| 506 |
)
|
| 507 |
+
print("Streaming enabled?", chatbot.streaming)
|
| 508 |
|
| 509 |
agent = create_tool_calling_agent(chatbot, tools, prompt)
|
| 510 |
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
|
|
|
|
| 516 |
|
| 517 |
# React to user input
|
| 518 |
if user_input := st.chat_input("You: ", key="chat_input"):
|
|
|
|
| 519 |
st.chat_message("user").markdown(user_input)
|
| 520 |
with st.spinner("Processing..."):
|
|
|
|
|
|
|
| 521 |
st.session_state.conversation_history.append({"role": "user", "content": user_input})
|
| 522 |
|
| 523 |
conversation_input = "\n".join(
|
|
|
|
| 525 |
)
|
| 526 |
|
| 527 |
try:
|
|
|
|
| 528 |
response = agent_executor.invoke({"input": conversation_input})
|
| 529 |
|
|
|
|
| 530 |
chatbot_response = response['output']
|
| 531 |
st.session_state.conversation_history.append({"role": "assistant", "content": chatbot_response})
|
| 532 |
+
|
| 533 |
if "bye" in chatbot_response.lower():
|
| 534 |
+
log_history(st.session_state.email, st.session_state.conversation_history)
|
| 535 |
|
|
|
|
| 536 |
with st.chat_message("assistant"):
|
| 537 |
st.markdown(chatbot_response)
|
| 538 |
|
| 539 |
except Exception as e:
|
| 540 |
+
st.write("Blocked by content policy \n", e)
|
| 541 |
|
| 542 |
def main():
|
| 543 |
# Check if the user is logged in
|