sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[BUG] Message management active while serving the agent via A2A

Open juliangrueber opened this issue 1 year ago • 17 comments

Checks

  • [x] I have updated to the lastest minor and patch version of Strands
  • [x] I have checked the documentation and this is not expected behavior
  • [x] I have searched ./issues and there are no duplicates of my issue

Strands Version

1.10.0

Python Version

Python 3.12.11

Operating System

Linux, CloudDesktop

Installation Method

pip

Steps to Reproduce

  1. Host the agent as provided by the be example
  2. Add a logger.info(f"Current messages: {self.agent.messages}") into the line: https://github.com/strands-agents/sdk-python/blob/776fd93751cc26e3d535776b17612c2e3068cc2b/src/strands/multiagent/a2a/executor.py#L105
  3. Run the client example from the docs with logging level info. Ask the same questions twice:

In the logs you should see the following:

INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
INFO:     127.0.0.1:41184 - "GET /a2a/.well-known/agent-card.json HTTP/1.1" 200 OK
2025-10-06 21:17:52 - INFO - Current messages: []
2025-10-06 21:17:52 - INFO - Creating Strands MetricsClient
INFO:     127.0.0.1:41184 - "POST /a2a/ HTTP/1.1" 200 OK
INFO:     127.0.0.1:41192 - "GET /a2a/.well-known/agent-card.json HTTP/1.1" 200 OK
2025-10-06 21:17:56 - INFO - Current messages: [{'role': 'user', 'content': [{'text': 'What was my previous question?'}]}, {'role': 'assistant', 'content': [{'text': 'You haven\'t asked me a question before this one. This is our first interaction in this conversation. Your current question is "What was my previous question?"'}]}]
INFO:     127.0.0.1:41192 - "POST /a2a/ HTTP/1.1" 200 OK

Expected Behavior

The session management is expected to be handled by the implementation TaskStore coming from a2a-sdk not by the instance of the Strands Agent

Actual Behavior

The agent keeps the previous messages in memory, collecting all the messages which the server receives.

Additional Context

No response

Possible Solution

https://github.com/strands-agents/sdk-python/blob/776fd93751cc26e3d535776b17612c2e3068cc2b/src/strands/multiagent/a2a/server.py

"""A2A-compatible wrapper for Strands Agent.

This module provides the A2AAgent class, which adapts a Strands Agent to the A2A protocol,
allowing it to be used in A2A-compatible systems.
"""

import logging
- from typing import Any, Literal
+ from typing import Any, Callable, Literal
from urllib.parse import urlparse


class A2AServer:
    """A2A-compatible wrapper for Strands Agent."""

    def __init__(
        self,
-        agent: SAAgent,
+       agent_generator: Callable[[], SAAgent],
        *,
        # AgentCard
        host: str = "127.0.0.1",
        port: int = 9000,
        http_url: str | None = None,
        serve_at_root: bool = False,
        version: str = "0.0.1",
        skills: list[AgentSkill] | None = None,
        # RequestHandler
        task_store: TaskStore | None = None,
        queue_manager: QueueManager | None = None,
        push_config_store: PushNotificationConfigStore | None = None,
        push_sender: PushNotificationSender | None = None,
    ):

-        self.strands_agent = agent
+       self.agent_generator = agent_generator
+       self.strands_agent = self.agent_generator()
        self.name = self.strands_agent.name
        self.description = self.strands_agent.description
        self.capabilities = AgentCapabilities(streaming=True)
        self.request_handler = DefaultRequestHandler(
-            agent_executor=StrandsA2AExecutor(self.strands_agent),
+            agent_executor=StrandsA2AExecutor(self.agent_generator),
            task_store=task_store or InMemoryTaskStore(),
            queue_manager=queue_manager,
            push_config_store=push_config_store,
            push_sender=push_sender,
        )
        self._agent_skills = skills
 

https://github.com/strands-agents/sdk-python/blob/776fd93751cc26e3d535776b17612c2e3068cc2b/src/strands/multiagent/a2a/executor.py


class StrandsA2AExecutor(AgentExecutor):

-     def __init__(self, agent: SAAgent):
+     def __init__(self, agent_generator: Callable[[], SAAgent]):

    async def _execute_streaming(self, context: RequestContext, updater: TaskUpdater) -> None:
        """Execute request in streaming mode.

        Streams the agent's response in real-time, sending incremental updates
        as they become available from the agent.

        Args:
            context: The A2A request context, containing the user's input and other metadata.
            updater: The task updater for managing task state and sending updates.
        """
        # Convert A2A message parts to Strands ContentBlocks
        if context.message and hasattr(context.message, "parts"):
            content_blocks = self._convert_a2a_parts_to_content_blocks(context.message.parts)
            if not content_blocks:
                raise ValueError("No content blocks available")
        else:
            raise ValueError("No content blocks available")

+         agent = self.agent_generator()

        try:
-            async for event in self.agent.stream_async(content_blocks):
+           async for event in agent.stream_async(content_blocks):
                await self._handle_streaming_event(event, updater)
        except Exception:
            logger.exception("Error in streaming execution")
            raise



Related Issues

No response

juliangrueber avatar Oct 06 '25 21:10 juliangrueber

Hi, marking this as open to contribution, one important consideration is that we cannot break backwards compatibility of this interface. We likely need to "reset" the agent instead of/in addition to adding this "agent supplier"

dbschmigelski avatar Oct 07 '25 14:10 dbschmigelski

Hi, thanks for the feedback.

Actually, to be consistent, we would something like the following :


def agent_generator(context_id: str)-> strands.Agent:

      # Create a session manager with a unique session ID
      session_manager = FileSessionManager(session_id=context_id)
      return Agent(session_manager=session_manager)


A2AServer(agent_generator=agent_generator)

In the executor.py

class StrandsA2AExecutor(AgentExecutor):

    async def _execute_streaming(self, context: RequestContext, updater: TaskUpdater) -> None:

      agent = self.agent_generator(context.context_id)
      try:
          async for event in agent.stream_async(content_blocks):

Alternatively, we can make a deep copy of the not-invoked strands agent that is passed to the StrandsA2AExecutor and modify the session_id. Would there be some existing strands functionality that we could leverage for this @dbschmigelski ?

juliangrueber avatar Oct 07 '25 17:10 juliangrueber

I've been running in to this issue as well, glad to see this written up.

For me this seems like a potential blocker to using Strands for A2A unless I write my own Executor.

niallthomson avatar Oct 09 '25 23:10 niallthomson

We'd probably want to go a bit further and pass in the entire context:

def agent_generator(context: RequestContext)-> strands.Agent:

  # Create a session manager with a unique session ID
  session_manager = FileSessionManager(session_id=context_id)
  return Agent(session_manager=session_manager)

this would enable pulling additional properties from the context making it more reusable

zastrowm avatar Nov 03 '25 13:11 zastrowm

I've been running in to this issue as well, glad to see this written up.

For me this seems like a potential blocker to using Strands for A2A unless I write my own Executor.

This is a blocker for me as well. More than a month has passed so far =(

BnnaFish avatar Dec 01 '25 18:12 BnnaFish

We'd probably want to go a bit further and pass in the entire context

Yes as I've played around more with my "forked" version of the A2A server and executor I've ended up wanting the entire context for:

  1. Creating the session manager
  2. Accessing information from the inbound A2A request (like headers)
  3. Adding stuff to the Strands invocation state

niallthomson avatar Dec 02 '25 01:12 niallthomson

i have been facing the same issue, any work around?

MD-AZMAL avatar Dec 04 '25 15:12 MD-AZMAL

We are also blocked in adopting Strands Agents in production environments due to this with A2A.

blakeromano avatar Dec 08 '25 20:12 blakeromano

@juliangrueber can you confirm this behaviour in the agents that are deployed to runtime? I have verified if the agent is deployed in runtime as long as the session_id is passed in header the context for that session is preserved and it does not conflict with other sessions, unlike running it locally where there's no isolation? i havent checked this behaviour for A2A agents in runtime

MD-AZMAL avatar Dec 09 '25 05:12 MD-AZMAL

We'd probably want to go a bit further and pass in the entire context

Yes as I've played around more with my "forked" version of the A2A server and executor I've ended up wanting the entire context for:

  1. Creating the session manager
  2. Accessing information from the inbound A2A request (like headers)
  3. Adding stuff to the Strands invocation state

i ended up going on a similar route, instead of relying on headers i am passing the context in A2A metadata be it session_id or actor_id and adding it to strands invocation state, however instead of the session manager i am using the agentcore memory with hooks and accessing the state variable in the hook itself, could you share your thoughts on session_manager

MD-AZMAL avatar Dec 09 '25 05:12 MD-AZMAL

@MD-AZMAL I think you are referring to this feature https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-sessions.html#extended-conversations Were you able to verify this beyond 8h?

juliangrueber avatar Dec 09 '25 08:12 juliangrueber

i havent verified this beyond 8h but i have a way around it if the context is missing i can handle that in memory hook, check if the agent.messages list is empty i can populate it with the past conversations

MD-AZMAL avatar Dec 09 '25 13:12 MD-AZMAL

i havent verified this beyond 8h but i have a way around it if the context is missing i can handle that in memory hook, check if the agent.messages list is empty i can populate it with the past conversations

MD-AZMAL, It sounds like you have a great work around while we wait for the official fix. Can you share your code changes? Did you have to fork or could you implement it with Hooks and Middleware? Thanks, Gary

GaryStimson avatar Dec 09 '25 19:12 GaryStimson

i havent verified this beyond 8h but i have a way around it if the context is missing i can handle that in memory hook, check if the agent.messages list is empty i can populate it with the past conversations

MD-AZMAL, It sounds like you have a great workaround while we wait for the official fix. Can you share your code changes? Did you have to fork or could you implement it with Hooks and Middleware? Thanks, Gary

Hi Gary, i did had to make some changes to the A2A SDK code in the strands agent, so it can ensure the metadata is being added to the agent state, which can then be later accessed by any of the memory hooks. I had made these changes locally, I am uploading it to GitHub. Here is the link Click Here

you need to ensure you are using the A2A server from the updated package, and while invoking the agent using a2a you can pass your information using metadata like the following example. It is similar to the bedrock agent runtime examples you can find here


def create_message(text: str, metadata: dict[str, Any] | None = None) -> Message:
    return Message(
        kind="message",
        role=Role.user,
        parts=[Part(TextPart(kind="text", text=text))],
        metadata=metadata if metadata is not None else {},
        message_id=uuid4().hex,
    )

msg = create_message(
            message, metadata={"session_id": session_id, "actor_id": actor_id}
        )

client = factory.create(agent_card)

 async for event in client.send_message(msg):
   pass

then in the a2a agent i simply add the memory hook, as follows


client = MemoryClient(region_name="us-east-1")


memory = {
    "memory_id": "ANY_MEMORY_ID",
}

agent = Agent(
    model=model,
    agent_id="agent_id",
    system_prompt="You are a helpful assistant",
    tools=[
        calculator,
        current_time,
    ],
    name="Calculator agent",
    description="""
       Helps in calculation
    """,
    hooks=[MemoryHookProvider(client, memory["memory_id"])],
)

# Make sure the A2AServer is coming from my forked code
a2a_server = A2AServer(agent=agent, http_url=runtime_url, serve_at_root=True)


@app.get("/ping")
def ping():
    return {"status": "healthy"}


app.mount("/", a2a_server.to_fastapi_app())


if __name__ == "__main__":
    uvicorn.run(app, host=host, port=port)

Here's the memory hook

class MemoryHookProvider(HookProvider):
    def __init__(self, memory_client: MemoryClient, memory_id: str):
        self.memory_client = memory_client
        self.memory_id = memory_id

    def on_before_invocation(self, event: BeforeInvocationEvent):
        """Load recent conversation history when agent starts"""
        if self.is_memory_loaded:
            return

        try:
            # Get session info from agent state
            actor_id = event.agent.state.get("actor_id")
            session_id = event.agent.state.get("session_id")

            if not actor_id or not session_id:
                print("Missing actor_id or session_id in agent state")
                return

            # Load the last 5 conversation turns from memory
            recent_turns = self.memory_client.get_last_k_turns(
                memory_id=self.memory_id, actor_id=actor_id, session_id=session_id, k=8
            )

    
            if recent_turns:
                # Format conversation history for context
                context_messages = []
                for turn in recent_turns:
                    for message in turn:
                        role = message["role"]
                        content = message["content"]["text"]
                        context_messages.append(f"{role}: {content}")

                context = "\n".join(context_messages)
                
                # Add context to agent's system prompt.
                current_system_prompt = (
                    event.agent.system_prompt
                    if event.agent.system_prompt is not None
                    else ""
                )

                event.agent.system_prompt = (
                    f"{current_system_prompt}\n\nRecent conversation:\n{context}"
                )

                print(f"✅ Loaded {len(recent_turns)} conversation turns")

        except Exception as e:
            print(f"Memory load error: {e}")

    def on_message_added(self, event: MessageAddedEvent):
        """Store messages in memory"""
        messages = event.agent.messages
        try:
            # Get session info from agent state
            actor_id = event.agent.state.get("actor_id")
            session_id = event.agent.state.get("session_id")

            if not actor_id or not session_id:
                print("Missing actor_id or session_id in agent state")
                return

            if messages[-1]["content"][0].get("text"):
                self.memory_client.create_event(
                    memory_id=self.memory_id,
                    actor_id=actor_id,
                    session_id=session_id,
                    messages=[
                        (
                            messages[-1]["content"][0].get("text", ""),
                            messages[-1]["role"],
                        )
                    ],
                )
        except Exception as e:
            print(f"Memory save error: {e}")

    def register_hooks(self, registry: HookRegistry):
        # Register memory hooks
        registry.add_callback(MessageAddedEvent, self.on_message_added)
        registry.add_callback(BeforeInvocationEvent, self.on_before_invocation)

MD-AZMAL avatar Dec 10 '25 06:12 MD-AZMAL

Awesome work MD-AZMAL! I didn't think about using a hook. I took your example and expanded it to not need to take the fork (didnt need to change A2AServer). Instead I used a middleware on the FastAPI layer to inject the X-Amzn-Bedrock-AgentCore-Runtime-Session-Id and X-User-ID headers from the session information into the agent state and then used your hook to build the memory dynamically. This worked as a good workaround until the official fix comes out. Thanks again!

GaryStimson avatar Dec 10 '25 12:12 GaryStimson

Awesome work MD-AZMAL! I didn't think about using a hook. I took your example and expanded it to not need to take the fork (didnt need to change A2AServer). Instead I used a middleware on the FastAPI layer to inject the X-Amzn-Bedrock-AgentCore-Runtime-Session-Id and X-User-ID headers from the session information into the agent state and then used your hook to build the memory dynamically. This worked as a good workaround until the official fix comes out. Thanks again!

That's amazing! i never thought of using FastAPI middleware, would you mind sharing the code snippet. Your method is better as it doesn't require modifying any existing library code. Good work @GaryStimson!

MD-AZMAL avatar Dec 11 '25 10:12 MD-AZMAL

Closing as resolved by PR #2628 (merged 2026-06-09) — it added an agent_factory mechanism with per-context agent isolation in StrandsA2AExecutor/A2AServer, so callers no longer share or leak conversation state. The deprecated single-agent path now swaps per-context snapshots under a lock and forbids a shared session_manager.

Reference: https://github.com/strands-agents/harness-sdk/pull/2628

Comment to reopen if the agent_factory API doesn't cover your setup.

yonib05 avatar Jun 19 '26 16:06 yonib05