Skip to content

Chat Messages (🧪Beta)

albert.collections.chat_messages.ChatMessageCollection

ChatMessageCollection(*, session: AsyncAlbertSession)

Async collection for managing messages within a chat session (🧪Beta).

Beta Feature!

Please do not use in production or without explicit guidance from Albert. You might otherwise have a bad experience. This feature currently falls outside of the Albert support contract, but we'd love your feedback!

Parameters:

Name Type Description Default
session AsyncAlbertSession

The Albert async session instance.

required

Methods:

Name Description
create

Adds a message to a chat session.

get_by_id

Retrieves a single message by its source request ID and sequence.

get_all

Iterates over messages in a session.

update

Updates the content of a message.

delete

Deletes a message from a session.

Parameters:

Name Type Description Default
session AsyncAlbertSession

The async session used to make API requests.

required
Source code in src/albert/collections/chat_messages.py
def __init__(self, *, session: AsyncAlbertSession):
    """
    Initializes the ChatMessageCollection with the provided session.

    Parameters
    ----------
    session : AsyncAlbertSession
        The async session used to make API requests.
    """
    self._session = session
    self._sessions_base = f"/api/{self._api_version}/chats/sessions"

create

create(*, message: ChatMessage) -> ChatMessage

Add a message to a chat session.

Parameters:

Name Type Description Default
message ChatMessage

The message to create. parent_id must be set to the session ID. source_request_id is auto-generated if not provided.

required

Returns:

Type Description
ChatMessage

The created message.

Source code in src/albert/collections/chat_messages.py
@validate_call
async def create(self, *, message: ChatMessage) -> ChatMessage:
    """
    Add a message to a chat session.

    Parameters
    ----------
    message : ChatMessage
        The message to create. ``parent_id`` must be set to the session ID.
        ``source_request_id`` is auto-generated if not provided.

    Returns
    -------
    ChatMessage
        The created message.
    """
    payload = message.model_dump(by_alias=True, exclude_unset=True, mode="json")
    # parentId is encoded in the URL path, not the request body
    payload.pop("parentId", None)
    payload.setdefault("sourceRequestId", str(uuid.uuid4()))
    url = f"{self._sessions_base}/{message.parent_id}/messages"
    response = await self._session.post(url, json=payload)
    # TODO(backend): POST /sessions/{id}/messages response does not include the
    # Content field, so message.content will be None after create. The create
    # response should mirror the full message object including Content so callers
    # don't need a follow-up get_by_id to access the payload they just sent.
    return ChatMessage(**response.json())

get_by_id

get_by_id(
    *,
    session_id: str,
    source_request_id: str,
    sequence: str,
    component_type: ChatComponentType | None = None,
) -> ChatMessage

Retrieve a single message by its source request ID and sequence.

Parameters:

Name Type Description Default
session_id str

The ID of the parent session.

required
source_request_id str

The request trace identifier of the message.

required
sequence str

The zero-padded sequence of the message (e.g. "000").

required
component_type ChatComponentType | None

Narrows the lookup to a specific component type.

None

Returns:

Type Description
ChatMessage

The matching message.

Source code in src/albert/collections/chat_messages.py
@validate_call
async def get_by_id(
    self,
    *,
    session_id: str,
    source_request_id: str,
    sequence: str,
    component_type: ChatComponentType | None = None,
) -> ChatMessage:
    """
    Retrieve a single message by its source request ID and sequence.

    Parameters
    ----------
    session_id : str
        The ID of the parent session.
    source_request_id : str
        The request trace identifier of the message.
    sequence : str
        The zero-padded sequence of the message (e.g. "000").
    component_type : ChatComponentType | None, optional
        Narrows the lookup to a specific component type.

    Returns
    -------
    ChatMessage
        The matching message.
    """
    url = f"{self._sessions_base}/{session_id}/messages/{source_request_id}"
    params: dict = {"sequence": sequence}
    if component_type is not None:
        params["componentType"] = component_type.value
    response = await self._session.get(url, params=params)
    return ChatMessage(**response.json())

get_all

get_all(
    *, session_id: str, max_items: int | None = None
) -> AsyncIterator[ChatMessage]

Iterate over messages in a session.

Parameters:

Name Type Description Default
session_id str

The ID of the session whose messages to list.

required
max_items int | None

Maximum number of items to return in total. If None, fetches all available items.

None

Yields:

Type Description
ChatMessage

Messages in the session, oldest first.

Source code in src/albert/collections/chat_messages.py
@validate_call
async def get_all(
    self,
    *,
    session_id: str,
    max_items: int | None = None,
) -> AsyncIterator[ChatMessage]:
    """
    Iterate over messages in a session.

    Parameters
    ----------
    session_id : str
        The ID of the session whose messages to list.
    max_items : int | None, optional
        Maximum number of items to return in total. If None, fetches all available items.

    Yields
    ------
    ChatMessage
        Messages in the session, oldest first.
    """
    url = f"{self._sessions_base}/{session_id}/messages"
    async for message in AsyncAlbertPaginator(
        session=self._session,
        path=url,
        deserialize=lambda item: ChatMessage(**item),
        max_items=max_items,
    ):
        yield message

update

update(
    *,
    session_id: str,
    source_request_id: str,
    sequence: str,
    content: str | dict,
) -> ChatMessage

Update the content of a message.

Parameters:

Name Type Description Default
session_id str

The ID of the parent session.

required
source_request_id str

The request trace identifier of the message.

required
sequence str

The zero-padded sequence of the message (e.g. "000").

required
content str | dict

The new content for the message.

required

Returns:

Type Description
ChatMessage

The updated message.

Notes

The following fields can be updated: content.

Source code in src/albert/collections/chat_messages.py
@validate_call
async def update(
    self,
    *,
    session_id: str,
    source_request_id: str,
    sequence: str,
    content: str | dict,
) -> ChatMessage:
    """
    Update the content of a message.

    Parameters
    ----------
    session_id : str
        The ID of the parent session.
    source_request_id : str
        The request trace identifier of the message.
    sequence : str
        The zero-padded sequence of the message (e.g. "000").
    content : str | dict
        The new content for the message.

    Returns
    -------
    ChatMessage
        The updated message.

    Notes
    -----
    The following fields can be updated: ``content``.
    """
    url = f"{self._sessions_base}/{session_id}/messages/{source_request_id}"
    payload = {"data": [{"operation": "update", "attribute": "Content", "newValue": content}]}
    await self._session.patch(url, params={"sequence": sequence}, json=payload)
    return await self.get_by_id(
        session_id=session_id,
        source_request_id=source_request_id,
        sequence=sequence,
    )

delete

delete(
    *,
    session_id: str,
    source_request_id: str,
    sequence: str,
) -> None

Delete a message from a session.

Parameters:

Name Type Description Default
session_id str

The ID of the parent session.

required
source_request_id str

The request trace identifier of the message.

required
sequence str

The zero-padded sequence of the message (e.g. "000").

required

Returns:

Type Description
None
Source code in src/albert/collections/chat_messages.py
@validate_call
async def delete(
    self,
    *,
    session_id: str,
    source_request_id: str,
    sequence: str,
) -> None:
    """
    Delete a message from a session.

    Parameters
    ----------
    session_id : str
        The ID of the parent session.
    source_request_id : str
        The request trace identifier of the message.
    sequence : str
        The zero-padded sequence of the message (e.g. "000").

    Returns
    -------
    None
    """
    url = f"{self._sessions_base}/{session_id}/messages/{source_request_id}"
    await self._session.delete(url, params={"sequence": sequence})