Spaces:
Sleeping
Sleeping
Dmitry Beresnev commited on
Commit ·
6381e7f
1
Parent(s): 62a5a49
add simple compacting
Browse files113 unmodified lines114115116117118119781 unmodified lines901902903904905906907908134 unmodified lines104310441045104610471048113 unmodified linesLOG_REQUEST_BODY_MAX_CHARS = int(os.getenv("LOG_REQUEST_BODY_MAX_CHARS", "2000"))CONTEXT_SIZE = int(os.getenv("CONTEXT_SIZE", "2048"))@dataclassclass CachedModel:781 unmodified linesraise HTTPException(status_code=500, detail="Current model not loaded")# Forward to llama-server using aiohttppayload = {"messages": request.messages,"max_tokens": request.max_tokens,"temperature": request.temperature,}134 unmodified linesif 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:113 unmodified lines114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183781 unmodified lines965966967968969970971972973134 unmodified lines110811091110111111121113111411151116113 unmodified linesLOG_REQUEST_BODY_MAX_CHARS = int(os.getenv("LOG_REQUEST_BODY_MAX_CHARS", "2000"))CONTEXT_SIZE = int(os.getenv("CONTEXT_SIZE", "2048"))PROMPT_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:"""Rough token estimate based on character count."""if not text:return 0return int(len(text) / CHARS_PER_TOKEN_EST) + 1def _truncate_text_to_tokens(text: str, max_tokens: int) -> str:"""Truncate text to an approximate token budget."""if not text or max_tokens <= 0:return ""max_chars = int(max_tokens * CHARS_PER_TOKEN_EST)if len(text) <= max_chars:return textreturn text[:max_chars] + "...[truncated]"def _compact_messages(messages: list[dict], max_tokens: int) -> list[dict]:"""Compact messages to fit within the prompt budget.Strategy:- Cap system message content size.- Drop oldest non-system messages until within budget.- As a last resort, truncate the oldest remaining non-system message."""if not messages:return messagesprompt_budget = CONTEXT_SIZE - max_tokens - PROMPT_MARGIN_TOKENSif prompt_budget <= 0:return messages# Work on a copy to avoid mutating caller inputcompacted = [dict(m) for m in messages]# Cap system messagessystem_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)# Drop oldest non-system messages until under budgetwhile total_tokens(compacted) > prompt_budget:idx = next((i for i, m in enumerate(compacted) if m.get("role") != "system"), None)if idx is None:breakcompacted.pop(idx)# Last resort: truncate oldest non-system contentif total_tokens(compacted) > prompt_budget:idx = next((i for i, m in enumerate(compacted) if m.get("role") != "system"), None)if idx is not None:remaining_budget = max(1, prompt_budget - (total_tokens(compacted) - _estimate_tokens(str(compacted[idx].get("content", "")))))compacted[idx]["content"] = _truncate_text_to_tokens(str(compacted[idx].get("content", "")), remaining_budget)return compacted@dataclassclass CachedModel:781 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,"temperature": request.temperature,}134 unmodified linesif not http_session or http_session.closed:raise 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:
app.py+69-1