History compaction: chat.compact()

Đang mở
#356 1 bình luận 0 reaction 0 người được giao Xem trên GitHub

Maintainer thường phản hồi trong vòng 1 ngày

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
35/100
Loại issue
Tính năng
Độ rõ ràng
Cần làm rõ
Mức độ hoạt động
Ít trao đổi
Công nghệ
python
Lĩnh vực
ai

Hướng nghiên cứu

Bắt đầu bằng cách đọc Chat.token_count() và set_turns() trong chatlas/_chat.py, sau đó kiểm tra _chat_impl/_chat_impl_async cùng các kiểu content và turn trong chatlas/_content.py và chatlas/_turn.py. Hãy giải quyết các câu hỏi thiết kế còn bỏ ngỏ về ranh giới tóm tắt, nội dung không phải văn bản, việc tính toán và cơ chế kích hoạt tự động trước khi triển khai; công việc được xem là hoàn tất khi đã xác định API compact() và xác minh hành vi cho các chat đồng bộ và bất đồng bộ.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

ai-triage:needs-review enhancement

Motivation

Long-running chatlas sessions (agents, chatbots, notebooks kept open all day) eventually blow the context window, and chatlas currently has no built-in remedy beyond manually calling chat.set_turns() to prune history yourself. LangChain 1.0 ships SummarizationMiddleware, which auto-summarizes older messages once a token threshold is hit, and this pattern is now standard in agent products (Claude Code included). This is arguably the concrete design proposal for chatlas#8 ("Make it easier to impose limits on conversation size") — this issue frames a specific mechanism to close (part of) that issue.

Proposed approach

A plain method, not hidden middleware — explicit and inspectable, in keeping with chatlas's existing style (chat.set_turns(), chat.get_turns() in chatlas/_chat.py):

from chatlas import ChatAnthropic

chat = ChatAnthropic()
# ... long conversation ...

# Manual, opt-in trigger (default):
if chat.token_count(include="complete") > 100_000:
    chat.compact()  # and chat.compact_async()

# Optionally, summarize with a cheaper/faster model than the main conversation:
chat.compact(model=ChatAnthropic(model="claude-haiku-4-5"))

# Opt-in automatic triggering, off by default:
chat.compact(auto=True, threshold=100_000)  # checked at the start of each .chat() call

Implementation sketch:

  • Leverage Chat.token_count()/token_count_async() (chatlas/_chat.py:671), specifically the recently-added include="complete" mode, which already estimates system prompt + .get_turns() history — exactly the heuristic needed to decide whether to compact.
  • compact() selects a prefix of self._turns to summarize (e.g. all but the last N turns, or all but the last complete user/assistant pair), submits them to the provider (or a caller-supplied Chat for a cheaper model) with a summarization prompt, and replaces that prefix with a single synthetic turn pair (a UserTurn/SystemTurn note plus an AssistantTurn containing the summary as ContentText) via Chat.set_turns() (chatlas/_chat.py:357), which already supports exactly this "trim and replace" use case per its own docstring ("Clearing (or trimming) the chat history").
  • Non-text content during summarization: ContentToolRequest/ContentToolResult pairs, ContentImageInline/ContentPDF, etc. (chatlas/_content.py) inside the summarized range should be described in the summary text (e.g. "user uploaded a PDF; assistant called search_docs(query=...) and got N results") rather than silently dropped, since dropping tool results that established facts the model relied on can cause it to contradict itself later. Turn.__str__ (chatlas/_turn.py:115) already gives a reasonable string form of each content type to seed this.
  • AssistantTurn.cost/.tokens (chatlas/_turn.py:340,343) for the summarized turns are lost from get_tokens()/get_cost() accounting once replaced — this should be documented as expected (cost already spent isn't un-spent) and possibly preserved as metadata on the synthetic turn rather than silently discarded.

Alternatives / prior art

  • Closes/addresses part of chatlas#8 directly.
  • No direct ellmer equivalent found (searched tidyverse/ellmer for "compact", "summar" — no hits), so this would be new ground for the ellmer/chatlas pairing; worth raising upstream once chatlas's design is validated, per the project's alignment goal.
  • Alternative considered and rejected for v1: automatic middleware-style compaction with no explicit call, à la LangChain's SummarizationMiddleware. Given YAGNI and that chatlas favors explicit methods over hidden hooks (see how set_model_params(), set_turns() are all explicit calls), default to manual/explicit triggering, with auto=True as an opt-in convenience layered on top of the same method.

Open questions

  • Where should the threshold check live if auto=True — inside _chat_impl/_chat_impl_async (chatlas/_chat.py:2647,2734) before submitting turns, or as a wrapper the caller opts into explicitly?
  • Should compact() support summarizing tool results into a persisted ContentToolResult-shaped stub token (to keep e.g. expand_tool_result in chatlas/_content_expand.py and dangling-request logic in chatlas/_turn.py happy) rather than plain text?
  • Is a single summary turn enough, or should compaction be tiered (e.g. keep a rolling summary + last K turns, re-summarizing as needed)?
  • Should the system prompt ever be folded into compaction, or always preserved verbatim (current set_turns() behavior preserves it automatically)?

Drafted from a competitive review of llm / Pydantic AI / LangChain / LiteLLM (July 2026); filed via Claude Code on behalf of @cpsievert.

Ngôn ngữ chính
Python
Star
179
Fork
32
Merge trung bình
1 ngày 3 giờ
Pull request đã merge (30 ngày)
10

Chuẩn bị môi trường

Dự án này không cung cấp dev container, Dockerfile hay hướng dẫn đóng góp, nên bạn cần tự thiết lập môi trường: hãy bắt đầu từ README và xem hướng dẫn đóng góp lần đầu của chúng tôi để biết các bước chung.

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của posit-dev/chatlas

Tất cả issue của posit-dev/chatlas

Issue tương tự

Thêm issue về Python

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.