> Full SurrealDB documentation index: https://surrealdb.com/docs/llms.txt

# Reflection

Synthesise insights from patterns across stored memories.

Reflection is a reasoning operation over the memory store. Unlike retrieval, which surfaces existing facts that match a query, reflection asks SurrealDB Agent Memory to examine a set of memories and draw conclusions from them - to reason about patterns, identify trends, and synthesise insights that do not exist as explicit stored attributes.

The result is a synthesised text insight backed by evidence citations. If `persist` is enabled, the synthesised insights are also stored as new experiential memory attributes, making them available to future queries.

## How it works

When you call `memory.reflect()`, SurrealDB Agent Memory:

1. Retrieves the memories most relevant to your query using hybrid retrieval, respecting scope.
2. Sends the retrieved evidence to an LLM with a synthesis prompt instructing it to reason over the material and surface patterns, risks, or insights.
3. Returns the synthesised text alongside the supporting memories.
4. If `persist=True`, asks the model to turn the insights into attributes, and writes them inside the caller's `memory:write` region. The model names the subject entity and picks each attribute's memory category.

Reflection is more expensive than retrieval - it always involves an LLM call - but it produces conclusions that no single stored attribute contains.

## Basic usage

```python
out = await memory.reflect(
    query="What patterns do you see in customer complaints this month?",
    persist=False)

print(out.reflection)   # synthesised insight text
print(out.evidence)     # list of supporting memory hits
```

```typescript
import { AgentMemory } from "@surrealdb/memory";

const memory = new AgentMemory({ context: "ctx_01jt4kx...", apiKey: "sp-..." });

const out = await memory.reflect(
    "What patterns do you see in customer complaints this month?",
    { persist: false });

console.log(out.reflection);
console.log(out.evidence);
```

### REST

```http
POST /api/v1/{context_id}/reflect
Content-Type: application/json

{
  "query": "What patterns do you see in customer complaints this month?",
  "persist": false
}
```

The request takes only `query` and `persist`. Any other field, such as `scope` or `model`, is ignored without an error: the evidence comes from the key's whole read region, and the model is the deployment default.

```json
{
  "reflection": "Three recurring patterns emerged across 47 complaint sessions this month…",
  "evidence": [
    "billing proration came up in 18 sessions",
    "search accuracy complaints clustered after the 3rd deployment"
  ],
  "persistedAttributes": [],
  "traceId": "mZrlXhKPuV1H9S1l"
}
```

## Persisting synthesised insights

Setting `persist=True` instructs SurrealDB Agent Memory to write the synthesised insights back to memory as new attributes. This makes the reflection available to future retrieval queries without repeating the synthesis LLM call.

```python
out = await memory.reflect(
    query="What does this user value most in a development tool?",
    persist=True)

print(out.reflection)
print(out.persisted_attributes)  # list of newly created attribute records
```

```typescript
const out = await memory.reflect(
    "What does this user value most in a development tool?",
    { persist: true });

console.log(out.reflection);
console.log(out.persistedAttributes);
```

When `persist=True`, the response includes **`persistedAttributes`** listing the attribute records that were written:

```json
{
  "reflection": "Alice consistently prioritises fast feedback loops…",
  "evidence": ["Alice mentioned keyboard shortcuts three times", "…"],
  "persistedAttributes": [
    {
      "id": "01k7e2q4xe",
      "entityId": "01k7e2q4xf",
      "key": "core_tool_values",
      "value": "Fast feedback loops, keyboard-driven workflows",
      "memoryCategory": "knowledge"
    }
  ],
  "traceId": "…"
}
```

Each persisted insight is stored on an entity of type `insight`, named by the model. `insight` is not one of the fixed entity types, so the entity is stored with type `other`. The attribute's memory category is the one the model chose, so its decay rate follows that category (for example 0.995 per day for `knowledge`). Persisted insights carry `source.kind = "reflect"`, are available immediately for retrieval, and appear in future profile requests under the section for their category.

## Permissions for persist

`persist=True` writes attributes, so it requires **`memory:write`** - and the write lands inside the caller's write region, never outside it. There is no persist-scope argument: the region the key holds is the region reflect can write to.

A key granted `memory:write` on `org/acme/*` can persist org-level insights drawn from across the whole org. A key granted only `org/acme/user/alice` persists at that path and below, however wide the evidence it reasoned over.

This prevents agents from writing to scopes they do not own. An agent operating for user A cannot persist insights visible to user B, even if the reflection was informed by shared org-level memory.

## Use cases

**Project risk analysis**: A project management agent reflects on all task and decision records for a project to identify risks the team has not explicitly surfaced.

```python
risks = await memory.reflect(
    query="What risks are present in this project that we haven't explicitly discussed?",
    persist=True)
```

**Sales pattern recognition**: A sales coaching agent reflects on call notes and outcome records to identify what approaches correlate with successful closes.

```python
patterns = await memory.reflect(
    query="What conversational patterns appear most often in deals that closed this quarter?",
    persist=True)
```

**Support gap identification**: A support agent reflects on unresolved queries to identify topics where the knowledge base is insufficient.

```python
gaps = await memory.reflect(
    query="Which questions did I fail to answer confidently this week, and what knowledge would have helped?",
    persist=True)
```

## Reflection versus retrieval

| | Retrieval (`memory.query`) | Reflection (`memory.reflect`) |
|---|---|---|
| Operation | Finds existing attributes matching a query | Reasons over retrieved attributes to produce new insights |
| LLM involvement | Only for query understanding and the `escalated` tier (HyDE rewrite) | Always |
| Output | Ranked list of stored facts | Synthesised insight text + evidence |
| Persist option | N/A - retrieval is read-only | Optional - writes new attributes |
| Cost | Low to medium | Higher - always incurs an LLM call |

Use retrieval when you need to surface known facts. Use reflection when you need to reason about patterns, draw conclusions, or produce summaries that span many individual memory records.
