Spaces:
Build error
Build error
Update model_classes.py
Browse files- model_classes.py +24 -66
model_classes.py
CHANGED
|
@@ -21,10 +21,11 @@ from langchain.schema import Document
|
|
| 21 |
from scipy.sparse import csr_matrix, vstack
|
| 22 |
from sklearn.preprocessing import normalize
|
| 23 |
from langchain.schema import Document
|
| 24 |
-
from collections import defaultdict
|
| 25 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 26 |
import concurrent.futures
|
| 27 |
import heapq
|
|
|
|
|
|
|
| 28 |
|
| 29 |
class IntelligentIntentRecognizer:
|
| 30 |
def __init__(self, vectorstore):
|
|
@@ -283,18 +284,6 @@ class DynamicConceptAnalyzer:
|
|
| 283 |
|
| 284 |
return min(confidence, 1.0)
|
| 285 |
|
| 286 |
-
from scipy.sparse import csr_matrix, vstack
|
| 287 |
-
from sklearn.preprocessing import normalize
|
| 288 |
-
import numpy as np
|
| 289 |
-
import networkx as nx
|
| 290 |
-
from datetime import datetime
|
| 291 |
-
from typing import Dict, List, Optional, Any, Tuple
|
| 292 |
-
from langchain.schema import Document
|
| 293 |
-
from collections import defaultdict
|
| 294 |
-
from sklearn.metrics.pairwise import cosine_similarity
|
| 295 |
-
import concurrent.futures
|
| 296 |
-
import heapq
|
| 297 |
-
|
| 298 |
class EnhancedHybridSearcher:
|
| 299 |
"""Optimierte Hybrid-Suche für RAG Chatbots mit integrierten Suchstrategien"""
|
| 300 |
|
|
@@ -337,17 +326,13 @@ class EnhancedHybridSearcher:
|
|
| 337 |
|
| 338 |
# 1. Hauptsuchfunktion
|
| 339 |
def hybrid_search(self, query: str, context: Optional[Dict[str, Any]] = None,
|
| 340 |
-
|
| 341 |
-
"""Hauptsuchfunktion, die alle Suchmethoden kombiniert"""
|
| 342 |
try:
|
| 343 |
# Cache-Check
|
| 344 |
cache_key = f"{query}_{str(context)}"
|
| 345 |
if cache_key in self.result_cache:
|
| 346 |
return self.result_cache[cache_key]
|
| 347 |
-
|
| 348 |
-
# Start Performance-Tracking
|
| 349 |
-
start_time = datetime.now()
|
| 350 |
-
|
| 351 |
# 1. Parallele Suche
|
| 352 |
search_results = self._parallel_search(query, k*2)
|
| 353 |
|
|
@@ -362,23 +347,15 @@ class EnhancedHybridSearcher:
|
|
| 362 |
weights
|
| 363 |
)
|
| 364 |
|
| 365 |
-
#
|
| 366 |
-
|
| 367 |
-
combined_results = self._context_reranking(
|
| 368 |
-
combined_results,
|
| 369 |
-
context,
|
| 370 |
-
query
|
| 371 |
-
)
|
| 372 |
-
|
| 373 |
-
# 5. Qualitätsverbesserung
|
| 374 |
-
final_results = self._enhance_results(combined_results[:k], query)
|
| 375 |
|
| 376 |
# Update Cache und Metriken
|
| 377 |
self._update_cache(cache_key, final_results)
|
| 378 |
-
self._update_performance_metrics(query, final_results,
|
| 379 |
|
| 380 |
return final_results
|
| 381 |
-
|
| 382 |
except Exception as e:
|
| 383 |
print(f"Fehler in hybrid_search: {str(e)}")
|
| 384 |
return []
|
|
@@ -456,14 +433,13 @@ class EnhancedHybridSearcher:
|
|
| 456 |
def _semantic_search(self, query: str, k: int) -> List[Dict[str, Any]]:
|
| 457 |
"""Führt semantische Suche durch"""
|
| 458 |
try:
|
| 459 |
-
results = self.vectorstore.
|
| 460 |
return [
|
| 461 |
{
|
| 462 |
'content': doc.page_content,
|
| 463 |
'score': float(score),
|
| 464 |
'type': 'semantic',
|
| 465 |
-
'metadata': doc.metadata if hasattr(doc, 'metadata') else {}
|
| 466 |
-
'quality_metrics': self._calculate_quality_metrics(doc.page_content)
|
| 467 |
}
|
| 468 |
for doc, score in results
|
| 469 |
]
|
|
@@ -702,10 +678,9 @@ class EnhancedHybridSearcher:
|
|
| 702 |
return self.search_weights
|
| 703 |
|
| 704 |
def _combine_all_results(self, search_results: Dict[str, List[Dict]],
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
"""Kombiniert alle Suchergebnisse mit adaptiver Gewichtung"""
|
| 709 |
try:
|
| 710 |
combined_scores = defaultdict(lambda: {
|
| 711 |
'score': 0.0,
|
|
@@ -714,47 +689,30 @@ class EnhancedHybridSearcher:
|
|
| 714 |
'quality_metrics': {}
|
| 715 |
})
|
| 716 |
|
| 717 |
-
# Kombiniere
|
| 718 |
for search_type, results in search_results.items():
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
# Sammle Metadaten
|
| 728 |
-
entry['metadata'].update(result.get('metadata', {}))
|
| 729 |
-
if 'quality_metrics' in result:
|
| 730 |
-
entry['quality_metrics'].update(result['quality_metrics'])
|
| 731 |
-
|
| 732 |
-
# Berechne finale Scores
|
| 733 |
-
for content, entry in combined_scores.items():
|
| 734 |
-
# Diversity Bonus
|
| 735 |
-
entry['score'] *= (1 + 0.1 * len(entry['sources']))
|
| 736 |
-
|
| 737 |
-
# Qualitätsbonus
|
| 738 |
-
if entry['quality_metrics']:
|
| 739 |
-
avg_quality = np.mean(list(entry['quality_metrics'].values()))
|
| 740 |
-
entry['score'] *= (1 + 0.2 * avg_quality)
|
| 741 |
|
| 742 |
-
# Erstelle sortierte Liste
|
| 743 |
return sorted([
|
| 744 |
{
|
| 745 |
'content': content,
|
| 746 |
'score': data['score'],
|
| 747 |
'sources': data['sources'],
|
| 748 |
-
'metadata': data['metadata']
|
| 749 |
-
'quality_metrics': data['quality_metrics']
|
| 750 |
}
|
| 751 |
for content, data in combined_scores.items()
|
| 752 |
], key=lambda x: x['score'], reverse=True)
|
| 753 |
-
|
| 754 |
except Exception as e:
|
| 755 |
print(f"Fehler beim Kombinieren der Ergebnisse: {str(e)}")
|
| 756 |
return []
|
| 757 |
-
|
| 758 |
def _add_graph_edges(self, graph: nx.DiGraph, documents: List[Document]):
|
| 759 |
"""Fügt Kanten zwischen ähnlichen Dokumenten hinzu"""
|
| 760 |
try:
|
|
|
|
| 21 |
from scipy.sparse import csr_matrix, vstack
|
| 22 |
from sklearn.preprocessing import normalize
|
| 23 |
from langchain.schema import Document
|
|
|
|
| 24 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 25 |
import concurrent.futures
|
| 26 |
import heapq
|
| 27 |
+
from scipy.sparse import csr_matrix, vstack
|
| 28 |
+
from sklearn.preprocessing import normalize
|
| 29 |
|
| 30 |
class IntelligentIntentRecognizer:
|
| 31 |
def __init__(self, vectorstore):
|
|
|
|
| 284 |
|
| 285 |
return min(confidence, 1.0)
|
| 286 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
class EnhancedHybridSearcher:
|
| 288 |
"""Optimierte Hybrid-Suche für RAG Chatbots mit integrierten Suchstrategien"""
|
| 289 |
|
|
|
|
| 326 |
|
| 327 |
# 1. Hauptsuchfunktion
|
| 328 |
def hybrid_search(self, query: str, context: Optional[Dict[str, Any]] = None,
|
| 329 |
+
k: int = 5) -> List[Dict[str, Any]]:
|
|
|
|
| 330 |
try:
|
| 331 |
# Cache-Check
|
| 332 |
cache_key = f"{query}_{str(context)}"
|
| 333 |
if cache_key in self.result_cache:
|
| 334 |
return self.result_cache[cache_key]
|
| 335 |
+
|
|
|
|
|
|
|
|
|
|
| 336 |
# 1. Parallele Suche
|
| 337 |
search_results = self._parallel_search(query, k*2)
|
| 338 |
|
|
|
|
| 347 |
weights
|
| 348 |
)
|
| 349 |
|
| 350 |
+
# Schneide auf k Ergebnisse
|
| 351 |
+
final_results = combined_results[:k]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 352 |
|
| 353 |
# Update Cache und Metriken
|
| 354 |
self._update_cache(cache_key, final_results)
|
| 355 |
+
self._update_performance_metrics(query, final_results, datetime.now())
|
| 356 |
|
| 357 |
return final_results
|
| 358 |
+
|
| 359 |
except Exception as e:
|
| 360 |
print(f"Fehler in hybrid_search: {str(e)}")
|
| 361 |
return []
|
|
|
|
| 433 |
def _semantic_search(self, query: str, k: int) -> List[Dict[str, Any]]:
|
| 434 |
"""Führt semantische Suche durch"""
|
| 435 |
try:
|
| 436 |
+
results = self.vectorstore.similarity_search_with_relevance_scores(query, k=k) # Geänderte Methode
|
| 437 |
return [
|
| 438 |
{
|
| 439 |
'content': doc.page_content,
|
| 440 |
'score': float(score),
|
| 441 |
'type': 'semantic',
|
| 442 |
+
'metadata': doc.metadata if hasattr(doc, 'metadata') else {}
|
|
|
|
| 443 |
}
|
| 444 |
for doc, score in results
|
| 445 |
]
|
|
|
|
| 678 |
return self.search_weights
|
| 679 |
|
| 680 |
def _combine_all_results(self, search_results: Dict[str, List[Dict]],
|
| 681 |
+
query: str,
|
| 682 |
+
context: Optional[Dict],
|
| 683 |
+
weights: Dict[str, float]) -> List[Dict[str, Any]]:
|
|
|
|
| 684 |
try:
|
| 685 |
combined_scores = defaultdict(lambda: {
|
| 686 |
'score': 0.0,
|
|
|
|
| 689 |
'quality_metrics': {}
|
| 690 |
})
|
| 691 |
|
| 692 |
+
# Kombiniere nur vorhandene Ergebnisse
|
| 693 |
for search_type, results in search_results.items():
|
| 694 |
+
if search_type in weights: # Nur wenn Gewicht existiert
|
| 695 |
+
for result in results:
|
| 696 |
+
key = result['content']
|
| 697 |
+
entry = combined_scores[key]
|
| 698 |
+
entry['score'] += result['score'] * weights[search_type]
|
| 699 |
+
entry['sources'].append(search_type)
|
| 700 |
+
entry['metadata'].update(result.get('metadata', {}))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 701 |
|
|
|
|
| 702 |
return sorted([
|
| 703 |
{
|
| 704 |
'content': content,
|
| 705 |
'score': data['score'],
|
| 706 |
'sources': data['sources'],
|
| 707 |
+
'metadata': data['metadata']
|
|
|
|
| 708 |
}
|
| 709 |
for content, data in combined_scores.items()
|
| 710 |
], key=lambda x: x['score'], reverse=True)
|
| 711 |
+
|
| 712 |
except Exception as e:
|
| 713 |
print(f"Fehler beim Kombinieren der Ergebnisse: {str(e)}")
|
| 714 |
return []
|
| 715 |
+
|
| 716 |
def _add_graph_edges(self, graph: nx.DiGraph, documents: List[Document]):
|
| 717 |
"""Fügt Kanten zwischen ähnlichen Dokumenten hinzu"""
|
| 718 |
try:
|