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

# customer.context.fetch

> Retrieve customer-scoped context: shared organizational knowledge, policies, and team-wide memories visible to every user within a customer.

> [!WARNING]
>
> **B2B only.** `customer.context.fetch` (`POST /v1/context/customer/fetch`) is
> available only on a B2B instance, that is one whose
> `user_context_isolation` is `strict`. On a B2C instance
> (`user_context_isolation: "equals_customer"`) there is no customer scope, the
> call is not available, and it is rejected with HTTP 400. Call
> `GET /api/v1/auth/whoami` to see which mode your instance is in: it returns
> `user_context_isolation`. On a B2C instance, fetch at user scope with
> [`user.context.fetch`](https://docs.maximem.ai/sdk-reference/context/user-fetch) instead.

```python Python theme={null}
await sdk.customer.context.fetch(
    customer_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,
    scope_path=None,
    response_shape="by_type",
)
```

```typescript TypeScript theme={null}
await sdk.customer.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. Works in any Python or Node 20+ process, including serverless functions.

Retrieve context scoped to a specific customer organization. Customer-scoped memories are visible to all users within that customer. This is useful for fetching shared organizational knowledge, company policies, and team-wide context.

### Parameters

**customer\_id** `string` *required*

The customer identifier to fetch context for. Always required, because this call is B2B-only: a B2C instance does not accept `customer_id` anywhere. See [B2C vs B2B](https://docs.maximem.ai/concepts/memory-scopes.md#b2c-vs-b2b-which-scopes-apply-to-you).

**conversation\_id** `string`

Optional conversation identifier. When provided, results are biased toward memories relevant to the active conversation. When supplied, it must be a valid UUID [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 customer memories. If omitted, returns the most recent and highest-confidence customer-scoped memories. 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`.

**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. 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 customer organization |
| `preference` | Customer organizational preferences |
| `episode` | Significant events within the customer organization |
| `emotion` | Sentiment and emotional context within the organization |
| `temporal_event` | Time-bound events (project deadlines, fiscal year, etc.) |

**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. 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`).

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

The level of your [scope ladder](https://docs.maximem.ai/concepts/scope-ladder.md) to read from, below the customer, for example `{"customer": "acme", "team": "payments"}`. Use the same customer as `customer_id`. Only needed when your ladder has a level between customer and user. Every level above the one you read from must be named. A path is refused (400) if it has a gap, if it reaches the user level (use [`user.context.fetch`](https://docs.maximem.ai/sdk-reference/context/user-fetch) for that), 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` 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. 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.

**metadata** `object`

Response metadata including `total_results`, `query_time_ms`, `tokens_used`, `scope`, and `mode`.

### Example

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

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

context = await sdk.customer.context.fetch(
    customer_id="cust_acme_corp",
    search_query=["project management tools", "engineering stack"],
    max_results=5,
    types=["fact", "preference"],
    mode="accurate",
)

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

```javascript JavaScript theme={null}
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.customer.context.fetch({
  customer_id: 'cust_acme_corp',
  search_query: ['project management tools', 'engineering stack'],
  max_results: 5,
  types: ['fact', 'preference'],
  mode: 'accurate',
});

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

```typescript TypeScript theme={null}
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.customer.context.fetch({
  customer_id: 'cust_acme_corp',
  search_query: ['project management tools', 'engineering stack'],
  max_results: 5,
  types: ['fact', 'preference'],
  mode: 'accurate',
});

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

```json Response theme={null}
{
  "facts": [
    {
      "id": "mem_cust_f1a2b3c4",
      "content": "Acme Corp uses Jira for project management and Slack for communication",
      "confidence": 0.94,
      "entities": [
        { "canonical_name": "Acme Corp", "type": "organization", "entity_id": "ent_acme001" }
      ],
      "source": {
        "ingestion_id": "ing_cust_7a8b9c0d",
        "document_type": "ai-chat-conversation",
        "document_created_at": "2025-01-12T14:30:00Z"
      },
      "relevance_score": 0.92,
      "scope": "customer"
    },
    {
      "id": "mem_cust_d5e6f7a8",
      "content": "Engineering team uses Python 3.11 and PostgreSQL for all services",
      "confidence": 0.91,
      "entities": [
        { "canonical_name": "Acme Corp Engineering", "type": "team", "entity_id": "ent_acme_eng" }
      ],
      "source": {
        "ingestion_id": "ing_cust_0a9b8c7d",
        "document_type": "document",
        "document_created_at": "2025-01-08T09:00:00Z"
      },
      "relevance_score": 0.88,
      "scope": "customer"
    }
  ],
  "preferences": [
    {
      "id": "mem_cust_b9c0d1e2",
      "content": "Team prefers detailed code reviews over quick approvals",
      "confidence": 0.87,
      "entities": [],
      "source": {
        "ingestion_id": "ing_cust_7a8b9c0d",
        "document_type": "ai-chat-conversation",
        "document_created_at": "2025-01-12T14:30:00Z"
      },
      "relevance_score": 0.79,
      "scope": "customer"
    }
  ],
  "episodes": [],
  "emotions": [],
  "metadata": {
    "total_results": 3,
    "query_time_ms": 187,
    "tokens_used": 456,
    "scope": {
      "customer_id": "cust_acme_corp",
      "client_id": "cli_a1b2c3d4e5f67890"
    },
    "mode": "accurate"
  }
}
```

> [!TIP]
>
> Customer-scoped memories take priority over client-scoped memories when they cover the same topic, following the [scope chain](https://docs.maximem.ai/concepts/memory-scopes.md) priority rules. To merge customer and client context in a single call, use [`sdk.context.fetch`](https://docs.maximem.ai/sdk-reference/context/fetch).

### 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.customer.context.fetch(
    customer_id="cust_acme",
    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.customer.context.fetch({
  customer_id: 'cust_acme',
  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` is not `"fast"` or `"accurate"`.
* `InvalidInputError`: when `precision_level` is not `"high"` or `"medium"`.
* `InvalidInputError`: when `response_shape` is not `"ranked"` or `"by_type"`.
* `InvalidInputError`: when the server refuses `scope_path` (see above).
* `CustomerIdNotAcceptedError`, a subclass of `InvalidInputError`: on a B2C instance, which has no customer scope (Python 0.5.12 and JavaScript 0.5.11 and later; in Python it is also a `ValueError`).
* `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.user.context.fetch`](https://docs.maximem.ai/sdk-reference/context/user-fetch): user-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.