changes made
This commit is contained in:
parent
abb2cffa62
commit
a57138b7bc
2 changed files with 89 additions and 56 deletions
|
|
@ -28,7 +28,7 @@ The app expects Qdrant to be running on localhost:6333. Adjust the configuration
|
||||||
docker pull qdrant/qdrant
|
docker pull qdrant/qdrant
|
||||||
|
|
||||||
docker run -p 6333:6333 -p 6334:6334 \
|
docker run -p 6333:6333 -p 6334:6334 \
|
||||||
-v $(pwd)/qdrant_storage:/qdrant/storage:z \
|
-v "$(pwd)/qdrant_storage:/qdrant/storage:z" \
|
||||||
qdrant/qdrant
|
qdrant/qdrant
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,86 +14,115 @@ openai_api_key = st.text_input("Enter OpenAI API Key", type="password")
|
||||||
|
|
||||||
if openai_api_key:
|
if openai_api_key:
|
||||||
os.environ['OPENAI_API_KEY'] = openai_api_key
|
os.environ['OPENAI_API_KEY'] = openai_api_key
|
||||||
|
|
||||||
class CustomerSupportAIAgent:
|
class CustomerSupportAIAgent:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
|
# Initialize Mem0 with Qdrant as the vector store
|
||||||
config = {
|
config = {
|
||||||
"vector_store": {
|
"vector_store": {
|
||||||
"provider": "qdrant",
|
"provider": "qdrant",
|
||||||
"config": {
|
"config": {
|
||||||
"model": "gpt-4o-mini",
|
|
||||||
"host": "localhost",
|
"host": "localhost",
|
||||||
"port": 6333,
|
"port": 6333,
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
self.memory = Memory.from_config(config)
|
try:
|
||||||
|
self.memory = Memory.from_config(config)
|
||||||
|
except Exception as e:
|
||||||
|
st.error(f"Failed to initialize memory: {e}")
|
||||||
|
st.stop() # Stop execution if memory initialization fails
|
||||||
|
|
||||||
self.client = OpenAI()
|
self.client = OpenAI()
|
||||||
self.app_id = "customer-support"
|
self.app_id = "customer-support"
|
||||||
|
|
||||||
def handle_query(self, query, user_id=None):
|
def handle_query(self, query, user_id=None):
|
||||||
relevant_memories = self.memory.search(query=query, user_id=user_id)
|
try:
|
||||||
context = "Relevant past information:\n"
|
# Search for relevant memories
|
||||||
if relevant_memories and "results" in relevant_memories:
|
relevant_memories = self.memory.search(query=query, user_id=user_id)
|
||||||
for memory in relevant_memories["results"]:
|
|
||||||
if "memory" in memory:
|
# Build context from relevant memories
|
||||||
context += f"- {memory['memory']}\n"
|
context = "Relevant past information:\n"
|
||||||
|
if relevant_memories and "results" in relevant_memories:
|
||||||
|
for memory in relevant_memories["results"]:
|
||||||
|
if "memory" in memory:
|
||||||
|
context += f"- {memory['memory']}\n"
|
||||||
|
|
||||||
full_prompt = f"{context}\nCustomer: {query}\nSupport Agent:"
|
# Generate a response using OpenAI
|
||||||
|
full_prompt = f"{context}\nCustomer: {query}\nSupport Agent:"
|
||||||
|
response = self.client.chat.completions.create(
|
||||||
|
model="gpt-4",
|
||||||
|
messages=[
|
||||||
|
{"role": "system", "content": "You are a customer support AI agent for TechGadgets.com, an online electronics store."},
|
||||||
|
{"role": "user", "content": full_prompt}
|
||||||
|
]
|
||||||
|
)
|
||||||
|
answer = response.choices[0].message.content
|
||||||
|
|
||||||
response = self.client.chat.completions.create(
|
# Add the query and answer to memory
|
||||||
model="gpt-4o-mini",
|
self.memory.add(query, user_id=user_id, metadata={"app_id": self.app_id, "role": "user"})
|
||||||
messages=[
|
self.memory.add(answer, user_id=user_id, metadata={"app_id": self.app_id, "role": "assistant"})
|
||||||
{"role": "system", "content": "You are a customer support AI agent for TechGadgets.com, an online electronics store."},
|
|
||||||
{"role": "user", "content": full_prompt}
|
|
||||||
]
|
|
||||||
)
|
|
||||||
answer = response.choices[0].message.content
|
|
||||||
|
|
||||||
self.memory.add(query, user_id=user_id, metadata={"app_id": self.app_id, "role": "user"})
|
return answer
|
||||||
self.memory.add(answer, user_id=user_id, metadata={"app_id": self.app_id, "role": "assistant"})
|
except Exception as e:
|
||||||
|
st.error(f"An error occurred while handling the query: {e}")
|
||||||
return answer
|
return "Sorry, I encountered an error. Please try again later."
|
||||||
|
|
||||||
def get_memories(self, user_id=None):
|
def get_memories(self, user_id=None):
|
||||||
return self.memory.get_all(user_id=user_id)
|
try:
|
||||||
|
# Retrieve all memories for a user
|
||||||
|
return self.memory.get_all(user_id=user_id)
|
||||||
|
except Exception as e:
|
||||||
|
st.error(f"Failed to retrieve memories: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
def generate_synthetic_data(self, user_id):
|
def generate_synthetic_data(self, user_id: str) -> dict | None:
|
||||||
today = datetime.now()
|
try:
|
||||||
order_date = (today - timedelta(days=10)).strftime("%B %d, %Y")
|
today = datetime.now()
|
||||||
expected_delivery = (today + timedelta(days=2)).strftime("%B %d, %Y")
|
order_date = (today - timedelta(days=10)).strftime("%B %d, %Y")
|
||||||
|
expected_delivery = (today + timedelta(days=2)).strftime("%B %d, %Y")
|
||||||
|
|
||||||
prompt = f"""Generate a detailed customer profile and order history for a TechGadgets.com customer with ID {user_id}. Include:
|
prompt = f"""Generate a detailed customer profile and order history for a TechGadgets.com customer with ID {user_id}. Include:
|
||||||
1. Customer name and basic info
|
1. Customer name and basic info
|
||||||
2. A recent order of a high-end electronic device (placed on {order_date}, to be delivered by {expected_delivery})
|
2. A recent order of a high-end electronic device (placed on {order_date}, to be delivered by {expected_delivery})
|
||||||
3. Order details (product, price, order number)
|
3. Order details (product, price, order number)
|
||||||
4. Customer's shipping address
|
4. Customer's shipping address
|
||||||
5. 2-3 previous orders from the past year
|
5. 2-3 previous orders from the past year
|
||||||
6. 2-3 customer service interactions related to these orders
|
6. 2-3 customer service interactions related to these orders
|
||||||
7. Any preferences or patterns in their shopping behavior
|
7. Any preferences or patterns in their shopping behavior
|
||||||
|
|
||||||
Format the output as a JSON object."""
|
Format the output as a JSON object."""
|
||||||
|
|
||||||
response = self.client.chat.completions.create(
|
response = self.client.chat.completions.create(
|
||||||
model="gpt-4o-mini",
|
model="gpt-4",
|
||||||
messages=[
|
messages=[
|
||||||
{"role": "system", "content": "You are a data generation AI that creates realistic customer profiles and order histories. Always respond with valid JSON."},
|
{"role": "system", "content": "You are a data generation AI that creates realistic customer profiles and order histories. Always respond with valid JSON."},
|
||||||
{"role": "user", "content": prompt}
|
{"role": "user", "content": prompt}
|
||||||
],
|
]
|
||||||
response_format={"type": "json_object"}
|
)
|
||||||
)
|
|
||||||
|
|
||||||
customer_data = json.loads(response.choices[0].message.content)
|
customer_data = json.loads(response.choices[0].message.content)
|
||||||
|
|
||||||
# Add generated data to memory
|
# Add generated data to memory
|
||||||
for key, value in customer_data.items():
|
for key, value in customer_data.items():
|
||||||
if isinstance(value, list):
|
if isinstance(value, list):
|
||||||
for item in value:
|
for item in value:
|
||||||
self.memory.add(json.dumps(item), user_id=user_id, metadata={"app_id": self.app_id, "role": "system"})
|
self.memory.add(
|
||||||
else:
|
json.dumps(item),
|
||||||
self.memory.add(f"{key}: {json.dumps(value)}", user_id=user_id, metadata={"app_id": self.app_id, "role": "system"})
|
user_id=user_id,
|
||||||
|
metadata={"app_id": self.app_id, "role": "system"}
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.memory.add(
|
||||||
|
f"{key}: {json.dumps(value)}",
|
||||||
|
user_id=user_id,
|
||||||
|
metadata={"app_id": self.app_id, "role": "system"}
|
||||||
|
)
|
||||||
|
|
||||||
return customer_data
|
return customer_data
|
||||||
|
except Exception as e:
|
||||||
|
st.error(f"Failed to generate synthetic data: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
# Initialize the CustomerSupportAIAgent
|
# Initialize the CustomerSupportAIAgent
|
||||||
support_agent = CustomerSupportAIAgent()
|
support_agent = CustomerSupportAIAgent()
|
||||||
|
|
@ -113,7 +142,10 @@ if openai_api_key:
|
||||||
if customer_id:
|
if customer_id:
|
||||||
with st.spinner("Generating customer data..."):
|
with st.spinner("Generating customer data..."):
|
||||||
st.session_state.customer_data = support_agent.generate_synthetic_data(customer_id)
|
st.session_state.customer_data = support_agent.generate_synthetic_data(customer_id)
|
||||||
st.sidebar.success("Synthetic data generated successfully!")
|
if st.session_state.customer_data:
|
||||||
|
st.sidebar.success("Synthetic data generated successfully!")
|
||||||
|
else:
|
||||||
|
st.sidebar.error("Failed to generate synthetic data.")
|
||||||
else:
|
else:
|
||||||
st.sidebar.error("Please enter a customer ID first.")
|
st.sidebar.error("Please enter a customer ID first.")
|
||||||
|
|
||||||
|
|
@ -156,7 +188,8 @@ if openai_api_key:
|
||||||
st.markdown(query)
|
st.markdown(query)
|
||||||
|
|
||||||
# Generate and display response
|
# Generate and display response
|
||||||
answer = support_agent.handle_query(query, user_id=customer_id)
|
with st.spinner("Generating response..."):
|
||||||
|
answer = support_agent.handle_query(query, user_id=customer_id)
|
||||||
|
|
||||||
# Add assistant response to chat history
|
# Add assistant response to chat history
|
||||||
st.session_state.messages.append({"role": "assistant", "content": answer})
|
st.session_state.messages.append({"role": "assistant", "content": answer})
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue