mirror of
https://github.com/Shubhamsaboo/awesome-llm-apps.git
synced 2026-05-02 18:45:05 -05:00
changes made
This commit is contained in:
@@ -28,7 +28,7 @@ The app expects Qdrant to be running on localhost:6333. Adjust the configuration
|
||||
docker pull qdrant/qdrant
|
||||
|
||||
docker run -p 6333:6333 -p 6334:6334 \
|
||||
-v $(pwd)/qdrant_storage:/qdrant/storage:z \
|
||||
-v "$(pwd)/qdrant_storage:/qdrant/storage:z" \
|
||||
qdrant/qdrant
|
||||
```
|
||||
|
||||
|
||||
@@ -14,86 +14,115 @@ openai_api_key = st.text_input("Enter OpenAI API Key", type="password")
|
||||
|
||||
if openai_api_key:
|
||||
os.environ['OPENAI_API_KEY'] = openai_api_key
|
||||
|
||||
|
||||
class CustomerSupportAIAgent:
|
||||
def __init__(self):
|
||||
# Initialize Mem0 with Qdrant as the vector store
|
||||
config = {
|
||||
"vector_store": {
|
||||
"provider": "qdrant",
|
||||
"config": {
|
||||
"model": "gpt-4o-mini",
|
||||
"host": "localhost",
|
||||
"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.app_id = "customer-support"
|
||||
|
||||
def handle_query(self, query, user_id=None):
|
||||
relevant_memories = self.memory.search(query=query, user_id=user_id)
|
||||
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"
|
||||
try:
|
||||
# Search for relevant memories
|
||||
relevant_memories = self.memory.search(query=query, user_id=user_id)
|
||||
|
||||
# Build context from relevant memories
|
||||
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(
|
||||
model="gpt-4o-mini",
|
||||
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
|
||||
# Add the query and answer to memory
|
||||
self.memory.add(query, user_id=user_id, metadata={"app_id": self.app_id, "role": "user"})
|
||||
self.memory.add(answer, user_id=user_id, metadata={"app_id": self.app_id, "role": "assistant"})
|
||||
|
||||
self.memory.add(query, user_id=user_id, metadata={"app_id": self.app_id, "role": "user"})
|
||||
self.memory.add(answer, user_id=user_id, metadata={"app_id": self.app_id, "role": "assistant"})
|
||||
|
||||
return answer
|
||||
return answer
|
||||
except Exception as e:
|
||||
st.error(f"An error occurred while handling the query: {e}")
|
||||
return "Sorry, I encountered an error. Please try again later."
|
||||
|
||||
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):
|
||||
today = datetime.now()
|
||||
order_date = (today - timedelta(days=10)).strftime("%B %d, %Y")
|
||||
expected_delivery = (today + timedelta(days=2)).strftime("%B %d, %Y")
|
||||
def generate_synthetic_data(self, user_id: str) -> dict | None:
|
||||
try:
|
||||
today = datetime.now()
|
||||
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:
|
||||
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})
|
||||
3. Order details (product, price, order number)
|
||||
4. Customer's shipping address
|
||||
5. 2-3 previous orders from the past year
|
||||
6. 2-3 customer service interactions related to these orders
|
||||
7. Any preferences or patterns in their shopping behavior
|
||||
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
|
||||
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)
|
||||
4. Customer's shipping address
|
||||
5. 2-3 previous orders from the past year
|
||||
6. 2-3 customer service interactions related to these orders
|
||||
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(
|
||||
model="gpt-4o-mini",
|
||||
messages=[
|
||||
{"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}
|
||||
],
|
||||
response_format={"type": "json_object"}
|
||||
)
|
||||
response = self.client.chat.completions.create(
|
||||
model="gpt-4",
|
||||
messages=[
|
||||
{"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}
|
||||
]
|
||||
)
|
||||
|
||||
customer_data = json.loads(response.choices[0].message.content)
|
||||
customer_data = json.loads(response.choices[0].message.content)
|
||||
|
||||
# Add generated data to memory
|
||||
for key, value in customer_data.items():
|
||||
if isinstance(value, list):
|
||||
for item in value:
|
||||
self.memory.add(json.dumps(item), 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"})
|
||||
# Add generated data to memory
|
||||
for key, value in customer_data.items():
|
||||
if isinstance(value, list):
|
||||
for item in value:
|
||||
self.memory.add(
|
||||
json.dumps(item),
|
||||
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
|
||||
support_agent = CustomerSupportAIAgent()
|
||||
@@ -113,7 +142,10 @@ if openai_api_key:
|
||||
if customer_id:
|
||||
with st.spinner("Generating customer data..."):
|
||||
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:
|
||||
st.sidebar.error("Please enter a customer ID first.")
|
||||
|
||||
@@ -156,7 +188,8 @@ if openai_api_key:
|
||||
st.markdown(query)
|
||||
|
||||
# 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
|
||||
st.session_state.messages.append({"role": "assistant", "content": answer})
|
||||
|
||||
Reference in New Issue
Block a user