Smritea

Java SDK

Reference for the Smritea Java SDK. Install it, create a client, and call add, search, get and delete.

Ask AI about this page

The Java SDK is the ai.smritea:smritea-sdk package. It gives you a thread-safe, synchronous SmriteaClient with four calls: add, search, get and delete. It needs Java 11 or later. Every error is an unchecked exception.

Install

Add the dependency to your Maven pom.xml. Replace LATEST with the current release number from Maven Central.

<dependency>
  <groupId>ai.smritea</groupId>
  <artifactId>smritea-sdk</artifactId>
  <version>LATEST</version>
</dependency>

For Gradle, add this line:

implementation 'ai.smritea:smritea-sdk:LATEST'

Import the client and the model types:

import ai.smritea.sdk.SmriteaClient;
import ai.smritea.sdk.model.*;
import ai.smritea.sdk.errors.*;

Create a client

SmriteaClient takes your API key and your app ID. You must pass both, and a null value throws NullPointerException. Create them in the dashboard; see Create an app and API key.

Constructor argumentTypeDefaultDescription
apiKeyStringnoneThe API key, in the form smrt_<prefix>_<secret>.
appIdStringnoneThe app ID, in the form app_....
baseUrlStringhttps://api-us.smritea.aiThe host for your region. See Regions.
maxRetriesint2Retries after a rate limit. 0 turns retries off.
traceIdStringnoneA trace ID to send with each call. A bad value throws IllegalArgumentException.
httpClientjava.net.http.HttpClienta new clientYour own HTTP client. Set timeouts here.

The constructors accept the first two, four, five or six arguments, in the order shown. Pass null for baseUrl to use the default. The client has no timeout argument. Set a timeout on the HttpClient you pass in.

Methods

The table lists the client methods and what each one returns.

MethodReturnsDescription
add(String content, AddOptions opts)MemoryCreationResultExtracts and stores memories from the text.
search(String query, SearchOptions opts)List<SearchResult>Finds memories that match the query.
get(String id)MemoryReturns one memory by ID.
delete(String id)voidDeletes one memory by ID.

Pass null for no options. The getAll method exists but throws UnsupportedOperationException. Use search to find memories.

Add options

Build options with the fluent methods on new AddOptions().

MethodDescription
withScope(scope)Who and what the memory belongs to.
withMetadata(map)Values must be strings, integers or floats.
withEventOccurredAt(String)An RFC 3339 string, such as 2026-11-05T10:00:00Z. Smritea uses it to resolve words like "yesterday" and to date the memory.
withRelativeStanding(RelativeStanding)The importance and decay settings for the memory.

Build a RelativeStanding with new RelativeStanding(). Chain withImportance(Float), withDecayFactor(Float) and withDecayFunction(String). Import it from ai.smritea.sdk.model. The importance ranges from 0 to 1. The decay factor is 0 or higher. The decay function takes exponential, gaussian or linear. Decay affects quick_search, context_aware_search and deep_search with temporal or rrf_temporal; importance affects deep_search with rrf or rrf_temporal.

Search options

Build options with the fluent methods on new SearchOptions().

MethodDescription
withScope(scope)Limits results to this scope.
withSpeakerActorId(id)Who is asking. It never filters results.
withLimit(n)Most results to return. Omit it to use the app default.
withMethod(m)quick_search, deep_search or context_aware_search.
withRerankerType(r)Applies to deep_search only. See Search methods and rerankers.
withGraphDepth(n)A value from 1 to 5.
withValidAt(t)An RFC 3339 time. Returns memories valid at that moment.
withFromTime(t), withToTime(t)An RFC 3339 range. Use either one alone for an open range.
withMetadataFilter(map)See Filter by metadata.

You cannot combine withValidAt with withFromTime or withToTime.

Memory scope

Build a scope with MemoryScope.builder(). Every field is optional. See Memory scope for the rules.

Builder methodDescription
actorId(id)The actor's ID, up to 64 characters. Set it with actorType.
actorType(type)user, agent or system.
actorName(name)A display name, up to 255 characters. Used by add only.
conversationId(id)A conversation ID, up to 64 characters.
sourceType(type)conversation, document or api. Defaults to api.
participantIds(list)A list of one or more IDs. Search only.

Results

search returns a List<SearchResult>. It never returns null.

GetterDescription
getScore()The relevance score.
getContent()The memory text.
getId()The memory ID.
getScope()The scope fields of the memory.

add returns a MemoryCreationResult.

GetterDescription
getMemories()The memories the call stored. Never null. Empty when getExplicitSkip() is true.
getFactsExtracted()How many facts the text held.
getSkippedCount()How many facts the call skipped.
getUpdatedCount()How many existing memories the call updated.
getExplicitSkip()True when nothing was worth storing.

get returns a Memory. It has getId, getAppId, getContent, getScope, getMetadata, getActiveFrom, getActiveTo, getCreatedAt and getUpdatedAt. Read the actor and conversation through getScope().

Exceptions

Every error extends SmriteaError, which extends RuntimeException. The SDK picks the class from the HTTP status.

ExceptionHTTP statusWhen
SmriteaBadRequestError400A parameter is invalid.
SmriteaUnauthorizedError401The API key is missing or wrong.
SmriteaPaymentRequiredError402Your plan quota has run out.
SmriteaForbiddenError403The key cannot do this.
SmriteaNotFoundError404The memory does not exist.
SmriteaConflictError409The request conflicts with current state.
SmriteaUnprocessableError422The request is well formed but not allowed.
SmriteaTooManyRequestsError429You hit a rate limit.
SmriteaErrorotherAny other failure, including 5xx.

Each exception has getHttpStatus(), getCode(), isRetryable(), getBody() and getRequestId(). SmriteaTooManyRequestsError also has getRetryAfter(), in seconds.

The SDK retries a 429 up to maxRetries times. It never retries a 402. For every code, see Errors and codes.

Example

This program stores a memory, searches for it and handles the failures.

import ai.smritea.sdk.SmriteaClient;
import ai.smritea.sdk.errors.SmriteaError;
import ai.smritea.sdk.errors.SmriteaPaymentRequiredError;
import ai.smritea.sdk.errors.SmriteaTooManyRequestsError;
import ai.smritea.sdk.model.AddOptions;
import ai.smritea.sdk.model.MemoryScope;
import ai.smritea.sdk.model.SearchOptions;
import ai.smritea.sdk.model.SearchResult;
import java.util.List;

public class Example {
    public static void main(String[] args) {
        SmriteaClient client = new SmriteaClient(
            System.getenv("SMRITEA_API_KEY"),
            System.getenv("SMRITEA_APP_ID"));
        MemoryScope alice = MemoryScope.builder()
            .actorId("alice")
            .actorType("user")
            .build();

        try {
            client.add("Alice is vegetarian and loves hiking",
                new AddOptions().withScope(alice));
            List<SearchResult> results = client.search(
                "What does Alice eat?",
                new SearchOptions().withScope(alice));
            for (SearchResult r : results) {
                System.out.printf("%.2f  %s%n", r.getScore(), r.getContent());
            }
        } catch (SmriteaPaymentRequiredError e) {
            System.out.println("Plan quota used up (402)");
        } catch (SmriteaTooManyRequestsError e) {
            System.out.println("Rate limited. Retry in " + e.getRetryAfter());
        } catch (SmriteaError e) {
            System.out.println(
                e.getHttpStatus() + " " + e.getCode() + " " + e.getRequestId());
        }
    }
}

Don't see your language? Request it on GitHub. Search existing requests first and add a 👍 if yours is there. That helps the Smritea team rank requests.

Last updated on