# DO NOT EDIT — generated by _sdk_gen/ from the OpenAPI spec.
# Regenerate with: ./generate.sh
from __future__ import annotations

from typing import Any
from typing import Literal, overload

from goodmem._base import AsyncCRUDNamespace, CRUDNamespace
from goodmem._base import _op_meta, _expand_label_filters
from goodmem._base import _op_meta, _prepare_create_payload
from goodmem._generated.models.batch_memory_creation_request import BatchMemoryCreationRequest
from goodmem._generated.models.batch_memory_deletion_request import BatchMemoryDeletionRequest
from goodmem._generated.models.batch_memory_response import BatchMemoryResponse
from goodmem._generated.models.batch_memory_retrieval_request import BatchMemoryRetrievalRequest
from goodmem._generated.models.memory import Memory
from goodmem._generated.models.memory_creation_request import MemoryCreationRequest
from goodmem._generated.models.memory_list_response import MemoryListResponse
from goodmem._generated.models.retrieve_memory_event import RetrieveMemoryEvent
from goodmem._generated.models.retrieve_memory_request import RetrieveMemoryRequest
from goodmem.errors import raise_for_status
from goodmem.pagination import AsyncPaginator, Paginator
from goodmem.streaming import AsyncStream, Format, Stream, _ACCEPT, _validate_format


class MemoriesAPIBase(CRUDNamespace):
    """Memories API — auto-generated structural base.

    Auto-generated structural base. Do not edit.
    Override in goodmem/api/memories.py to add domain-specific logic.
    """

    _base_path = "/v1/memories"
    _create_model = MemoryCreationRequest
    _update_model = None
    _response_model = Memory
    _list_response_model = MemoryListResponse
    _list_items_field = "memories"
    _rest_metadata: dict = {'create': {'http_method': 'POST', 'path': '/v1/memories', 'response': 'Memory', 'body_model': 'MemoryCreationRequest', 'body_expr': 'MemoryCreationRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json', 'multipart/form-data'], 'supports_multipart': True, 'multipart_request_field': 'request', 'multipart_file_field': 'file'}, 'get': {'http_method': 'GET', 'path': '/v1/memories/{id}', 'response': 'Memory', 'query_params': ['id', 'include_content', 'include_processing_history']}, 'list': {'http_method': 'GET', 'path': '/v1/spaces/{spaceId}/memories', 'response': 'MemoryListResponse', 'query_params': ['space_id', 'include_content', 'status_filter', 'filter', 'max_results', 'next_token', 'sort_by', 'sort_order'], 'auto_next_token': True}, 'delete': {'http_method': 'DELETE', 'path': '/v1/memories/{id}', 'response': 'None', 'query_params': ['id']}, 'content': {'http_method': 'GET', 'path': '/v1/memories/{id}/content', 'response': 'bytes', 'query_params': ['id']}, 'batch_create': {'http_method': 'POST', 'path': '/v1/memories:batchCreate', 'response': 'BatchMemoryResponse', 'body_model': 'BatchMemoryCreationRequest', 'body_expr': 'BatchMemoryCreationRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json', 'multipart/form-data'], 'supports_multipart': True, 'multipart_request_field': 'requests', 'multipart_file_field': 'file'}, 'batch_delete': {'http_method': 'POST', 'path': '/v1/memories:batchDelete', 'response': 'BatchMemoryResponse', 'body_model': 'BatchMemoryDeletionRequest', 'body_expr': 'BatchMemoryDeletionRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'batch_get': {'http_method': 'POST', 'path': '/v1/memories:batchGet', 'response': 'BatchMemoryResponse', 'body_model': 'BatchMemoryRetrievalRequest', 'body_expr': 'BatchMemoryRetrievalRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'retrieve': {'http_method': 'POST', 'path': '/v1/memories:retrieve', 'query_params': ['accept'], 'body_model': 'RetrieveMemoryRequest', 'body_expr': 'RetrieveMemoryRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json'], 'accept_from': 'format'}}

    def create(self, **kwargs: Any) -> Any:
        """Create a new memory

        Creates a new memory in a specified space and starts asynchronous processing. The memory begins in PENDING status while a background job performs chunking and embedding generation. IMPORTANT: This operation is NOT idempotent - each request creates a new memory record. Returns INVALID_ARGUMENT if space_id, original_content, or content_type is missing or invalid. Returns NOT_FOUND if the specified space does not exist. Requires CREATE_MEMORY_OWN permission for spaces you own (or CREATE_MEMORY_ANY for admin users to create in any space). Side effects include creating the memory record, generating a unique UUID, and enqueuing a background processing job.

        Args:
            memory_id (string, optional): Optional client-provided UUID for the memory. If omitted, the server generates one. Returns ALREADY_EXISTS if the ID is already in use.
            space_id (string): ID of the space where this memory will be stored
            original_content (string, optional): Original content as plain text (use either this or original_content_b64)
            original_content_b64 (string, optional): Original content as base64-encoded binary data (use either this or original_content)
            original_content_ref (string, optional): Reference to external content location
            content_type (string): MIME type of the content
            metadata (object, optional): Additional metadata for the memory
            chunking_config (ChunkingConfiguration, optional): Chunking strategy for this memory (if not provided, uses space default)
            file_field (string, optional): Optional multipart file field name to bind binary content; required when multiple files are uploaded in a batch multipart request.

        Returns:
            Memory
        """
        op = _op_meta(self, 'create')
        json_payload, data_payload, files_payload = _prepare_create_payload(
            create_model=self._create_model, op=op, kwargs=dict(kwargs),
        )
        resp = self._http.post(
            self._base_path,
            json=json_payload,
            data=data_payload,
            files=files_payload,
            headers=self._headers,
        )
        return self._handle_response(resp, self._create_response_model or self._response_model)

    def get(self, *, id: str, include_content: bool | None = None, include_processing_history: bool | None = None) -> Any:
        """Get a memory by ID

        Retrieves a single memory by its ID. PERMISSION CLARIFICATION: With READ_MEMORY_OWN permission, access is granted if you own the parent space OR if the parent space is public (public_read=true). With READ_MEMORY_ANY permission, you can access any memory regardless of ownership. This is a read-only operation with no side effects and is safe to retry. Returns NOT_FOUND if the memory or its parent space does not exist.

        Args:
            id (string): The unique identifier of the memory to retrieve
            include_content (boolean, optional): Whether to include the original content in the response (defaults to false)
            include_processing_history (boolean, optional): Whether to include background job processing history in the response (defaults to false)

        Returns:
            Memory
        """
        params = {}
        if include_content is not None:
            params["includeContent"] = include_content
        if include_processing_history is not None:
            params["includeProcessingHistory"] = include_processing_history
        resp = self._http.get(
            f"{self._base_path}/{id}",
            params=params or None,
            headers=self._headers,
        )
        return self._handle_response(resp, self._response_model)

    def delete(self, *, id: str) -> None:
        """Delete a memory

        Permanently deletes a memory and its associated chunks. This operation cannot be undone and immediately removes the memory record from the database. IDEMPOTENCY: This operation is safe to retry - may return NOT_FOUND if the memory was already deleted or never existed. Requires DELETE_MEMORY_OWN permission for memories in spaces you own (or DELETE_MEMORY_ANY for admin users to delete any memory). Side effects include permanent removal of the memory record and all associated chunk data.

        Args:
            id (string): The unique identifier of the memory to delete
        """
        resp = self._http.delete(f"{self._base_path}/{id}", headers=self._headers)
        raise_for_status(resp)

    def content(self, *, id: str) -> bytes:
        """Download memory content

        Streams the original binary payload for a memory. The response uses the memory's stored content type when available. Returns 404 when the memory does not have inline content; clients can check original_content_ref from the metadata endpoint to locate external content.

        Args:
            id (string): The unique identifier of the memory to download
        """
        resp = self._http.get(
            f"{self._base_path}/{id}/content",
            headers=self._headers,
        )
        raise_for_status(resp)
        return resp.content

    def batch_create(self, *, requests, **kwargs: Any) -> BatchMemoryResponse:
        """Create multiple memories in a batch

        Creates multiple memories in a single operation, with individual success/failure results.

        Args:
            requests (array): Array of memory creation requests

        Returns:
            BatchMemoryResponse
        """
        _params = {**kwargs}
        _params['requests'] = requests
        body = BatchMemoryCreationRequest.model_validate(_params)
        resp = self._http.post(
            "/v1/memories:batchCreate",
            json=body.model_dump(by_alias=True, exclude_unset=True),
            headers=self._headers,
        )
        return self._handle_response(resp, BatchMemoryResponse)

    def batch_delete(self, *, requests, **kwargs: Any) -> BatchMemoryResponse:
        """Delete memories in batch

        Deletes memories using selector entries. Each selector can target either a specific memory ID or a filtered subset scoped to a specific space.

        Args:
            requests (array): Array of delete selectors

        Returns:
            BatchMemoryResponse
        """
        _params = {**kwargs}
        _params['requests'] = requests
        body = BatchMemoryDeletionRequest.model_validate(_params)
        resp = self._http.post(
            "/v1/memories:batchDelete",
            json=body.model_dump(by_alias=True, exclude_unset=True),
            headers=self._headers,
        )
        return self._handle_response(resp, BatchMemoryResponse)

    def batch_get(self, *, memory_ids, include_content=None, include_processing_history=None, **kwargs: Any) -> BatchMemoryResponse:
        """Get multiple memories by ID

        Retrieves multiple memories in a single operation, with individual success/failure results.

        Args:
            memory_ids (array): Array of memory IDs to retrieve
            include_content (boolean, optional): Whether to include the original content in the response
            include_processing_history (boolean, optional): Whether to include background job processing history for each memory

        Returns:
            BatchMemoryResponse
        """
        _params = {**kwargs}
        _params['memory_ids'] = memory_ids
        if include_content is not None:
            _params['include_content'] = include_content
        if include_processing_history is not None:
            _params['include_processing_history'] = include_processing_history
        body = BatchMemoryRetrievalRequest.model_validate(_params)
        resp = self._http.post(
            "/v1/memories:batchGet",
            json=body.model_dump(by_alias=True, exclude_unset=True),
            headers=self._headers,
        )
        return self._handle_response(resp, BatchMemoryResponse)

    def _retrieve_with_body(
        self,
        body_dict: dict,
        *,
        stream: bool,
        format: Format,
    ) -> Stream[RetrieveMemoryEvent] | list[RetrieveMemoryEvent]:
        """Execute a retrieve request with a pre-built body dict.

        Shared by the structural base and any convenience overrides.
        """
        stream_obj = Stream(
            self._http,
            method="POST",
            url="/v1/memories:retrieve",
            model=RetrieveMemoryEvent,
            format=format,
            json=body_dict,
            headers={**self._headers, "Accept": _ACCEPT[format]},
        )
        if stream:
            return stream_obj
        with stream_obj as s:
            return list(s)

    @overload
    def retrieve(
        self,
        *,
        stream: Literal[False],
        format: Format = ...,
        **kwargs: Any,
    ) -> list[RetrieveMemoryEvent]: ...

    @overload
    def retrieve(
        self,
        *,
        stream: Literal[True] = ...,
        format: Format = ...,
        **kwargs: Any,
    ) -> Stream[RetrieveMemoryEvent]: ...

    def retrieve(
        self,
        *,
        stream: bool = True,
        format: Format = "ndjson",
        **kwargs: Any,
    ) -> Stream[RetrieveMemoryEvent] | list[RetrieveMemoryEvent]:
        """Advanced semantic memory retrieval with JSON

        Streams semantic retrieval results with full feature support including context items and embedder weight overrides, per-space filters, and request-level HNSW tuning. Supports SSE (text/event-stream) and NDJSON (application/x-ndjson) formats.

        Args:
            message (string): Primary query/message for semantic search.
            context (array, optional): Optional context items (text or binary) to provide additional context for the search.
            space_keys (array): List of spaces to search with optional per-embedder weight overrides.
            requested_size (integer, optional): Maximum number of memories to retrieve.
            fetch_memory (boolean, optional): Whether to include full Memory objects in the response.
            fetch_memory_content (boolean, optional): Whether to include memory content in the response. Requires fetch_memory=true.
            hnsw (HnswOptions, optional): Optional request-level HNSW tuning overrides. Advanced usage; available on POST retrieve.
            post_processor (PostProcessor, optional): Optional post-processor configuration to transform retrieval results.
        """
        fmt = _validate_format(format)
        body = RetrieveMemoryRequest.model_validate(kwargs)
        body_dict = body.model_dump(by_alias=True, exclude_unset=True)
        return self._retrieve_with_body(body_dict, stream=stream, format=fmt)

    def list(self, *, space_id: str, **kwargs: Any) -> Any:
        """List memories in a space

        Lists all memories within a given space. Pagination is supported via max_results and next_token (opaque). next_token is a URL-safe Base64 string without padding; do not parse or construct it. This is a read-only operation with no side effects and is safe to retry. Requires LIST_MEMORY_OWN or LIST_MEMORY_ANY permission. Returns NOT_FOUND if the specified space does not exist.

        Args:
            space_id (string): The unique identifier of the space containing the memories
            include_content (boolean, optional): Whether to include the original content in the response (defaults to false)
            status_filter (string, optional): Filter memories by processing status (PENDING, PROCESSING, COMPLETED, FAILED)
            filter (string, optional): Optional metadata filter expression for list results
            max_results (integer, optional): Maximum number of results per page (defaults to 50, clamped to [1, 500]).
            next_token (string, optional): Opaque pagination token for the next page. URL-safe Base64 without padding; do not parse or construct it.
            sort_by (string, optional): Field to sort by (e.g., 'created_at')
            sort_order (SortOrder, optional): Sort direction (ASCENDING or DESCENDING)

        Returns:
            MemoryListResponse
        """
        op = _op_meta(self, 'list')
        params = dict(kwargs)
        return Paginator(
            fetch_fn=lambda token: self._http.get(
                f"/v1/spaces/{space_id}/memories",
                params={**params, 'nextToken': token} if token else params or None,
                headers=self._headers,
            ),
            response_model=self._list_response_model,
            items_field=self._list_items_field,
        )


class AsyncMemoriesAPIBase(AsyncCRUDNamespace):
    """Async Memories API — auto-generated structural base.

    Auto-generated structural base. Do not edit.
    Override in goodmem/api/memories.py to add domain-specific logic.
    """

    _base_path = "/v1/memories"
    _create_model = MemoryCreationRequest
    _update_model = None
    _response_model = Memory
    _list_response_model = MemoryListResponse
    _list_items_field = "memories"
    _rest_metadata: dict = {'create': {'http_method': 'POST', 'path': '/v1/memories', 'response': 'Memory', 'body_model': 'MemoryCreationRequest', 'body_expr': 'MemoryCreationRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json', 'multipart/form-data'], 'supports_multipart': True, 'multipart_request_field': 'request', 'multipart_file_field': 'file'}, 'get': {'http_method': 'GET', 'path': '/v1/memories/{id}', 'response': 'Memory', 'query_params': ['id', 'include_content', 'include_processing_history']}, 'list': {'http_method': 'GET', 'path': '/v1/spaces/{spaceId}/memories', 'response': 'MemoryListResponse', 'query_params': ['space_id', 'include_content', 'status_filter', 'filter', 'max_results', 'next_token', 'sort_by', 'sort_order'], 'auto_next_token': True}, 'delete': {'http_method': 'DELETE', 'path': '/v1/memories/{id}', 'response': 'None', 'query_params': ['id']}, 'content': {'http_method': 'GET', 'path': '/v1/memories/{id}/content', 'response': 'bytes', 'query_params': ['id']}, 'batch_create': {'http_method': 'POST', 'path': '/v1/memories:batchCreate', 'response': 'BatchMemoryResponse', 'body_model': 'BatchMemoryCreationRequest', 'body_expr': 'BatchMemoryCreationRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json', 'multipart/form-data'], 'supports_multipart': True, 'multipart_request_field': 'requests', 'multipart_file_field': 'file'}, 'batch_delete': {'http_method': 'POST', 'path': '/v1/memories:batchDelete', 'response': 'BatchMemoryResponse', 'body_model': 'BatchMemoryDeletionRequest', 'body_expr': 'BatchMemoryDeletionRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'batch_get': {'http_method': 'POST', 'path': '/v1/memories:batchGet', 'response': 'BatchMemoryResponse', 'body_model': 'BatchMemoryRetrievalRequest', 'body_expr': 'BatchMemoryRetrievalRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json']}, 'retrieve': {'http_method': 'POST', 'path': '/v1/memories:retrieve', 'query_params': ['accept'], 'body_model': 'RetrieveMemoryRequest', 'body_expr': 'RetrieveMemoryRequest(**kwargs)', 'body_kind': 'json', 'body_kinds': ['application/json'], 'accept_from': 'format'}}

    async def create(self, **kwargs: Any) -> Any:
        """Create a new memory

        Creates a new memory in a specified space and starts asynchronous processing. The memory begins in PENDING status while a background job performs chunking and embedding generation. IMPORTANT: This operation is NOT idempotent - each request creates a new memory record. Returns INVALID_ARGUMENT if space_id, original_content, or content_type is missing or invalid. Returns NOT_FOUND if the specified space does not exist. Requires CREATE_MEMORY_OWN permission for spaces you own (or CREATE_MEMORY_ANY for admin users to create in any space). Side effects include creating the memory record, generating a unique UUID, and enqueuing a background processing job.

        Args:
            memory_id (string, optional): Optional client-provided UUID for the memory. If omitted, the server generates one. Returns ALREADY_EXISTS if the ID is already in use.
            space_id (string): ID of the space where this memory will be stored
            original_content (string, optional): Original content as plain text (use either this or original_content_b64)
            original_content_b64 (string, optional): Original content as base64-encoded binary data (use either this or original_content)
            original_content_ref (string, optional): Reference to external content location
            content_type (string): MIME type of the content
            metadata (object, optional): Additional metadata for the memory
            chunking_config (ChunkingConfiguration, optional): Chunking strategy for this memory (if not provided, uses space default)
            file_field (string, optional): Optional multipart file field name to bind binary content; required when multiple files are uploaded in a batch multipart request.

        Returns:
            Memory
        """
        op = _op_meta(self, 'create')
        json_payload, data_payload, files_payload = _prepare_create_payload(
            create_model=self._create_model, op=op, kwargs=dict(kwargs),
        )
        resp = await self._http.post(
            self._base_path,
            json=json_payload,
            data=data_payload,
            files=files_payload,
            headers=self._headers,
        )
        return self._handle_response(resp, self._create_response_model or self._response_model)

    async def get(self, *, id: str, include_content: bool | None = None, include_processing_history: bool | None = None) -> Any:
        """Get a memory by ID

        Retrieves a single memory by its ID. PERMISSION CLARIFICATION: With READ_MEMORY_OWN permission, access is granted if you own the parent space OR if the parent space is public (public_read=true). With READ_MEMORY_ANY permission, you can access any memory regardless of ownership. This is a read-only operation with no side effects and is safe to retry. Returns NOT_FOUND if the memory or its parent space does not exist.

        Args:
            id (string): The unique identifier of the memory to retrieve
            include_content (boolean, optional): Whether to include the original content in the response (defaults to false)
            include_processing_history (boolean, optional): Whether to include background job processing history in the response (defaults to false)

        Returns:
            Memory
        """
        params = {}
        if include_content is not None:
            params["includeContent"] = include_content
        if include_processing_history is not None:
            params["includeProcessingHistory"] = include_processing_history
        resp = await self._http.get(
            f"{self._base_path}/{id}",
            params=params or None,
            headers=self._headers,
        )
        return self._handle_response(resp, self._response_model)

    async def delete(self, *, id: str) -> None:
        """Delete a memory

        Permanently deletes a memory and its associated chunks. This operation cannot be undone and immediately removes the memory record from the database. IDEMPOTENCY: This operation is safe to retry - may return NOT_FOUND if the memory was already deleted or never existed. Requires DELETE_MEMORY_OWN permission for memories in spaces you own (or DELETE_MEMORY_ANY for admin users to delete any memory). Side effects include permanent removal of the memory record and all associated chunk data.

        Args:
            id (string): The unique identifier of the memory to delete
        """
        resp = await self._http.delete(f"{self._base_path}/{id}", headers=self._headers)
        raise_for_status(resp)

    async def content(self, *, id: str) -> bytes:
        """Download memory content

        Streams the original binary payload for a memory. The response uses the memory's stored content type when available. Returns 404 when the memory does not have inline content; clients can check original_content_ref from the metadata endpoint to locate external content.

        Args:
            id (string): The unique identifier of the memory to download
        """
        resp = await self._http.get(
            f"{self._base_path}/{id}/content",
            headers=self._headers,
        )
        raise_for_status(resp)
        return resp.content

    async def batch_create(self, *, requests, **kwargs: Any) -> BatchMemoryResponse:
        """Create multiple memories in a batch

        Creates multiple memories in a single operation, with individual success/failure results.

        Args:
            requests (array): Array of memory creation requests

        Returns:
            BatchMemoryResponse
        """
        _params = {**kwargs}
        _params['requests'] = requests
        body = BatchMemoryCreationRequest.model_validate(_params)
        resp = await self._http.post(
            "/v1/memories:batchCreate",
            json=body.model_dump(by_alias=True, exclude_unset=True),
            headers=self._headers,
        )
        return self._handle_response(resp, BatchMemoryResponse)

    async def batch_delete(self, *, requests, **kwargs: Any) -> BatchMemoryResponse:
        """Delete memories in batch

        Deletes memories using selector entries. Each selector can target either a specific memory ID or a filtered subset scoped to a specific space.

        Args:
            requests (array): Array of delete selectors

        Returns:
            BatchMemoryResponse
        """
        _params = {**kwargs}
        _params['requests'] = requests
        body = BatchMemoryDeletionRequest.model_validate(_params)
        resp = await self._http.post(
            "/v1/memories:batchDelete",
            json=body.model_dump(by_alias=True, exclude_unset=True),
            headers=self._headers,
        )
        return self._handle_response(resp, BatchMemoryResponse)

    async def batch_get(self, *, memory_ids, include_content=None, include_processing_history=None, **kwargs: Any) -> BatchMemoryResponse:
        """Get multiple memories by ID

        Retrieves multiple memories in a single operation, with individual success/failure results.

        Args:
            memory_ids (array): Array of memory IDs to retrieve
            include_content (boolean, optional): Whether to include the original content in the response
            include_processing_history (boolean, optional): Whether to include background job processing history for each memory

        Returns:
            BatchMemoryResponse
        """
        _params = {**kwargs}
        _params['memory_ids'] = memory_ids
        if include_content is not None:
            _params['include_content'] = include_content
        if include_processing_history is not None:
            _params['include_processing_history'] = include_processing_history
        body = BatchMemoryRetrievalRequest.model_validate(_params)
        resp = await self._http.post(
            "/v1/memories:batchGet",
            json=body.model_dump(by_alias=True, exclude_unset=True),
            headers=self._headers,
        )
        return self._handle_response(resp, BatchMemoryResponse)

    async def _retrieve_with_body(
        self,
        body_dict: dict,
        *,
        stream: bool,
        format: Format,
    ) -> AsyncStream[RetrieveMemoryEvent] | list[RetrieveMemoryEvent]:
        """Execute a retrieve request with a pre-built body dict.
        """
        stream_obj = AsyncStream(
            self._http,
            method="POST",
            url="/v1/memories:retrieve",
            model=RetrieveMemoryEvent,
            format=format,
            json=body_dict,
            headers={**self._headers, "Accept": _ACCEPT[format]},
        )
        if stream:
            return stream_obj
        async with stream_obj as s:
            return [event async for event in s]

    async def retrieve(
        self,
        *,
        stream: bool = True,
        format: Format = "ndjson",
        **kwargs: Any,
    ) -> AsyncStream[RetrieveMemoryEvent] | list[RetrieveMemoryEvent]:
        """Advanced semantic memory retrieval with JSON

        Streams semantic retrieval results with full feature support including context items and embedder weight overrides, per-space filters, and request-level HNSW tuning. Supports SSE (text/event-stream) and NDJSON (application/x-ndjson) formats.

        Args:
            message (string): Primary query/message for semantic search.
            context (array, optional): Optional context items (text or binary) to provide additional context for the search.
            space_keys (array): List of spaces to search with optional per-embedder weight overrides.
            requested_size (integer, optional): Maximum number of memories to retrieve.
            fetch_memory (boolean, optional): Whether to include full Memory objects in the response.
            fetch_memory_content (boolean, optional): Whether to include memory content in the response. Requires fetch_memory=true.
            hnsw (HnswOptions, optional): Optional request-level HNSW tuning overrides. Advanced usage; available on POST retrieve.
            post_processor (PostProcessor, optional): Optional post-processor configuration to transform retrieval results.
        """
        fmt = _validate_format(format)
        body = RetrieveMemoryRequest.model_validate(kwargs)
        body_dict = body.model_dump(by_alias=True, exclude_unset=True)
        return await self._retrieve_with_body(body_dict, stream=stream, format=fmt)

    async def list(self, *, space_id: str, **kwargs: Any) -> Any:
        """List memories in a space

        Lists all memories within a given space. Pagination is supported via max_results and next_token (opaque). next_token is a URL-safe Base64 string without padding; do not parse or construct it. This is a read-only operation with no side effects and is safe to retry. Requires LIST_MEMORY_OWN or LIST_MEMORY_ANY permission. Returns NOT_FOUND if the specified space does not exist.

        Args:
            space_id (string): The unique identifier of the space containing the memories
            include_content (boolean, optional): Whether to include the original content in the response (defaults to false)
            status_filter (string, optional): Filter memories by processing status (PENDING, PROCESSING, COMPLETED, FAILED)
            filter (string, optional): Optional metadata filter expression for list results
            max_results (integer, optional): Maximum number of results per page (defaults to 50, clamped to [1, 500]).
            next_token (string, optional): Opaque pagination token for the next page. URL-safe Base64 without padding; do not parse or construct it.
            sort_by (string, optional): Field to sort by (e.g., 'created_at')
            sort_order (SortOrder, optional): Sort direction (ASCENDING or DESCENDING)

        Returns:
            MemoryListResponse
        """
        op = _op_meta(self, 'list')
        params = dict(kwargs)
        return AsyncPaginator(
            fetch_fn=lambda token: self._http.get(
                f"/v1/spaces/{space_id}/memories",
                params={**params, 'nextToken': token} if token else params or None,
                headers=self._headers,
            ),
            response_model=self._list_response_model,
            items_field=self._list_items_field,
        )

