Spaces:
Sleeping
Sleeping
Dmitry Beresnev commited on
Commit ·
e9b8569
1
Parent(s): 7d65cc9
fix logger
Browse files419 unmodified lines42042142242342442524 unmodified lines450451452453454455456457458414 unmodified lines8738748758768778788792 unmodified lines88288388488588688788888989019 unmodified lines91091191291391491591658 unmodified lines9759769779789799809812 unmodified lines98498598698798898925 unmodified lines10151016101710181019102022 unmodified lines10431044104510461047104810491050419 unmodified linesasync def log_received_request(request: Request, call_next):"""Log incoming requests and responses with basic metadata."""request_id = uuid.uuid4().hex[:12]start = time.perf_counter()body_text = ""24 unmodified lineselapsed_ms = (time.perf_counter() - start) * 1000logger.info(f"⬅️ {request_id} {response.status_code} {elapsed_ms:.1f}ms")return responseexcept Exception as exc:elapsed_ms = (time.perf_counter() - start) * 1000logger.error(f"⬅️ {request_id} 500 {elapsed_ms:.1f}ms error={exc}")raise414 unmodified linessummary="Chat Completions",description="High-performance OpenAI-compatible chat completions with connection pooling.")async def chat_completions(request: ChatCompletionRequest):"""OpenAI-compatible chat completions with performance optimizations.2 unmodified lines- HTTP connection pooling- Request metrics tracking"""try:request_start = time.time()# Get current model from cachecached_model = model_cache.get(current_model)if not cached_model:19 unmodified linesreturn resultexcept aiohttp.ClientError as e:raise HTTPException(status_code=500, detail=f"llama-server error: {str(e)}")async def search_web_async(query: str, max_results: int = 5) -> list[dict]:58 unmodified linessummary="Web-Augmented Chat Completions",description="Chat completions with real-time web search and result caching.")async def web_chat_completions(request: WebChatRequest):"""Chat completions with web search augmentation.2 unmodified lines- LRU cache for search results (1 hour TTL)- Parallel execution where possible"""try:# Get the last user message as search queryuser_messages = [msg for msg in request.messages if msg.get("role") == "user"]25 unmodified linesaugmented_messages.insert(-1, system_prompt)# Get current model from cachecached_model = model_cache.get(current_model)if not cached_model:22 unmodified linesreturn resultexcept aiohttp.ClientError as e:raise HTTPException(status_code=500, detail=f"llama-server error: {str(e)}")except Exception as e:raise HTTPException(status_code=500, detail=f"Error: {str(e)}")419 unmodified lines42042142242342442542624 unmodified lines451452453454455456457458459414 unmodified lines8748758768778788798802 unmodified lines88388488588688788888989089189289389489519 unmodified lines91591691791891992092192292392492558 unmodified lines9849859869879889899902 unmodified lines99399499599699799899925 unmodified lines10251026102710281029103010311032103322 unmodified lines105610571058105910601061106210631064106510661067419 unmodified linesasync def log_received_request(request: Request, call_next):"""Log incoming requests and responses with basic metadata."""request_id = uuid.uuid4().hex[:12]request.state.request_id = request_idstart = time.perf_counter()body_text = ""24 unmodified lineselapsed_ms = (time.perf_counter() - start) * 1000logger.info(f"⬅️ {request_id} {response.status_code} {elapsed_ms:.1f}ms")return responseexcept Exception:elapsed_ms = (time.perf_counter() - start) * 1000logger.exception(f"⬅️ {request_id} 500 {elapsed_ms:.1f}ms unhandled error")raise414 unmodified linessummary="Chat Completions",description="High-performance OpenAI-compatible chat completions with connection pooling.")async def chat_completions(request: ChatCompletionRequest, raw_request: Request):"""OpenAI-compatible chat completions with performance optimizations.2 unmodified lines- HTTP connection pooling- Request metrics tracking"""request_id = getattr(raw_request.state, "request_id", "-")try:request_start = time.time()if not http_session or http_session.closed:raise HTTPException(status_code=500, detail="HTTP session not initialized")# Get current model from cachecached_model = model_cache.get(current_model)if not cached_model:19 unmodified linesreturn resultexcept aiohttp.ClientError as e:logger.exception(f"request_id={request_id} llama-server error")raise HTTPException(status_code=500, detail=f"llama-server error: {str(e)}")except Exception:logger.exception(f"request_id={request_id} chat_completions error")raiseasync def search_web_async(query: str, max_results: int = 5) -> list[dict]:58 unmodified linessummary="Web-Augmented Chat Completions",description="Chat completions with real-time web search and result caching.")async def web_chat_completions(request: WebChatRequest, raw_request: Request):"""Chat completions with web search augmentation.2 unmodified lines- LRU cache for search results (1 hour TTL)- Parallel execution where possible"""request_id = getattr(raw_request.state, "request_id", "-")try:# Get the last user message as search queryuser_messages = [msg for msg in request.messages if msg.get("role") == "user"]25 unmodified linesaugmented_messages.insert(-1, system_prompt)if not http_session or http_session.closed:raise HTTPException(status_code=500, detail="HTTP session not initialized")# Get current model from cachecached_model = model_cache.get(current_model)if not cached_model:22 unmodified linesreturn resultexcept aiohttp.ClientError as e:logger.exception(f"request_id={request_id} llama-server error")raise HTTPException(status_code=500, detail=f"llama-server error: {str(e)}")except HTTPException:raiseexcept Exception as e:logger.exception(f"request_id={request_id} web_chat_completions error")raise HTTPException(status_code=500, detail=f"Error: {str(e)}")
79 unmodified lines8081828384858687888990913 unmodified lines959697989910010111 unmodified lines11311411511611711811912012112212312412535 unmodified lines16116216316479 unmodified linesReturns:Configured logger instance"""# Create or get loggerlogger = logging.getLogger(name)# Only configure handlers once for the root loggerif not cls._initialized and name == "AGI":logger.setLevel(level)# Console handler with colorsconsole_handler = logging.StreamHandler(sys.stdout)3 unmodified linesdatefmt='%Y-%m-%d %H:%M:%S')console_handler.setFormatter(console_formatter)logger.addHandler(console_handler)# File handler with rotation (if enabled)if log_file:11 unmodified linesdatefmt='%Y-%m-%d %H:%M:%S')file_handler.setFormatter(file_formatter)logger.addHandler(file_handler)# Prevent propagation to avoid duplicate logslogger.propagate = Falsecls._initialized = Truereturn logger# Convenience function for easy import35 unmodified linesapi_logger.info("API logger initialized")client_logger = get_logger("client")client_logger.info("Client logger initialized")79 unmodified lines808182838485868788893 unmodified lines9394959697989911 unmodified lines11111211311411511611711811912012135 unmodified lines15715815916079 unmodified linesReturns:Configured logger instance"""# Always return a named logger, but configure root handlers onceif not cls._initialized:root_logger = logging.getLogger()root_logger.setLevel(level)# Console handler with colorsconsole_handler = logging.StreamHandler(sys.stdout)3 unmodified linesdatefmt='%Y-%m-%d %H:%M:%S')console_handler.setFormatter(console_formatter)root_logger.addHandler(console_handler)# File handler with rotation (if enabled)if log_file:11 unmodified linesdatefmt='%Y-%m-%d %H:%M:%S')file_handler.setFormatter(file_formatter)root_logger.addHandler(file_handler)cls._initialized = Truereturn logging.getLogger(name)# Convenience function for easy import35 unmodified linesapi_logger.info("API logger initialized")client_logger = get_logger("client")client_logger.info("Client logger initialized")
app.py+21-4
logger.py+8-12