anda_brain 0.6.2

🧠 Anda Brain (ε€§θ„‘) β€” Autonomous Graph Memory for AI Agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
---
name: anda-brain
description: |
  Long-term memory service for LLM agents.
  Provides persistent, structured memory (Cognitive Nexus) through three operations:
  Formation (encode conversations into memory), Recall (query memory with natural language), and Maintenance (consolidate and prune memory).

  Use this service when:
  - You need to persist facts, preferences, relationships, or events across sessions
  - You want to recall previous conversations, decisions, or user context
  - You need structured long-term memory without understanding KIP syntax
  - You want to trigger memory consolidation or cleanup

  Common trigger phrases:
  - "remember this", "save this for later", "don't forget"
  - "what did I say last time?", "recall my preferences"
  - "what do we know about X?", "who is X?"
  - "run memory maintenance", "consolidate memory"
metadata:
  version: 0.1.0
  url: https://brain.anda.ai/SKILL.md
  keywords:
    - long-term memory
    - agent memory
    - knowledge graph
    - cognitive nexus
    - memory formation
    - memory recall
    - memory maintenance
    - KIP
    - persistent memory
---

# 🧠 Anda Brain

Persistent long-term memory service for LLM agents, powered by a Knowledge Graph (Cognitive Nexus) and KIP (Knowledge Interaction Protocol). Anda Brain is [open-source software](https://github.com/ldclabs/anda-brain) β€” you can self-host it or use the cloud SaaS at `https://brain.anda.ai`.

Business agents interact entirely through **natural language** and a simple REST API β€” no KIP knowledge required.

```
Business Agent  ──natural language──▢  Brain  ──KIP──▢  Cognitive Nexus
 (your agent)                         (this service)          (knowledge graph)
```

---

## What You Get

Three operational modes cover the full memory lifecycle:

| Mode | Endpoint | Purpose | Auth |
|------|----------|---------|------|
| **Formation** | `POST /v1/{space_id}/formation` | Encode conversations into structured memory | `write` (CWT or space token) |
| **Recall** | `POST /v1/{space_id}/recall` | Query memory with natural language | `read` (CWT or space token) |

Supporting endpoints:

| Method | Endpoint | Purpose | Auth |
|--------|----------|---------|------|
| `GET` | `/` | Anda Brain website | β€” |
| `GET` | `/info` | Service info (name, version, sharding) | β€” |
| `GET` | `/SKILL.md` | This skill description | β€” |
| `GET` | `/v1/{space_id}/info` | Space status and statistics | `read` (CWT or space token) |
| `GET` | `/v1/{space_id}/conversations/{conversation_id}` | Get one conversation detail | `read` (CWT or space token) |
| `GET` | `/v1/{space_id}/conversations` | List conversations (cursor pagination) | `read` (CWT or space token) |
| `GET` | `/v1/{space_id}/management/space_tokens` | List space tokens | `read` (CWT) |
| `POST` | `/v1/{space_id}/management/add_space_token` | Add a space token | `write` (CWT) |
| `POST` | `/v1/{space_id}/management/revoke_space_token` | Revoke a space token | `write` (CWT) |
| `PATCH` | `/v1/{space_id}/management/update_space` | Update space information (name, description, public/private) | `write` (CWT) |
| `PATCH` | `/v1/{space_id}/management/restart_formation` | Restart formation for a conversation (re-encode with updated model/config) | `write` (CWT) |
| `PATCH` | `/v1/{space_id}/management/update_byok` | Update BYOK configuration for the space | `write` (CWT) |
| `POST` | `/admin/{space_id}/update_space_tier` | Update a space tier | manager (CWT) |
| `POST` | `/admin/create_space` | Create a new memory space | manager (CWT) |
> Auth scopes in tables apply when authentication is enabled (`ED25519_PUBKEYS` is set).

---

## When to Use This Service

Use Anda Brain when your agent needs to:

- **Persist knowledge across sessions** β€” user preferences, facts, decisions, relationships, events
- **Recall previous context** β€” what happened before, what the user said, what decisions were made
- **Share memory across agents** β€” multiple agents can read/write to the same space
- **Maintain memory health** β€” consolidate old events, deduplicate facts, decay stale knowledge

The service handles all the complexity of knowledge graph management. Your agent just sends messages and asks questions in natural language.

## When NOT to Use

- Temporary conversation context that only matters in the current session
- Large file storage (use object storage instead)
- Real-time data streaming
- Secrets, passwords, or API keys (the service is not a vault)

---

## Concepts

### Memory Space

Each space is an isolated environment with its own knowledge graph, conversation history, and database. Spaces are identified by a `space_id` string.

### Memory Types

The Formation agent extracts three types of memory from conversations:

1. **Episodic Memory** (Events) β€” What happened, when, who participated, outcome
2. **Semantic Memory** (Stable Knowledge) β€” Facts, preferences, relationships, domain knowledge
3. **Cognitive Memory** (Patterns) β€” Behavioral patterns, decision criteria, communication style

### Cognitive Nexus

The underlying knowledge graph consists of:

- **Concept Nodes** β€” Entities with a type and name (e.g., `{type: "Person", name: "Alice"}`, `{type: "Preference", name: "dark_mode"}`)
- **Proposition Links** β€” Directed relationships between concepts (e.g., `(Alice, "prefers", dark_mode)`)

---

## Authentication

If `ED25519_PUBKEYS` is configured, protected endpoints require a Bearer token in the `Authorization` header.

If `ED25519_PUBKEYS` is empty/not provided, authentication is disabled and requests are accepted without signature verification.

```
Authorization: Bearer <base64_encoded_cose_sign1_token>
```

Management endpoints (`/v1/{space_id}/management/*`) and admin endpoints (`/admin/*`) still follow their role/scope checks when auth is enabled.

---

## API Reference

For complete endpoint and TypeScript schema details, see:
- `https://github.com/ldclabs/anda-brain/blob/main/anda_brain/API.md` (English)
- `https://github.com/ldclabs/anda-brain/blob/main/anda_brain/API_cn.md` (δΈ­ζ–‡)

### Content Negotiation

The API supports triple serialization. Set `Content-Type` and `Accept` headers accordingly:

- `application/json` β€” JSON (default)
- `application/cbor` β€” CBOR (binary, more compact)
- `text/markdown` β€” Markdown (raw text or formatted Markdown)

All responses are wrapped in an RPC envelope when using JSON or CBOR:

```json
{
  "result": { ... },
  "error": null
}
```

When `Accept: text/markdown` is used, the response is returned as raw text or a Markdown formatted string.

On error:

```json
{
  "result": null,
  "error": {
    "message": "error description",
    "data": { ... }
  }
}
```

#### Markdown Serialization Sample

If `Accept: text/markdown` is specified, the `result` field's content will be directly serialized as the response body.

**Request:**
```http
POST /v1/my_space_001/recall
Accept: text/markdown

What are Alice's preferences?
```

**Response (HTTP 200):**
```markdown
Alice has the following known preferences:
- **Dark mode** in all applications (confidence: 0.9, since 2025-01-15)
- **Email communication** preferred over phone calls (confidence: 0.8, since 2025-01-10)

Alice is currently working on **Project Aurora** and was last seen on 2025-01-15 discussing settings preferences.

Gaps:
- No information found about Alice's language preferences.
```

---

### Create Space

Create a new isolated memory space.

```
POST /admin/create_space
Authorization: Bearer <token>
Content-Type: application/json
```

**Request:**

```json
{
  "user": "<owner_principal_id>",
  "space_id": "my_space_001",
  "tier": 0
}
```

**Response:**

```json
{
  "result": { ... }
}
```

---

### Formation β€” Encode Conversations into Memory

Send conversation messages to be analyzed and encoded into the knowledge graph. The service extracts facts, preferences, relationships, events, and patterns, then stores them as structured knowledge.

Processing is asynchronous β€” the endpoint returns immediately with a conversation ID while encoding continues in the background. New submissions are queued and processed sequentially.

```
POST /v1/{space_id}/formation
Authorization: Bearer <token>
Content-Type: application/json
```

**Request:**

```json
{
  "messages": [
    {
      "role": "user",
      "content": "I prefer dark mode for all my apps. My timezone is UTC+8.",
      "name": "Alice"
    },
    {
      "role": "assistant",
      "content": "Got it! I've noted your preference for dark mode and UTC+8 timezone."
    }
  ],
  "context": {
    "counterparty": "alice_principal_id",
    "agent": "customer_bot_001",
    "source": "source_123",
    "topic": "settings"
  },
  "timestamp": "2026-03-09T10:30:00Z"
}
```

**Response:**

```json
{
  "result": { "conversation": 1, ... }
}
```

**Fields:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `messages` | `Message[]` | Yes | Conversation messages (role: `user` / `assistant` / `system`) |
| `context` | `InputContext` | No | Contextual metadata to help with encoding |
| `context.counterparty` | `string` | No | User identifier |
| `context.agent` | `string` | No | Calling agent identifier |
| `context.source` | `string` | No | Identifier of the source of the current interaction content |
| `context.topic` | `string` | No | Conversation topic |
| `timestamp` | `string` | Yes | ISO 8601 timestamp of the conversation |

**Tips for best results:**

- Include the `context` field whenever possible β€” it helps the encoder associate knowledge correctly
- Send complete conversation segments, not individual messages
- Include timestamps to enable proper temporal reasoning
- The `name` field in messages helps distinguish between multiple users in the same conversation

---

### Recall β€” Query Memory

Ask a natural language question and receive a synthesized answer drawn from the knowledge graph and conversation history.

```
POST /v1/{space_id}/recall
Authorization: Bearer <token>
Content-Type: application/json
```

**Request:**

```json
{
  "query": "What are Alice's preferences?",
  "context": {
    "counterparty": "alice_principal_id",
    "topic": "settings"
  }
}
```

**Response:**

```json
{
  "result": {
    "content": "Alice prefers dark mode for all applications and operates in the UTC+8 timezone.",
    ...
  }
}
```

Note: `result.content` is the primary contract. Additional fields may vary by model/runtime.

**Query examples:**

| Intent | Example query |
|--------|--------------|
| Entity lookup | "Who is Alice?" |
| Relationship | "Who does Alice work with?" |
| Attribute | "What are Alice's preferences?" |
| Event recall | "What happened in our last meeting?" |
| Domain exploration | "What do we know about Project Aurora?" |
| Pattern detection | "Does Alice prefer email or chat?" |
| Existence check | "Have we discussed the pricing strategy?" |

---

### Space Status

Get statistics and health information for a memory space.

```
GET /v1/{space_id}/info
Authorization: Bearer <token>
```

**Response:**

```json
{
  "result": {
    "space_id": "my_space_001",
    "owner": "principal_id",
    "db_stats": {
      "total_items": 150,
      "total_bytes": 524288
    },
    "concepts": 85,
    "propositions": 120,
    "conversations": 12,
    ...
  }
}
```

---

## Integration Pattern

A typical integration workflow for a business agent (use `brain.anda.ai` as the host):

### 1. Remember: Send conversations for memory encoding

After each meaningful conversation with a user, send the messages to Formation:

```bash
curl -sX POST https://brain.anda.ai/v1/my_space_001/formation \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [
      {"role": "user", "content": "I work at Acme Corp as a senior engineer."},
      {"role": "assistant", "content": "Nice to meet you! Noted that you are a senior engineer at Acme Corp."}
    ],
    "context": {"counterparty": "user_123", "agent": "onboarding_bot"},
    "timestamp": "2026-03-09T10:30:00Z"
  }'
```

### 2. Recall: Query memory before responding

Before generating a response, check if relevant memory exists:

```bash
curl -sX POST https://brain.anda.ai/v1/my_space_001/recall \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "Where does this user work and what is their role?",
    "context": {"counterparty": "user_123"}
  }'
```

---

## OpenClaw Integration

The [`anda-brain`](https://github.com/ldclabs/anda-brain/tree/main/anda-brain-openclaw) plugin integrates Anda Brain into [OpenClaw](https://openclaw.ai/) agents, providing automatic memory encoding and a `recall_memory` tool β€” no manual API calls needed.

### Prerequisites: Create a Brain Space (for cloud SaaS users)

Before installing the plugin, you need a `spaceId` and `spaceToken`:

1. Go to the **Anda Brain Console**: [https://anda.ai/brain]https://anda.ai/brain
2. Sign in and **create a new brain space** β€” you will get your `spaceId`.
3. In the space settings, **create an API Key** β€” this is your `spaceToken`.

> If you are self-hosting Anda Brain, create spaces via the admin API instead (see [Integration Pattern]#integration-pattern above).

### Install

1. Install the plugin package:
```bash
openclaw plugins install anda-brain
```

2. Update anda-brain configuration in `openclaw.json` with the `spaceId` and `spaceToken` obtained from the console:
```json
{
  "plugins": {
    "entries": {
      "anda-brain": {
        "enabled": true,
        "config": {
          "spaceId": "my_space_001",
          "spaceToken": "STxxxxx",
          "baseUrl": "https://brain.anda.ai" // or "http://localhost:8042" for self-hosted/local
        }
      }
    }
  }
}
```

3. Restart OpenClaw Gateway.
```sh
openclaw gateway restart
```

Required fields:

- `spaceId`: your Brain space ID (created at [anda.ai/brain]https://anda.ai/brain)
- `spaceToken`: your space API Key (created at [anda.ai/brain]https://anda.ai/brain)
- `baseUrl`: optional, defaults to `https://brain.anda.ai`; set this to your own deployment for self-hosted or local use

### What It Does

| Feature | Mechanism | Description |
|---------|-----------|-------------|
| **Memory encoding** | `agent_end` hook | After each agent turn, conversation messages are automatically sent to `POST /v1/{space_id}/formation` (fire-and-forget). |
| **Memory recall** | `recall_memory` tool | Registered as an agent tool; the LLM can call it with a natural language query to retrieve knowledge via `POST /v1/{space_id}/recall`. |

### Configuration Options

| Option | Type | Required | Default | Description |
|--------|------|----------|---------|-------------|
| `spaceId` | `string` | Yes | β€” | Memory space ID |
| `spaceToken` | `string` | Yes | β€” | Space token for API authentication |
| `baseUrl` | `string` | No | `https://brain.anda.ai` | Anda Brain service URL |
| `defaultContext` | `InputContext` | No | β€” | Default context included with every request (`counterparty`, `agent`, `source`, `topic`) |
| `formationTimeoutMs` | `number` | No | `30000` | Formation request timeout (ms) |
| `recallTimeoutMs` | `number` | No | `120000` | Recall request timeout (ms) β€” recall may take 10–100s |

### `recall_memory` Tool Parameters

The plugin registers a `recall_memory` tool that the LLM can invoke:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | `string` | Yes | Natural language question (e.g. "What are Alice's preferences?") |
| `context.counterparty` | `string` | No | Current user identifier |
| `context.agent` | `string` | No | Calling agent identifier |
| `context.topic` | `string` | No | Topic hint for disambiguation |

---

## Troubleshooting

| Symptom | Fix |
|---------|-----|
| `401 Unauthorized` | If auth is enabled (`ED25519_PUBKEYS` set), check Bearer token signature, `aud` (space ID), and required `scope` (`read`/`write`) |
| `404 Not Found` on space endpoints | Verify the `space_id` exists and the token `aud` matches the target space |
| Formation returns but nothing in memory | Formation is async β€” check space status after a few seconds; look at the conversation status |
| Recall seems empty or insufficient | Memory may not be encoded yet, or the query is too narrow; try broader phrasing and include `context` |
| Maintenance rejected | Only one maintenance cycle can run at a time per space; wait for the current one to finish |
| Empty recall for new space | Expected β€” a new space has no memory yet; send conversations via Formation first |

---

## Configuration Reference

The service is configured via CLI arguments and environment variables:

| Env Variable | Default | Description |
|--------------|---------|-------------|
| `LISTEN_ADDR` | `127.0.0.1:8042` | Listen address |
| `ED25519_PUBKEYS` | β€” | Comma-separated Base64-encoded Ed25519 public keys; if empty, API authentication is disabled |
| `MODEL_FAMILY` | `gemini` | Model family to use for encoding and recall (e.g., `gemini`, `anthropic`, `openai`) |
| `MODEL_API_KEY` | β€” | Google Gemini API key |
| `MODEL_API_BASE` | `https://generativelanguage.googleapis.com/v1beta/models` | Gemini API base URL |
| `MODEL_NAME` | `gemini-3-flash-preview` | LLM model for agents |
| `HTTPS_PROXY` | β€” | HTTPS proxy URL |
| `SHARDING_IDX` | `0` | Shard index for this instance |
| `MANAGERS` | β€” | Comma-separated manager principal IDs |

**Storage backends:**

| Backend | Command | Key Config |
|---------|---------|------------|
| In-memory (dev) | `cargo run -p anda_brain` | β€” |
| Local filesystem | `cargo run -p anda_brain -- local` | `LOCAL_DB_PATH` (default `./db`) |
| AWS S3 | `cargo run -p anda_brain -- aws` | `AWS_BUCKET`, `AWS_REGION` |