---
jupytext:
  formats: md:myst
  text_representation:
    extension: .md
    format_name: myst
    format_version: 0.13
    jupytext_version: 1.11.5
kernelspec:
  display_name: Python 3.10
  language: python
  name: python3
---

# Agent State Service

## Overview

The **Agent State Service** is a core component used to **store and manage the serializable state of agents**, enabling them to maintain context across multiple turns or even across sessions.
Unlike the **Session History Service**, which mainly stores text messages, the **State Service** focuses on saving the agent’s **structured, serializable internal data**, such as:

- Variable values
- Execution progress
- Intermediate results from tool usage
- Environment configuration or preferences

The State Service organizes data according to the following dimensions:

- `user_id`: distinguishes users
- `session_id`: distinguishes sessions (default is `"default"`)
- `round_id`: distinguishes conversation turns (optional; if omitted, the latest turn ID is generated automatically)

Role during agent execution:

- **Save state** (`save_state`): Store the agent’s state at a given moment.
- **Restore state** (`export_state`): Restore previously saved state in the next conversation turn or session.

```{note}
The state is a fully serializable Python `dict`, usually generated by the agent’s `state_dict()` method and loadable via `load_state_dict`, making it easy to wrap and transfer across platforms.
```

## Usage in AgentScope

Unlike the **Session History Service**, the **Agent State Service** in AgentScope generally does **not require an adapter**. It can directly call `save_state` and `export_state` to persist and load state.

```{code-cell}
from agentscope_runtime.engine.services.agent_state import InMemoryStateService

# Initialize the service
state_service = InMemoryStateService()
await state_service.start()

# Suppose the agent has a state_dict method
agent_state = agent.state_dict()

# Save state (returns round_id)
round_id = await state_service.save_state(
    user_id="User1",
    session_id="TestSession",
    state=agent_state
)
print(f"State saved in round {round_id}")

# Export latest state (or specify round_id)
loaded_state = await state_service.export_state(
    user_id="User1",
    session_id="TestSession"
)
agent.load_state_dict(loaded_state)
```

## Available Backend Implementations

Similar to the Session History Service, the Agent State Service also supports different storage backends:

| Service Type             | Import Path                                                  | Storage Location           | Persistence          | Production-ready | Features                                                     | Applicable Scenarios                                    |
| ------------------------ | ------------------------------------------------------------ | -------------------------- | -------------------- | ---------------- | ------------------------------------------------------------ | ------------------------------------------------------- |
| **InMemoryStateService** | `from agentscope_runtime.engine.services.agent_state import InMemoryStateService` | In-process memory          | ❌ No                 | ❌ No             | Simple and fast, no external dependencies, data lost when process ends | Development, debugging, unit testing                    |
| **RedisStateService**    | `from agentscope_runtime.engine.services.agent_state import RedisStateService` | Redis (in-memory database) | ✅ Optional (RDB/AOF) | ✅ Yes            | Supports distributed shared state, cross-process access, Redis persistence optional | High-performance production, cross-process data sharing |

## Switching Between Implementations

Since the `StateService` interface is consistent across implementations, switching backend types is straightforward—just replace the instantiation.

Example: InMemory → Redis

```{code-cell}
from agentscope_runtime.engine.services.agent_state import RedisStateService

state_service = RedisStateService(redis_url="redis://localhost:6379/0")
await state_service.start()

# Save state
await state_service.save_state(user_id="User1", session_id="ProdSession", state=agent.state_dict())

# Export state
state = await state_service.export_state(user_id="User1", session_id="ProdSession")
agent.load_state_dict(state)
```

## Recommendations

- **Development, debugging, or testing**: Use `InMemoryStateService` — no external dependencies, fast iteration.
- **Production with cross-process state sharing**: Use `RedisStateService` — can be combined with Redis persistence and HA clusters.
- **Long-term storage with strong consistency or auditing needs**: Consider implementing a database-backed custom `StateService`.

## Summary

- The **Agent State Service** saves internal serializable state, unlike the Session History Service which only stores messages.
- State is organized by `user_id`, `session_id`, and `round_id`.
- In AgentScope, it is usually called directly without adapters.
- Backend switching is easy thanks to a unified interface.
- Choose between InMemory, Redis, or custom implementations based on your scenario.
