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-utilRequires 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>(...).awaitexposes all IR 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. 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
- 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.