Smritea

Go SDK

Reference for the Smritea Go SDK. Install it, create a client, and call Add, Search, Get and Delete.

Ask AI about this page

The Go SDK lives in the github.com/SmrutAI/smritea-sdk/go module. Its package name is smritea. The client has four calls: Add, Search, Get and Delete. It needs Go 1.22 or later and is safe for concurrent use.

Install

go get github.com/SmrutAI/smritea-sdk/go

Import the module with the smritea alias:

import smritea "github.com/SmrutAI/smritea-sdk/go"

var _ = smritea.NewClient

Create a client

smritea.NewClient takes a ClientConfig and returns a *SmriteaClient. It never returns an error. You must set APIKey and AppID. Create them in the dashboard; see Create an app and API key.

FieldTypeDefaultDescription
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.
MaxRetries*int2Retries after a rate limit. Use smritea.Int(0) to turn retries off.
TraceIDstringemptyA trace ID to send with each call.
HTTPClient*http.Clienthttp.DefaultClientYour own HTTP client. Set timeouts here.

The client has no timeout field. Set a timeout on the HTTPClient you pass in.

A bad TraceID does not fail NewClient. Every later call then returns a *SmriteaBadRequestError with the code INVALID_TRACE_ID, and sends no request.

Methods

Every method takes a context.Context first.

MethodReturnsDescription
Add(ctx, content, opts)(*MemoryCreationResult, error)Extracts and stores memories from the text.
Search(ctx, query, opts)([]*SearchResult, error)Finds memories that match the query.
Get(ctx, memoryID)(*Memory, error)Returns one memory by ID.
Delete(ctx, memoryID)errorDeletes one memory by ID.

The GetAll method exists but always returns an error. Use Search to find memories.

Build options with the fluent helpers smritea.NewAddOptions() and smritea.NewSearchOptions(). Pass nil for no options.

Add options

The table lists the builder methods that set the options for Add.

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 smritea.NewRelativeStanding(). Chain WithImportance(float32), WithDecayFactor(float32) and WithDecayFunction(string). 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

The table lists the builder methods that set the options for Search.

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 smritea.NewMemoryScope() and its With methods. Every field is optional. See Memory scope for the rules.

FieldDescription
ActorIDThe actor's ID, up to 64 characters. Set it with ActorType.
ActorTypeuser, agent or system.
ActorNameA display name, up to 255 characters. Used by Add only.
ConversationIDA conversation ID, up to 64 characters.
SourceTypeconversation, document or api. Defaults to api.
ParticipantIDsA slice of one or more IDs. Search only.

Results

Search returns a slice of *SearchResult. The fields are pointers. Read them with the getters, which are safe on a nil value.

GetterDescription
r.GetScore()The relevance score.
r.Memory.GetContent()The memory text.
r.Memory.GetId()The memory ID.

Add returns a *MemoryCreationResult.

FieldDescription
MemoriesThe memories the call stored. Empty when ExplicitSkip is true.
FactsExtractedHow many facts the text held.
SkippedCountHow many facts the call skipped.
UpdatedCountHow many existing memories the call updated.
ExplicitSkipTrue when nothing was worth storing.

Errors

Every error embeds SmriteaError. The SDK picks the type from the HTTP status.

TypeHTTP 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 error has HTTPStatus, Code, Retryable, Body and RequestID. SmriteaTooManyRequestsError also has RetryAfter, in seconds.

Check the typed errors before *SmriteaError. errors.As into *SmriteaError does not match a typed error.

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.

package main

import (
	"context"
	"errors"
	"fmt"
	"os"

	smritea "github.com/SmrutAI/smritea-sdk/go"
)

func main() {
	client := smritea.NewClient(smritea.ClientConfig{
		APIKey: os.Getenv("SMRITEA_API_KEY"),
		AppID:  os.Getenv("SMRITEA_APP_ID"),
	})
	ctx := context.Background()
	scope := smritea.NewMemoryScope().
		WithActorID("alice").
		WithActorType("user")

	_, err := client.Add(ctx, "Alice is vegetarian and loves hiking",
		smritea.NewAddOptions().WithScope(scope))
	if err != nil {
		report(err)
		return
	}
	results, err := client.Search(ctx, "What does Alice eat?",
		smritea.NewSearchOptions().WithScope(scope))
	if err != nil {
		report(err)
		return
	}
	for _, r := range results {
		fmt.Printf("%.2f  %s\n", r.GetScore(), r.Memory.GetContent())
	}
}

func report(err error) {
	var quota *smritea.SmriteaPaymentRequiredError
	var limited *smritea.SmriteaTooManyRequestsError
	var base *smritea.SmriteaError
	switch {
	case errors.As(err, &quota):
		fmt.Println("Plan quota used up (402)")
	case errors.As(err, &limited):
		wait := 0
		if limited.RetryAfter != nil {
			wait = *limited.RetryAfter
		}
		fmt.Println("Rate limited (429)", wait)
	case errors.As(err, &base):
		fmt.Println(base.HTTPStatus, base.Code, base.RequestID)
	default:
		fmt.Println(err)
	}
}

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