generated from amazon-archives/__template_Apache-2.0
-
Notifications
You must be signed in to change notification settings - Fork 731
feat(agent): add take_snapshot() and load_snapshot() methods #1948
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
Draft
zastrowm
wants to merge
4
commits into
strands-agents:main
Choose a base branch
from
zastrowm:snapshots_rewrite
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+519
−1
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| """SDK type definitions.""" | ||
|
|
||
| from ._snapshot import Snapshot | ||
| from .collections import PaginatedList | ||
|
|
||
| __all__ = ["PaginatedList"] | ||
| __all__ = ["PaginatedList", "Snapshot"] |
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,131 @@ | ||
| """Snapshot types, constants, and helpers for agent state capture.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
| from datetime import datetime, timezone | ||
| from typing import Any, Literal, TypedDict | ||
|
|
||
| from .exceptions import SnapshotException | ||
|
|
||
| SnapshotField = Literal["messages", "state", "conversation_manager_state", "interrupt_state", "system_prompt"] | ||
| SnapshotPreset = Literal["session"] | ||
|
|
||
| ALL_SNAPSHOT_FIELDS: tuple[SnapshotField, ...] = ( | ||
| "messages", | ||
| "state", | ||
| "conversation_manager_state", | ||
| "interrupt_state", | ||
| "system_prompt", | ||
| ) | ||
|
|
||
| SNAPSHOT_SCHEMA_VERSION = "1.0" | ||
|
|
||
| SNAPSHOT_PRESETS: dict[str, tuple[SnapshotField, ...]] = { | ||
| "session": ("messages", "state", "conversation_manager_state", "interrupt_state"), | ||
| } | ||
|
|
||
|
|
||
| class TakeSnapshotOptions(TypedDict, total=False): | ||
| """Internal options for take_snapshot. Not exported publicly.""" | ||
|
|
||
| preset: SnapshotPreset | ||
| include: list[SnapshotField] | ||
| exclude: list[SnapshotField] | ||
| app_data: dict[str, Any] | ||
|
|
||
|
|
||
| @dataclass | ||
| class Snapshot: | ||
| """Point-in-time capture of agent state as a versioned JSON-compatible object.""" | ||
|
|
||
| schema_version: str | ||
| created_at: str # ISO 8601 UTC | ||
| data: dict[str, Any] | ||
| app_data: dict[str, Any] | ||
|
|
||
| def validate(self) -> None: | ||
| """Validate that this snapshot can be loaded by the current SDK version. | ||
|
|
||
| Raises: | ||
| SnapshotException: If schema_version is not "1.0". | ||
| """ | ||
| if self.schema_version != SNAPSHOT_SCHEMA_VERSION: | ||
| raise SnapshotException( | ||
| f"Unsupported snapshot schema version: {self.schema_version!r}. " | ||
| f"Current version: {SNAPSHOT_SCHEMA_VERSION}" | ||
| ) | ||
|
|
||
| def to_dict(self) -> dict[str, Any]: | ||
| """Serialize to a plain JSON-compatible dict.""" | ||
| return { | ||
| "schema_version": self.schema_version, | ||
| "created_at": self.created_at, | ||
| "data": self.data, | ||
| "app_data": self.app_data, | ||
| } | ||
|
|
||
| @classmethod | ||
| def from_dict(cls, d: dict[str, Any]) -> Snapshot: | ||
| """Reconstruct a Snapshot from a dict produced by to_dict(). | ||
|
|
||
| Raises: | ||
| SnapshotException: If schema_version is not "1.0". | ||
| """ | ||
| snapshot = cls( | ||
| schema_version=d.get("schema_version", ""), | ||
| created_at=d["created_at"], | ||
| data=d["data"], | ||
| app_data=d.get("app_data", {}), | ||
| ) | ||
| snapshot.validate() | ||
| return snapshot | ||
|
|
||
|
|
||
| def resolve_snapshot_fields(options: TakeSnapshotOptions) -> set[SnapshotField]: | ||
| """Resolve the set of fields to capture based on options. | ||
|
|
||
| Applies: preset → include → exclude (in that order). | ||
|
|
||
| Raises: | ||
| SnapshotException: If any field name is invalid or the resolved set is empty. | ||
| """ | ||
| valid = set(ALL_SNAPSHOT_FIELDS) | ||
|
|
||
| # Validate include/exclude field names | ||
| for field in options.get("include") or []: | ||
| if field not in valid: | ||
| raise SnapshotException(f"Invalid snapshot field: {field!r}. Valid fields: {sorted(valid)}") | ||
| for field in options.get("exclude") or []: | ||
| if field not in valid: | ||
| raise SnapshotException(f"Invalid snapshot field: {field!r}. Valid fields: {sorted(valid)}") | ||
|
|
||
| # Step 1: start with preset | ||
| preset = options.get("preset") | ||
| if preset is not None: | ||
| fields: set[SnapshotField] = set(SNAPSHOT_PRESETS[preset]) | ||
| else: | ||
| fields = set() | ||
|
|
||
| # Step 2: union with include | ||
| include = options.get("include") | ||
| if include: | ||
| fields |= set(include) | ||
|
|
||
| # Step 3: subtract exclude | ||
| exclude = options.get("exclude") | ||
| if exclude: | ||
| fields -= set(exclude) | ||
|
|
||
| if not fields: | ||
| raise SnapshotException( | ||
| "No snapshot fields resolved. Provide a preset or at least one field in 'include'. " | ||
| "Note: passing only 'exclude' without a preset or 'include' always results in an empty set." | ||
| ) | ||
|
|
||
| return fields | ||
|
|
||
|
|
||
| def _utc_now_iso() -> str: | ||
| """Return the current UTC time as an ISO 8601 string ending in 'Z'.""" | ||
| return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") | ||
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
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.