Skip to content

[Bug]: Object of type Role is not JSON serializable because of Enum typing of Message.Role instead of StrEnum #107

@thijs-hakkenberg

Description

@thijs-hakkenberg

What happened?

Because the Role used in Message is an enum, a strongly typed implementation like this:

from a2a.types import Message, MessageSendParams, Task

    async def send_message(self, text: str, context_id: str = None) -> Task:
        """Send a message using A2A v10 protocol"""

        context_id = context_id or str(uuid4())
        message_id = str(uuid4())

        message = Message(
            messageId=message_id,
            contextId=context_id,
            role=Role.user,
            parts=[Part(root=TextPart(text=text))],
        )

        params = MessageSendParams(message=message)

        payload = {
            "jsonrpc": "2.0",
            "id": 1,
            "method": "message/send",
            "params": params.model_dump(),
        }
        print(payload)

        response = post(self.base_url, json=payload)
        return response.json()

will fail as enum cannot be serialized (throws: TypeError: Object of type Role is not JSON serializable)

By changing a2a.types

from enum import Enum

class Role(Enum):
    """
    Message sender's role
    """

    agent = 'agent'
    user = 'user'

into

from enum import StrEnum


class Role(StrEnum):
    """
    Message sender's role
    """

    agent = 'agent'
    user = 'user'

the role can be serialized to JSON with model_dump() as Pydantic can treat it as a string. As i cannot create branches I can’t create a PR. Would strongly suggest this approach for other string based enums as well.

Workaround would be to create an anti-corruption serialization function for MessageSendParams serialization

Relevant log output

 TypeError: Object of type Role is not JSON serializable

Code of Conduct

  • I agree to follow this project's Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions