> ## Documentation Index
> Fetch the complete documentation index at: https://docs.maximem.ai/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Maximem Synap is a managed memory layer for AI agents: it ingests conversations and documents, extracts structured memory, and returns scoped context to the agent at retrieval time.
> The Python and JavaScript/TypeScript SDKs are the supported way to use Synap. Write integration code with SDK calls, not raw HTTP requests.
> Start with the Quickstart: https://docs.maximem.ai/getting-started/quickstart.md. Every SDK method is documented in the SDK reference: https://docs.maximem.ai/sdk-reference/overview.md.
> For requests about adding Vity memory to OpenClaw, Hermes, an MCP client, or a browser, start with the Vity Quickstart: https://docs.maximem.ai/vity/quickstart.md.

# user.context.fetch

> Retrieve user-scoped context: facts, preferences, episodes, and temporal events about a specific end user.

```python Python theme={null}
await sdk.user.context.fetch(
    user_id,
    conversation_id=None,
    search_query=None,
    max_results=10,
    types=None,
    mode="fast",
    precision_level="high",
    query_date=None,
    max_results_per_query=None,
    customer_id=None,
    context_mode="in-conversation",
    include_profile=True,
    last_n_conversations=1,
    scope_path=None,
    response_shape="by_type",
)
```

```typescript TypeScript theme={null}
await sdk.user.context.fetch(options?: FetchOptions)
```

REST One HTTPS request, unless the answer is already cached locally: in the cache the [anticipation stream](https://docs.maximem.ai/sdk-reference/instance/listen.md) fills or, in Python, the 5-minute response cache. A summary-mode call always goes to the server. Works in any Python or Node 20+ process, including serverless functions.

Fetch context scoped to a single end user. User-scoped memories capture personal facts, preferences, and history that the SDK has accumulated for this user across their conversations. Use this on the server before composing a prompt so the model can ground its response in what you already know about the person.

### Parameters

**user\_id** `string` *required*

The user identifier to fetch context for. An id you have not written memories for returns an empty result; it is not an error.

**conversation\_id** `string`

Optional conversation identifier. When provided, results are biased toward memories relevant to the active conversation and the SDK can inject periodic user summaries (every fifth fetch in a conversation) into the response. When supplied, it must be a valid UUID (e.g. `str(uuid.uuid4())`) [registered via `record_message`](https://docs.maximem.ai/concepts/context-end-to-end#short-term-context).

**search\_query** `string | string[]`

One or more search queries to find relevant user memories. If omitted, the response returns the user's profile in `profile` with empty memory lists when one exists. A user without a profile follows the normal retrieval path. A single fetch searches at most 5 queries; with more, the first five are searched and the response's `retrieval.warnings` says so. Send the rest in another fetch.

**max\_results** `integer`

Maximum number of memory items to return. Defaults to `10`. Maximum `50`. The same limit applies when the anticipation cache answers the fetch.

**max\_results\_per\_query** `integer`

How many items each search query may contribute when `search_query` holds more than one. Without it, a query with many strong matches can take every place and a query with a single weaker match gets none. `max_results` stays the ceiling on the whole response: three queries at `5` each under `max_results=10` return ten, not fifteen. The same allocation applies to an anticipation-cache hit. Ignored with a single query. Optional; when omitted, the best `max_results` items overall are returned. In JavaScript and TypeScript, pass it as `max_results_per_query` (or `maxResultsPerQuery`).

**types** `string[]`

Filter results to specific memory types. If omitted, all types are included.

| Value | Description |
| - | - |
| `fact` | Factual information about the user |
| `preference` | Stated or inferred user preferences |
| `episode` | Notable events from the user's history |
| `emotion` | Sentiment and emotional context |
| `temporal_event` | Time-bound events (deadlines, appointments, recurring dates) |

**mode** `string`

Retrieval mode that controls the speed-quality tradeoff: the retrieval axis (`fast` vs `accurate`) of [Retrieval Modes](https://docs.maximem.ai/concepts/retrieval-modes.md).

| Value | Description |
| - | - |
| `fast` | Vector search only. Lower latency. **Default.** |
| `accurate` | Full vector + graph + re-ranking. Higher quality, higher latency. |

For real per-mode latency on your instance, see **Dashboard → Usage**.

**precision\_level** `string`

Controls how precisely results are filtered before they're returned.

| Value | Description |
| - | - |
| `high` | Results go through an additional relevance-refinement pass before being returned. **Default.** |
| `medium` | Skips the refinement pass for faster responses. Recall isn't impacted (the same candidate memories are searched), but outputs are less precisely filtered. |

Independent of `mode`; combine with either `fast` or `accurate`. For real latency on your instance, see **Dashboard → Usage**.

**query\_date** `string`

The moment the question is being asked, for example `"2023-03-11"`. Synap resolves a time the question names ("in March", "two months ago") from that moment instead of from now, which matters when you replay a past conversation. Lenient: `"2023-03-11"`, `"2023/03/11 21:26"` and `"2023/03/11 (Sat) 21:26"` all parse, and anything unreadable silently falls back to now instead of failing the read. Not used in summary mode. Python 0.5.4 and later. JavaScript and TypeScript 0.5.4 and later, as `query_date` (or `queryDate`).

**response\_shape** `string`

How the memories come back. Pass `"ranked"`: you get one list, `items`, with the most relevant memory first across every type. Each item carries its type (`category`), its place (`rank`, from 1) and the score it was ranked by (`metadata.rank_score`). Quotes from your source conversations and documents come back as their own type, `"excerpts"`, placed by their own score. You can pass the list to your model as it is: there is nothing to merge or sort.

| Value | Description |
| - | - |
| `ranked` | One list, best first across types. |
| `by_type` | Five lists, one per memory type, which loses the order across types. The default today, kept so existing code is unaffected; the default moves to `ranked` in a later release, with notice. |

The typed lists (`facts`, `preferences`, ...) are filled either way, with one difference: the quotes from your source conversations and documents are in `excerpts` and not in `facts`, so code that reads only `facts` no longer sees them. The list is in rank order, but when the token budget is exceeded the cut keeps whole memory types in a fixed order, so it does not always keep the best items overall. In JavaScript and TypeScript, pass it as `response_shape` (or `responseShape`).

**customer\_id** `string`

Customer identifier the user belongs to. Required on B2B. **Not accepted on B2C**: passing it is rejected with HTTP 400. See [B2C vs B2B](https://docs.maximem.ai/concepts/memory-scopes.md#b2c-vs-b2b-which-scopes-apply-to-you). **Required for B2B instances.** On a B2C instance (`user_context_isolation: "equals_customer"`) it must be omitted: sending it returns HTTP 400.

**scope\_path** `dict[str, str]`

The level of your [scope ladder](https://docs.maximem.ai/concepts/scope-ladder.md) to read at, for example `{"customer": "acme", "team": "payments", "user": "dana"}`. Use the same customer and user as `customer_id` and `user_id`. Usually not needed: once a user has been placed at a level, by a write or a fetch that named the full path, the ids alone reach their whole chain. Send it the first time, or when the same user id sits under more than one level. Every level above the one you name must be named. A path is refused (400) if it has a gap, or if nested scoping is off or the ladder has not been accepted. In summary mode the path is checked but does not change what is read. Python 0.4.6 and later. JavaScript and TypeScript 0.4.4 and later, as `scope_path` (or `scopePath`).

**context\_mode** `string`

`"in-conversation"` (default) returns the usual item lists. `"conversation-summary"` instead returns a caller `profile` and summaries of the last `last_n_conversations` conversations: the call-start read for async integrations. In summary mode only `user_id`, `customer_id`, `include_profile` and `last_n_conversations` are used. The search parameters, `query_date` and `max_results_per_query` are ignored, and `scope_path` is checked but not used. `customer_id` is required on B2B.

**include\_profile** `boolean`

Summary mode only: include the caller profile. Defaults to `True`.

**last\_n\_conversations** `integer`

Summary mode only: number of previous conversations to summarize. Defaults to `1`. Range 0–20.

### Returns

A `ContextResponse` with the following fields:

**items** `array`

With `response_shape="ranked"`: every memory once, most relevant first across types. Each item has `id`, `rank` (1 is best), `category` (`facts`, `preferences`, `episodes`, `emotions`, `temporal_events` or `excerpts`), `content`, `metadata.rank_score` (higher is better), `confidence`, the date fields and `matched_queries`. Empty with `by_type`.

**excerpts** `array`

With `response_shape="ranked"`: the quotes from your source conversations and documents, as their own list. With `by_type` they are filed under `facts`.

**facts** `array`

Array of fact memories relevant to the query. Each includes `content`, `confidence`, `entities`, `source`, and `relevance_score`. Every memory item also carries `matched_queries`: the `search_query` strings that found it, in the order you sent them. A result of a subquery the server wrote names the query it came from. In JavaScript and TypeScript, read it as `matchedQueries`.

**preferences** `array`

Array of preference memories.

**episodes** `array`

Array of episode memories.

**emotions** `array`

Array of emotion memories.

**temporal\_events** `array`

Array of time-bound event memories.

**metadata** `object`

Response metadata including `correlation_id`, `source` (`cache` | `cloud` | `anticipation`), `ttl_seconds`, and `retrieved_at`.

**profile** `UserProfileModel | None`

Summary mode only: the caller profile (`attributes`, `overview`, `extras`, `meta`, plus `.raw`). `None` outside summary mode.

**conversations** `array | None`

Summary mode only: a list of `ConversationSummaryModel` (per-call `summary`, `classification`, `analysis`, `summary_status`, timestamps). `None` outside summary mode.

### Example

```python Python theme={null}
import uuid
from maximem_synap import MaximemSynapSDK

sdk = MaximemSynapSDK()  # reads SYNAP_API_KEY from your environment
await sdk.initialize()

context = await sdk.user.context.fetch(
    user_id="user_jane_doe",
    conversation_id=str(uuid.uuid4()),  # must be a valid UUID
    search_query=["dietary restrictions", "favorite restaurants"],
    max_results=5,
    types=["fact", "preference"],
    mode="accurate",
)

for fact in context.facts:
    print(f"[{fact.confidence:.2f}] {fact.content}")

for pref in context.preferences:
    print(f"prefers: {pref.content}")
```

```javascript JavaScript theme={null}
import { randomUUID } from 'node:crypto';
import { SynapClient } from '@maximem/synap-js-sdk';

const sdk = new SynapClient(); // reads SYNAP_API_KEY from your environment
await sdk.initialize();

const context = await sdk.user.context.fetch({
  user_id: 'user_jane_doe',
  conversation_id: randomUUID(),
  // must be a valid UUID
  search_query: ['dietary restrictions', 'favorite restaurants'],
  max_results: 5,
  types: ['fact', 'preference'],
  mode: 'accurate',
});

for (const fact of context.facts ?? []) {
  console.log(`[${(fact.confidence ?? 0).toFixed(2)}] ${fact.content}`);
}

for (const pref of context.preferences ?? []) {
  console.log(`prefers: ${pref.content}`);
}
```

```typescript TypeScript theme={null}
import { randomUUID } from 'node:crypto';
import { SynapClient } from '@maximem/synap-js-sdk';

const sdk = new SynapClient(); // reads SYNAP_API_KEY from your environment
await sdk.initialize();

const context = await sdk.user.context.fetch({
  user_id: 'user_jane_doe',
  conversation_id: randomUUID(),
  // must be a valid UUID
  search_query: ['dietary restrictions', 'favorite restaurants'],
  max_results: 5,
  types: ['fact', 'preference'],
  mode: 'accurate',
});

for (const fact of context.facts ?? []) {
  console.log(`[${(fact.confidence ?? 0).toFixed(2)}] ${fact.content}`);
}

for (const pref of context.preferences ?? []) {
  console.log(`prefers: ${pref.content}`);
}
```

### Ranked results

With `response_shape="ranked"`, read `items` in order. The most relevant memory comes first, whatever its type.

```python Python theme={null}
context = await sdk.user.context.fetch(
    user_id="user_jane_doe",
    search_query=["refund for a cancelled ride"],
    response_shape="ranked",
)

for item in context.items:
    print(item.rank, item.category, item.content)
```

```typescript TypeScript theme={null}
const context = await sdk.user.context.fetch({
  user_id: 'user_jane_doe',
  search_query: ['refund for a cancelled ride'],
  response_shape: 'ranked',
});

for (const item of context.items ?? []) {
  console.log(item['rank'], item['category'], item.content);
}
```

### Raises

* `InvalidInputError`: when `mode`, `precision_level` or `response_shape` is not an accepted value.
* `InvalidInputError`: when `user_id` is empty (Python 0.5.13 and later; all JavaScript versions).
* `InvalidInputError`: when `context_mode` is not `"in-conversation"` or `"conversation-summary"`, or `last_n_conversations` is not an integer from 0 to 20.
* `InvalidInputError`: on a B2B instance when `customer_id` is missing (the server refuses it with 400).
* `CustomerIdNotAcceptedError`, a subclass of `InvalidInputError`: when `customer_id` is passed on a B2C instance (Python 0.5.12 and JavaScript 0.5.11 and later).
* `AuthenticationError` with the message "SDK not initialized": when called before `await sdk.initialize()` (Python). JavaScript resolves the client's identity on the first call instead.
* `AuthenticationError`: when the API key is invalid or revoked.

### See also

* [`sdk.customer.context.fetch`](https://docs.maximem.ai/sdk-reference/context/customer-fetch): customer-scoped context
* [`sdk.client.context.fetch`](https://docs.maximem.ai/sdk-reference/context/client-fetch): organizational (client) context
* [`sdk.context.fetch`](https://docs.maximem.ai/sdk-reference/context/fetch): unified scope-chain fetch


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.