goodmem-client 1.5.11
API for interacting with the GoodMem service, providing vector-based memory storage and retrieval with multiple embedder support.
License: Apache 2.0
Requires Python: >=3.9
Keywords: OpenAPI, OpenAPI-Generator, GoodMem API, vector, embeddings, memory

# goodmem-client

[![PyPI version](https://img.shields.io/pypi/v/goodmem-client.svg)](https://pypi.org/project/goodmem-client/)
Python client for GoodMem - a vector-based memory storage and retrieval service. Provides APIs for creating memory spaces, storing memories with vector embeddings, and performing semantic search with streaming retrieval. Supports multiple embedding providers and advanced metadata handling.

This Python package is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project:

- API version: v1
- Package version: 1.5.11
- Generator version: 7.13.0
- Build package: org.openapitools.codegen.languages.PythonClientCodegen
For more information, please visit [https://goodmem.io/support](https://goodmem.io/support)

## Server Compatibility

This client version is generated with **GoodMem server v1.0.230**.


## Requirements.

Python 3.9+

## Installation & Usage
### pip install

You can install the package directly from PyPI:

```sh
pip install goodmem-client
```

If you prefer uv:

```sh
uv pip install goodmem-client
```

Then import the package:
```python
import goodmem_client
```

### Setuptools

Install via [Setuptools](http://pypi.python.org/pypi/setuptools).

```sh
python setup.py install --user
```
(or `sudo python setup.py install` to install the package for all users)

Then import the package:
```python
import goodmem_client
```

### Tests

Execute `pytest` to run the tests.

## Getting Started

Please follow the [installation procedure](#installation--usage) and then run the following:

```python

# Import required modules
from goodmem_client.api import APIKeysApi, SpacesApi
from goodmem_client.configuration import Configuration
from goodmem_client.api_client import ApiClient
from goodmem_client.models import CreateApiKeyRequest
from goodmem_client.streaming import MemoryStreamClient
from goodmem_client.rest import ApiException
from pprint import pprint

# Configure the API client
configuration = Configuration()
configuration.host = "http://localhost:8080"  # Use your server URL

# Set authentication
configuration.api_key = {"ApiKeyAuth": "your-api-key"}

# Create API client
api_client = ApiClient(configuration=configuration)  # Your API key here

# Create an instance of the API class
api_instance = APIKeysApi(api_client=api_client)

# Prepare a create request with labels
create_request = CreateApiKeyRequest(
    labels={
        "environment": "development",
        "service": "chat-ui"
    }
)

try:
    # Create a new API key
    api_response = api_instance.create_api_key(create_api_key_request=create_request)
    print("API Key created successfully:")
    print(f"API Key ID: {api_response.api_key_metadata.api_key_id}")
    print(f"Raw API Key: {api_response.raw_api_key}")
except ApiException as e:
    print(f"Exception when calling APIKeysApi->create_api_key: {e}")
```

### Streaming Memory Retrieval

For memory retrieval operations, use the streaming client which is the primary way to search and retrieve memories:

```python
from goodmem_client.api import SpacesApi
from goodmem_client.streaming import MemoryStreamClient
from goodmem_client.configuration import Configuration
from goodmem_client.api_client import ApiClient

# Configure client
configuration = Configuration()
configuration.host = "http://localhost:8080"
configuration.api_key = {"ApiKeyAuth": "your-api-key"}

api_client = ApiClient(configuration=configuration)

# Create streaming client
spaces_api = SpacesApi(api_client=api_client)
stream_client = MemoryStreamClient(api_client)

# Get space ID (first available space)
spaces = spaces_api.list_spaces()
space_id = spaces.spaces[0].space_id if spaces.spaces else None

# Stream memory retrieval using advanced POST endpoint with custom post-processor
for event in stream_client.retrieve_memory_stream(
    message="your search query",
    space_ids=[space_id] if space_id else None,
    requested_size=5,
    fetch_memory=True,
    fetch_memory_content=False,
    format="ndjson",
    post_processor_name="com.goodmem.retrieval.postprocess.ChatPostProcessorFactory",
    post_processor_config={
        "llm_id": "your-llm-uuid",
        "reranker_id": "your-reranker-uuid",
        "relevance_threshold": 0.5,
        "max_results": 10
    }
):
    if event.abstract_reply:
        print(f"Abstract: {event.abstract_reply.text}")
    elif event.retrieved_item and event.retrieved_item.memory:
        memory = event.retrieved_item.memory
        print(f"Memory: {memory.get('memoryId')}")
        if 'metadata' in memory:
            print(f"Metadata: {memory['metadata']}")

# Alternative: Use convenience method for ChatPostProcessor with simple parameters
for event in stream_client.retrieve_memory_stream_chat(
    message="your search query",
    space_ids=[space_id] if space_id else None,
    requested_size=5,
    fetch_memory=True,
    format="ndjson",
    pp_llm_id="your-llm-uuid",
    pp_reranker_id="your-reranker-uuid",
    pp_relevance_threshold=0.5,
    pp_max_results=10
):
    if event.abstract_reply:
        print(f"Abstract: {event.abstract_reply.text}")
```

For comprehensive examples, see the `samples` directory:
- `apikey_sample.py` - API key CRUD operations
- `streaming_sample.py` - Memory retrieval with streaming
- `reproduce_issue_71.py` - Memory creation with metadata

### Using Filter Expressions

Filter expressions allow you to pre-filter memories based on metadata before semantic search. This enables more precise retrieval by combining metadata filtering with vector similarity.

```python
from goodmem_client.streaming import MemoryStreamClient
from goodmem_client.models.space_key import SpaceKey
from goodmem_client.configuration import Configuration
from goodmem_client.api_client import ApiClient

# Configure client
configuration = Configuration()
configuration.host = "http://localhost:8080"
configuration.api_key = {"ApiKeyAuth": "your-api-key"}

api_client = ApiClient(configuration=configuration)
stream_client = MemoryStreamClient(api_client)

# Example 1: Filter by category
space_key = SpaceKey(
    space_id="your-space-id",
    filter="CAST(val('$.category') AS TEXT) = 'technology'"
)

for event in stream_client.retrieve_memory_stream(
    message="artificial intelligence",
    space_keys=[space_key],
    requested_size=5
):
    if event.retrieved_item and event.retrieved_item.chunk:
        chunk = event.retrieved_item.chunk
        print(f"Chunk: {chunk.chunk.get('chunkText', '')[:100]}...")

# Example 2: Filter by time range
space_key = SpaceKey(
    space_id="your-space-id",
    filter="CAST(val('$.created_at') AS TEXT) >= '2025-01-01T00:00:00Z'"
)

for event in stream_client.retrieve_memory_stream(
    message="recent developments",
    space_keys=[space_key],
    requested_size=5
):
    if event.retrieved_item and event.retrieved_item.chunk:
        chunk = event.retrieved_item.chunk
        print(f"Relevance: {chunk.relevance_score:.4f}")
        print(f"Text: {chunk.chunk.get('chunkText', '')[:80]}...")

# Example 3: Complex filter with multiple conditions
space_key = SpaceKey(
    space_id="your-space-id",
    filter="""
        CAST(val('$.priority') AS TEXT) = 'high'
        AND CAST(val('$.status') AS TEXT) = 'active'
        AND CAST(val('$.score') AS INTEGER) >= 80
    """
)

for event in stream_client.retrieve_memory_stream(
    message="important tasks",
    space_keys=[space_key],
    requested_size=10
):
    if event.retrieved_item and event.retrieved_item.chunk:
        print(f"Found matching chunk")

# Example 4: Different filters for different spaces
space_keys = [
    SpaceKey(
        space_id="space-1-id",
        filter="CAST(val('$.category') AS TEXT) = 'research'"
    ),
    SpaceKey(
        space_id="space-2-id",
        filter="CAST(val('$.category') AS TEXT) = 'documentation'"
    )
]

for event in stream_client.retrieve_memory_stream(
    message="machine learning concepts",
    space_keys=space_keys,
    requested_size=10
):
    if event.memory_definition:
        space_id = event.memory_definition.get('spaceId')
        metadata = event.memory_definition.get('metadata', {})
        print(f"Memory from space: {space_id}, category: {metadata.get('category')}")

# Example 5: Mix filtered and unfiltered spaces
space_keys = [
    SpaceKey(
        space_id="space-1-id",
        filter="CAST(val('$.source') AS TEXT) = 'trusted_source'"
    ),
    SpaceKey(
        space_id="space-2-id"  # No filter - all memories from this space
    )
]

for event in stream_client.retrieve_memory_stream(
    message="information query",
    space_keys=space_keys,
    requested_size=10
):
    if event.retrieved_item and event.retrieved_item.chunk:
        print(f"Relevance: {event.retrieved_item.chunk.relevance_score:.4f}")
```

**Filter Expression Syntax:**
- Extract field: `val('$.field_name')`
- Extract array: `vals('$.array_field[*]')`
- Check field exists: `exists('$.field_name')`
- String comparison: `CAST(val('$.category') AS TEXT) = 'technology'`
- Numeric comparison: `CAST(val('$.score') AS INTEGER) >= 80`
- Date comparison: `CAST(val('$.created_at') AS DATE) >= CAST('2025-01-01' AS DATE)`
- String pattern: `CAST(val('$.title') AS TEXT) LIKE '%AI%'`
- Case-insensitive pattern: `CAST(val('$.title') AS TEXT) ILIKE '%ai%'`
- Array membership: `'tag1' IN vals('$.tags')`
- Multiple conditions: Use `AND`, `OR`, `NOT` operators

For more details on filter expressions, see the [GoodMem filter documentation](https://docs.goodmem.ai/docs/how-to/metadata-filters/).

## Documentation for API Endpoints

All URIs are relative to *https://localhost:8080*

Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*APIKeysApi* | [**create_api_key**](docs/APIKeysApi.md#create_api_key) | **POST** /v1/apikeys | Create a new API key
*APIKeysApi* | [**delete_api_key**](docs/APIKeysApi.md#delete_api_key) | **DELETE** /v1/apikeys/{id} | Delete an API key
*APIKeysApi* | [**list_api_keys**](docs/APIKeysApi.md#list_api_keys) | **GET** /v1/apikeys | List API keys
*APIKeysApi* | [**update_api_key**](docs/APIKeysApi.md#update_api_key) | **PUT** /v1/apikeys/{id} | Update an API key
*AdministrationApi* | [**drain_server**](docs/AdministrationApi.md#drain_server) | **POST** /v1/admin:drain | Request the server to enter drain mode
*AdministrationApi* | [**purge_background_jobs**](docs/AdministrationApi.md#purge_background_jobs) | **POST** /v1/admin/background-jobs:purge | Purge completed background jobs
*AdministrationApi* | [**reload_license**](docs/AdministrationApi.md#reload_license) | **POST** /v1/admin/license:reload | Reload the active license from disk
*EmbeddersApi* | [**create_embedder**](docs/EmbeddersApi.md#create_embedder) | **POST** /v1/embedders | Create a new embedder
*EmbeddersApi* | [**delete_embedder**](docs/EmbeddersApi.md#delete_embedder) | **DELETE** /v1/embedders/{id} | Delete an embedder
*EmbeddersApi* | [**get_embedder**](docs/EmbeddersApi.md#get_embedder) | **GET** /v1/embedders/{id} | Get an embedder by ID
*EmbeddersApi* | [**list_embedders**](docs/EmbeddersApi.md#list_embedders) | **GET** /v1/embedders | List embedders
*EmbeddersApi* | [**update_embedder**](docs/EmbeddersApi.md#update_embedder) | **PUT** /v1/embedders/{id} | Update an embedder
*LLMsApi* | [**create_llm**](docs/LLMsApi.md#create_llm) | **POST** /v1/llms | Create a new LLM
*LLMsApi* | [**delete_llm**](docs/LLMsApi.md#delete_llm) | **DELETE** /v1/llms/{id} | Delete an LLM
*LLMsApi* | [**get_llm**](docs/LLMsApi.md#get_llm) | **GET** /v1/llms/{id} | Get an LLM by ID
*LLMsApi* | [**list_llms**](docs/LLMsApi.md#list_llms) | **GET** /v1/llms | List LLMs
*LLMsApi* | [**update_llm**](docs/LLMsApi.md#update_llm) | **PUT** /v1/llms/{id} | Update an LLM
*MemoriesApi* | [**batch_create_memory**](docs/MemoriesApi.md#batch_create_memory) | **POST** /v1/memories:batchCreate | Create multiple memories in a batch
*MemoriesApi* | [**batch_delete_memory**](docs/MemoriesApi.md#batch_delete_memory) | **POST** /v1/memories:batchDelete | Delete multiple memories by ID
*MemoriesApi* | [**batch_get_memory**](docs/MemoriesApi.md#batch_get_memory) | **POST** /v1/memories:batchGet | Get multiple memories by ID
*MemoriesApi* | [**create_memory**](docs/MemoriesApi.md#create_memory) | **POST** /v1/memories | Create a new memory
*MemoriesApi* | [**delete_memory**](docs/MemoriesApi.md#delete_memory) | **DELETE** /v1/memories/{id} | Delete a memory
*MemoriesApi* | [**get_memory**](docs/MemoriesApi.md#get_memory) | **GET** /v1/memories/{id} | Get a memory by ID
*MemoriesApi* | [**get_memory_content**](docs/MemoriesApi.md#get_memory_content) | **GET** /v1/memories/{id}/content | Download memory content
*MemoriesApi* | [**list_memories**](docs/MemoriesApi.md#list_memories) | **GET** /v1/spaces/{spaceId}/memories | List memories in a space
*MemoriesApi* | [**retrieve_memory**](docs/MemoriesApi.md#retrieve_memory) | **GET** /v1/memories:retrieve | Stream semantic memory retrieval
*MemoriesApi* | [**retrieve_memory_advanced**](docs/MemoriesApi.md#retrieve_memory_advanced) | **POST** /v1/memories:retrieve | Advanced semantic memory retrieval with JSON
*OCRApi* | [**ocr_document**](docs/OCRApi.md#ocr_document) | **POST** /v1/ocr:document | Run OCR on a document or image
*PingApi* | [**ping_once**](docs/PingApi.md#ping_once) | **POST** /v1/ping:once | Run a single ping probe
*PingApi* | [**ping_stream**](docs/PingApi.md#ping_stream) | **POST** /v1/ping:stream | Stream ping probe results
*RerankersApi* | [**create_reranker**](docs/RerankersApi.md#create_reranker) | **POST** /v1/rerankers | Create a new reranker
*RerankersApi* | [**delete_reranker**](docs/RerankersApi.md#delete_reranker) | **DELETE** /v1/rerankers/{id} | Delete a reranker
*RerankersApi* | [**get_reranker**](docs/RerankersApi.md#get_reranker) | **GET** /v1/rerankers/{id} | Get a reranker by ID
*RerankersApi* | [**list_rerankers**](docs/RerankersApi.md#list_rerankers) | **GET** /v1/rerankers | List rerankers
*RerankersApi* | [**update_reranker**](docs/RerankersApi.md#update_reranker) | **PUT** /v1/rerankers/{id} | Update a reranker
*SpacesApi* | [**create_space**](docs/SpacesApi.md#create_space) | **POST** /v1/spaces | Create a new Space
*SpacesApi* | [**delete_space**](docs/SpacesApi.md#delete_space) | **DELETE** /v1/spaces/{id} | Delete a space
*SpacesApi* | [**get_space**](docs/SpacesApi.md#get_space) | **GET** /v1/spaces/{id} | Get a space by ID
*SpacesApi* | [**list_spaces**](docs/SpacesApi.md#list_spaces) | **GET** /v1/spaces | List spaces
*SpacesApi* | [**update_space**](docs/SpacesApi.md#update_space) | **PUT** /v1/spaces/{id} | Update a space
*SystemApi* | [**get_system_info**](docs/SystemApi.md#get_system_info) | **GET** /v1/system/info | Retrieve server build metadata
*SystemApi* | [**initialize_system**](docs/SystemApi.md#initialize_system) | **POST** /v1/system/init | Initialize the system
*UsersApi* | [**get_current_user**](docs/UsersApi.md#get_current_user) | **GET** /v1/users/me | Get current user profile
*UsersApi* | [**get_user**](docs/UsersApi.md#get_user) | **GET** /v1/users/{id} | Get a user by ID
*UsersApi* | [**get_user_by_email**](docs/UsersApi.md#get_user_by_email) | **GET** /v1/users/email/{email} | Get user by email address


## Documentation For Models

 - [AbstractReply](docs/AbstractReply.md)
 - [ActiveLicenseMetadata](docs/ActiveLicenseMetadata.md)
 - [AdminDrainRequest](docs/AdminDrainRequest.md)
 - [AdminDrainResponse](docs/AdminDrainResponse.md)
 - [AdminPurgeJobsRequest](docs/AdminPurgeJobsRequest.md)
 - [AdminPurgeJobsResponse](docs/AdminPurgeJobsResponse.md)
 - [AdminReloadLicenseResponse](docs/AdminReloadLicenseResponse.md)
 - [ApiKeyAuth](docs/ApiKeyAuth.md)
 - **[ApiKeyResponse](docs/ApiKeyResponse.md)** - API key metadata and information
 - [BackgroundJobAttempt](docs/BackgroundJobAttempt.md)
 - [BackgroundJobSummary](docs/BackgroundJobSummary.md)
 - **[BatchMemoryCreationRequest](docs/BatchMemoryCreationRequest.md)** - Request for creating multiple memories
 - **[BatchMemoryDeletionRequest](docs/BatchMemoryDeletionRequest.md)** - Request for deleting multiple memories
 - [BatchMemoryResponse](docs/BatchMemoryResponse.md)
 - [BatchMemoryResult](docs/BatchMemoryResult.md)
 - **[BatchMemoryRetrievalRequest](docs/BatchMemoryRetrievalRequest.md)** - Request for retrieving multiple memories
 - [BinaryContent](docs/BinaryContent.md)
 - [BoundingBox](docs/BoundingBox.md)
 - [ChunkReference](docs/ChunkReference.md)
 - [ChunkingConfiguration](docs/ChunkingConfiguration.md)
 - [ContextItem](docs/ContextItem.md)
 - **[CreateApiKeyRequest](docs/CreateApiKeyRequest.md)** - Request for creating a new API key
 - **[CreateApiKeyResponse](docs/CreateApiKeyResponse.md)** - Response containing new API key details
 - [CreateLLMResponse](docs/CreateLLMResponse.md)
 - [CredentialKind](docs/CredentialKind.md)
 - [DistributionType](docs/DistributionType.md)
 - [DocumentTimings](docs/DocumentTimings.md)
 - **[EmbedderCreationRequest](docs/EmbedderCreationRequest.md)** - Request for creating a new embedder
 - **[EmbedderResponse](docs/EmbedderResponse.md)** - Embedder configuration and metadata
 - [EmbedderWeight](docs/EmbedderWeight.md)
 - [EndpointAuthentication](docs/EndpointAuthentication.md)
 - [ErrorDetail](docs/ErrorDetail.md)
 - [GcpAdcAuth](docs/GcpAdcAuth.md)
 - [GoodMemStatus](docs/GoodMemStatus.md)
 - [ImageInfo](docs/ImageInfo.md)
 - [LLMCapabilities](docs/LLMCapabilities.md)
 - [LLMCreationRequest](docs/LLMCreationRequest.md)
 - [LLMProviderType](docs/LLMProviderType.md)
 - [LLMResponse](docs/LLMResponse.md)
 - [LLMSamplingParams](docs/LLMSamplingParams.md)
 - [LLMUpdateRequest](docs/LLMUpdateRequest.md)
 - [LengthMeasurement](docs/LengthMeasurement.md)
 - **[ListApiKeysResponse](docs/ListApiKeysResponse.md)** - Response containing list of API keys
 - **[ListEmbeddersResponse](docs/ListEmbeddersResponse.md)** - Response containing list of embedders
 - [ListLLMsResponse](docs/ListLLMsResponse.md)
 - [ListRerankersResponse](docs/ListRerankersResponse.md)
 - **[ListSpacesResponse](docs/ListSpacesResponse.md)** - Response containing list of spaces
 - **[Memory](docs/Memory.md)** - Memory object with content and metadata
 - [MemoryChunkResponse](docs/MemoryChunkResponse.md)
 - **[MemoryCreationRequest](docs/MemoryCreationRequest.md)** - Request for creating a new memory
 - **[MemoryListResponse](docs/MemoryListResponse.md)** - Response containing list of memories
 - **[Modality](docs/Modality.md)** - Enumeration of supported modalities (TEXT, IMAGE, etc.)
 - [OcrCategory](docs/OcrCategory.md)
 - [OcrCell](docs/OcrCell.md)
 - [OcrDocumentRequest](docs/OcrDocumentRequest.md)
 - [OcrDocumentResponse](docs/OcrDocumentResponse.md)
 - [OcrInputFormat](docs/OcrInputFormat.md)
 - [OcrLayout](docs/OcrLayout.md)
 - [OcrPage](docs/OcrPage.md)
 - [OcrPageResult](docs/OcrPageResult.md)
 - [PageTimings](docs/PageTimings.md)
 - [PingEndpointInfo](docs/PingEndpointInfo.md)
 - [PingEvent](docs/PingEvent.md)
 - [PingNotice](docs/PingNotice.md)
 - [PingOnceRequest](docs/PingOnceRequest.md)
 - [PingPayloadType](docs/PingPayloadType.md)
 - [PingResult](docs/PingResult.md)
 - [PingStreamRequest](docs/PingStreamRequest.md)
 - [PingSummary](docs/PingSummary.md)
 - [PingTargetType](docs/PingTargetType.md)
 - [PingTiming](docs/PingTiming.md)
 - [PostProcessor](docs/PostProcessor.md)
 - [ProcessingHistory](docs/ProcessingHistory.md)
 - **[ProviderType](docs/ProviderType.md)** - Enumeration of embedding providers (OPENAI, etc.)
 - [RecursiveChunkingConfiguration](docs/RecursiveChunkingConfiguration.md)
 - [RerankerCreationRequest](docs/RerankerCreationRequest.md)
 - [RerankerResponse](docs/RerankerResponse.md)
 - [ResultSetBoundary](docs/ResultSetBoundary.md)
 - [RetrieveMemoryEvent](docs/RetrieveMemoryEvent.md)
 - [RetrieveMemoryRequest](docs/RetrieveMemoryRequest.md)
 - [RetrievedItem](docs/RetrievedItem.md)
 - [RpcStatus](docs/RpcStatus.md)
 - [SecretReference](docs/SecretReference.md)
 - [SentenceChunkingConfiguration](docs/SentenceChunkingConfiguration.md)
 - [SeparatorKeepStrategy](docs/SeparatorKeepStrategy.md)
 - **[Space](docs/Space.md)** - Space object for organizing memories
 - **[SpaceCreationRequest](docs/SpaceCreationRequest.md)** - Request for creating a new space
 - **[SpaceEmbedder](docs/SpaceEmbedder.md)** - Associates an embedder with a space, including retrieval configuration
 - **[SpaceEmbedderConfig](docs/SpaceEmbedderConfig.md)** - Configuration for associating an embedder with a space
 - [SpaceKey](docs/SpaceKey.md)
 - [SystemInfoResponse](docs/SystemInfoResponse.md)
 - **[SystemInitResponse](docs/SystemInitResponse.md)** - Response from system initialization
 - **[UpdateApiKeyRequest](docs/UpdateApiKeyRequest.md)** - Request for updating an API key
 - **[UpdateEmbedderRequest](docs/UpdateEmbedderRequest.md)** - Request for updating an embedder
 - [UpdateRerankerRequest](docs/UpdateRerankerRequest.md)
 - **[UpdateSpaceRequest](docs/UpdateSpaceRequest.md)** - Request for updating a space
 - **[UserResponse](docs/UserResponse.md)** - User account information


<a id="documentation-for-authorization"></a>
## Documentation For Authorization


Authentication schemes defined for the API:
<a id="BearerAuth"></a>
### BearerAuth

- **Type**: Bearer authentication

<a id="ApiKeyAuth"></a>
### ApiKeyAuth

- **Type**: API key
- **API key parameter name**: x-api-key
- **Location**: HTTP header



## Contact & Support

For questions or issues with the Python client, please visit:
- GitHub repository: https://github.com/PAIR-Systems-Inc/goodmem
- PyPI package: https://pypi.org/project/goodmem-client/


## Author

support@goodmem.io