Repository navigation
Expand file tree
/
Copy pathvtorynka_api.py
More file actions
179 lines (151 loc) · 6.09 KB
/
Copy pathvtorynka_api.py
File metadata and controls
179 lines (151 loc) · 6.09 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
import ssl
import logging
import aiohttp
from typing import Optional
from dataclasses import dataclass
logger = logging.getLogger(__name__)
API_BASE_URL = "https://api.vtorynka.com.ua"
PROPERTY_BASE_URL = "https://vtorynka.com.ua/ua/property"
@dataclass
class PropertyOffer:
"""Property offer from Vtorynka API"""
slug: str
title: str
price: Optional[int]
rooms: Optional[int]
area: Optional[float]
address: Optional[str]
type_code: Optional[str]
category_code: Optional[str]
@property
def url(self) -> str:
return f"{PROPERTY_BASE_URL}/{self.slug}"
async def filter_offers(
type_code: Optional[str] = None,
category_code: Optional[str] = None,
locality_name: Optional[str] = None,
price_from: Optional[int] = None,
price_to: Optional[int] = None,
rooms: Optional[str] = None,
page: int = 1,
limit: int = 5
) -> tuple[list[PropertyOffer], int]:
"""
Filter property offers from Vtorynka API
Args:
type_code: Type of deal - 'sale' or 'rent'
category_code: Category - 'flat', 'house', etc.
locality_name: City name - 'kyiv', 'odesa', etc.
price_from: Minimum price
price_to: Maximum price
rooms: Number of rooms, can be comma-separated for multiple values (e.g., "1,2,3")
page: Page number for pagination
limit: Number of results per page
Returns:
tuple: (list of PropertyOffer, total count)
"""
params = {}
if type_code:
params["typeCode"] = type_code
if category_code:
params["categoryCode"] = category_code
if locality_name:
params["localityName"] = locality_name
if price_from is not None:
params["priceFrom"] = price_from
if price_to is not None:
params["priceTo"] = price_to
if rooms:
params["rooms"] = rooms
params["page"] = page
params["limit"] = limit
url = f"{API_BASE_URL}/realty/offers/filter"
try:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
connector = aiohttp.TCPConnector(ssl=ssl_context)
async with aiohttp.ClientSession(connector=connector) as session:
# Log the full URL with params
query_string = "&".join(f"{k}={v}" for k, v in params.items())
full_url = f"{url}?{query_string}" if query_string else url
logger.info(f"Vtorynka API request: {full_url}")
async with session.get(url, params=params, timeout=aiohttp.ClientTimeout(total=10)) as response:
if response.status != 200:
return [], 0
data = await response.json()
offers = []
items = data.get("data", data.get("items", data)) if isinstance(data, dict) else data
if isinstance(items, list):
for item in items:
offer = PropertyOffer(
slug=item.get("slug", ""),
title=item.get("title", item.get("name", "")),
price=item.get("price"),
rooms=item.get("rooms", item.get("roomCount")),
area=item.get("area", item.get("totalArea")),
address=item.get("address", item.get("location", "")),
type_code=item.get("typeCode", type_code),
category_code=item.get("categoryCode", category_code)
)
if offer.slug:
offers.append(offer)
total = data.get("total", data.get("count", len(offers))) if isinstance(data, dict) else len(offers)
logger.info(f"Vtorynka API response: {len(offers)} offers (total: {total})")
return offers, total
except Exception as e:
logger.error(f"Vtorynka API error: {e}")
return [], 0
def format_offers_json(offers: list[PropertyOffer]) -> str:
"""Format offers list as JSON for AI processing"""
import json
if not offers:
return json.dumps({"offers": [], "total": 0})
offers_data = []
for offer in offers:
offers_data.append({
"title": offer.title,
"rooms": offer.rooms,
"area": offer.area,
"price": offer.price,
"address": offer.address,
"url": offer.url
})
return json.dumps({"offers": offers_data, "total": len(offers_data)}, ensure_ascii=False)
# Function definition for OpenAI function calling
SEARCH_PROPERTIES_FUNCTION = {
"name": "search_properties",
"description": "Search for real estate properties/apartments using filters. Use this when a user asks about available properties, wants to see listings, or specifies criteria like number of rooms, price range, or location.",
"parameters": {
"type": "object",
"properties": {
"type_code": {
"type": "string",
"enum": ["sale", "rent"],
"description": "Type of deal: 'sale' for buying, 'rent' for renting. Default is 'sale'."
},
"category_code": {
"type": "string",
"enum": ["apartment", "house", "commercial", "land"],
"description": "Property category: 'apartment' for apartments/flats, 'house' for houses"
},
"locality_name": {
"type": "string",
"enum": ["Kyev", "Odesa", "Lviv", "Kharkiv", "Dnipro"],
"description": "City name. IMPORTANT: Use 'Kyev' for Kyiv (not 'Kyiv'!)"
},
"price_from": {
"type": "integer",
"description": "Minimum price in USD"
},
"price_to": {
"type": "integer",
"description": "Maximum price in USD"
},
"rooms": {
"type": "string",
"description": "Number of rooms. Can be single value '2' or comma-separated '1,2,3' for multiple options"
}
}
}
}