thisisdev commited on
Commit
9cc7f92
·
verified ·
1 Parent(s): fe93fa0

Main Function for Customer Support Agent

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +201 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,203 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ from openai import OpenAI
3
+ from mem0 import Memory
4
+ import os
5
+ import json
6
+ from datetime import datetime, timedelta
7
 
8
+ # Set up the Streamlit App
9
+ st.title("AI Customer Support Agent with Memory 🛒")
10
+ st.caption("Chat with a customer support assistant who remembers your past interactions.")
11
+
12
+ # Set the OpenAI API key
13
+ openai_api_key = st.text_input("Enter OpenAI API Key", type="password")
14
+
15
+ if openai_api_key:
16
+ os.environ['OPENAI_API_KEY'] = openai_api_key
17
+
18
+ class CustomerSupportAIAgent:
19
+ def __init__(self):
20
+ # Initialize Mem0 with Qdrant as the vector store
21
+ config = {
22
+ "vector_store": {
23
+ "provider": "qdrant",
24
+ "config": {
25
+ "host": "localhost",
26
+ "port": 6333,
27
+ }
28
+ },
29
+ }
30
+ try:
31
+ self.memory = Memory.from_config(config)
32
+ except Exception as e:
33
+ st.error(f"Failed to initialize memory: {e}")
34
+ st.stop() # Stop execution if memory initialization fails
35
+
36
+ self.client = OpenAI()
37
+ self.app_id = "customer-support"
38
+
39
+ def handle_query(self, query, user_id=None):
40
+ try:
41
+ # Search for relevant memories
42
+ relevant_memories = self.memory.search(query=query, user_id=user_id)
43
+
44
+ # Build context from relevant memories
45
+ context = "Relevant past information:\n"
46
+ if relevant_memories and "results" in relevant_memories:
47
+ for memory in relevant_memories["results"]:
48
+ if "memory" in memory:
49
+ context += f"- {memory['memory']}\n"
50
+
51
+ # Generate a response using OpenAI
52
+ full_prompt = f"{context}\nCustomer: {query}\nSupport Agent:"
53
+ response = self.client.chat.completions.create(
54
+ model="gpt-4",
55
+ messages=[
56
+ {"role": "system", "content": "You are a customer support AI agent for TechGadgets.com, an online electronics store."},
57
+ {"role": "user", "content": full_prompt}
58
+ ]
59
+ )
60
+ answer = response.choices[0].message.content
61
+
62
+ # Add the query and answer to memory
63
+ self.memory.add(query, user_id=user_id, metadata={"app_id": self.app_id, "role": "user"})
64
+ self.memory.add(answer, user_id=user_id, metadata={"app_id": self.app_id, "role": "assistant"})
65
+
66
+ return answer
67
+ except Exception as e:
68
+ st.error(f"An error occurred while handling the query: {e}")
69
+ return "Sorry, I encountered an error. Please try again later."
70
+
71
+ def get_memories(self, user_id=None):
72
+ try:
73
+ # Retrieve all memories for a user
74
+ return self.memory.get_all(user_id=user_id)
75
+ except Exception as e:
76
+ st.error(f"Failed to retrieve memories: {e}")
77
+ return None
78
+
79
+ def generate_synthetic_data(self, user_id: str) -> dict | None:
80
+ try:
81
+ today = datetime.now()
82
+ order_date = (today - timedelta(days=10)).strftime("%B %d, %Y")
83
+ expected_delivery = (today + timedelta(days=2)).strftime("%B %d, %Y")
84
+
85
+ prompt = f"""Generate a detailed customer profile and order history for a TechGadgets.com customer with ID {user_id}. Include:
86
+ 1. Customer name and basic info
87
+ 2. A recent order of a high-end electronic device (placed on {order_date}, to be delivered by {expected_delivery})
88
+ 3. Order details (product, price, order number)
89
+ 4. Customer's shipping address
90
+ 5. 2-3 previous orders from the past year
91
+ 6. 2-3 customer service interactions related to these orders
92
+ 7. Any preferences or patterns in their shopping behavior
93
+
94
+ Format the output as a JSON object."""
95
+
96
+ response = self.client.chat.completions.create(
97
+ model="gpt-4",
98
+ messages=[
99
+ {"role": "system", "content": "You are a data generation AI that creates realistic customer profiles and order histories. Always respond with valid JSON."},
100
+ {"role": "user", "content": prompt}
101
+ ]
102
+ )
103
+
104
+ customer_data = json.loads(response.choices[0].message.content)
105
+
106
+ # Add generated data to memory
107
+ for key, value in customer_data.items():
108
+ if isinstance(value, list):
109
+ for item in value:
110
+ self.memory.add(
111
+ json.dumps(item),
112
+ user_id=user_id,
113
+ metadata={"app_id": self.app_id, "role": "system"}
114
+ )
115
+ else:
116
+ self.memory.add(
117
+ f"{key}: {json.dumps(value)}",
118
+ user_id=user_id,
119
+ metadata={"app_id": self.app_id, "role": "system"}
120
+ )
121
+
122
+ return customer_data
123
+ except Exception as e:
124
+ st.error(f"Failed to generate synthetic data: {e}")
125
+ return None
126
+
127
+ # Initialize the CustomerSupportAIAgent
128
+ support_agent = CustomerSupportAIAgent()
129
+
130
+ # Sidebar for customer ID and memory view
131
+ st.sidebar.title("Enter your Customer ID:")
132
+ previous_customer_id = st.session_state.get("previous_customer_id", None)
133
+ customer_id = st.sidebar.text_input("Enter your Customer ID")
134
+
135
+ if customer_id != previous_customer_id:
136
+ st.session_state.messages = []
137
+ st.session_state.previous_customer_id = customer_id
138
+ st.session_state.customer_data = None
139
+
140
+ # Add button to generate synthetic data
141
+ if st.sidebar.button("Generate Synthetic Data"):
142
+ if customer_id:
143
+ with st.spinner("Generating customer data..."):
144
+ st.session_state.customer_data = support_agent.generate_synthetic_data(customer_id)
145
+ if st.session_state.customer_data:
146
+ st.sidebar.success("Synthetic data generated successfully!")
147
+ else:
148
+ st.sidebar.error("Failed to generate synthetic data.")
149
+ else:
150
+ st.sidebar.error("Please enter a customer ID first.")
151
+
152
+ if st.sidebar.button("View Customer Profile"):
153
+ if st.session_state.customer_data:
154
+ st.sidebar.json(st.session_state.customer_data)
155
+ else:
156
+ st.sidebar.info("No customer data generated yet. Click 'Generate Synthetic Data' first.")
157
+
158
+ if st.sidebar.button("View Memory Info"):
159
+ if customer_id:
160
+ memories = support_agent.get_memories(user_id=customer_id)
161
+ if memories:
162
+ st.sidebar.write(f"Memory for customer **{customer_id}**:")
163
+ if memories and "results" in memories:
164
+ for memory in memories["results"]:
165
+ if "memory" in memory:
166
+ st.write(f"- {memory['memory']}")
167
+ else:
168
+ st.sidebar.info("No memory found for this customer ID.")
169
+ else:
170
+ st.sidebar.error("Please enter a customer ID to view memory info.")
171
+
172
+ # Initialize the chat history
173
+ if "messages" not in st.session_state:
174
+ st.session_state.messages = []
175
+
176
+ # Display the chat history
177
+ for message in st.session_state.messages:
178
+ with st.chat_message(message["role"]):
179
+ st.markdown(message["content"])
180
+
181
+ # Accept user input
182
+ query = st.chat_input("How can I assist you today?")
183
+
184
+ if query and customer_id:
185
+ # Add user message to chat history
186
+ st.session_state.messages.append({"role": "user", "content": query})
187
+ with st.chat_message("user"):
188
+ st.markdown(query)
189
+
190
+ # Generate and display response
191
+ with st.spinner("Generating response..."):
192
+ answer = support_agent.handle_query(query, user_id=customer_id)
193
+
194
+ # Add assistant response to chat history
195
+ st.session_state.messages.append({"role": "assistant", "content": answer})
196
+ with st.chat_message("assistant"):
197
+ st.markdown(answer)
198
+
199
+ elif not customer_id:
200
+ st.error("Please enter a customer ID to start the chat.")
201
+
202
+ else:
203
+ st.warning("Please enter your OpenAI API key to use the customer support agent.")