Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions diagrid/agent/strands/durable_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ def search(query: str) -> str:
durable = DurableAgent(agent, name="paper-searcher")
result = durable("Search for AI papers")
```

Like a plain Strands ``Agent``, a ``DurableAgent`` is one conversation:
each call starts from ``agent.messages`` and, when it finishes, writes the
full message list back to ``agent.messages``.
"""

def __init__(
Expand Down Expand Up @@ -282,9 +286,10 @@ def agent_workflow(ctx: Any, input_data: dict) -> Generator[Any, Any, dict]: #
)

# Build initial messages
messages: list[dict[str, Any]] = [
messages: list[dict[str, Any]] = list(input_data.get("messages", [])) + [
{"role": "user", "content": [{"text": task}]}
]
completed = False
final_text = ""
all_tool_calls: list[dict[str, Any]] = []
max_iterations = 10
Expand Down Expand Up @@ -316,6 +321,7 @@ def agent_workflow(ctx: Any, input_data: dict) -> Generator[Any, Any, dict]: #
# If no tool calls, we're done
if not tool_uses or stop_reason == "end_turn":
final_text = text
completed = True
print(
f"[WORKFLOW] Model finished: {stop_reason}",
flush=True,
Expand Down Expand Up @@ -364,6 +370,7 @@ def agent_workflow(ctx: Any, input_data: dict) -> Generator[Any, Any, dict]: #
return { # type: ignore[return-value]
"result": final_text,
"tool_calls": all_tool_calls,
"messages": messages if completed else None,
}

# Register everything
Expand Down Expand Up @@ -400,7 +407,7 @@ def __call__(self, task: str, timeout_seconds: int = 120) -> str:
# Use the new DaprWorkflowClient API with function reference
self._workflow_client.schedule_new_workflow(
workflow=self._workflow_func,
input={"task": task},
input={"task": task, "messages": list(self._agent.messages)},
instance_id=instance_id,
)

Expand Down Expand Up @@ -434,6 +441,10 @@ def __call__(self, task: str, timeout_seconds: int = 120) -> str:
output = json.loads(output)

if isinstance(output, dict):
updated = output.get("messages")
if updated is not None:
# Keep the same list object so ``agent.messages`` stays live.
self._agent.messages[:] = updated
return output.get("result", str(output))
return str(output) if output else ""

Expand Down
103 changes: 103 additions & 0 deletions diagrid/agent/strands/history.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Copyright (c) 2026-Present Diagrid Inc.
# SPDX-License-Identifier: BUSL-1.1

"""Conversation history for the Strands workflow runner.

History is keyed by runner name and session id. It lives in a Dapr state store
when one is available, otherwise in a dict inside the runner process.
"""

import logging
from typing import Any, Optional

logger = logging.getLogger(__name__)

# Matches the Strands ``SlidingWindowConversationManager`` default.
DEFAULT_WINDOW_SIZE = 40


def history_key(runner_name: str, session_id: str) -> str:
"""Return the state key that holds one session's messages for one runner."""
return f"strands-{runner_name}-{session_id}-messages"


def resolve_window_size(agent: Any) -> int:
"""Return how many messages to keep: the agent's sliding window, else 40."""
try:
from strands.agent.conversation_manager import (
SlidingWindowConversationManager,
)
except ImportError: # pragma: no cover - strands is required by this package
return DEFAULT_WINDOW_SIZE

manager = getattr(agent, "conversation_manager", None)
if isinstance(manager, SlidingWindowConversationManager):
return int(manager.window_size)
return DEFAULT_WINDOW_SIZE


def _is_plain_user_message(message: Any) -> bool:
"""True for a user message that carries no tool result."""
if not isinstance(message, dict) or message.get("role") != "user":
return False
content = message.get("content") or []
return not any(isinstance(b, dict) and "toolResult" in b for b in content)


def trim_history(messages: list[Any], window_size: int) -> list[Any]:
"""Keep the last ``window_size`` messages, starting at a clean user turn.

After cutting, messages are dropped from the front until the first one is a
user message without a ``toolResult``. Otherwise a tool result could be left
without the tool call it answers, and the model provider rejects that.
"""
kept = list(messages[-window_size:]) if window_size > 0 else []
start = 0
while start < len(kept) and not _is_plain_user_message(kept[start]):
start += 1
return kept[start:]


class HistoryStore:
"""Loads and saves session messages for one runner.

Uses ``state_store`` (a ``DaprStateStore``) when given. Without one, history
is kept in this process and a single warning says it will not survive a
restart or be shared between replicas.
"""

def __init__(self, runner_name: str, state_store: Optional[Any] = None) -> None:
self._runner_name = runner_name
self._state_store = state_store
self._local: dict[str, list[Any]] = {}
self._warned = False

def _warn_in_process(self) -> None:
if self._warned:
return
self._warned = True
logger.warning(
"No state store configured for runner %r: conversation history is "
"kept in this process only and will not survive a restart or be "
"shared between replicas. Add a Dapr state component named "
"'agent-memory' (or pass state_store) for durable history.",
self._runner_name,
)

def load(self, session_id: str) -> list[Any]:
"""Return the stored messages for ``session_id``, or an empty list."""
key = history_key(self._runner_name, session_id)
if self._state_store is not None:
stored = self._state_store.get(key)
return list(stored) if isinstance(stored, list) else []
self._warn_in_process()
return list(self._local.get(key, []))

def save(self, session_id: str, messages: list[Any]) -> None:
"""Store ``messages`` as the full history for ``session_id``."""
key = history_key(self._runner_name, session_id)
if self._state_store is not None:
self._state_store.save(key, messages)
return
self._warn_in_process()
self._local[key] = list(messages)
52 changes: 50 additions & 2 deletions diagrid/agent/strands/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from diagrid.agent.core.types.type import SupportedFrameworks
from diagrid.agent.core.workflow import BaseWorkflowRunner

from .history import HistoryStore, resolve_window_size, trim_history
from .workflow import WorkflowOutput

if TYPE_CHECKING:
Expand Down Expand Up @@ -65,6 +66,18 @@ def search_web(query: str) -> str:
runner.shutdown()
```

Conversation history:
``session_id`` identifies a conversation. Calls with the same
``session_id`` see the earlier turns, like repeated calls on one plain
Strands ``Agent``; use a new ``session_id`` to start fresh. History is
stored under ``strands-<name>-<session_id>-messages``, so runners with
different names never share it. It is saved after each successful run,
trimmed to the agent's ``SlidingWindowConversationManager.window_size``
(default 40). It goes to the state store (``state_store``, or the
``agent-memory`` component when present) and survives restarts. Without
one it stays in this process and a warning is logged. The agent's own
``messages`` and session manager are not used.

Attributes:
agent: The Strands Agent to execute
workflow_runtime: The Dapr WorkflowRuntime instance
Expand Down Expand Up @@ -104,6 +117,8 @@ def __init__(
state_store=state_store,
)

self._history = HistoryStore(name, self._state_store)

# Register metadata
self._register_agent_metadata(
agent=self._agent,
Expand All @@ -121,6 +136,21 @@ def _register_workflow_components(self) -> None:
"""Set up the workflow runtime, activities, and workflow."""
# Store references for closures
agent_ref = self._agent
history = self._history

# ============================================================
# Activities: load and save conversation history
# ============================================================
def load_history_activity(ctx: Any, input_data: dict) -> list: # type: ignore[type-arg]
"""Activity that returns the stored messages for a session."""
return history.load(input_data["session_id"])

def save_history_activity(ctx: Any, input_data: dict) -> None: # type: ignore[type-arg]
"""Activity that trims and stores the full message list."""
trimmed = trim_history(
input_data.get("messages", []), resolve_window_size(agent_ref)
)
history.save(input_data["session_id"], trimmed)

# ============================================================
# Activity: Call the model (LLM)
Expand Down Expand Up @@ -257,11 +287,16 @@ async def _execute() -> Any:
def agent_workflow(ctx: Any, input_data: dict) -> Generator[Any, Any, dict]: # type: ignore[type-arg]
"""Workflow that orchestrates the agent loop."""
task = input_data.get("task", "")
session_id = input_data.get("session_id", "")
system_prompt = agent_ref.system_prompt or ""

messages: list[dict[str, Any]] = [
stored = yield ctx.call_activity(
load_history_activity, input={"session_id": session_id}
)
messages: list[dict[str, Any]] = list(stored or []) + [
{"role": "user", "content": [{"text": task}]}
]
completed = False
final_text = ""
all_tool_calls: list[dict[str, Any]] = []

Expand All @@ -287,6 +322,7 @@ def agent_workflow(ctx: Any, input_data: dict) -> Generator[Any, Any, dict]: #

if not tool_uses or stop_reason == "end_turn":
final_text = text
completed = True
break

tool_results = []
Expand Down Expand Up @@ -315,6 +351,12 @@ def agent_workflow(ctx: Any, input_data: dict) -> Generator[Any, Any, dict]: #

messages.append({"role": "user", "content": tool_results})

if completed:
yield ctx.call_activity(
save_history_activity,
input={"session_id": session_id, "messages": messages},
)

return { # type: ignore[return-value]
"result": final_text,
"tool_calls": all_tool_calls,
Expand All @@ -324,6 +366,12 @@ def agent_workflow(ctx: Any, input_data: dict) -> Generator[Any, Any, dict]: #
self._workflow_runtime.register_workflow(
agent_workflow, name=self.workflow_name
)
self._workflow_runtime.register_activity(
load_history_activity, name="strands_load_history"
)
self._workflow_runtime.register_activity(
save_history_activity, name="strands_save_history"
)
self._workflow_runtime.register_activity(
call_model_activity, name="strands_call_model"
)
Expand Down Expand Up @@ -365,7 +413,7 @@ async def run_async(
if workflow_id is None:
workflow_id = f"strands-{session_id}-{uuid.uuid4().hex[:8]}"

input_data = {"task": task}
input_data = {"task": task, "session_id": session_id}

logger.info("Starting workflow: %s", workflow_id)
self._workflow_client.schedule_new_workflow(
Expand Down
44 changes: 44 additions & 0 deletions examples/strands/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,47 @@ Yield workflow events to caller
```

Each workflow activity is checkpointed by Dapr, providing durability guarantees.

## Conversation history

`DaprWorkflowAgentRunner` treats `session_id` as one conversation. A second
call with the same `session_id` sees the earlier turns, like repeated calls on
one plain Strands `Agent`. Use a new `session_id` to start fresh.

```python
runner.run_sync(task="My name is Ada.", session_id="chat-1")
runner.run_sync(task="What is my name?", session_id="chat-1") # sees the first turn
```

- History is stored under `strands-<runner name>-<session_id>-messages`, so two
runners with different names never share it.
- It is saved after each successful run and trimmed to the agent's
`SlidingWindowConversationManager.window_size` (default 40).
- For durable memory, add a Dapr state store component named `agent-memory`
(or pass `state_store=` to the runner). History then survives restarts and is
shared between replicas:

```yaml
apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: agent-memory
spec:
type: state.redis
version: v1
metadata:
- name: redisHost
value: "localhost:6379"
- name: redisPassword
value: ""
```

- Without a state store, history stays in the runner process and a warning is
logged: it does not survive a restart and is not shared between replicas.
- The agent's own `messages` and any Strands session manager are not used by
the runner.
- Callers that reuse one fixed `session_id` for unrelated tasks now carry
history between those tasks.

`DurableAgent` is a single conversation, like `Agent`: each call starts from
`agent.messages` and writes the result back to it.
Loading
Loading