-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
298 lines (256 loc) · 9.91 KB
/
server.py
File metadata and controls
298 lines (256 loc) · 9.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
from dotenv import load_dotenv
load_dotenv()
from fastapi import FastAPI, HTTPException, Body
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, EmailStr
from typing import Optional
import os, logging, uuid, re
from datetime import datetime, timedelta
# LangChain & Agent
from langchain_groq import ChatGroq
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain.memory import ConversationBufferMemory
# Database
from db import (
get_connection,
add_potential_customer,
save_consultation_to_db,
init_tables,
)
# Tools & Prompt
from promtt import custom_prompt
from tools import (
get_company_info,
classify_customer,
save_consultation_schedule_tool,
)
# ==============================
# LOGGING & APP INIT
# ==============================
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)
app = FastAPI(title="AT Shop API", version="1.0")
# ==============================
# CORS
# ==============================
origins = ["http://127.0.0.1:5500", "http://localhost:5500"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ==============================
# INIT DATABASE
# ==============================
init_tables()
# ==============================
# SESSION CACHE
# ==============================
session_cache = {}
# ==============================
# LLM CONFIG
# ==============================
api_key = os.getenv("API_KEY")
model = os.getenv("MODEL")
if not api_key or not model:
raise ValueError("❌ Thiếu API_KEY hoặc MODEL trong .env")
llm = ChatGroq(api_key=api_key, model=model)
prompt = ChatPromptTemplate.from_messages([
("system", custom_prompt),
MessagesPlaceholder(variable_name="chat_history"),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
])
memory = ConversationBufferMemory(k=20, memory_key="chat_history", return_messages=True)
tools = [get_company_info, classify_customer, save_consultation_schedule_tool]
agent = create_tool_calling_agent(llm=llm, prompt=prompt, tools=tools)
agent_executor = AgentExecutor(agent=agent, tools=tools, memory=memory, handle_parsing_errors=True)
# ==============================
# MODELS
# ==============================
class Question(BaseModel):
question: str
class PotentialCustomer(BaseModel):
name: str
phone: str
email: Optional[EmailStr] = None
address: Optional[str] = None
# ==============================
# HELPERS
# ==============================
VN_PHONE = re.compile(r"^0\d{9,10}$")
def is_valid_name(name: Optional[str]) -> bool:
if not name:
return False
n = name.strip().lower()
return len(n) >= 2 and n not in {"ban", "bạn", "toi", "tôi", "minh", "mình"}
def is_valid_phone(phone: Optional[str]) -> bool:
return bool(phone and VN_PHONE.match(phone))
def non_empty(s: Optional[str]) -> bool:
return bool(s and s.strip())
def parse_customer_info(text: str):
"""Tách số điện thoại/email khi người dùng nhập thẳng trong câu chat."""
text = text.strip()
phone_match = re.search(r"\b0\d{9,10}\b", text)
email_match = re.search(r'[\w\.-]+@[\w\.-]+', text)
parts = [p.strip() for p in text.split(',') if p.strip()]
name = parts[0] if len(parts) > 0 else None
address = parts[-1] if len(parts) > 1 else None
return {"name": name, "phone": phone_match.group(0) if phone_match else None, "email": email_match.group(0) if email_match else None, "address": address}
# ==============================
# 🕒 Xử lý cụm thời gian tiếng Việt tự nhiên
# ==============================
def parse_vietnamese_time_phrase(raw_time: str) -> str:
raw_time = raw_time.strip().lower()
now = datetime.now()
# Nếu có "mai" → cộng 1 ngày
if "mai" in raw_time:
now = now + timedelta(days=1)
# Mặc định buổi sáng
hour = 9
if "chiều" in raw_time:
hour = 15
elif "tối" in raw_time:
hour = 19
elif "trưa" in raw_time:
hour = 12
# Nếu có dạng số giờ
match_h = re.search(r"(\d{1,2})h", raw_time)
if match_h:
hour = int(match_h.group(1))
return now.replace(hour=hour, minute=0, second=0, microsecond=0).strftime("%Y-%m-%d %H:%M:%S")
# ==============================
# CHAT ENDPOINT
# ==============================
@app.post("/chat")
async def chat_endpoint(q: Question):
user_input = q.question.strip()
if not user_input:
raise HTTPException(status_code=400, detail="Câu hỏi không được để trống.")
# Gọi Agent
customer_type = classify_customer.run(user_input)
response = agent_executor.invoke({"input": user_input})
final_output = response.get("output", "").strip()
# 🧹 Ẩn tool call nội bộ
if "save_consultation_schedule_tool" in final_output or "function_call" in final_output:
final_output = re.split(r"save_consultation_schedule_tool|function_call", final_output, 1)[0].strip()
final_output = re.sub(
r"(save_consultation_schedule_tool|create_order|classify_customer).*",
"",
final_output,
flags=re.DOTALL
).strip()
# Phân tích dữ liệu khách hàng
info = parse_customer_info(user_input)
name = info.get("name")
phone = info.get("phone")
email = info.get("email")
address = info.get("address")
has_schedule = bool(re.search(r"\b(hẹn|lịch|tư\s*vấn|gọi\s*lại)\b", user_input, re.I))
has_time = bool(re.search(r"\d{1,2}[:h]\d{0,2}", user_input))
try:
consultation_time = None
# Parse thời gian cụ thể (vd: "10h 21/10/2025")
match_full = re.search(r"(\d{1,2})h\s*(\d{1,2})/(\d{1,2})/(\d{4})", user_input)
if match_full:
hour, day, month, year = match_full.groups()
consultation_time = f"{year}-{month.zfill(2)}-{day.zfill(2)} {hour.zfill(2)}:00:00"
else:
match_hour = re.search(r"(\d{1,2})[:h](\d{0,2})", user_input)
if match_hour:
hour, minute = match_hour.groups()
minute = minute if minute else "00"
consultation_time = f"{datetime.now().strftime('%Y-%m-%d')} {hour.zfill(2)}:{minute.zfill(2)}:00"
# Nếu là cụm 'sáng mai', 'chiều nay' ...
if not consultation_time and re.search(r"(sáng|chiều|tối|mai|nay)", user_input, re.I):
consultation_time = parse_vietnamese_time_phrase(user_input)
# Nếu có thông tin hợp lệ thì lưu
if phone and name and (has_schedule or has_time):
save_consultation_to_db(
name=name,
phone=phone,
email=email or "",
consultation_time=consultation_time or datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
note="AI tự động ghi nhận từ hội thoại",
address=address or ""
)
logger.info(f"✅ [AI] Lưu lịch tư vấn: {name} - {phone} ({consultation_time})")
elif name and phone and address:
add_potential_customer(name, phone, email, address)
logger.info(f"✅ [AI] Lưu khách hàng tiềm năng: {name} - {phone}")
except Exception as err:
logger.warning(f"⚠️ Không thể tự động lưu thông tin: {err}")
return {"responses": [final_output], "customer_type": customer_type}
# ==============================
# KHÁCH HÀNG TIỀM NĂNG
# ==============================
@app.get("/potential_customer")
async def get_potential_customers():
conn = get_connection()
if not conn:
raise HTTPException(status_code=500, detail="Không thể kết nối DB.")
cursor = conn.cursor()
cursor.execute("""
SELECT id, name, phone, email, address, created_at
FROM potential_customers ORDER BY created_at DESC
""")
rows = cursor.fetchall()
cursor.close()
conn.close()
customers = [
{"id": r[0], "name": r[1], "phone": r[2], "email": r[3], "address": r[4], "created_at": r[5]} for r in rows
]
return {"customers": customers}
@app.delete("/potential_customer/{id}")
async def delete_potential_customer(id: int):
conn = get_connection()
if not conn:
raise HTTPException(status_code=500, detail="Không thể kết nối DB.")
cursor = conn.cursor()
cursor.execute("DELETE FROM potential_customers WHERE id = %s", (id,))
conn.commit()
cursor.close()
conn.close()
return {"success": True, "message": "Đã xóa khách hàng thành công!"}
# ==============================
# LỊCH TƯ VẤN
# ==============================
@app.get("/consultations")
async def get_consultations():
conn = get_connection()
if not conn:
raise HTTPException(status_code=500, detail="Không thể kết nối DB.")
cursor = conn.cursor()
cursor.execute("""
SELECT id, name, email, phone, consultation_time, created_at
FROM consultations ORDER BY created_at DESC
""")
rows = cursor.fetchall()
cursor.close()
conn.close()
consultations = []
for row in rows:
consultation_time = row[4]
created_at = row[5]
if isinstance(consultation_time, datetime):
consultation_time = consultation_time.strftime("%Y-%m-%d %H:%M")
if isinstance(created_at, datetime):
created_at = created_at.strftime("%Y-%m-%d %H:%M:%S")
consultations.append({
"id": row[0],
"name": row[1],
"email": row[2],
"phone": row[3],
"consultation_time": consultation_time,
"created_at": created_at
})
return {"consultations": consultations}
# ==============================
# HEALTH CHECK
# ==============================
@app.get("/health")
async def health_check():
return {"status": "ok"}