This commit is contained in:
Timothy Jaeryang Baek committed 2026-06-11 12:02:00 +01:00
1 parent ad97cdac8f
commit 2b32568c37
7 files changed
+262 -4

No files matched your search

+1
View File
@@ -27,6 +27,7 @@ ENABLE_CHAT_RECONCILE_ON_STARTUP: bool = os.environ.get(
).lower() in ("true", "1", "yes")
CHAT_TOOL_MAX_CHARS = int(os.environ.get("CHAT_TOOL_MAX_CHARS", "50000"))
CHAT_TOOL_COMMAND_MAX_CHARS = int(os.environ.get("CHAT_TOOL_COMMAND_MAX_CHARS", "8000"))
CHAT_COMPACT_TOKEN_THRESHOLD = int(os.environ.get("CHAT_COMPACT_TOKEN_THRESHOLD", "80000"))
# ── AI stream settings ──────────────────────────────────────
STREAM_CONNECT_TIMEOUT_SECONDS = float(os.environ.get("CPTR_STREAM_CONNECT_TIMEOUT", "30"))
@@ -0,0 +1,21 @@
"""Add chat_summary to chat_messages for context compaction.
Revision ID: 0003
Revises: 0002
Create Date: 2026-06-11
"""
from alembic import op
import sqlalchemy as sa
revision = '0003'
down_revision = '0002'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.add_column('chat_messages', sa.Column('chat_summary', sa.Text(), nullable=True))
def downgrade() -> None:
op.drop_column('chat_messages', 'chat_summary')
+1
View File
@@ -228,6 +228,7 @@ class ChatMessage(Base):
output = Column(JSON, nullable=True) # Responses API output items
usage = Column(JSON, nullable=True) # {input_tokens, output_tokens, ...}
meta = Column(JSON, nullable=True) # {files, followups, error, ...}
chat_summary = Column(Text, nullable=True) # Compaction summary (covers all ancestors before this msg)
created_at = Column(BigInteger, nullable=False)
# ── Class methods ────────────────────────────────────────
+3
View File
@@ -47,6 +47,8 @@ async def export_chat_to_file(chat_id: str) -> None:
entry["output"] = m.output or []
if m.usage:
entry["usage"] = m.usage
if m.chat_summary:
entry["chat_summary"] = m.chat_summary
msg_map[m.id] = entry
@@ -58,6 +60,7 @@ async def export_chat_to_file(chat_id: str) -> None:
chat_data = {
"id": chat.id,
"title": chat.title,
"summary": chat.summary,
"created_at": chat.created_at,
"updated_at": chat.updated_at,
"history": {
+80 -4
View File
@@ -11,7 +11,9 @@ import logging
import uuid
from pathlib import Path
from cptr.env import CHAT_MAX_ITERATIONS
from cptr.env import CHAT_MAX_ITERATIONS, CHAT_TOOL_MAX_CHARS
from cptr.utils.context import should_compact
from cptr.utils.summarize import summarize_messages
from cptr.models import Chat, ChatMessage, Config
from cptr.socket.main import emit_to_user
from cptr.utils.ai import (
@@ -398,12 +400,19 @@ async def generate_chat_title(
# ── Message history ─────────────────────────────────────────
async def _load_message_history(chat_id: str, message_id: str) -> list[dict]:
async def _load_message_history(
chat_id: str, message_id: str
) -> tuple[list[dict], str | None]:
"""Load the ancestor chain from message_id to root as LLM messages.
Walks up via parent_id so only the active branch is included.
The current message (message_id) is always included even if done=False,
since it may contain completed tool calls from prior approval rounds.
If any message in the chain has a chat_summary, everything before it
is skipped and the summary is returned separately for the system prompt.
Returns (messages, chat_summary_or_None).
"""
all_msgs = await ChatMessage.get_all_by_chat(chat_id)
msg_map = {m.id: m for m in all_msgs}
@@ -416,6 +425,14 @@ async def _load_message_history(chat_id: str, message_id: str) -> list[dict]:
cur = msg_map.get(cur.parent_id) if cur.parent_id else None
chain.reverse() # root → leaf
# Find the most recent message with a chat_summary
existing_summary = None
for i, m in enumerate(chain):
if m.chat_summary:
chain = chain[i:] # keep this message and everything after
existing_summary = m.chat_summary
break
result = []
for m in chain:
# Skip in-progress assistant placeholders, but NOT the current
@@ -511,11 +528,16 @@ async def _load_message_history(chat_id: str, message_id: str) -> list[dict]:
}
result.append(entry)
return result
return result, existing_summary
def _append_tool_to_messages(messages: list[dict], event: dict, result: str, provider: str):
"""Append a tool call + result to the message history for the next API call."""
# Guard against oversized tool outputs
if len(result) > CHAT_TOOL_MAX_CHARS:
half = CHAT_TOOL_MAX_CHARS // 2
result = result[:half] + "\n\n...(truncated)...\n\n" + result[-half:]
# Add assistant message with tool_call
messages.append(
{
@@ -543,6 +565,30 @@ def _append_tool_to_messages(messages: list[dict], event: dict, result: str, pro
)
def _find_safe_split(messages: list[dict], target_keep: int) -> int:
"""Find a safe split index that doesn't break tool call pairs.
Returns the index where keep_zone starts. Ensures:
- Never splits between an assistant tool_call and its tool result
- keep_zone doesn't start with a tool result message
- At least 2 messages are kept
"""
n = len(messages)
split = max(2, n - target_keep)
# Walk forward from the initial split to find a safe boundary
while split < n - 1:
msg = messages[split]
# Don't start keep_zone with a tool result — it needs its preceding assistant
if msg.get("role") == "tool":
split += 1
continue
break
return min(split, n - 2) # always keep at least 2
# ── Connection resolution ───────────────────────────────────
@@ -651,7 +697,9 @@ async def run_chat_task(
base_url = connection.get("base_url") or _default_base_url(provider)
system = _load_system_prompt(workspace)
messages = await _load_message_history(chat_id, message_id)
messages, loaded_summary = await _load_message_history(chat_id, message_id)
if loaded_summary:
system += f"\n\n[CONVERSATION SUMMARY]\n{loaded_summary}"
if regeneration_prompt:
messages.append({"role": "user", "content": regeneration_prompt})
tools = get_tool_list()
@@ -679,6 +727,34 @@ async def run_chat_task(
approval_mode = "full" if chat_params["auto_approve_tools"] else "auto"
for _iteration in range(CHAT_MAX_ITERATIONS):
# ── Context compaction: summarize older messages if too large ──
if should_compact(messages, system):
target_keep = max(2, len(messages) * 2 // 5)
split_idx = _find_safe_split(messages, target_keep)
drop_zone = messages[:split_idx]
keep_zone = messages[split_idx:]
api_type = connection.get("api_type", "chat_completions")
summary = await summarize_messages(
drop_zone, loaded_summary,
provider, base_url, api_key, model,
api_type=api_type,
)
# Store on the current message — this IS the cutoff
await ChatMessage.update(message_id, chat_summary=summary)
loaded_summary = summary
# Append summary to system prompt (works for all providers)
system = _load_system_prompt(workspace)
system += f"\n\n[CONVERSATION SUMMARY]\n{summary}"
messages = keep_zone
logger.info(
"[task %s] compacted: dropped %d msgs, kept %d, summary=%d chars",
message_id[:8], len(drop_zone), len(keep_zone), len(summary),
)
form_data = ChatCompletionForm(
model=model,
messages=messages,
+54
View File
@@ -0,0 +1,54 @@
"""Context estimation for chat compaction.
Uses a character-based heuristic (len/4) to estimate token counts.
A follow-up will add real usage data from API responses for precision.
"""
from __future__ import annotations
from cptr.env import CHAT_COMPACT_TOKEN_THRESHOLD
def estimate_tokens(text: str) -> int:
"""Rough token estimate: len/4 for Latin text."""
return max(1, len(text) // 4)
def estimate_messages_tokens(messages: list[dict]) -> int:
"""Total estimated tokens for a message list."""
total = 0
for m in messages:
content = m.get("content", "")
if isinstance(content, list):
for block in content:
if block.get("type") == "text":
total += estimate_tokens(block.get("text", ""))
elif block.get("type") in ("image", "image_url"):
total += 1000 # rough estimate for images
else:
total += estimate_tokens(content)
# Tool call arguments
for tc in m.get("tool_calls", []):
total += estimate_tokens(tc.get("function", {}).get("arguments", ""))
total += 4 # per-message overhead (role, separators)
return total
def should_compact(messages: list[dict], system_prompt: str) -> bool:
"""True when estimated tokens exceed the compact token threshold."""
total = estimate_tokens(system_prompt) + estimate_messages_tokens(messages)
return total > _get_threshold()
def _get_threshold() -> int:
"""Read threshold: config.toml > env var/default."""
try:
from cptr.utils.config import load_config
config = load_config()
val = config.get("chat", {}).get("compact_token_threshold")
if val is not None:
return int(val)
except Exception:
pass
return CHAT_COMPACT_TOKEN_THRESHOLD
+102
View File
@@ -0,0 +1,102 @@
"""Summarize older messages for context compaction.
Uses the same LLM as the active chat to generate a rolling summary.
Falls back to naive truncation if the LLM call fails.
"""
from __future__ import annotations
import logging
logger = logging.getLogger(__name__)
DEFAULT_SUMMARIZE_PROMPT = (
"Summarize this conversation history concisely. Include:\n"
"- Key decisions made\n"
"- Files created, modified, or deleted\n"
"- Current task state and progress\n"
"- Important context the assistant needs going forward\n"
"- Any user preferences or instructions that should persist\n\n"
"Be factual and specific. Use bullet points. Keep under 500 words."
)
def _get_summarize_prompt() -> str:
"""Read from config.toml [chat] section, fall back to default."""
try:
from cptr.utils.config import load_config
config = load_config()
return config.get("chat", {}).get(
"compact_summary_prompt", DEFAULT_SUMMARIZE_PROMPT
)
except Exception:
return DEFAULT_SUMMARIZE_PROMPT
async def summarize_messages(
messages: list[dict],
existing_summary: str | None,
provider: str,
base_url: str,
api_key: str,
model: str,
api_type: str = "chat_completions",
) -> str:
"""Summarize messages into a compact rolling summary.
If existing_summary is provided, it's included so the new summary
incorporates everything before it.
"""
from cptr.utils.ai import chat_completion
parts: list[str] = []
if existing_summary:
parts.append(f"[Previous summary]\n{existing_summary}\n")
parts.append("[Recent messages to summarize]")
for m in messages:
role = m.get("role", "unknown")
content = m.get("content", "")
if isinstance(content, list):
content = " ".join(
b.get("text", "") for b in content if b.get("type") == "text"
)
# Truncate very long messages (e.g. tool outputs)
if len(content) > 2000:
content = content[:1000] + "\n...(truncated)...\n" + content[-500:]
parts.append(f"{role}: {content}")
text = "\n".join(parts)
# Cap input to summarization call
if len(text) > 30_000:
text = text[:15_000] + "\n...\n" + text[-10_000:]
try:
result = await chat_completion(
provider=provider,
base_url=base_url,
api_key=api_key,
model=model,
messages=[{"role": "user", "content": text}],
system=_get_summarize_prompt(),
max_tokens=1000,
api_type=api_type,
)
logger.info("[summarize] LLM summary: %d chars", len(result))
return result
except Exception:
logger.warning("[summarize] LLM call failed, using naive fallback", exc_info=True)
return _naive_summary(messages, existing_summary)
def _naive_summary(messages: list[dict], existing: str | None) -> str:
"""Fallback when LLM summarization fails."""
parts: list[str] = []
if existing:
parts.append(existing)
for m in messages:
role = m.get("role", "")
content = m.get("content", "")
if isinstance(content, str) and role in ("user", "assistant"):
parts.append(f"- {role}: {content[:200]}")
return "\n".join(parts)[:2000]