-
Notifications
You must be signed in to change notification settings - Fork 0
feat(memory): implement dual-mode archival in memory consolidation #524
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
550f61d
feat(memory): implement dual-mode archival in memory consolidation
Aureliolo 13080dc
fix(memory): fix mypy StrEnum comparison and update export test
Aureliolo 1830b89
refactor(memory): address review findings from 6 pre-PR agents
Aureliolo ece2ea6
fix(memory): address 28 review findings from 13 agents and 2 external…
Aureliolo 60a6d95
fix(memory): address 6 additional CodeRabbit findings from round 2
Aureliolo f41a700
fix(memory): validate mode_assignments IDs in ConsolidationResult
Aureliolo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,172 @@ | ||
| """Abstractive summarizer for sparse memory content. | ||
|
|
||
| Uses an LLM (via ``CompletionProvider``) to generate concise summaries | ||
| of conversational/narrative memory content. Falls back to truncation | ||
| if the LLM call fails. | ||
| """ | ||
|
|
||
| import asyncio | ||
|
|
||
| from synthorg.core.types import NotBlankStr # noqa: TC001 | ||
| from synthorg.memory.models import MemoryEntry # noqa: TC001 | ||
| from synthorg.observability import get_logger | ||
| from synthorg.observability.events.consolidation import ( | ||
| DUAL_MODE_ABSTRACTIVE_FALLBACK, | ||
| DUAL_MODE_ABSTRACTIVE_SUMMARY, | ||
| ) | ||
| from synthorg.providers.enums import MessageRole | ||
| from synthorg.providers.errors import ProviderError | ||
| from synthorg.providers.models import ChatMessage, CompletionConfig | ||
| from synthorg.providers.protocol import CompletionProvider # noqa: TC001 | ||
|
|
||
| logger = get_logger(__name__) | ||
|
|
||
| _TRUNCATE_LENGTH = 200 | ||
|
|
||
| _SYSTEM_PROMPT = ( | ||
| "You are a memory consolidation assistant. Summarize the following " | ||
| "memory content concisely, preserving key decisions, events, and " | ||
| "learnings. Be factual, specific, and brief." | ||
| ) | ||
|
|
||
|
|
||
| def _truncate_fallback(content: str) -> str: | ||
| """Truncate content as a fallback when LLM summarization fails.""" | ||
| if len(content) <= _TRUNCATE_LENGTH: | ||
| return content | ||
| return content[:_TRUNCATE_LENGTH] + "..." | ||
|
|
||
|
|
||
| class AbstractiveSummarizer: | ||
| """LLM-based abstractive summarizer for sparse content. | ||
|
|
||
| Uses a ``CompletionProvider`` to generate concise summaries of | ||
| conversational/narrative memory content. Falls back to truncation | ||
| if the LLM call fails with a retryable error. | ||
|
|
||
| Args: | ||
| provider: Completion provider for LLM calls. | ||
| model: Model identifier to use for summarization. | ||
| max_summary_tokens: Maximum tokens for the summary response. | ||
| temperature: Sampling temperature for summarization. | ||
|
|
||
| Raises: | ||
| ValueError: If ``model`` is empty or whitespace-only. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| provider: CompletionProvider, | ||
| model: NotBlankStr, | ||
| max_summary_tokens: int = 200, | ||
| temperature: float = 0.3, | ||
| ) -> None: | ||
| if not model or not model.strip(): | ||
| msg = "model must be a non-blank string" | ||
| raise ValueError(msg) | ||
| self._provider = provider | ||
| self._model = model | ||
| self._config = CompletionConfig( | ||
| temperature=temperature, | ||
| max_tokens=max_summary_tokens, | ||
| ) | ||
|
|
||
| async def summarize(self, content: str) -> str: | ||
| """Generate an abstractive summary of the given content. | ||
|
|
||
| Falls back to truncation if the LLM call fails with a | ||
| retryable error or returns empty content. Non-retryable | ||
| provider errors (authentication, invalid model) propagate. | ||
|
|
||
| Args: | ||
| content: The sparse/conversational text to summarize. | ||
|
|
||
| Returns: | ||
| Summary text. | ||
| """ | ||
| try: | ||
| messages = [ | ||
| ChatMessage(role=MessageRole.SYSTEM, content=_SYSTEM_PROMPT), | ||
| ChatMessage(role=MessageRole.USER, content=content), | ||
| ] | ||
| response = await self._provider.complete( | ||
| messages, | ||
| self._model, | ||
| config=self._config, | ||
| ) | ||
| if response.content and response.content.strip(): | ||
| logger.debug( | ||
| DUAL_MODE_ABSTRACTIVE_SUMMARY, | ||
| content_length=len(content), | ||
| summary_length=len(response.content), | ||
| model=self._model, | ||
| ) | ||
| return response.content.strip() | ||
| except MemoryError, RecursionError: | ||
| raise | ||
| except ProviderError as exc: | ||
| if not exc.is_retryable: | ||
| logger.warning( | ||
| DUAL_MODE_ABSTRACTIVE_FALLBACK, | ||
| content_length=len(content), | ||
| error=str(exc), | ||
| error_type=type(exc).__name__, | ||
| retryable=False, | ||
| ) | ||
| raise | ||
| logger.warning( | ||
| DUAL_MODE_ABSTRACTIVE_FALLBACK, | ||
| content_length=len(content), | ||
| error=str(exc), | ||
| error_type=type(exc).__name__, | ||
| ) | ||
| return _truncate_fallback(content) | ||
| except Exception as exc: | ||
| logger.warning( | ||
| DUAL_MODE_ABSTRACTIVE_FALLBACK, | ||
| content_length=len(content), | ||
| error=str(exc), | ||
| error_type=type(exc).__name__, | ||
| ) | ||
| return _truncate_fallback(content) | ||
|
|
||
| # Fallback: empty/whitespace-only LLM response | ||
| logger.debug( | ||
| DUAL_MODE_ABSTRACTIVE_FALLBACK, | ||
| content_length=len(content), | ||
| reason="empty_response", | ||
| ) | ||
| return _truncate_fallback(content) | ||
|
|
||
| async def summarize_batch( | ||
| self, | ||
| entries: tuple[MemoryEntry, ...], | ||
| ) -> tuple[tuple[NotBlankStr, str], ...]: | ||
| """Summarize multiple entries concurrently. | ||
|
|
||
| Each entry is summarized independently via ``asyncio.TaskGroup``. | ||
| Failures for individual entries fall back to truncation without | ||
| aborting the batch. | ||
|
|
||
| Args: | ||
| entries: Memory entries to summarize. | ||
|
|
||
| Returns: | ||
| Tuple of ``(entry_id, summary)`` pairs in input order. | ||
| """ | ||
| if not entries: | ||
| return () | ||
|
|
||
| results: dict[NotBlankStr, str] = {} | ||
| async with asyncio.TaskGroup() as tg: | ||
| tasks: dict[NotBlankStr, asyncio.Task[str]] = {} | ||
| for entry in entries: | ||
| tasks[entry.id] = tg.create_task( | ||
| self.summarize(entry.content), | ||
| ) | ||
|
|
||
| for entry_id, task in tasks.items(): | ||
| results[entry_id] = task.result() | ||
|
|
||
| return tuple((entry.id, results[entry.id]) for entry in entries) | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.