|
| 1 | +from typing import TYPE_CHECKING, Any, Generic, TypeVar |
| 2 | + |
| 3 | + |
| 4 | +if TYPE_CHECKING: |
| 5 | + from typing_extensions import override |
| 6 | +else: |
| 7 | + |
| 8 | + def override(func): # noqa: ANN001, ANN201 |
| 9 | + """Override decorator.""" |
| 10 | + return func |
| 11 | + |
| 12 | + |
| 13 | +from pydantic import BaseModel |
| 14 | + |
| 15 | +from a2a.types import Artifact, Message, TaskStatus |
| 16 | + |
| 17 | + |
| 18 | +try: |
| 19 | + from sqlalchemy import JSON, Dialect, String |
| 20 | + from sqlalchemy.orm import ( |
| 21 | + DeclarativeBase, |
| 22 | + Mapped, |
| 23 | + declared_attr, |
| 24 | + mapped_column, |
| 25 | + ) |
| 26 | + from sqlalchemy.types import TypeDecorator |
| 27 | +except ImportError as e: |
| 28 | + raise ImportError( |
| 29 | + 'Database models require SQLAlchemy. ' |
| 30 | + 'Install with one of: ' |
| 31 | + "'pip install a2a-sdk[postgresql]', " |
| 32 | + "'pip install a2a-sdk[mysql]', " |
| 33 | + "'pip install a2a-sdk[sqlite]', " |
| 34 | + "or 'pip install a2a-sdk[sql]'" |
| 35 | + ) from e |
| 36 | + |
| 37 | + |
| 38 | +T = TypeVar('T', bound=BaseModel) |
| 39 | + |
| 40 | + |
| 41 | +class PydanticType(TypeDecorator[T], Generic[T]): |
| 42 | + """SQLAlchemy type that handles Pydantic model serialization.""" |
| 43 | + |
| 44 | + impl = JSON |
| 45 | + cache_ok = True |
| 46 | + |
| 47 | + def __init__(self, pydantic_type: type[T], **kwargs: dict[str, Any]): |
| 48 | + """Initialize the PydanticType. |
| 49 | +
|
| 50 | + Args: |
| 51 | + pydantic_type: The Pydantic model type to handle. |
| 52 | + **kwargs: Additional arguments for TypeDecorator. |
| 53 | + """ |
| 54 | + self.pydantic_type = pydantic_type |
| 55 | + super().__init__(**kwargs) |
| 56 | + |
| 57 | + def process_bind_param( |
| 58 | + self, value: T | None, dialect: Dialect |
| 59 | + ) -> dict[str, Any] | None: |
| 60 | + """Convert Pydantic model to a JSON-serializable dictionary for the database.""" |
| 61 | + if value is None: |
| 62 | + return None |
| 63 | + return ( |
| 64 | + value.model_dump(mode='json') |
| 65 | + if isinstance(value, BaseModel) |
| 66 | + else value |
| 67 | + ) |
| 68 | + |
| 69 | + def process_result_value( |
| 70 | + self, value: dict[str, Any] | None, dialect: Dialect |
| 71 | + ) -> T | None: |
| 72 | + """Convert a JSON-like dictionary from the database back to a Pydantic model.""" |
| 73 | + if value is None: |
| 74 | + return None |
| 75 | + return self.pydantic_type.model_validate(value) |
| 76 | + |
| 77 | + |
| 78 | +class PydanticListType(TypeDecorator, Generic[T]): |
| 79 | + """SQLAlchemy type that handles lists of Pydantic models.""" |
| 80 | + |
| 81 | + impl = JSON |
| 82 | + cache_ok = True |
| 83 | + |
| 84 | + def __init__(self, pydantic_type: type[T], **kwargs: dict[str, Any]): |
| 85 | + """Initialize the PydanticListType. |
| 86 | +
|
| 87 | + Args: |
| 88 | + pydantic_type: The Pydantic model type for items in the list. |
| 89 | + **kwargs: Additional arguments for TypeDecorator. |
| 90 | + """ |
| 91 | + self.pydantic_type = pydantic_type |
| 92 | + super().__init__(**kwargs) |
| 93 | + |
| 94 | + def process_bind_param( |
| 95 | + self, value: list[T] | None, dialect: Dialect |
| 96 | + ) -> list[dict[str, Any]] | None: |
| 97 | + """Convert a list of Pydantic models to a JSON-serializable list for the DB.""" |
| 98 | + if value is None: |
| 99 | + return None |
| 100 | + return [ |
| 101 | + item.model_dump(mode='json') |
| 102 | + if isinstance(item, BaseModel) |
| 103 | + else item |
| 104 | + for item in value |
| 105 | + ] |
| 106 | + |
| 107 | + def process_result_value( |
| 108 | + self, value: list[dict[str, Any]] | None, dialect: Dialect |
| 109 | + ) -> list[T] | None: |
| 110 | + """Convert a JSON-like list from the DB back to a list of Pydantic models.""" |
| 111 | + if value is None: |
| 112 | + return None |
| 113 | + return [self.pydantic_type.model_validate(item) for item in value] |
| 114 | + |
| 115 | + |
| 116 | +# Base class for all database models |
| 117 | +class Base(DeclarativeBase): |
| 118 | + """Base class for declarative models in A2A SDK.""" |
| 119 | + |
| 120 | + |
| 121 | +# TaskMixin that can be used with any table name |
| 122 | +class TaskMixin: |
| 123 | + """Mixin providing standard task columns with proper type handling.""" |
| 124 | + |
| 125 | + id: Mapped[str] = mapped_column(String(36), primary_key=True, index=True) |
| 126 | + contextId: Mapped[str] = mapped_column(String(36), nullable=False) # noqa: N815 |
| 127 | + kind: Mapped[str] = mapped_column( |
| 128 | + String(16), nullable=False, default='task' |
| 129 | + ) |
| 130 | + |
| 131 | + # Properly typed Pydantic fields with automatic serialization |
| 132 | + status: Mapped[TaskStatus] = mapped_column(PydanticType(TaskStatus)) |
| 133 | + artifacts: Mapped[list[Artifact] | None] = mapped_column( |
| 134 | + PydanticListType(Artifact), nullable=True |
| 135 | + ) |
| 136 | + history: Mapped[list[Message] | None] = mapped_column( |
| 137 | + PydanticListType(Message), nullable=True |
| 138 | + ) |
| 139 | + |
| 140 | + # Using declared_attr to avoid conflict with Pydantic's metadata |
| 141 | + @declared_attr |
| 142 | + @classmethod |
| 143 | + def task_metadata(cls) -> Mapped[dict[str, Any] | None]: |
| 144 | + """Define the 'metadata' column, avoiding name conflicts with Pydantic.""" |
| 145 | + return mapped_column(JSON, nullable=True, name='metadata') |
| 146 | + |
| 147 | + @override |
| 148 | + def __repr__(self) -> str: |
| 149 | + """Return a string representation of the task.""" |
| 150 | + repr_template = ( |
| 151 | + '<{CLS}(id="{ID}", contextId="{CTX_ID}", status="{STATUS}")>' |
| 152 | + ) |
| 153 | + return repr_template.format( |
| 154 | + CLS=self.__class__.__name__, |
| 155 | + ID=self.id, |
| 156 | + CTX_ID=self.contextId, |
| 157 | + STATUS=self.status, |
| 158 | + ) |
| 159 | + |
| 160 | + |
| 161 | +def create_task_model( |
| 162 | + table_name: str = 'tasks', base: type[DeclarativeBase] = Base |
| 163 | +) -> type: |
| 164 | + """Create a TaskModel class with a configurable table name. |
| 165 | +
|
| 166 | + Args: |
| 167 | + table_name: Name of the database table. Defaults to 'tasks'. |
| 168 | + base: Base declarative class to use. Defaults to the SDK's Base class. |
| 169 | +
|
| 170 | + Returns: |
| 171 | + TaskModel class with the specified table name. |
| 172 | +
|
| 173 | + Example: |
| 174 | + # Create a task model with default table name |
| 175 | + TaskModel = create_task_model() |
| 176 | +
|
| 177 | + # Create a task model with custom table name |
| 178 | + CustomTaskModel = create_task_model('my_tasks') |
| 179 | +
|
| 180 | + # Use with a custom base |
| 181 | + from myapp.database import Base as MyBase |
| 182 | + TaskModel = create_task_model('tasks', MyBase) |
| 183 | + """ |
| 184 | + |
| 185 | + class TaskModel(TaskMixin, base): |
| 186 | + __tablename__ = table_name |
| 187 | + |
| 188 | + @override |
| 189 | + def __repr__(self) -> str: |
| 190 | + """Return a string representation of the task.""" |
| 191 | + repr_template = '<TaskModel[{TABLE}](id="{ID}", contextId="{CTX_ID}", status="{STATUS}")>' |
| 192 | + return repr_template.format( |
| 193 | + TABLE=table_name, |
| 194 | + ID=self.id, |
| 195 | + CTX_ID=self.contextId, |
| 196 | + STATUS=self.status, |
| 197 | + ) |
| 198 | + |
| 199 | + # Set a dynamic name for better debugging |
| 200 | + TaskModel.__name__ = f'TaskModel_{table_name}' |
| 201 | + TaskModel.__qualname__ = f'TaskModel_{table_name}' |
| 202 | + |
| 203 | + return TaskModel |
| 204 | + |
| 205 | + |
| 206 | +# Default TaskModel for backward compatibility |
| 207 | +class TaskModel(TaskMixin, Base): |
| 208 | + """Default task model with standard table name.""" |
| 209 | + |
| 210 | + __tablename__ = 'tasks' |
0 commit comments