Go SDK
beginnerComplete reference for the engramma-go package — installation, struct-based API, context propagation, error types, and concurrency patterns.
Installation
go get github.com/engramma/engramma-goRequires Go 1.21+.
Initialization
package main
import (
"os"
engramma "github.com/engramma/engramma-go"
)
func main() {
client := engramma.NewClient(os.Getenv("ENGRAMMA_API_KEY"))
}The API key is sent as the X-API-Key header on every request.
| Option | Type | Default | Description |
|---|---|---|---|
WithBaseURL | string | https://api.engramma-memory.com | API base URL |
WithTimeout | time.Duration | 30s | Request timeout |
WithMaxRetries | int | 3 | Automatic retries on 5xx and 429 |
WithHTTPClient | *http.Client | http.DefaultClient | Custom HTTP client |
Text operations
Store
Stores a text memory and returns pattern metadata.
ctx := context.Background()
result, err := client.Text.Store(ctx, &engramma.StoreRequest{
Text: "The deployment window is Tuesday 2-4pm UTC",
Metadata: map[string]interface{}{"category": "ops", "priority": "high"},
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Pattern ID: %s\n", result.PatternID)
fmt.Printf("Embedding dim: %d\n", result.EmbeddingDim)
fmt.Printf("Patterns used: %d / %d\n", result.PatternsUsed, result.PatternsLimit)Response fields:
| Field | Type | Description |
|---|---|---|
Success | bool | Whether the store succeeded |
PatternID | string | Unique ID (pat_...) |
EmbeddingDim | int | Dimension of the generated embedding (384) |
PatternsUsed | int | Current pattern count |
PatternsLimit | int | Maximum patterns allowed |
BatchStore
Store up to 50 memories in a single request.
results, err := client.Text.BatchStore(ctx, []engramma.StoreRequest{
{Text: "Alice joined the team on Jan 5"},
{Text: "Project deadline is March 15", Metadata: map[string]interface{}{"priority": "high"}},
{Text: "Budget approved for Q2", Metadata: map[string]interface{}{"dept": "finance"}},
})
if err != nil {
log.Fatal(err)
}
for _, r := range results.Items {
fmt.Printf("Stored: %s\n", r.PatternID)
}Maximum 50 items per batch request. Exceeding this limit returns a 422 validation error.
Retrieve
Retrieve memories by semantic similarity.
results, err := client.Text.Retrieve(ctx, &engramma.RetrieveRequest{
Query: "When can we deploy?",
TopK: 5,
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Latency: %dms\n", results.LatencyMs)
for _, r := range results.Results {
fmt.Printf("%s (similarity: %.4f, id: %s)\n", r.Text, r.Similarity, r.PatternID)
}| Field | Type | Required | Description |
|---|---|---|---|
Query | string | Yes | Natural-language query |
TopK | int | No | Max results (default: 5) |
Result fields:
| Field | Type | Description |
|---|---|---|
Text | string | The stored memory text |
Metadata | map[string]interface{} | Associated metadata |
Similarity | float64 | Cosine similarity score |
PatternID | string | Pattern identifier |
Recall
Active Inference retrieval that uses predictive processing to surface contextually relevant memories.
results, err := client.Text.Recall(ctx, &engramma.RecallRequest{
Query: "What happened before the outage?",
TemporalWeight: 0.8,
CausalWeight: 0.7,
Limit: 10,
})
if err != nil {
log.Fatal(err)
}
for _, r := range results.Results {
fmt.Printf("%s (similarity: %.4f)\n", r.Text, r.Similarity)
}Explain
Get a natural-language explanation of how a query relates to stored memories.
explanation, err := client.Text.Explain(ctx, &engramma.ExplainRequest{
Query: "When can we deploy?",
Lang: "en", // "en" or "fr"
})
if err != nil {
log.Fatal(err)
}
fmt.Println(explanation.Explanation)
fmt.Printf("Method: %s\n", explanation.Method)
fmt.Printf("Confidence: %.2f\n", explanation.Confidence)| Field | Type | Required | Description |
|---|---|---|---|
Query | string | Yes | The query to explain |
Lang | string | No | Response language: "en" (default) or "fr" |
Forget
Delete memories matching a query and optional category, above a similarity threshold.
err := client.Text.Forget(ctx, &engramma.ForgetRequest{
Query: "deployment window",
Category: "ops",
Threshold: 0.85,
})
if err != nil {
log.Fatal(err)
}| Field | Type | Required | Description |
|---|---|---|---|
Query | string | Yes | Semantic query to match memories for deletion |
Category | string | No | Filter by metadata category |
Threshold | float64 | No | Minimum similarity to delete (default: 0.85) |
Stats
Retrieve statistics about stored text memories.
stats, err := client.Text.Stats(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Total patterns: %d\n", stats.TotalPatterns)
fmt.Printf("Storage used: %d bytes\n", stats.StorageBytes)Consolidation
Sleep
Trigger memory consolidation (analogous to sleep-based memory consolidation).
result, err := client.Consolidation.Sleep(ctx, &engramma.SleepRequest{
Mode: "full", // "full" or "light"
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Consolidation started: %s\n", result.Status)| Field | Type | Required | Description |
|---|---|---|---|
Mode | string | Yes | "full" for deep consolidation, "light" for incremental |
Status
Check the current consolidation status.
status, err := client.Consolidation.Status(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("State: %s\n", status.State)
fmt.Printf("Progress: %.0f%%\n", status.Progress*100)Regime
Current
Get the current memory regime (encoding mode the system is operating in).
regime, err := client.Regime.Current(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Current regime: %s\n", regime.Mode)Causal operations
Strength
Compute causal strength between two concepts.
result, err := client.Causal.Strength(ctx, &engramma.CausalStrengthRequest{
Source: "deployment",
Target: "outage",
})
if err != nil {
log.Fatal(err)
}
fmt.Printf("Causal strength: %.4f\n", result.Strength)Neighbors
Find causally related concepts.
result, err := client.Causal.Neighbors(ctx, &engramma.CausalNeighborsRequest{
Concept: "deployment",
TopK: 10,
})
if err != nil {
log.Fatal(err)
}
for _, n := range result.Neighbors {
fmt.Printf("%s (strength: %.4f)\n", n.Concept, n.Strength)
}Context propagation
All methods accept context.Context as the first argument, enabling:
// Timeout per request
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
result, err := client.Text.Retrieve(ctx, &engramma.RetrieveRequest{Query: "test"})
// Cancellation
ctx, cancel := context.WithCancel(context.Background())
go func() {
time.Sleep(2 * time.Second)
cancel() // cancels the in-flight request
}()
result, err := client.Text.Retrieve(ctx, &engramma.RetrieveRequest{Query: "test"})
if errors.Is(err, context.Canceled) {
fmt.Println("Request was cancelled")
}
// Pass trace IDs from HTTP handlers
func handler(w http.ResponseWriter, r *http.Request) {
result, err := client.Text.Retrieve(r.Context(), &engramma.RetrieveRequest{
Query: "deployment schedule",
})
}Error types
The SDK returns structured errors that can be inspected with errors.As:
import "github.com/engramma/engramma-go/errors"
result, err := client.Text.Retrieve(ctx, &engramma.RetrieveRequest{Query: "test"})
if err != nil {
var apiErr *errors.APIError
if stderrors.As(err, &apiErr) {
switch apiErr.StatusCode {
case 401:
fmt.Println("Invalid API key")
case 429:
fmt.Printf("Rate limited. Retry after %ds\n", apiErr.RetryAfter)
case 404:
fmt.Println("Resource not found")
default:
fmt.Printf("API error %d: %s\n", apiErr.StatusCode, apiErr.Message)
}
} else {
fmt.Printf("Network error: %v\n", err)
}
}| Error Type | HTTP Status | Description |
|---|---|---|
*errors.AuthenticationError | 401 | Invalid or expired API key |
*errors.PermissionError | 403 | Key lacks required scope |
*errors.NotFoundError | 404 | Resource does not exist |
*errors.ValidationError | 422 | Invalid request parameters |
*errors.RateLimitError | 429 | Too many requests |
*errors.ServerError | 5xx | Internal server error |
All error types embed *errors.APIError and satisfy the error interface.
Concurrency patterns
The SDK is safe for concurrent use from multiple goroutines:
// Concurrent stores
var wg sync.WaitGroup
facts := []string{"Fact A", "Fact B", "Fact C", "Fact D"}
for _, fact := range facts {
wg.Add(1)
go func(text string) {
defer wg.Done()
_, err := client.Text.Store(ctx, &engramma.StoreRequest{Text: text})
if err != nil {
log.Printf("Failed to store: %v", err)
}
}(fact)
}
wg.Wait()
// Using errgroup for error propagation
g, ctx := errgroup.WithContext(ctx)
for _, fact := range facts {
g.Go(func() error {
_, err := client.Text.Store(ctx, &engramma.StoreRequest{Text: fact})
return err
})
}
if err := g.Wait(); err != nil {
log.Fatal(err)
}Retry policy
| Condition | Retried | Backoff |
|---|---|---|
| 429 (Rate Limit) | Yes | Uses Retry-After header |
| 500, 502, 503, 504 | Yes | Exponential: 1s, 2s, 4s |
| Network timeout | Yes | Exponential: 1s, 2s, 4s |
| 4xx (other) | No | — |
Configure retry behavior:
client := engramma.NewClient(
"nx_live_...",
engramma.WithMaxRetries(5),
engramma.WithRetryBackoff(2.0),
engramma.WithRetryMaxWait(30 * time.Second),
)Helper functions
// Pointer helpers for optional fields
engramma.Float64(0.9) // *float64
engramma.String("val") // *string
engramma.Int(5) // *int
engramma.Bool(true) // *boolNext steps
- Python SDK — Async-native Python client with Pydantic models
- JavaScript SDK — TypeScript-first browser and Node.js client
- API Reference Overview — Full endpoint documentation
- Causal Queries Guide — Advanced retrieval patterns