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. Models and operations are regenerated from the same API IR as the other GoodMem SDKs.

Install

After the first crates.io release:

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

Requires Rust 1.99 or newer and Tokio. For development before publication, use goodmem = { path = "../goodmem/clients/rust" } in your application's Cargo.toml.

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. Ordinary requests have a 30-second total 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 all IR 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. Requests are not retried automatically, avoiding duplicate writes.

Rust deliberately offers an async-only API and explicit typed requests rather than Python keyword overloads. There is no automatic retry layer, browser/WASM support, or support for opt-in terminal-record streams in this initial release. 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.

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(())
}

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