Skip to content

Chat Sessions (🧪Beta)

albert.collections.chat_sessions.ChatSessionCollection

ChatSessionCollection(*, session: AsyncAlbertSession)

Manage "Ask Albert" chat sessions in the Albert platform (🧪 Beta).

A chat session is a single conversation with Albert's AI assistant, "Ask Albert". Each session (ChatSession) holds an ordered series of message turns (ChatMessage, managed by ChatMessageCollection) and can be filed under a folder (ChatFolder, managed by ChatFolderCollection).

This is an async collection accessed as client.chat_sessions on an AsyncAlbert client.

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!

Example

from albert import AsyncAlbert
from albert.resources.chats import ChatSession

async with AsyncAlbert() as client:
    session = await client.chat_sessions.create(
        session=ChatSession(name="Titanium dioxide questions", source_session_id="ext-123")
    )
    async for s in client.chat_sessions.get_all(name=["titanium"]):
        print(s.id, s.name)

Parameters:

Name Type Description Default
session AsyncAlbertSession

The authenticated Albert async session used for API calls.

required

Attributes:

Name Type Description
base_path str

The base API route for chat session requests.

Methods:

Name Description
create

Create a new chat session.

get_by_id

Get a single session by its ID.

get_by_source_session_id

Get a session by its external source session ID.

get_all

Iterate over sessions, with optional filters.

update

Rename a session or move it between folders.

delete

Delete a session by its ID.

Parameters:

Name Type Description Default
session AsyncAlbertSession

The authenticated Albert async session used for API calls.

required
Source code in src/albert/collections/chat_sessions.py
def __init__(self, *, session: AsyncAlbertSession):
    """Initialize a ChatSessionCollection.

    Parameters
    ----------
    session : AsyncAlbertSession
        The authenticated Albert async session used for API calls.
    """
    self._session = session
    self.base_path: str = f"/api/{self._api_version}/chats/sessions"

base_path

base_path: str = f'/api/{self._api_version}/chats/sessions'

create

create(*, session: ChatSession) -> ChatSession

Create a new chat session.

Example

from albert import AsyncAlbert
from albert.resources.chats import ChatSession

async with AsyncAlbert() as client:
    session = await client.chat_sessions.create(
        session=ChatSession(name="Titanium dioxide questions", source_session_id="...")
    )

Parameters:

Name Type Description Default
session ChatSession

The session to create. name and source_session_id are required; set parent_id to file the session under a ChatFolder.

required

Returns:

Type Description
ChatSession

The created session, populated with its server-assigned id.

Source code in src/albert/collections/chat_sessions.py
@validate_call
async def create(self, *, session: ChatSession) -> ChatSession:
    """Create a new chat session.

    !!! example
        ```python
        from albert import AsyncAlbert
        from albert.resources.chats import ChatSession

        async with AsyncAlbert() as client:
            session = await client.chat_sessions.create(
                session=ChatSession(name="Titanium dioxide questions", source_session_id="...")
            )
        ```

    Parameters
    ----------
    session : ChatSession
        The session to create. ``name`` and ``source_session_id`` are required;
        set ``parent_id`` to file the session under a
        [`ChatFolder`][albert.resources.chats.ChatFolder].

    Returns
    -------
    ChatSession
        The created session, populated with its server-assigned ``id``.
    """
    response = await self._session.post(
        self.base_path,
        json=session.model_dump(by_alias=True, exclude_unset=True, mode="json"),
    )
    return ChatSession(**response.json())

get_by_id

get_by_id(*, id: str) -> ChatSession

Get a chat session by its ID.

Example

from albert import AsyncAlbert

async with AsyncAlbert() as client:
    session = await client.chat_sessions.get_by_id(id="...")

Parameters:

Name Type Description Default
id str

The identifier of the session to retrieve.

required

Returns:

Type Description
ChatSession

The fully populated session.

Source code in src/albert/collections/chat_sessions.py
@validate_call
async def get_by_id(self, *, id: str) -> ChatSession:
    """Get a chat session by its ID.

    !!! example
        ```python
        from albert import AsyncAlbert

        async with AsyncAlbert() as client:
            session = await client.chat_sessions.get_by_id(id="...")
        ```

    Parameters
    ----------
    id : str
        The identifier of the session to retrieve.

    Returns
    -------
    ChatSession
        The fully populated session.
    """
    response = await self._session.get(f"{self.base_path}/{id}")
    return ChatSession(**response.json())

get_by_source_session_id

get_by_source_session_id(
    *, source_session_id: str
) -> ChatSession

Get a chat session by its external source session ID.

Use this to look up a session by the identifier that links it to a source system, rather than by its Albert id.

Example

from albert import AsyncAlbert

async with AsyncAlbert() as client:
    session = await client.chat_sessions.get_by_source_session_id(source_session_id="...")

Parameters:

Name Type Description Default
source_session_id str

The external source session identifier (the session's source_session_id).

required

Returns:

Type Description
ChatSession

The matching session.

Source code in src/albert/collections/chat_sessions.py
@validate_call
async def get_by_source_session_id(self, *, source_session_id: str) -> ChatSession:
    """Get a chat session by its external source session ID.

    Use this to look up a session by the identifier that links it to a source
    system, rather than by its Albert ``id``.

    !!! example
        ```python
        from albert import AsyncAlbert

        async with AsyncAlbert() as client:
            session = await client.chat_sessions.get_by_source_session_id(source_session_id="...")
        ```

    Parameters
    ----------
    source_session_id : str
        The external source session identifier (the session's
        ``source_session_id``).

    Returns
    -------
    ChatSession
        The matching session.
    """
    response = await self._session.get(f"{self.base_path}/source/{source_session_id}")
    return ChatSession(**response.json())

get_all

get_all(
    *,
    name: list[str] | None = None,
    exact_match: bool = False,
    parent_id: str | None = None,
    max_items: int | None = None,
) -> AsyncIterator[ChatSession]

Iterate over chat sessions, with optional filters.

Transparently pages through results, yielding one session at a time. Returns the paginator directly so has_more remains available.

Example

from albert import AsyncAlbert

async with AsyncAlbert() as client:
    async for session in client.chat_sessions.get_all(name=["titanium"]):
        print(session.id, session.name)

Parameters:

Name Type Description Default
name list[str] | None

Filter to sessions whose name matches any of the given values.

None
exact_match bool

When True, name must match exactly; otherwise it matches as a substring. Defaults to False.

False
parent_id str | None

Filter to sessions filed under the given ChatFolder.

None
max_items int | None

Maximum number of sessions to yield in total. If None, yields all matching sessions.

None

Returns:

Type Description
AsyncIterator[ChatSession]

Sessions matching the given filters.

Source code in src/albert/collections/chat_sessions.py
@validate_call
def get_all(
    self,
    *,
    name: list[str] | None = None,
    exact_match: bool = False,
    parent_id: str | None = None,
    max_items: int | None = None,
) -> AsyncIterator[ChatSession]:
    """Iterate over chat sessions, with optional filters.

    Transparently pages through results, yielding one session at a time.
    Returns the paginator directly so ``has_more`` remains available.

    !!! example
        ```python
        from albert import AsyncAlbert

        async with AsyncAlbert() as client:
            async for session in client.chat_sessions.get_all(name=["titanium"]):
                print(session.id, session.name)
        ```

    Parameters
    ----------
    name : list[str] | None, optional
        Filter to sessions whose name matches any of the given values.
    exact_match : bool, optional
        When ``True``, ``name`` must match exactly; otherwise it matches as a
        substring. Defaults to ``False``.
    parent_id : str | None, optional
        Filter to sessions filed under the given
        [`ChatFolder`][albert.resources.chats.ChatFolder].
    max_items : int | None, optional
        Maximum number of sessions to yield in total. If ``None``, yields all
        matching sessions.

    Returns
    -------
    AsyncIterator[ChatSession]
        Sessions matching the given filters.
    """
    params: dict[str, str | list[str]] = {}
    if name:
        params["name"] = name
    if exact_match:
        params["exactMatch"] = "true"
    if parent_id is not None:
        params["parentId"] = parent_id

    return AsyncAlbertPaginator(
        session=self._session,
        path=self.base_path,
        deserialize=lambda item: ChatSession(**item),
        params=params,
        max_items=max_items,
    )

update

update(
    *,
    id: str,
    name: str | None = None,
    parent_id: str | None | _UnsetType = _UNSET,
) -> ChatSession

Update a chat session.

Rename a session and/or move it between folders. Only the arguments you pass are changed; omitted arguments are left untouched.

Example

from albert import AsyncAlbert

async with AsyncAlbert() as client:
    session = await client.chat_sessions.update(id="...", name="Renamed session")

Parameters:

Name Type Description Default
id str

The identifier of the session to update.

required
name str | None

A new display name for the session.

None
parent_id str | None

The ChatFolder to move the session into. Pass None to remove the session from its current folder. When omitted entirely, the folder is left unchanged.

_UNSET

Returns:

Type Description
ChatSession

The updated session.

Notes

The following fields can be updated: name, parent_id.

Source code in src/albert/collections/chat_sessions.py
@validate_call
async def update(
    self,
    *,
    id: str,
    name: str | None = None,
    parent_id: str | None | _UnsetType = _UNSET,
) -> ChatSession:
    """Update a chat session.

    Rename a session and/or move it between folders. Only the arguments you
    pass are changed; omitted arguments are left untouched.

    !!! example
        ```python
        from albert import AsyncAlbert

        async with AsyncAlbert() as client:
            session = await client.chat_sessions.update(id="...", name="Renamed session")
        ```

    Parameters
    ----------
    id : str
        The identifier of the session to update.
    name : str | None, optional
        A new display name for the session.
    parent_id : str | None, optional
        The [`ChatFolder`][albert.resources.chats.ChatFolder] to move the session
        into. Pass ``None`` to remove the session from its current folder. When
        omitted entirely, the folder is left unchanged.

    Returns
    -------
    ChatSession
        The updated session.

    Notes
    -----
    The following fields can be updated: ``name``, ``parent_id``.
    """
    data = []
    if name is not None:
        data.append({"operation": "update", "attribute": "name", "newValue": name})
    if parent_id is not _UNSET:
        data.append({"operation": "update", "attribute": "parentId", "newValue": parent_id})
    if not data:
        return await self.get_by_id(id=id)
    await self._session.patch(f"{self.base_path}/{id}", json={"data": data})
    return await self.get_by_id(id=id)

delete

delete(*, id: str) -> None

Delete a chat session by its ID.

Example

from albert import AsyncAlbert

async with AsyncAlbert() as client:
    await client.chat_sessions.delete(id="...")

Parameters:

Name Type Description Default
id str

The identifier of the session to delete.

required

Returns:

Type Description
None
Source code in src/albert/collections/chat_sessions.py
@validate_call
async def delete(self, *, id: str) -> None:
    """Delete a chat session by its ID.

    !!! example
        ```python
        from albert import AsyncAlbert

        async with AsyncAlbert() as client:
            await client.chat_sessions.delete(id="...")
        ```

    Parameters
    ----------
    id : str
        The identifier of the session to delete.

    Returns
    -------
    None
    """
    await self._session.delete(f"{self.base_path}/{id}")