> ## 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.

# conversation.context.fetch

> Fetch conversation-scoped context (facts, preferences, episodes) for a specific conversation.

```python Python theme={null}
await sdk.conversation.context.fetch(
    conversation_id: str,
    search_query: Optional[List[str]] = None,
    max_results: int = 10,
    types: Optional[List[str]] = None,
    mode: str = "fast",
    precision_level: str = "high",
    query_date: Optional[str] = None,
    max_results_per_query: Optional[int] = None,
    user_id: Optional[str] = None,
    customer_id: Optional[str] = None,
    scope_path: Optional[Dict[str, str]] = None,
    response_shape: str = "by_type",
) -> ContextResponse
```

```typescript TypeScript theme={null}
await sdk.conversation.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 (JavaScript 0.5.13 and later) or, in Python, the 5-minute response cache. Works in any Python or Node 20+ process, including serverless functions.

Retrieves the context Synap has built up for a single conversation: facts surfaced from earlier turns, user preferences, episodic memories, emotional cues, and temporal events. Use this to assemble grounding material before generating the next assistant turn.

Passing `user_id` (and `customer_id`) is strongly recommended: it scopes the in-process anticipation cache to that user so bundles prefetched for one user can never be served on another user's lookup.

### Parameters

**conversation\_id** `str` *required*

The conversation to fetch context for. Must be a valid UUID (e.g. `str(uuid.uuid4())`), the same id you used when [recording the conversation's messages](https://docs.maximem.ai/concepts/context-end-to-end.md#short-term-context).

**search\_query** `List[str]`

Optional list of query strings to bias retrieval. When omitted, Synap does not run a blank search: it returns the conversation state in `conversation_context`. A single fetch searches at most 5 queries; with more, the first five are searched. Every returned memory item carries `matched_queries`: the queries that found it, in the order you sent them. In JavaScript and TypeScript, read it as `matchedQueries`.

**max\_results** `int` (default: 10)

Maximum number of items to return per context type. The same limit applies when the anticipation cache answers the fetch.

**max\_results\_per\_query** `int`

How many items each search query may contribute when `search_query` holds more than one. `max_results` stays the ceiling on the whole response. This rule also applies to an anticipation-cache hit. Ignored with a single query. In JavaScript and TypeScript, pass it as `max_results_per_query` (or `maxResultsPerQuery`).

**types** `List[str]`

Context types to include. Defaults to all available types (facts, preferences, episodes, emotions, temporal events).

**mode** `str` (default: fast)

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

* `"fast"`: direct query, lower latency. Best for in-the-loop prompt assembly.
* `"accurate"`: LLM-enhanced queries, higher quality at higher latency. Best when you can afford the extra latency.

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

**precision\_level** `str` (default: high)

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

* `"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. 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. **Recommended.** |
| `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, so code that reads them keeps working. In JavaScript and TypeScript, pass it as `response_shape` (or `responseShape`).

**user\_id** `str`

External user id. Strongly recommended: scopes anticipation cache lookups to the right user and avoids deriving scope from a not-yet-written conversation row.

**customer\_id** `str`

External customer id, forwarded alongside `user_id` for the same scoping reason. On B2B, if you leave it out the server uses the one this conversation was recorded with. Not accepted on B2C. See [B2C vs B2B](https://docs.maximem.ai/concepts/memory-scopes.md#b2c-vs-b2b-which-scopes-apply-to-you).

**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"}`. Usually not needed: without one, the server uses the path this conversation's messages were first recorded with, and a user already placed at a level is reached by the ids alone. 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. Python 0.4.6 and later. JavaScript and TypeScript 0.5.10 and later, as `scope_path` (or `scopePath`).

### Returns

A `ContextResponse` containing the retrieved context.

**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** `List[Fact]`

Facts learned about the user during this conversation.

**preferences** `List[Preference]`

Stated or inferred preferences relevant to this conversation.

**episodes** `List[Episode]`

Episodic memories tied to this conversation.

**emotions** `List[Emotion]`

Detected emotional signals.

**temporal\_events** `List[TemporalEvent]`

Time-anchored events relevant to the conversation.

**conversation\_context** `Dict[str, Any]`

Compacted/summary context for this conversation, when available.

**metadata** `ResponseMetadata`

Correlation id, source (`cache`, `cloud` or `anticipation`), TTL, and retrieval timestamp.

### Example

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

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

# reuse the same conversation_id you recorded messages under
conversation_id = str(uuid.uuid4())

ctx = await sdk.conversation.context.fetch(
    conversation_id=conversation_id,
    search_query=["dinner plans", "dietary restrictions"],
    max_results=5,
    mode="fast",
    user_id="user_alice",
    customer_id="customer_acme",
)

for fact in ctx.facts:
    print(fact.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();

// reuse the same conversation_id you recorded messages under
let conversation_id = randomUUID();

const ctx = await sdk.conversation.context.fetch({
  conversation_id: conversation_id,
  search_query: ['dinner plans', 'dietary restrictions'],
  max_results: 5,
  mode: 'fast',
  user_id: 'user_alice',
  customer_id: 'customer_acme',
});

for (const fact of ctx.facts ?? []) {
  console.log(fact.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();

// reuse the same conversation_id you recorded messages under
let conversation_id = randomUUID();

const ctx = await sdk.conversation.context.fetch({
  conversation_id: conversation_id,
  search_query: ['dinner plans', 'dietary restrictions'],
  max_results: 5,
  mode: 'fast',
  user_id: 'user_alice',
  customer_id: 'customer_acme',
});

for (const fact of ctx.facts ?? []) {
  console.log(fact.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.conversation.context.fetch(
    conversation_id=conversation_id,
    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.conversation.context.fetch({
  conversation_id: conversationId,
  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 `conversation_id` is empty (Python 0.5.14 and later; all JavaScript versions).
* `InvalidConversationIdError`, a subclass of `InvalidInputError`: when `conversation_id` is not a valid UUID.
* `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. A missing key fails earlier, when the client is created (JavaScript) or initialized (Python).
* `NetworkTimeoutError`: the SDK could not reach Synap (a timeout, or a refused or dropped connection) after its retries. `ConnectionError` is the same class in both SDKs. JavaScript 0.5.13 and later; earlier JavaScript raised `ServiceUnavailableError` for a refused or dropped connection.

### See also

* [conversation.record\_message](https://docs.maximem.ai/sdk-reference/conversation/record-message.md)
* [conversation.context.compact](https://docs.maximem.ai/sdk-reference/conversation-context/compact.md)
* [conversation.context.get\_context\_for\_prompt](https://docs.maximem.ai/sdk-reference/conversation-context/get-context-for-prompt.md)


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