From c3833aae4eaf0570e2e24eb1d7c8391b5abddbf2 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Wed, 15 Jul 2026 17:14:30 -0400 Subject: [PATCH] refac --- cptr/frontend/src/lib/apis/chat.ts | 1 - cptr/routers/chat.py | 2 +- cptr/utils/ai.py | 1 + cptr/utils/chat_task.py | 37 +++++++++++++++++++++++++++++- cptr/utils/context.py | 5 ++-- 5 files changed, 40 insertions(+), 6 deletions(-) diff --git a/cptr/frontend/src/lib/apis/chat.ts b/cptr/frontend/src/lib/apis/chat.ts index eb1e171..5809ee9 100644 --- a/cptr/frontend/src/lib/apis/chat.ts +++ b/cptr/frontend/src/lib/apis/chat.ts @@ -34,7 +34,6 @@ export interface ContextUsage { estimated_tokens: number; threshold: number; percent: number; - source: 'estimated'; } export type TaskStatus = 'pending' | 'in_progress' | 'completed' | 'cancelled'; diff --git a/cptr/routers/chat.py b/cptr/routers/chat.py index 326b851..63e4c96 100644 --- a/cptr/routers/chat.py +++ b/cptr/routers/chat.py @@ -478,7 +478,7 @@ async def _get_chat_context_usage(chat, model_id: str | None = None) -> dict | N [{"role": m.role, "content": m.content or ""} for m in trailing_messages] ) return build_context_usage( - tokens, threshold=compact_token_threshold, source="estimated" + tokens, threshold=compact_token_threshold ) return estimate_context_usage(messages, system, threshold=compact_token_threshold) diff --git a/cptr/utils/ai.py b/cptr/utils/ai.py index f922bb5..e461f20 100644 --- a/cptr/utils/ai.py +++ b/cptr/utils/ai.py @@ -637,6 +637,7 @@ async def stream_openai_completions( "type": "usage", "input_tokens": raw.get("prompt_tokens", 0), "output_tokens": raw.get("completion_tokens", 0), + "total_tokens": raw.get("total_tokens", 0), } # Emit any remaining reasoning if no usage event was received diff --git a/cptr/utils/chat_task.py b/cptr/utils/chat_task.py index 598d8c0..78d777a 100644 --- a/cptr/utils/chat_task.py +++ b/cptr/utils/chat_task.py @@ -16,6 +16,8 @@ from cptr.events import EVENTS, publish_event from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_COMMAND_MAX_CHARS, CHAT_TOOL_MAX_CHARS from cptr.utils.context import ( build_context_usage, + estimate_messages_tokens, + estimate_tokens, normalize_usage, resolve_compact_token_threshold, should_compact, @@ -2204,12 +2206,35 @@ async def run_chat_task( pending_call_ids: set[str] = set() response_reasoning_items: list[dict] = [] # Pair with tool outputs on the next request streamed_reasoning_chars = 0 + estimated_prompt_tokens = 0 + last_emitted_context_tokens = 0 + if provider_type == "llama.cpp": + estimated_prompt_tokens = estimate_tokens(system) + estimate_messages_tokens( + api_messages + ) + last_emitted_context_tokens = estimated_prompt_tokens + await emit( + context_usage=build_context_usage( + estimated_prompt_tokens, + threshold=compact_token_threshold, + ) + ) async for event in stream: if event["type"] == "text_delta": content += event["content"] text_buffer += event["content"] await emit(delta=event["content"]) + if provider_type == "llama.cpp" and usage_context_tokens(last_usage) <= 0: + estimated_context_tokens = estimated_prompt_tokens + estimate_tokens(content) + if estimated_context_tokens - last_emitted_context_tokens >= 256: + last_emitted_context_tokens = estimated_context_tokens + await emit( + context_usage=build_context_usage( + estimated_context_tokens, + threshold=compact_token_threshold, + ) + ) _sync_state() elif event["type"] == "tool_call": @@ -2259,7 +2284,7 @@ async def run_chat_task( if tokens > 0: await emit( context_usage=build_context_usage( - tokens, threshold=compact_token_threshold, source="estimated" + tokens, threshold=compact_token_threshold ) ) @@ -2273,6 +2298,16 @@ async def run_chat_task( message_id[:8], streamed_reasoning_chars, ) + if provider_type == "llama.cpp" and usage_context_tokens(last_usage) <= 0: + estimated_context_tokens = estimated_prompt_tokens + estimate_tokens( + content + ) + await emit( + context_usage=build_context_usage( + estimated_context_tokens, + threshold=compact_token_threshold, + ) + ) await _save_message( "done", content=content, diff --git a/cptr/utils/context.py b/cptr/utils/context.py index ad04667..ea6c363 100644 --- a/cptr/utils/context.py +++ b/cptr/utils/context.py @@ -60,7 +60,7 @@ def should_compact( return total > resolved_threshold -def build_context_usage(tokens: int, *, threshold: int | None = None, source: str) -> dict: +def build_context_usage(tokens: int, *, threshold: int | None = None) -> dict: """Return context fullness stats for estimated token counts.""" resolved_threshold = threshold or _get_threshold() percent = round((tokens / resolved_threshold) * 100) if resolved_threshold > 0 else 0 @@ -69,7 +69,6 @@ def build_context_usage(tokens: int, *, threshold: int | None = None, source: st "estimated_tokens": tokens, "threshold": resolved_threshold, "percent": max(0, percent), - "source": source, } @@ -109,7 +108,7 @@ def estimate_context_usage( """Return context fullness stats using the same estimate as compaction.""" resolved_threshold = threshold or _get_threshold() estimated_tokens = estimate_tokens(system_prompt) + estimate_messages_tokens(messages) - return build_context_usage(estimated_tokens, threshold=resolved_threshold, source="estimated") + return build_context_usage(estimated_tokens, threshold=resolved_threshold) def _parse_positive_int(value: object) -> int | None: