Skip to content

Conversation

@afarntrog
Copy link
Contributor

@afarntrog afarntrog commented Dec 31, 2025

Description

Add pluggable serialization strategies for AgentState

Introduce StateSerializer protocol with JSON and Pickle implementations, enabling AgentState to serialize/deserialize with configurable strategies.

Key additions:

  • StateSerializer protocol for custom serializers
  • JSONSerializer (default) maintains backward compatibility with validation
  • PickleSerializer supports rich Python types (datetime, UUID, etc.)

See more details in the following discussion: #1409

DX:

Basic Usage with Default JSON Serializer

from strands import Agent
agent = Agent()

# Store JSON-compatible values
agent.state.set("user_id", "12345")
agent.state.set("preferences", {"theme": "dark", "language": "en"})
agent.state.set("visit_count", 42)

data = agent.state.serialize() # This is called under-the-hood in session management etc
deserialize_data = agent.state.deserialize(data)

Using PickleSerializer for Rich Python Types

from datetime import datetime
from uuid import uuid4
from strands import Agent, PickleSerializer
from dataclasses import dataclass

@dataclass
class UserDataclass:
    name: str
    role: str

agent = Agent(state=AgentState(serializer=PickleSerializer()))

# Now you can store any Python object
agent.state.set("created_at", datetime.now())
agent.state.set("session_id", uuid4())
agent.state.set("user", UserDataclass(name="Alice", role="admin"))

data = agent.state.serialize() # This is called under-the-hood in session management etc

Custom Serializers

from typing import Any
from strands import StateSerializer, AgentState
import msgpack  # Example: using msgpack

class MsgPackSerializer:
    """Custom serializer using msgpack."""
    
    def serialize(self, data: dict[str, Any]) -> bytes:
        return msgpack.packb(data)
    
    def deserialize(self, data: bytes) -> dict[str, Any]:
        return msgpack.unpackb(data)
    
    def validate(self, value: Any) -> None:
        # msgpack supports similar types to JSON
        try:
            msgpack.packb(value)
        except Exception as e:
            raise ValueError(f"Not msgpack serializable: {e}")

# Use custom serializer
state = AgentState(serializer=MsgPackSerializer())

Related Issues

#1245

Documentation PR

Type of Change

New feature

Testing

How have you tested the change? Verify that the changes do not break functionality or introduce warnings in consuming repositories: agents-docs, agents-tools, agents-cli

  • I ran hatch run prepare

Checklist

  • I have read the CONTRIBUTING document
  • I have added any necessary tests that prove my fix is effective or my feature works
  • I have updated the documentation accordingly
  • I have added an appropriate example to the documentation to outline the feature, or no new docs are needed
  • My changes generate no new warnings
  • Any dependent changes have been merged and published

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Introduce StateSerializer protocol with JSON and Pickle implementations,
enabling AgentState to serialize/deserialize with configurable strategies.
Adds transient state support via persist=False on set(), allowing runtime
values to be excluded from serialization.

Key additions:
- StateSerializer protocol for custom serializers
- JSONSerializer (default) maintains backward compatibility with validation
- PickleSerializer supports rich Python types (datetime, UUID, etc.)
- state_serializer parameter on Agent/BidiAgent constructors
@codecov
Copy link

codecov bot commented Dec 31, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@afarntrog afarntrog self-assigned this Jan 2, 2026
…zer validation

Remove the persist parameter and transient state tracking from AgentState.
This functionality will potentially be re-added in a future phase.

Add validation to PickleSerializer to catch unpicklable objects (DB
connections, file handles, sockets) at set() time rather than serialize()
time, providing fail-fast behavior consistent with JSONSerializer.
…ctor

Move serializer configuration to AgentState object for cleaner API.
…ctor

Move serializer configuration to AgentState object for cleaner API.
@github-actions github-actions bot added size/m and removed size/m labels Jan 2, 2026
@zastrowm zastrowm marked this pull request as draft January 7, 2026 14:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant