GoodMemGoodMem
ReferenceClient SDKsRust

Rust SDK

Install and use the typed async Rust SDK. Reference clients, resource methods, request options, models, and errors.

crate goodmem

Typed asynchronous access to the GoodMem REST API.

Install

cargo add goodmem
cargo add tokio --features macros,rt-multi-thread
cargo add futures-util

Requires Rust 1.99 or newer and Tokio.

Connect and list spaces

use goodmem::{Client, api::SpacesListOptions};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::builder(std::env::var("GOODMEM_BASE_URL")?)
        .api_key(std::env::var("GOODMEM_API_KEY")?)
        .build()?;
    let page = client.spaces().list(&SpacesListOptions::default()).await?;
    for space in page.spaces {
        println!("{}: {}", space.space_id, space.name);
    }
    Ok(())
}

The base URL can include a path prefix. API keys are optional for bootstrap operations. Each ordinary HTTP attempt has a 30-second timeout; event streams use an idle timeout between chunks, so long-lived active streams remain open. Configure a larger timeout for long-running administrative or inference calls. ClientBuilder::timeout also works with http_client: it sets the SDK budget without changing the custom reqwest client's own timeout settings. A shorter timeout configured on that client can still end a request sooner.

Ingest and retrieve

use goodmem::{Client, models::*, api::MemoriesRetrieveOptions};
use futures_util::StreamExt;

async fn search(client: &Client, space_id: &str) -> goodmem::Result<()> {
    let request = JsonMemoryCreationRequest::text(space_id, "GoodMem stores persistent memory.");
    let memory = client.memories().create(&request).await?;
    println!("Queued memory {}", memory.memory_id);
    // Ingestion is asynchronous. Wait for processing to complete before expecting
    // this new memory in results; examples/basic_rag.rs shows the polling step.
    let query = RetrieveMemoryRequest::new("persistent memory", [space_id.to_owned()]);
    let mut events = client.memories().retrieve(&query, &MemoriesRetrieveOptions::default()).await?;
    while let Some(event) = events.next().await {
        println!("{:?}", event?);
    }
    Ok(())
}

API conventions

  • client.<namespace>().<method>(...).await exposes the API operations, including access policy, administration, decision models, enrollment, and OCR. Nested operations use snake_case, such as admin().background_jobs_purge(...).
  • Request structs and query/header options retain every caller-settable field. Optional fields use Option<T> and are omitted from JSON when None. Struct updates with ..Default::default() are convenient for optional fields; required fields still need meaningful values. validate() checks the shared contract, and every HTTP call validates before sending.
  • Known model registries are bundled. EmbedderCreationRequest::from_model, LlmCreationRequest::from_model, and RerankerCreationRequest::from_model fill known provider defaults. Use explicit request structs for custom models.
  • SpaceCreationRequest::new uses the shared default chunking configuration. Nested model fields use Box<T> to support recursive model graphs.
  • *_pages() methods lazily return typed pages for paginated endpoints. Drop a page/event stream to cancel. There are no background workers.
  • Retrieval and ping support NDJSON and SSE. Empty domain-event frames are ignored; malformed JSON is an error. Future server enum values deserialize as UnknownValue, preserving the rest of the response. Unknown values cannot be sent as request enum values. SSE close events end iteration; SSE error events return an error with the server's status and message.
  • memories().content and pages_image return Download with bytes, HTTP status, and response headers. Content options expose Range, If-Match, and Accept-Encoding.
  • memories().create_file uploads bytes as multipart with typed metadata. The part name uses trimmed file_field, defaulting to file when absent or blank. memories().batch_create_files accepts a collection of UploadFile values; each request's file_field names its file part. Omit inline content from multipart metadata. batch_create_file is a convenience for a single-item batch. JsonMemoryCreationRequest::bytes provides a base64 JSON alternative.
  • Errors preserve HTTP status; Error::kind() distinguishes authorization, missing resources, conflicts, preconditions, rate limits, and server failures.
  • Debug representations redact fields listed in the shared sensitive-field contract. HTTP redirects are disabled by default. Automatic retries are limited to the wake conditions described below.

Rust deliberately offers an async-only API and explicit typed requests rather than Python keyword overloads. There is no browser/WASM support or support for opt-in terminal-record streams. Do not set GoodMem-Stream-Terminal. If supplying a custom reqwest client, disable redirects and avoid a total timeout that would cut off active streams.

Wake retries

GoodMem Cloud can return HTTP 503 with Retry-After while an instance starts. The client retries qualifying responses with a default wake budget of 180 seconds. This policy applies to any configured server URL that returns the same headers. It does not start an offline local server.

A retry requires HTTP 503, X-Goodmem-Activator-Wake: retry, a valid Retry-After, and a replayable body. This applies to every method. The marker means the activator did not forward the request. Network errors and unmarked responses are not retried.

The budget limits retry starts. Each attempt keeps its normal timeout, so the last attempt can finish after the budget. Successful streams are not restarted or limited by the wake budget. Drop the future or stream to cancel it.

Use RetryPolicy to configure or disable retries:

use goodmem::{Client, RetryPolicy};

fn main() -> goodmem::Result<()> {
    let _client = Client::builder("http://localhost:8080")
        .retry_policy(RetryPolicy::none())
        .build()?;
    Ok(())
}

Use RetryPolicy::default().wake_timeout(duration) to change the 180-second default. Zero disables wake retries. Error::Http preserves the status and parsed retry_after hint. Include .. when matching this non-exhaustive variant. Multipart bodies that cannot be cloned are not replayed.

See Paused instances and retries for the shared policy, timeout behavior, and upload differences.

Batch file uploads

use goodmem::{Client, UploadFile, models::{JsonBatchMemoryCreationRequest, JsonMemoryCreationRequest}};

async fn upload_notes(client: &Client, space_id: &str) -> goodmem::Result<()> {
    let mut requests = Vec::new();
    let mut files = Vec::new();
    for (field, text) in [("first", "First note"), ("second", "Second note")] {
        requests.push(JsonMemoryCreationRequest {
            space_id: space_id.to_owned(),
            content_type: "text/plain".into(),
            file_field: Some(field.into()),
            ..Default::default()
        });
        files.push(UploadFile {
            field_name: field.into(),
            filename: format!("{field}.txt"),
            content_type: "text/plain".into(),
            data: text.as_bytes().to_vec(),
        });
    }
    client.memories().batch_create_files(&JsonBatchMemoryCreationRequest { requests }, files).await?;
    Ok(())
}

Documentation

Crate reference

Resource APIs

StructAccessor
Embeddersclient.embedders()
Rerankersclient.rerankers()
Llmsclient.llms()
DecisionModelsclient.decision_models()
Spacesclient.spaces()
Memoriesclient.memories()
Ocrclient.ocr()
Systemclient.system()
Instanceclient.instance()
Usersclient.users()
ServiceIdentitiesclient.service_identities()
UserEnrollmentsclient.user_enrollments()
Adminclient.admin()
AccessPolicyclient.access_policy()
Apikeysclient.apikeys()
Pingclient.ping()

Resource methods validate requests before sending them. Optional model fields use Option<T>; fields set to None are omitted from outgoing JSON. Default initializes a struct but does not guarantee that its required fields are valid.

On this page