strands_session_dynamodb 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ """Amazon DynamoDB session manager for Strands Agents."""
2
+
3
+ from .session_manager import DynamoDBSessionManager, DynamoDBSessionStorage
4
+
5
+ __all__ = ["DynamoDBSessionManager", "DynamoDBSessionStorage"]
@@ -0,0 +1,173 @@
1
+ """Amazon DynamoDB session backend for Strands Agents.
2
+
3
+ Provides a ``DynamoDBSessionStorage`` (implementing the ``SessionStorage``
4
+ interface from ``strands-agents-session``) and a thin ``DynamoDBSessionManager``
5
+ that wires it into ``KeyValueSessionManager``. All the session-repository logic
6
+ lives in the base package; this module is just the storage layer.
7
+
8
+ Single DynamoDB table, both keys strings (``PK`` HASH, ``SK`` RANGE). Payloads
9
+ are stored as a JSON string in a ``data`` attribute, which sidesteps DynamoDB's
10
+ float/empty-value quirks.
11
+ """
12
+
13
+ import time
14
+ from typing import TYPE_CHECKING, Any, Dict, List, Optional
15
+
16
+ import boto3
17
+ from boto3.dynamodb.conditions import Key
18
+ from botocore.exceptions import ClientError
19
+
20
+ from strands_agents_session import KeyValueSessionManager, SessionStorage
21
+
22
+ if TYPE_CHECKING: # pragma: no cover
23
+ from botocore.config import Config as BotocoreConfig
24
+
25
+
26
+ class DynamoDBSessionStorage(SessionStorage):
27
+ """DynamoDB implementation of the session ``SessionStorage`` interface."""
28
+
29
+ def __init__(
30
+ self,
31
+ table_name: str,
32
+ *,
33
+ boto_session: "boto3.Session | None" = None,
34
+ boto_client_config: "BotocoreConfig | None" = None,
35
+ region_name: str | None = None,
36
+ endpoint_url: str | None = None,
37
+ ttl_seconds: int | None = None,
38
+ ) -> None:
39
+ session = boto_session or boto3.Session(region_name=region_name)
40
+ self.dynamodb = session.resource(
41
+ "dynamodb", endpoint_url=endpoint_url, config=boto_client_config
42
+ )
43
+ self.client = session.client(
44
+ "dynamodb", endpoint_url=endpoint_url, config=boto_client_config
45
+ )
46
+ self.table_name = table_name
47
+ self.ttl_seconds = ttl_seconds
48
+ self.table = self._get_or_create_table(table_name)
49
+
50
+ def _get_or_create_table(self, table_name: str):
51
+ table = self.dynamodb.Table(table_name)
52
+ try:
53
+ table.load()
54
+ return table
55
+ except ClientError as e:
56
+ if e.response["Error"]["Code"] != "ResourceNotFoundException":
57
+ raise
58
+ table = self.dynamodb.create_table(
59
+ TableName=table_name,
60
+ KeySchema=[
61
+ {"AttributeName": "PK", "KeyType": "HASH"},
62
+ {"AttributeName": "SK", "KeyType": "RANGE"},
63
+ ],
64
+ AttributeDefinitions=[
65
+ {"AttributeName": "PK", "AttributeType": "S"},
66
+ {"AttributeName": "SK", "AttributeType": "S"},
67
+ ],
68
+ BillingMode="PAY_PER_REQUEST",
69
+ )
70
+ table.wait_until_exists()
71
+ if self.ttl_seconds:
72
+ try:
73
+ self.client.update_time_to_live(
74
+ TableName=table_name,
75
+ TimeToLiveSpecification={"Enabled": True, "AttributeName": "ttl"},
76
+ )
77
+ except ClientError: # pragma: no cover
78
+ pass
79
+ return table
80
+
81
+ # SessionStorage ----------------------------------------------------
82
+
83
+ def put(self, item: Dict[str, Any]) -> None:
84
+ ddb_item = {"PK": item["pk"], "SK": item["sk"], "data": item["data"]}
85
+ if self.ttl_seconds:
86
+ ddb_item["ttl"] = int(time.time()) + self.ttl_seconds
87
+ self.table.put_item(Item=ddb_item)
88
+
89
+ def get(self, pk: str, sk: str) -> Optional[Dict[str, Any]]:
90
+ item = self.table.get_item(Key={"PK": pk, "SK": sk}).get("Item")
91
+ if not item:
92
+ return None
93
+ return {"pk": item["PK"], "sk": item["SK"], "data": item["data"]}
94
+
95
+ def query(
96
+ self, pk: str, sk_gte: Optional[str] = None, limit: Optional[int] = None
97
+ ) -> List[Dict[str, Any]]:
98
+ condition = Key("PK").eq(pk)
99
+ if sk_gte is not None:
100
+ condition = condition & Key("SK").gte(sk_gte)
101
+
102
+ items: List[dict] = []
103
+ start_key = None
104
+ while True:
105
+ query_kwargs: Dict[str, Any] = {
106
+ "KeyConditionExpression": condition,
107
+ "ScanIndexForward": True,
108
+ }
109
+ if start_key is not None:
110
+ query_kwargs["ExclusiveStartKey"] = start_key
111
+ if limit is not None:
112
+ query_kwargs["Limit"] = limit - len(items)
113
+ resp = self.table.query(**query_kwargs)
114
+ items.extend(resp.get("Items", []))
115
+ start_key = resp.get("LastEvaluatedKey")
116
+ if limit is not None and len(items) >= limit:
117
+ items = items[:limit]
118
+ break
119
+ if not start_key:
120
+ break
121
+
122
+ return [{"pk": i["PK"], "sk": i["SK"], "data": i["data"]} for i in items]
123
+
124
+ def delete(self, pk: str, sk: str) -> None:
125
+ self.table.delete_item(Key={"PK": pk, "SK": sk})
126
+
127
+ def delete_partition(self, pk: str) -> None:
128
+ start_key = None
129
+ while True:
130
+ query_kwargs: Dict[str, Any] = {"KeyConditionExpression": Key("PK").eq(pk)}
131
+ if start_key is not None:
132
+ query_kwargs["ExclusiveStartKey"] = start_key
133
+ resp = self.table.query(**query_kwargs)
134
+ items = resp.get("Items", [])
135
+ with self.table.batch_writer() as batch:
136
+ for i in items:
137
+ batch.delete_item(Key={"PK": i["PK"], "SK": i["SK"]})
138
+ start_key = resp.get("LastEvaluatedKey")
139
+ if not start_key:
140
+ break
141
+
142
+
143
+ class DynamoDBSessionManager(KeyValueSessionManager):
144
+ """DynamoDB-backed session manager for Strands Agents.
145
+
146
+ agent = Agent(session_manager=DynamoDBSessionManager(
147
+ session_id="user-123", table_name="strands-sessions",
148
+ ))
149
+
150
+ The table is created automatically (on-demand billing) if it does not exist.
151
+ """
152
+
153
+ def __init__(
154
+ self,
155
+ session_id: str,
156
+ table_name: str,
157
+ *,
158
+ boto_session: "boto3.Session | None" = None,
159
+ boto_client_config: "BotocoreConfig | None" = None,
160
+ region_name: str | None = None,
161
+ endpoint_url: str | None = None,
162
+ ttl_seconds: int | None = None,
163
+ **kwargs: Any,
164
+ ) -> None:
165
+ storage = DynamoDBSessionStorage(
166
+ table_name,
167
+ boto_session=boto_session,
168
+ boto_client_config=boto_client_config,
169
+ region_name=region_name,
170
+ endpoint_url=endpoint_url,
171
+ ttl_seconds=ttl_seconds,
172
+ )
173
+ super().__init__(session_id=session_id, storage=storage)
@@ -0,0 +1,113 @@
1
+ Metadata-Version: 2.4
2
+ Name: strands_session_dynamodb
3
+ Version: 0.1.0
4
+ Summary: Amazon DynamoDB session manager (storage backend) for Strands Agents — persists sessions, agent state, and messages
5
+ Project-URL: Homepage, https://github.com/skamalj/strands-agents-session
6
+ Project-URL: Repository, https://github.com/skamalj/strands-agents-session.git
7
+ Author-email: Kamal <skamalj@github.com>
8
+ Keywords: agent-state,aws,dynamodb,memory,persistence,session,strands,strands-agents
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Requires-Python: >=3.10
14
+ Requires-Dist: boto3
15
+ Requires-Dist: strands-agents
16
+ Requires-Dist: strands-agents-session>=0.1.0
17
+ Description-Content-Type: text/markdown
18
+
19
+ # strands-session-dynamodb
20
+
21
+ Amazon DynamoDB **session manager** (storage backend) for [Strands Agents](https://strandsagents.com). Persists an agent's sessions, **agent state**, conversation-manager state, and messages to a single DynamoDB table so conversations resume across runs.
22
+
23
+ It implements Strands' `SessionRepository` and mixes in `RepositorySessionManager` — exactly like the built-in `S3SessionManager` — so all the session lifecycle logic (message indexing, restore, `removed_message_count` offsetting, tool-use repair, change detection) is reused unchanged. This package only supplies the DynamoDB storage.
24
+
25
+ > **Storage only, by design.** In Strands, message *pruning* is the job of a `ConversationManager` (`SlidingWindow`, `Summarizing`), which is deliberately decoupled from storage. This package does **not** prune — pruning at the storage layer would corrupt Strands' message-index/offset restore logic. Use a `conversation_manager` for that.
26
+
27
+ ## Why DynamoDB instead of S3
28
+
29
+ Strands ships an `S3SessionManager` out of the box, so why DynamoDB? Because agent sessions are a **request-bound, small-item** workload — the exact shape where DynamoDB wins on both cost and latency.
30
+
31
+ Strands writes **one item per message** plus an agent record re-synced each turn — lots of tiny (sub-KB) reads and writes. The bill is dominated by *request count*, not bytes stored, and that's where the two services price very differently:
32
+
33
+ | | S3 Standard | DynamoDB on-demand |
34
+ |---|---|---|
35
+ | Write | ~$5.00 / million PUT (any size) | ~$1.25 / million WRU (per 1 KB) |
36
+ | Read | ~$0.40 / million GET (per object) | ~$0.25 / million RRU (per 4 KB) |
37
+ | Free tier | none | 25 WCU + 25 RCU + 25 GB, perpetual |
38
+ | Latency | tens of ms | single-digit ms |
39
+
40
+ Two structural advantages for small items:
41
+
42
+ - **Writes:** S3 charges per request regardless of size — a 200-byte message costs the same PUT as a 4 MB one. DynamoDB bills per KB, so tiny messages hit the cheapest unit *and* the per-unit price is ~4× lower.
43
+ - **Reads:** `list_messages` is **one Query** in DynamoDB, and one RRU covers 4 KB — so several small messages per RRU. In S3 it's **one GET per message object**. Batching crushes the per-item read cost.
44
+
45
+ For a workload of ~1M small message-writes/month with periodic restores, this is roughly a **3–4× lower bill** on DynamoDB — and often **free** under DynamoDB's perpetual free tier, which S3 has no equivalent of. Add native **TTL** for automatic session expiry and single-digit-ms access, and DynamoDB is the better default for hot session/agent-state storage.
46
+
47
+ **When S3 still wins:** very large message payloads (big tool results, images) that approach or exceed DynamoDB's 400 KB item limit, or cold/archival sessions rarely read (S3 storage is ~10× cheaper per GB). A robust production setup is DynamoDB for the session/message records + S3 overflow only for oversized blobs.
48
+
49
+ ## Installation
50
+
51
+ ```bash
52
+ pip install strands-session-dynamodb
53
+ # or, via the family's extra:
54
+ pip install "strands-agents-session[dynamodb]"
55
+ ```
56
+
57
+ **Requires Python 3.10+.**
58
+
59
+ ## Quick start
60
+
61
+ ```python
62
+ from strands import Agent
63
+ from strands_session_dynamodb import DynamoDBSessionManager
64
+
65
+ session_manager = DynamoDBSessionManager(
66
+ session_id="user-123",
67
+ table_name="strands-sessions",
68
+ region_name="us-east-1",
69
+ )
70
+
71
+ agent = Agent(session_manager=session_manager)
72
+
73
+ agent("Hi, I'm Kamal")
74
+ agent("What's my name?") # remembers within the session
75
+ ```
76
+
77
+ Next run, same `session_id` → the agent restores its full history and state from DynamoDB. The table is created automatically (on-demand billing) if it does not exist.
78
+
79
+ ## API
80
+
81
+ ### `DynamoDBSessionManager(session_id, table_name, *, region_name=None, boto_session=None, boto_client_config=None, endpoint_url=None, ttl_seconds=None)`
82
+
83
+ | Parameter | Description |
84
+ |---|---|
85
+ | `session_id` | Session identifier |
86
+ | `table_name` | DynamoDB table (auto-created if absent) |
87
+ | `region_name` | AWS region |
88
+ | `boto_session` | Optional pre-built `boto3.Session` |
89
+ | `boto_client_config` | Optional `botocore` client config |
90
+ | `endpoint_url` | Custom endpoint (e.g. DynamoDB Local / LocalStack) |
91
+ | `ttl_seconds` | If set, writes a `ttl` epoch attribute and enables table TTL for automatic session expiry |
92
+
93
+ ## AWS setup
94
+
95
+ Standard AWS credential resolution (env vars, `~/.aws/credentials`, profile, or IAM role). The credentials need permission to create the table (if absent) and read/write items.
96
+
97
+ ## Data model
98
+
99
+ Single table, both keys strings:
100
+
101
+ | Item | PK | SK |
102
+ |---|---|---|
103
+ | Session | `SESSION#<session_id>` | `META` |
104
+ | Agent | `SESSION#<session_id>` | `AGENT#<agent_id>` |
105
+ | Message | `SESSION#<session_id>#AGENT#<agent_id>` | `MSG#<zero-padded id>` |
106
+
107
+ Messages live in a per-agent partition with a zero-padded, lexically ordered sort key, so `list_messages(offset, limit)` is a native range Query — matching the `removed_message_count` offset semantics Strands relies on. Payloads are stored as a JSON string.
108
+
109
+ > **Item-size note:** DynamoDB items are capped at 400 KB. A single message with a very large payload (e.g. big tool results / images) could exceed that; S3 has no such limit. For such workloads, keep large blobs in S3 and reference them.
110
+
111
+ ## License
112
+
113
+ MIT
@@ -0,0 +1,5 @@
1
+ strands_session_dynamodb/__init__.py,sha256=EFFcd44WOlcZB5_tVM04jTJnLVIdSoCz29AD1qpk_VM,199
2
+ strands_session_dynamodb/session_manager.py,sha256=WgvclLinqLmmTtvdR6EjCacIRoe4OGdUcw9glu17gXI,6416
3
+ strands_session_dynamodb-0.1.0.dist-info/METADATA,sha256=egYlWZnX2_d_zw4mLLll6ARcjQh7-S4AyNRzcdkOtaM,6092
4
+ strands_session_dynamodb-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
5
+ strands_session_dynamodb-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any