Spaces:
Sleeping
Sleeping
File size: 9,167 Bytes
108d8af | 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 | """
Async wrapper for knowledge base operations.
Provides non-blocking async/await interface for knowledge base operations,
suitable for async MCP server and concurrent requests.
"""
import asyncio
import logging
from typing import List, Dict, Any, Optional
from functools import partial
from concurrent.futures import ThreadPoolExecutor
from time import time
from .knowledge_base import KnowledgeBase
from .vector_search import SearchResult
from .response_models import SearchResponse, QueryResponse, SearchResultItem
logger = logging.getLogger(__name__)
class AsyncKnowledgeBase:
"""
Async wrapper for KnowledgeBase operations.
Runs blocking operations in thread pool to avoid blocking event loop.
"""
def __init__(self, kb: KnowledgeBase, max_workers: int = 4):
"""
Initialize async knowledge base
Args:
kb: Underlying KnowledgeBase instance
max_workers: Max thread pool workers
"""
self.kb = kb
self.executor = ThreadPoolExecutor(max_workers=max_workers)
self._search_cache = {} # Simple cache for frequent queries
self._cache_ttl = 300 # 5 minutes
async def search(
self,
query: str,
top_k: int = 5,
use_cache: bool = True,
) -> SearchResponse:
"""
Async search operation
Args:
query: Search query
top_k: Number of results
use_cache: Use cache if available
Returns:
SearchResponse with results
"""
start_time = time()
try:
# Check cache
cache_key = f"{query}:{top_k}"
if use_cache and cache_key in self._search_cache:
cached_response, cache_time = self._search_cache[cache_key]
if time() - cache_time < self._cache_ttl:
logger.debug(f"Cache hit for query: {query}")
return cached_response
# Run search in thread pool (non-blocking)
loop = asyncio.get_event_loop()
results = await loop.run_in_executor(
self.executor,
partial(self.kb.search, query, top_k)
)
# Format results
formatted_results = []
for i, result in enumerate(results, 1):
formatted_results.append(SearchResultItem(
rank=i,
score=round(result.score, 3),
content=result.content,
source=result.source,
metadata=result.metadata
))
response = SearchResponse(
status="success",
query=query,
result_count=len(formatted_results),
results=formatted_results,
elapsed_ms=round((time() - start_time) * 1000, 2)
)
# Cache result
if use_cache:
self._search_cache[cache_key] = (response, time())
return response
except Exception as e:
logger.error(f"Search error: {e}")
return SearchResponse(
status="error",
query=query,
result_count=0,
results=[],
elapsed_ms=round((time() - start_time) * 1000, 2),
error=str(e)
)
async def search_products(
self,
query: str,
top_k: int = 10,
) -> SearchResponse:
"""
Async product search
Args:
query: Search query
top_k: Number of results
Returns:
SearchResponse with product results
"""
start_time = time()
try:
loop = asyncio.get_event_loop()
results = await loop.run_in_executor(
self.executor,
partial(self.kb.search_products, query, top_k)
)
formatted_results = []
for i, result in enumerate(results, 1):
formatted_results.append(SearchResultItem(
rank=i,
score=round(result.score, 3),
content=result.content,
source=result.source,
metadata=result.metadata
))
return SearchResponse(
status="success",
query=query,
result_count=len(formatted_results),
results=formatted_results,
elapsed_ms=round((time() - start_time) * 1000, 2)
)
except Exception as e:
logger.error(f"Product search error: {e}")
return SearchResponse(
status="error",
query=query,
result_count=0,
results=[],
elapsed_ms=round((time() - start_time) * 1000, 2),
error=str(e)
)
async def search_documentation(
self,
query: str,
top_k: int = 5,
) -> SearchResponse:
"""
Async documentation search
Args:
query: Search query
top_k: Number of results
Returns:
SearchResponse with documentation results
"""
start_time = time()
try:
loop = asyncio.get_event_loop()
results = await loop.run_in_executor(
self.executor,
partial(self.kb.search_documentation, query, top_k)
)
formatted_results = []
for i, result in enumerate(results, 1):
formatted_results.append(SearchResultItem(
rank=i,
score=round(result.score, 3),
content=result.content,
source=result.source,
metadata=result.metadata
))
return SearchResponse(
status="success",
query=query,
result_count=len(formatted_results),
results=formatted_results,
elapsed_ms=round((time() - start_time) * 1000, 2)
)
except Exception as e:
logger.error(f"Documentation search error: {e}")
return SearchResponse(
status="error",
query=query,
result_count=0,
results=[],
elapsed_ms=round((time() - start_time) * 1000, 2),
error=str(e)
)
async def query(
self,
question: str,
top_k: Optional[int] = None,
) -> QueryResponse:
"""
Async query with natural language
Args:
question: Natural language question
top_k: Number of sources to use
Returns:
QueryResponse with answer
"""
start_time = time()
try:
loop = asyncio.get_event_loop()
answer = await loop.run_in_executor(
self.executor,
partial(self.kb.query, question, top_k)
)
return QueryResponse(
status="success",
question=question,
answer=answer,
source_count=top_k or 5,
confidence=0.85, # Placeholder
elapsed_ms=round((time() - start_time) * 1000, 2)
)
except Exception as e:
logger.error(f"Query error: {e}")
return QueryResponse(
status="error",
question=question,
answer="",
source_count=0,
confidence=0.0,
elapsed_ms=round((time() - start_time) * 1000, 2),
error=str(e)
)
async def batch_search(
self,
queries: List[str],
top_k: int = 5,
) -> List[SearchResponse]:
"""
Async batch search multiple queries
Args:
queries: List of search queries
top_k: Number of results per query
Returns:
List of SearchResponse objects
"""
tasks = [self.search(query, top_k) for query in queries]
return await asyncio.gather(*tasks)
def clear_cache(self):
"""Clear search result cache"""
self._search_cache.clear()
logger.info("Search cache cleared")
def get_cache_stats(self) -> Dict[str, Any]:
"""Get cache statistics"""
return {
"cached_queries": len(self._search_cache),
"cache_ttl_seconds": self._cache_ttl,
}
async def shutdown(self):
"""Shutdown executor"""
self.executor.shutdown(wait=True)
logger.info("AsyncKnowledgeBase shut down")
|