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-utilRequires 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>(...).awaitexposes the API operations, including access policy, administration, decision models, enrollment, and OCR. Nested operations use snake_case, such asadmin().background_jobs_purge(...).- Request structs and query/header options retain every caller-settable field.
Optional fields use
Option<T>and are omitted from JSON whenNone. 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, andRerankerCreationRequest::from_modelfill known provider defaults. Use explicit request structs for custom models. SpaceCreationRequest::newuses the shared default chunking configuration. Nested model fields useBox<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. SSEcloseevents end iteration; SSEerrorevents return an error with the server's status and message. memories().contentandpages_imagereturnDownloadwith bytes, HTTP status, and response headers. Content options expose Range, If-Match, and Accept-Encoding.memories().create_fileuploads bytes as multipart with typed metadata. The part name uses trimmedfile_field, defaulting tofilewhen absent or blank.memories().batch_create_filesaccepts a collection ofUploadFilevalues; each request'sfile_fieldnames its file part. Omit inline content from multipart metadata.batch_create_fileis a convenience for a single-item batch.JsonMemoryCreationRequest::bytesprovides 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
- Client, configuration, streams, and errors
- Structs, enums, and type aliases
- Convenience constructors and registries
Resource APIs
| Struct | Accessor |
|---|---|
Embedders | client.embedders() |
Rerankers | client.rerankers() |
Llms | client.llms() |
DecisionModels | client.decision_models() |
Spaces | client.spaces() |
Memories | client.memories() |
Ocr | client.ocr() |
System | client.system() |
Instance | client.instance() |
Users | client.users() |
ServiceIdentities | client.service_identities() |
UserEnrollments | client.user_enrollments() |
Admin | client.admin() |
AccessPolicy | client.access_policy() |
Apikeys | client.apikeys() |
Ping | client.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.