Spaces:
Sleeping
Sleeping
Dmitry Beresnev commited on
Commit ·
a8f6b6b
1
Parent(s): 130d9e3
Log elapsed time and token rate when the response arrives.
Browse filesAdd a hard timeout (e.g., 300s) and return a friendly 504.
Add a rule to drop system prompts above a cap unless explicitly allowed.
115 unmodified lines11611711811912012135 unmodified lines157158159160161162163815 unmodified lines97998098198298398415 unmodified lines1000100110021003100410051006100710081009101010111012101310141015101610171 unmodified line1019102010211022102310241 unmodified line102610271028102910301031118 unmodified lines11501151115211531154115514 unmodified lines117011711172117311741175117611771178117911801181118211831184118511868 unmodified lines119511961197119811991200115 unmodified linesPROMPT_MARGIN_TOKENS = int(os.getenv("PROMPT_MARGIN_TOKENS", "256"))CHARS_PER_TOKEN_EST = float(os.getenv("CHARS_PER_TOKEN_EST", "4.0"))def _estimate_tokens(text: str) -> int:35 unmodified linessystem_cap = min(1024, max(256, prompt_budget // 3))for msg in compacted:if msg.get("role") == "system" and "content" in msg:msg["content"] = _truncate_text_to_tokens(str(msg["content"]), system_cap)def total_tokens(msgs: list[dict]) -> int:return sum(_estimate_tokens(str(m.get("content", ""))) for m in msgs)815 unmodified linesf"original_tokens≈{original_tokens} budget≈{prompt_budget}")compacted_messages = _compact_messages(request.messages, request.max_tokens)compacted_tokens = _estimate_messages_tokens(compacted_messages)15 unmodified lines"max_tokens": request.max_tokens,"temperature": request.temperature,}async with http_session.post(f"{cached_model.url}/v1/chat/completions",json=payload) as response:if response.status >= 400:error_text = await response.text()logger.error(f"request_id={request_id} llama-server {response.status} "f"error_body={error_text[:1000]}")response.raise_for_status()result = await response.json()# Update metricsrequest_latency = time.time() - request_start1 unmodified linecached_model.total_latency += request_latencymetrics.record_request(current_model, request_latency)return resultexcept aiohttp.ClientResponseError as e:logger.exception(f"request_id={request_id} llama-server error")1 unmodified lineexcept 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")raise118 unmodified linesf"original_tokens≈{original_tokens} budget≈{prompt_budget}")augmented_messages = _compact_messages(augmented_messages, request.max_tokens)compacted_tokens = _estimate_messages_tokens(augmented_messages)14 unmodified linesif not cached_model:raise HTTPException(status_code=500, detail="Current model not loaded")# Forward to llama-server with augmented contextasync with http_session.post(f"{cached_model.url}/v1/chat/completions",json={"messages": augmented_messages,"max_tokens": request.max_tokens,"temperature": request.temperature,}) as response:response.raise_for_status()result = await response.json()# Add metadata about search resultsresult["web_search"] = {8 unmodified linesexcept 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:115 unmodified lines11611711811912012112212312435 unmodified lines160161162163164165166167168169815 unmodified lines985986987988989990991992993994995996997998999100015 unmodified lines1016101710181019102010211022102310241025102610271028102910301031103210331034103510361 unmodified line1038103910401041104210431044104510461047104810491050105110521053105410551 unmodified line105710581059106010611062106310641065118 unmodified lines118411851186118711881189119011911192119311941195119611971198119914 unmodified lines121412151216121712181219122012211222122312241225122612271228122912301231123212338 unmodified lines124212431244124512461247124812491250115 unmodified linesPROMPT_MARGIN_TOKENS = int(os.getenv("PROMPT_MARGIN_TOKENS", "256"))CHARS_PER_TOKEN_EST = float(os.getenv("CHARS_PER_TOKEN_EST", "4.0"))SYSTEM_PROMPT_MAX_TOKENS = int(os.getenv("SYSTEM_PROMPT_MAX_TOKENS", "512"))ALLOW_LONG_SYSTEM_PROMPT = os.getenv("ALLOW_LONG_SYSTEM_PROMPT", "0") == "1"HARD_REQUEST_TIMEOUT = int(os.getenv("HARD_REQUEST_TIMEOUT", "300"))def _estimate_tokens(text: str) -> int:35 unmodified linessystem_cap = min(1024, max(256, prompt_budget // 3))for msg in compacted:if msg.get("role") == "system" and "content" in msg:if not ALLOW_LONG_SYSTEM_PROMPT and _estimate_tokens(str(msg["content"])) > SYSTEM_PROMPT_MAX_TOKENS:msg["content"] = ""else:msg["content"] = _truncate_text_to_tokens(str(msg["content"]), system_cap)def total_tokens(msgs: list[dict]) -> int:return sum(_estimate_tokens(str(m.get("content", ""))) for m in msgs)815 unmodified linesf"original_tokens≈{original_tokens} budget≈{prompt_budget}")# Drop system prompts above cap unless allowedif not ALLOW_LONG_SYSTEM_PROMPT:for msg in request.messages:if msg.get("role") == "system" and _estimate_tokens(str(msg.get("content", ""))) > SYSTEM_PROMPT_MAX_TOKENS:logger.warning(f"request_id={request_id} system_prompt_dropped "f"tokens≈{_estimate_tokens(str(msg.get('content', '')))} cap≈{SYSTEM_PROMPT_MAX_TOKENS}")breakcompacted_messages = _compact_messages(request.messages, request.max_tokens)compacted_tokens = _estimate_messages_tokens(compacted_messages)15 unmodified lines"max_tokens": request.max_tokens,"temperature": request.temperature,}async def _do_request():async with http_session.post(f"{cached_model.url}/v1/chat/completions",json=payload) as response:if response.status >= 400:error_text = await response.text()logger.error(f"request_id={request_id} llama-server {response.status} "f"error_body={error_text[:1000]}")response.raise_for_status()return await response.json()result = await asyncio.wait_for(_do_request(), timeout=HARD_REQUEST_TIMEOUT)# Update metricsrequest_latency = time.time() - request_start1 unmodified linecached_model.total_latency += request_latencymetrics.record_request(current_model, request_latency)# Log elapsed time and token rate (if usage available)usage = result.get("usage") if isinstance(result, dict) else Noneif usage and usage.get("completion_tokens"):completion_tokens = usage.get("completion_tokens", 0)tok_per_sec = completion_tokens / max(request_latency, 1e-6)logger.info(f"request_id={request_id} done "f"time={request_latency:.2f}s tokens={completion_tokens} tok/s={tok_per_sec:.1f}")else:logger.info(f"request_id={request_id} done time={request_latency:.2f}s")return resultexcept aiohttp.ClientResponseError as e:logger.exception(f"request_id={request_id} llama-server error")1 unmodified lineexcept 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 asyncio.TimeoutError:logger.error(f"request_id={request_id} timeout after {HARD_REQUEST_TIMEOUT}s")raise HTTPException(status_code=504, detail="Upstream model timed out. Please retry.")except Exception:logger.exception(f"request_id={request_id} chat_completions error")raise118 unmodified linesf"original_tokens≈{original_tokens} budget≈{prompt_budget}")# Drop system prompts above cap unless allowedif not ALLOW_LONG_SYSTEM_PROMPT:for msg in augmented_messages:if msg.get("role") == "system" and _estimate_tokens(str(msg.get("content", ""))) > SYSTEM_PROMPT_MAX_TOKENS:logger.warning(f"request_id={request_id} system_prompt_dropped "f"tokens≈{_estimate_tokens(str(msg.get('content', '')))} cap≈{SYSTEM_PROMPT_MAX_TOKENS}")breakaugmented_messages = _compact_messages(augmented_messages, request.max_tokens)compacted_tokens = _estimate_messages_tokens(augmented_messages)14 unmodified linesif not cached_model:raise HTTPException(status_code=500, detail="Current model not loaded")async def _do_request():# Forward to llama-server with augmented contextasync with http_session.post(f"{cached_model.url}/v1/chat/completions",json={"messages": augmented_messages,"max_tokens": request.max_tokens,"temperature": request.temperature,}) as response:response.raise_for_status()return await response.json()result = await asyncio.wait_for(_do_request(), timeout=HARD_REQUEST_TIMEOUT)# Add metadata about search resultsresult["web_search"] = {8 unmodified linesexcept 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 asyncio.TimeoutError:logger.error(f"request_id={request_id} timeout after {HARD_REQUEST_TIMEOUT}s")raise HTTPException(status_code=504, detail="Upstream model timed out. Please retry.")except HTTPException:raiseexcept Exception as e:
app.py+74-24