-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
164 lines (133 loc) · 5.65 KB
/
agent.py
File metadata and controls
164 lines (133 loc) · 5.65 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
import json
import re
import logging
from openai import AsyncOpenAI
from config import OPENAI_API_KEY, get_system_prompt
logger = logging.getLogger(__name__)
_client = None
def get_client():
"""Lazy initialization of OpenAI client"""
global _client
if _client is None:
_client = AsyncOpenAI(api_key=OPENAI_API_KEY)
return _client
def format_response(text: str, language: str = "uk") -> str:
"""Format AI response: remove markdown, add emojis"""
# 1. Remove markdown formatting
text = re.sub(r'\*\*(.+?)\*\*', r'\1', text)
text = re.sub(r'__(.+?)__', r'\1', text)
text = re.sub(r'(?<!\*)\*([^*]+?)\*(?!\*)', r'\1', text)
text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'\1: \2', text)
text = re.sub(r'^#{1,6}\s+', '', text, flags=re.MULTILINE)
# 2. Remove any existing emojis
text = re.sub(r'[\U0001F300-\U0001F9FF\U0001FA00-\U0001FAFF]', '', text)
# 3. Protect URLs
url_pattern = r'(https?://[^\s]+)'
urls = re.findall(url_pattern, text)
for i, url in enumerate(urls):
text = text.replace(url, f"__URL_{i}__", 1)
# 4. Add emojis to specific patterns (only at word boundaries, not inside words)
replacements = [
(r'(?i)\b(квартир\w*)\b', r'🏠 \1'),
(r'(?i)\b(apartment\w*|flat)\b', r'🏠 \1'),
(r'(?i)\b(кімнат\w*)\b', r'🚪 \1'),
(r'(?i)\b(room\w*)\b', r'🚪 \1'),
(r'(?i)\b(ціна|вартість)\b', r'💰 \1'),
(r'(?i)\b(price|cost)\b', r'💰 \1'),
(r'(?i)\b(адрес\w*)\b', r'📍 \1'),
(r'(?i)\b(address)\b', r'📍 \1'),
(r'(?i)\b(площ\w*)\b', r'📐 \1'),
(r'(?i)\b(area)\b', r'📐 \1'),
(r'(?i)\b(перегляд\w*)\b', r'👀 \1'),
(r'(?i)\b(viewing)\b', r'👀 \1'),
(r'(?i)\b(посилання|link)\b', r'🔗 \1'),
]
for pattern, repl in replacements:
text = re.sub(pattern, repl, text)
# 5. Clean up spaces
text = re.sub(r' +', ' ', text)
text = re.sub(r'\n ', '\n', text)
# 6. Restore URLs
for i, url in enumerate(urls):
text = text.replace(f"__URL_{i}__", url)
# 7. Add Vtorynka portal link when mentioned (if not already linked)
if 'vtorynka.com.ua' not in text.lower():
text = re.sub(
r'(?i)\b(Вторинк[аиіує]|Вторинці|Вторинкою)\b',
r'\1 (https://vtorynka.com.ua)',
text,
count=1 # Only add link once
)
return text.strip()
def parse_ai_response(response_text: str, language: str = "uk") -> tuple[str, dict | None]:
"""Parse JSON response from AI and format it nicely
Returns:
tuple: (formatted_message, seller_lead_data)
"""
try:
# Try to extract JSON from response
json_match = re.search(r'\{[\s\S]*\}', response_text)
if json_match:
data = json.loads(json_match.group())
else:
# No JSON found, return as plain text
return format_response(response_text, language), None
message = data.get("message", "")
seller_lead = data.get("seller_lead")
# Format the message with emojis
formatted_message = format_response(message, language)
# Parse seller lead data
seller_lead_data = None
if seller_lead and isinstance(seller_lead, dict):
name = seller_lead.get("name")
phone = seller_lead.get("phone")
if name and phone:
seller_lead_data = {
"name": name,
"phone": phone,
"property_type": seller_lead.get("property_type", ""),
"address": seller_lead.get("address", ""),
"rooms": seller_lead.get("rooms", ""),
"area": seller_lead.get("area", ""),
"price": seller_lead.get("price", ""),
"callback_time": seller_lead.get("callback_time", "")
}
return formatted_message, seller_lead_data
except json.JSONDecodeError:
# If JSON parsing fails, return formatted plain text
logger.warning(f"Failed to parse AI response as JSON: {response_text[:100]}")
return format_response(response_text, language), None
async def get_ai_response(
conversation_history: list,
user_message: str,
language: str = "en",
listing_context: str = ""
) -> tuple[str, dict | None]:
"""
Get response from AI agent
Args:
conversation_history: Previous messages
user_message: Current user message
language: User's selected language ('en' or 'uk')
listing_context: Pre-extracted listing data from URLs
Returns:
tuple: (agent response, seller lead data or None)
"""
system_prompt = get_system_prompt(language)
messages = [{"role": "system", "content": system_prompt}]
messages.extend(conversation_history)
# If listing data was extracted, prepend it to the user message
if listing_context:
enriched_message = f"{listing_context}\n\n---\nПовідомлення користувача: {user_message}" if language == "uk" else f"{listing_context}\n\n---\nUser message: {user_message}"
messages.append({"role": "user", "content": enriched_message})
else:
messages.append({"role": "user", "content": user_message})
response = await get_client().chat.completions.create(
model="gpt-4o-mini",
max_tokens=1024,
messages=messages
)
assistant_message = response.choices[0].message
response_text = assistant_message.content or ""
# Parse JSON response and format with emojis
return parse_ai_response(response_text, language)