Spaces:
Sleeping
Sleeping
Dmitry Beresnev commited on
Commit ·
130d9e3
1
Parent(s): 6381e7f
a “slow request” logging, log when a request exceeds the budgeted prompt and gets compacted
Browse files178 unmodified lines179180181182183184768 unmodified lines9539549559569579586 unmodified lines96596696796896997097128 unmodified lines10001001100210031004100568 unmodified lines10741075107610771078107929 unmodified lines1109111011111112111311141115111629 unmodified lines114611471148114911501151178 unmodified linesreturn compacted@dataclassclass CachedModel:"""Represents a cached model with its process and connection info."""768 unmodified lines- Request metrics tracking"""request_id = getattr(raw_request.state, "request_id", "-")try:request_start = time.time()6 unmodified linesraise HTTPException(status_code=500, detail="Current model not loaded")# Forward to llama-server using aiohttpcompacted_messages = _compact_messages(request.messages, request.max_tokens)payload = {"messages": compacted_messages,"max_tokens": request.max_tokens,28 unmodified linesexcept Exception:logger.exception(f"request_id={request_id} chat_completions error")raiseasync def search_web_async(query: str, max_results: int = 5) -> list[dict]:68 unmodified lines- 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"]29 unmodified linesraise HTTPException(status_code=500, detail="HTTP session not initialized")# Compact messages to fit within contextaugmented_messages = _compact_messages(augmented_messages, request.max_tokens)# Get current model from cachecached_model = model_cache.get(current_model)if not cached_model:29 unmodified linesexcept Exception as e:logger.exception(f"request_id={request_id} web_chat_completions error")raise HTTPException(status_code=500, detail=f"Error: {str(e)}")@app.get(178 unmodified lines179180181182183184185186187188189768 unmodified lines9589599609619629639646 unmodified lines971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100028 unmodified lines10291030103110321033103410351036103768 unmodified lines110611071108110911101111111229 unmodified lines1142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117029 unmodified lines120012011202120312041205120612071208178 unmodified linesreturn compacteddef _estimate_messages_tokens(messages: list[dict]) -> int:"""Estimate total tokens for a list of messages."""return sum(_estimate_tokens(str(m.get("content", ""))) for m in messages)@dataclassclass CachedModel:"""Represents a cached model with its process and connection info."""768 unmodified lines- Request metrics tracking"""request_id = getattr(raw_request.state, "request_id", "-")slow_task: Optional[asyncio.Task] = Nonetry:request_start = time.time()6 unmodified linesraise HTTPException(status_code=500, detail="Current model not loaded")# Forward to llama-server using aiohttpprompt_budget = CONTEXT_SIZE - request.max_tokens - PROMPT_MARGIN_TOKENSoriginal_tokens = _estimate_messages_tokens(request.messages)if prompt_budget > 0 and original_tokens > prompt_budget:logger.warning(f"request_id={request_id} prompt_compaction "f"original_tokens≈{original_tokens} budget≈{prompt_budget}")compacted_messages = _compact_messages(request.messages, request.max_tokens)compacted_tokens = _estimate_messages_tokens(compacted_messages)if compacted_tokens < original_tokens:logger.info(f"request_id={request_id} prompt_compacted "f"tokens≈{original_tokens}->{compacted_tokens}")async def _slow_request_logger():await asyncio.sleep(30)elapsed = time.time() - request_startlogger.warning(f"request_id={request_id} slow_request {elapsed:.1f}s")slow_task = asyncio.create_task(_slow_request_logger())payload = {"messages": compacted_messages,"max_tokens": request.max_tokens,28 unmodified linesexcept Exception:logger.exception(f"request_id={request_id} chat_completions error")raisefinally:if slow_task and not slow_task.done():slow_task.cancel()async def search_web_async(query: str, max_results: int = 5) -> list[dict]:68 unmodified lines- Parallel execution where possible"""request_id = getattr(raw_request.state, "request_id", "-")slow_task: Optional[asyncio.Task] = Nonetry:# Get the last user message as search queryuser_messages = [msg for msg in request.messages if msg.get("role") == "user"]29 unmodified linesraise HTTPException(status_code=500, detail="HTTP session not initialized")# Compact messages to fit within contextprompt_budget = CONTEXT_SIZE - request.max_tokens - PROMPT_MARGIN_TOKENSoriginal_tokens = _estimate_messages_tokens(augmented_messages)if prompt_budget > 0 and original_tokens > prompt_budget:logger.warning(f"request_id={request_id} prompt_compaction "f"original_tokens≈{original_tokens} budget≈{prompt_budget}")augmented_messages = _compact_messages(augmented_messages, request.max_tokens)compacted_tokens = _estimate_messages_tokens(augmented_messages)if compacted_tokens < original_tokens:logger.info(f"request_id={request_id} prompt_compacted "f"tokens≈{original_tokens}->{compacted_tokens}")async def _slow_request_logger():await asyncio.sleep(30)logger.warning(f"request_id={request_id} slow_request 30.0s")slow_task = asyncio.create_task(_slow_request_logger())# Get current model from cachecached_model = model_cache.get(current_model)if not cached_model:29 unmodified linesexcept Exception as e:logger.exception(f"request_id={request_id} web_chat_completions error")raise HTTPException(status_code=500, detail=f"Error: {str(e)}")finally:if slow_task and not slow_task.done():slow_task.cancel()@app.get(
app.py+57