Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import os
|
3 |
+
import json
|
4 |
+
import datetime
|
5 |
+
import openai
|
6 |
+
from datasets import load_dataset, Dataset, concatenate_datasets
|
7 |
+
from huggingface_hub import login
|
8 |
+
|
9 |
+
# -- Einstellungen für Hugging Face Dataset Repository --
|
10 |
+
# Ersetze "your_username/customer_memory" durch deinen eigenen Repository-Namen!
|
11 |
+
DATASET_REPO = "your_username/customer_memory"
|
12 |
+
|
13 |
+
# Hugging Face Login
|
14 |
+
hf_token = st.sidebar.text_input("Enter your Hugging Face Token", type="password")
|
15 |
+
if hf_token:
|
16 |
+
login(token=hf_token)
|
17 |
+
st.sidebar.success("Logged in to Hugging Face!")
|
18 |
+
|
19 |
+
# Hilfsfunktion: Versuche, das Dataset vom HF Hub zu laden; falls nicht vorhanden, initialisiere es
|
20 |
+
def load_memory_dataset():
|
21 |
+
try:
|
22 |
+
ds = load_dataset(DATASET_REPO, split="train")
|
23 |
+
st.write("Dataset loaded from HF Hub.")
|
24 |
+
except Exception as e:
|
25 |
+
st.write("Dataset not found on HF Hub. Creating a new one...")
|
26 |
+
# Leeres Dataset mit den Spalten: user_id, query, response
|
27 |
+
data = {"user_id": [], "query": [], "response": []}
|
28 |
+
ds = Dataset.from_dict(data)
|
29 |
+
ds.push_to_hub(DATASET_REPO)
|
30 |
+
st.write("New dataset created and pushed to HF Hub.")
|
31 |
+
return ds
|
32 |
+
|
33 |
+
# Hilfsfunktion: Füge einen neuen Eintrag (Memory) hinzu und pushe das aktualisierte Dataset
|
34 |
+
def add_to_memory(user_id, query, response):
|
35 |
+
ds = load_memory_dataset()
|
36 |
+
# Neuer Eintrag als kleines Dataset
|
37 |
+
new_entry = Dataset.from_dict({
|
38 |
+
"user_id": [user_id],
|
39 |
+
"query": [query],
|
40 |
+
"response": [response]
|
41 |
+
})
|
42 |
+
# Bestehendes Dataset mit dem neuen Eintrag zusammenführen
|
43 |
+
updated_ds = concatenate_datasets([ds, new_entry])
|
44 |
+
# Aktualisiere das Dataset auf HF Hub
|
45 |
+
updated_ds.push_to_hub(DATASET_REPO)
|
46 |
+
st.write("Memory updated.")
|
47 |
+
|
48 |
+
# Hilfsfunktion: Filtere das Dataset nach einer bestimmten customer_id
|
49 |
+
def get_memory(user_id):
|
50 |
+
ds = load_memory_dataset()
|
51 |
+
return ds.filter(lambda x: x["user_id"] == user_id)
|
52 |
+
|
53 |
+
# OpenAI GPT-4 API-Anbindung
|
54 |
+
def generate_response(prompt):
|
55 |
+
response = openai.ChatCompletion.create(
|
56 |
+
model="gpt-4",
|
57 |
+
messages=[
|
58 |
+
{"role": "system", "content": "You are a customer support AI for TechGadgets.com."},
|
59 |
+
{"role": "user", "content": prompt}
|
60 |
+
]
|
61 |
+
)
|
62 |
+
return response.choices[0].message.content
|
63 |
+
|
64 |
+
# Streamlit App UI
|
65 |
+
st.title("AI Customer Support Agent with Memory 🛒")
|
66 |
+
st.caption("Chat with a customer support assistant who remembers your past interactions.")
|
67 |
+
|
68 |
+
# OpenAI API Key Eingabe
|
69 |
+
openai_api_key = st.text_input("Enter OpenAI API Key", type="password")
|
70 |
+
if openai_api_key:
|
71 |
+
os.environ["OPENAI_API_KEY"] = openai_api_key
|
72 |
+
openai.api_key = openai_api_key
|
73 |
+
|
74 |
+
# Sidebar: Customer ID und Optionen
|
75 |
+
st.sidebar.title("Enter your Customer ID:")
|
76 |
+
customer_id = st.sidebar.text_input("Customer ID")
|
77 |
+
|
78 |
+
# Optional: Synthetic Data generieren (Beispiel-Daten)
|
79 |
+
if st.sidebar.button("Generate Synthetic Data"):
|
80 |
+
if customer_id:
|
81 |
+
synthetic_data = {
|
82 |
+
"name": "Max Mustermann",
|
83 |
+
"recent_order": {
|
84 |
+
"product": "High-end Smartphone",
|
85 |
+
"order_date": (datetime.datetime.now() - datetime.timedelta(days=10)).strftime("%B %d, %Y"),
|
86 |
+
"delivery_date": (datetime.datetime.now() + datetime.timedelta(days=2)).strftime("%B %d, %Y"),
|
87 |
+
"order_number": "ORD123456"
|
88 |
+
},
|
89 |
+
"previous_orders": [
|
90 |
+
{"product": "Laptop", "order_date": "January 12, 2025"},
|
91 |
+
{"product": "Tablet", "order_date": "March 01, 2025"}
|
92 |
+
],
|
93 |
+
"customer_service_interactions": [
|
94 |
+
"Asked about order status",
|
95 |
+
"Inquired about warranty"
|
96 |
+
]
|
97 |
+
}
|
98 |
+
st.session_state.customer_data = synthetic_data
|
99 |
+
st.sidebar.success("Synthetic data generated!")
|
100 |
+
else:
|
101 |
+
st.sidebar.error("Please enter a customer ID first.")
|
102 |
+
|
103 |
+
if st.sidebar.button("View Customer Profile"):
|
104 |
+
if "customer_data" in st.session_state and st.session_state.customer_data:
|
105 |
+
st.sidebar.json(st.session_state.customer_data)
|
106 |
+
else:
|
107 |
+
st.sidebar.info("No synthetic data available.")
|
108 |
+
|
109 |
+
if st.sidebar.button("View Memory Info"):
|
110 |
+
if customer_id:
|
111 |
+
memories = get_memory(customer_id)
|
112 |
+
st.sidebar.write(f"Memory for customer **{customer_id}**:")
|
113 |
+
for mem in memories:
|
114 |
+
st.sidebar.write(f"**Query:** {mem['query']}\n**Response:** {mem['response']}\n---")
|
115 |
+
else:
|
116 |
+
st.sidebar.error("Please enter a customer ID.")
|
117 |
+
|
118 |
+
# Initialisiere Chatverlauf in session_state
|
119 |
+
if "messages" not in st.session_state:
|
120 |
+
st.session_state.messages = []
|
121 |
+
|
122 |
+
# Zeige bisherigen Chatverlauf
|
123 |
+
for message in st.session_state.messages:
|
124 |
+
st.chat_message(message["role"]).markdown(message["content"])
|
125 |
+
|
126 |
+
# Haupt-Chat: Benutzer-Eingabe
|
127 |
+
query = st.chat_input("How can I assist you today?")
|
128 |
+
if query and customer_id:
|
129 |
+
# Hole bisherigen Memory-Context
|
130 |
+
memories = get_memory(customer_id)
|
131 |
+
context = ""
|
132 |
+
for mem in memories:
|
133 |
+
context += f"Query: {mem['query']}\nResponse: {mem['response']}\n"
|
134 |
+
# Kombiniere Kontext mit aktueller Anfrage
|
135 |
+
full_prompt = context + f"\nCustomer: {query}\nSupport Agent:"
|
136 |
+
with st.spinner("Generating response..."):
|
137 |
+
answer = generate_response(full_prompt)
|
138 |
+
# Aktualisiere den Chatverlauf
|
139 |
+
st.session_state.messages.append({"role": "user", "content": query})
|
140 |
+
st.session_state.messages.append({"role": "assistant", "content": answer})
|
141 |
+
st.chat_message("assistant").markdown(answer)
|
142 |
+
# Speicher die Interaktion in der Memory (Dataset)
|
143 |
+
add_to_memory(customer_id, query, answer)
|
144 |
+
elif query and not customer_id:
|
145 |
+
st.error("Please enter a customer ID to start the chat.")
|
146 |
+
else:
|
147 |
+
st.warning("Please enter your OpenAI API key to use the customer support agent.")
|