Spaces:
Sleeping
Sleeping
Update CosmosDBHandlers/cosmosConnector.py
Browse files
CosmosDBHandlers/cosmosConnector.py
CHANGED
|
@@ -3,14 +3,14 @@ from jsonschema import ValidationError
|
|
| 3 |
from langchain_openai import AzureOpenAIEmbeddings
|
| 4 |
from models.converterModels import PowerConverter
|
| 5 |
import os
|
| 6 |
-
from azure.cosmos import CosmosClient
|
| 7 |
from typing import List, Optional, Dict
|
| 8 |
import logging
|
| 9 |
import os
|
| 10 |
from dotenv import load_dotenv
|
| 11 |
from semantic_kernel.functions import kernel_function
|
| 12 |
from rapidfuzz import process, fuzz
|
| 13 |
-
|
| 14 |
load_dotenv()
|
| 15 |
# Initialize logging
|
| 16 |
logger = logging.getLogger(__name__)
|
|
@@ -22,6 +22,7 @@ class CosmosLampHandler:
|
|
| 22 |
os.getenv("AZURE_COSMOS_DB_ENDPOINT"),
|
| 23 |
os.getenv("AZURE_COSMOS_DB_KEY")
|
| 24 |
)
|
|
|
|
| 25 |
self.database = self.client.get_database_client("TAL_DB")
|
| 26 |
self.container = self.database.get_container_client("Converters_with_embeddings")
|
| 27 |
self.logger = logging.Logger("test")
|
|
@@ -235,7 +236,7 @@ class CosmosLampHandler:
|
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
-
async def query_converters(self, query: str) -> List[PowerConverter]:
|
| 239 |
try:
|
| 240 |
print(f"Executing query: {query}")
|
| 241 |
items = list(self.container.query_items(
|
|
@@ -247,12 +248,24 @@ class CosmosLampHandler:
|
|
| 247 |
|
| 248 |
items = [PowerConverter(**item) for item in items] if items else []
|
| 249 |
|
| 250 |
-
self.logger.info(f"Query returned {len(items)} items after conversion")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
|
| 252 |
return str(items)
|
| 253 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
except Exception as e:
|
| 255 |
-
self.logger.info(f"Query failed: {str(e)}")
|
| 256 |
return f"Query failed: {str(e)}"
|
| 257 |
|
| 258 |
|
|
@@ -261,7 +274,8 @@ class CosmosLampHandler:
|
|
| 261 |
artnr: Optional[int] = None,
|
| 262 |
current: Optional[str]=None,
|
| 263 |
input_voltage: Optional[str] = None,
|
| 264 |
-
output_voltage: Optional[str] = None
|
|
|
|
| 265 |
) -> List[PowerConverter]:
|
| 266 |
"""Query converters by voltage ranges"""
|
| 267 |
try:
|
|
@@ -274,7 +288,8 @@ class CosmosLampHandler:
|
|
| 274 |
# Parse voltage ranges
|
| 275 |
input_min, input_max = self._parse_voltage(input_voltage) if input_voltage else (None, None)
|
| 276 |
output_min, output_max = self._parse_voltage(output_voltage) if output_voltage else (None, None)
|
| 277 |
-
|
|
|
|
| 278 |
# Build query
|
| 279 |
query_parts = []
|
| 280 |
if input_min and input_max:
|
|
@@ -282,7 +297,7 @@ class CosmosLampHandler:
|
|
| 282 |
self.logger.info(f"c.nom_input_voltage_v.min <= {input_max} AND c.nom_input_voltage_v.max >= {input_min}")
|
| 283 |
if output_min and output_max:
|
| 284 |
query_parts.append(f"c.output_voltage_v.min <= {output_max} AND c.output_voltage_v.max >= {output_min}")
|
| 285 |
-
self.logger.info(f"c.nom_input_voltage_v.min <= {
|
| 286 |
if current:
|
| 287 |
query_parts.append(f"c.type LIKE '%{current}%'")
|
| 288 |
|
|
@@ -294,7 +309,21 @@ class CosmosLampHandler:
|
|
| 294 |
enable_cross_partition_query=True
|
| 295 |
))
|
| 296 |
|
| 297 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
except Exception as e:
|
| 300 |
self.logger.error(f"Voltage query failed: {str(e)}")
|
|
|
|
| 3 |
from langchain_openai import AzureOpenAIEmbeddings
|
| 4 |
from models.converterModels import PowerConverter
|
| 5 |
import os
|
| 6 |
+
from azure.cosmos import CosmosClient, exceptions
|
| 7 |
from typing import List, Optional, Dict
|
| 8 |
import logging
|
| 9 |
import os
|
| 10 |
from dotenv import load_dotenv
|
| 11 |
from semantic_kernel.functions import kernel_function
|
| 12 |
from rapidfuzz import process, fuzz
|
| 13 |
+
from CosmosDBHandlers.cosmosChatHistoryHandler import ChatMemoryHandler
|
| 14 |
load_dotenv()
|
| 15 |
# Initialize logging
|
| 16 |
logger = logging.getLogger(__name__)
|
|
|
|
| 22 |
os.getenv("AZURE_COSMOS_DB_ENDPOINT"),
|
| 23 |
os.getenv("AZURE_COSMOS_DB_KEY")
|
| 24 |
)
|
| 25 |
+
self.chat_memory_handler = ChatMemoryHandler()
|
| 26 |
self.database = self.client.get_database_client("TAL_DB")
|
| 27 |
self.container = self.database.get_container_client("Converters_with_embeddings")
|
| 28 |
self.logger = logging.Logger("test")
|
|
|
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
+
async def query_converters(self, query: str, user_input:str) -> List[PowerConverter]:
|
| 240 |
try:
|
| 241 |
print(f"Executing query: {query}")
|
| 242 |
items = list(self.container.query_items(
|
|
|
|
| 248 |
|
| 249 |
items = [PowerConverter(**item) for item in items] if items else []
|
| 250 |
|
| 251 |
+
self.logger.info(f"Query returned {len(items)} items after conversion")
|
| 252 |
+
|
| 253 |
+
if len(items)==0:
|
| 254 |
+
await self.chat_memory_handler.log_sql_query(user_input, query, "null")
|
| 255 |
+
|
| 256 |
+
else:
|
| 257 |
+
await self.chat_memory_handler.log_sql_query(user_input, query, "success")
|
| 258 |
|
| 259 |
return str(items)
|
| 260 |
|
| 261 |
+
except exceptions.CosmosHttpResponseError as ex:
|
| 262 |
+
await self.chat_memory_handler.log_sql_query(user_input, query, "error")
|
| 263 |
+
print(f"Cosmos DB error: {ex}")
|
| 264 |
+
self.logger.error(f"Bad request SQL failed: {str(e)}")
|
| 265 |
+
return []
|
| 266 |
+
|
| 267 |
except Exception as e:
|
| 268 |
+
self.logger.info(f"Query failed: {str(e)}")
|
| 269 |
return f"Query failed: {str(e)}"
|
| 270 |
|
| 271 |
|
|
|
|
| 274 |
artnr: Optional[int] = None,
|
| 275 |
current: Optional[str]=None,
|
| 276 |
input_voltage: Optional[str] = None,
|
| 277 |
+
output_voltage: Optional[str] = None,
|
| 278 |
+
lamp_type: Optional[str] = None
|
| 279 |
) -> List[PowerConverter]:
|
| 280 |
"""Query converters by voltage ranges"""
|
| 281 |
try:
|
|
|
|
| 288 |
# Parse voltage ranges
|
| 289 |
input_min, input_max = self._parse_voltage(input_voltage) if input_voltage else (None, None)
|
| 290 |
output_min, output_max = self._parse_voltage(output_voltage) if output_voltage else (None, None)
|
| 291 |
+
normalized_lamp_type = self._normalize_lamp_name(lamp_type) if lamp_type else None
|
| 292 |
+
|
| 293 |
# Build query
|
| 294 |
query_parts = []
|
| 295 |
if input_min and input_max:
|
|
|
|
| 297 |
self.logger.info(f"c.nom_input_voltage_v.min <= {input_max} AND c.nom_input_voltage_v.max >= {input_min}")
|
| 298 |
if output_min and output_max:
|
| 299 |
query_parts.append(f"c.output_voltage_v.min <= {output_max} AND c.output_voltage_v.max >= {output_min}")
|
| 300 |
+
self.logger.info(f"c.nom_input_voltage_v.min <= {output_max} AND c.nom_input_voltage_v.max >= {output_min}")
|
| 301 |
if current:
|
| 302 |
query_parts.append(f"c.type LIKE '%{current}%'")
|
| 303 |
|
|
|
|
| 309 |
enable_cross_partition_query=True
|
| 310 |
))
|
| 311 |
|
| 312 |
+
converters = []
|
| 313 |
+
for item in results:
|
| 314 |
+
if normalized_lamp_type:
|
| 315 |
+
item_lamps = item.get("lamps", {})
|
| 316 |
+
if not item_lamps: # Skip if no lamps data
|
| 317 |
+
continue
|
| 318 |
+
|
| 319 |
+
lamp_matches = self._fuzzy_match_lamp(normalized_lamp_type, item_lamps.keys())
|
| 320 |
+
if not lamp_matches:
|
| 321 |
+
continue
|
| 322 |
+
|
| 323 |
+
converters.append(PowerConverter(**item))
|
| 324 |
+
|
| 325 |
+
self.logger.info(f"Found {len(converters)} matching converters")
|
| 326 |
+
return converters
|
| 327 |
|
| 328 |
except Exception as e:
|
| 329 |
self.logger.error(f"Voltage query failed: {str(e)}")
|