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

# Knowledge-Base Assistant

> Answer questions from your policies and handbooks: upload the files, fetch quotes with citations, and show the source.

> [!NOTE]
>
> **Status:** In Development · Playground demo coming soon.
> The recipe below is complete and runnable today on an Instance with documents enabled; only the hosted playground showcase is pending.

An assistant that answers from your own documents: an HR handbook, a returns policy, a security policy. Every answer comes with the passage it was drawn from and a way to open the original file, so people can check it.

## What you'll build

* **Upload** a set of policy and handbook files once, shared across your whole application
* **Answer** each question from the passages Synap returns, and nothing else
* **Cite** every answer with the document, section and page it came from
* **Show the source**: open the original file behind a citation
* **Update** a policy by uploading it again; the assistant serves the latest version

**Est. build time:** 30-40 minutes.

## When to use this recipe

Build this if:

* Your agent's knowledge lives in files rather than in conversations
* Everyone using the agent should see the same knowledge (company-wide policies, product docs)
* People need to verify an answer, not just trust it
* The documents change over time and the agent must follow

If the knowledge belongs to one person or one customer, upload at that scope instead; see [Choose a scope](#1-choose-a-scope).

## Architecture at a glance

```text theme={null}
policy files ──► memories.create ──► Synap (passages, versions, originals)
                                          │
question ──► context.fetch ───────────────┘
                 │
                 ▼
     passages + citations ──► your LLM ──► answer + sources
                                                  │
                          citation ──► documents.original ──► the file
```

The model only sees passages Synap returned, so the answer can be traced to a source.

## Stack

| Layer | Choice |
| - | - |
| **Synap SDK** | `maximem-synap` (Python) / `@maximem/synap-js-sdk` (TypeScript) |
| **LLM** | Any model; the recipe leaves the call to you (`ask_llm`) |
| **Files** | PDF, Word, Excel, PowerPoint, Markdown, text, CSV, HTML or JSON, up to 10 MB each |

## Prerequisites

* A Synap API key. See [Authentication](https://docs.maximem.ai/setup/authentication.md)
* Documents enabled on your Instance. Without them, an upload is refused
* **Python:** Python 3.11+. **TypeScript:** Node.js 20+

```bash theme={null}
export SYNAP_API_KEY=...
```

```bash Python theme={null}
pip install maximem-synap
```

```bash TypeScript theme={null}
npm install @maximem/synap-js-sdk
```

## Build it

### 1. Choose a scope

A document is filed at the scope you name when you upload it, the same way a memory is. Company-wide knowledge goes at **client scope**: send no `user_id` and no `customer_id`, and every user of your application can find it. Knowledge for one customer takes a `customer_id` on a B2B Instance, and knowledge for one person takes a `user_id`. See [Memory scopes](https://docs.maximem.ai/concepts/memory-scopes.md).

This recipe uses client scope, so the uploads and the fetch below carry no ids.

### 2. Upload the files

Give each file a stable `document_id`. It is how Synap knows a later upload is the same document.

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

FILES = {
    "hr-handbook": "docs/hr-handbook.pdf",
    "returns-policy": "docs/returns-policy.md",
    "security-policy": "docs/security-policy.docx",
}

sdk = MaximemSynapSDK()
await sdk.initialize()

keys = {}
for document_id, path in FILES.items():
    result = await sdk.memories.create(
        document=FilePart(path=path),
        document_id=document_id,
    )
    keys[document_id] = result.document_key
    print(document_id, result.version_status, result.processing_stage)
```

```typescript TypeScript theme={null}
import { SynapClient, filePart } from '@maximem/synap-js-sdk';

const FILES: Record<string, string> = {
  'hr-handbook': 'docs/hr-handbook.pdf',
  'returns-policy': 'docs/returns-policy.md',
  'security-policy': 'docs/security-policy.docx',
};

const sdk = new SynapClient();
await sdk.initialize();

const keys: Record<string, string> = {};
for (const [documentId, path] of Object.entries(FILES)) {
  const result = await sdk.memories.create({
    document: filePart({ path }),
    document_id: documentId,
  });
  keys[documentId] = result.document_key as string;
  console.log(documentId, result.version_status, result.processing_stage);
}
```

Synap works out each file's type from its content. You can also declare one, such as `document_type="policy"` (`document_type: 'policy'` in TypeScript, JavaScript 0.9.0 and later).

### 3. Wait until the files are searchable

Uploads return at once; reading and indexing happen in the background. A file can be found as soon as it is `searchable`.

```python Python theme={null}
for document_id, key in keys.items():
    while True:
        doc = await sdk.documents.get(key)
        stage = doc["processing_stage"]
        if stage in ("searchable", "processed"):
            break
        if stage == "failed":
            raise RuntimeError(f"{document_id}: {doc.get('failure_reason')}")
        await asyncio.sleep(2)
```

```typescript TypeScript theme={null}
for (const [documentId, key] of Object.entries(keys)) {
  for (;;) {
    const doc = await sdk.documents.get(key);
    const stage = doc['processing_stage'];
    if (stage === 'searchable' || stage === 'processed') break;
    if (stage === 'failed') throw new Error(`${documentId}: ${doc['failure_reason']}`);
    await new Promise((resolve) => setTimeout(resolve, 2000));
  }
}
```

### 4. Answer with citations

Fetch the passages for the question, hand only those to your model, and return the answer with the citations of the passages.

```python Python theme={null}
SYSTEM = (
    "Answer only from the numbered passages. Cite them like [1]. "
    "If they do not contain the answer, say you could not find it."
)

async def answer(question: str) -> dict:
    context = await sdk.client.context.fetch(search_query=[question], max_results=5)
    passages = context.passages or []
    if not passages:
        return {"answer": "I could not find that in our documents.", "sources": []}

    numbered = "\n\n".join(f"[{i}] {p['content']}" for i, p in enumerate(passages, 1))
    reply = await ask_llm(system=SYSTEM, user=f"{numbered}\n\nQuestion: {question}")

    sources = []
    for i, p in enumerate(passages, 1):
        c = p.get("citation") or {}
        sources.append({
            "n": i,
            "document_id": c.get("document_id"),
            "version": c.get("version"),
            "section": " > ".join(c.get("section_path") or []),
            "page": c.get("page"),
            "document_key": c.get("document_key"),   # absent when you may not open the original
        })
    return {"answer": reply, "sources": sources}
```

```typescript TypeScript theme={null}
type Passage = {
  content: string;
  citation?: {
    document_id?: string;
    document_key?: string;
    version?: number;
    section_path?: string[];
    page?: number;
  };
};

const SYSTEM =
  'Answer only from the numbered passages. Cite them like [1]. ' +
  'If they do not contain the answer, say you could not find it.';

export async function answer(question: string) {
  const context = await sdk.client.context.fetch({ search_query: [question], max_results: 5 });
  const passages = (context.passages ?? []) as Passage[];
  if (passages.length === 0) {
    return { answer: 'I could not find that in our documents.', sources: [] };
  }

  const numbered = passages.map((p, i) => `[${i + 1}] ${p.content}`).join('\n\n');
  const reply = await askLlm(SYSTEM, `${numbered}\n\nQuestion: ${question}`);

  const sources = passages.map((p, i) => ({
    n: i + 1,
    document_id: p.citation?.document_id,
    version: p.citation?.version,
    section: (p.citation?.section_path ?? []).join(' > '),
    page: p.citation?.page,
    document_key: p.citation?.document_key, // absent when you may not open the original
  }));
  return { answer: reply, sources };
}
```

`ask_llm` and `askLlm` stand for your own model call. Synap returns the citations; how you show them is yours to decide. See [Citations](https://docs.maximem.ai/concepts/citations.md) for every field.

### 5. Show the source

When a user clicks a source, open the original file of the version that was cited.

```python Python theme={null}
async def open_source(source: dict) -> bytes:
    if not source["document_key"]:
        raise PermissionError("This source cannot be opened from here")
    return await sdk.documents.original(source["document_key"], version=source["version"])
```

```typescript TypeScript theme={null}
async function openSource(source: { document_key?: string; version?: number }): Promise<Uint8Array> {
  if (!source.document_key || source.version === undefined) {
    throw new Error('This source cannot be opened from here');
  }
  return sdk.documents.original({ document_key: source.document_key, version: source.version });
}
```

`documents.original` returns the file's bytes: stream them to the browser or save them. It answers only for documents the caller may see, so a source without a `document_key` is shown as a citation only.

## Run & verify

```python theme={null}
result = await answer("How long do customers have to return an item?")
print(result["answer"])
for s in result["sources"]:
    print(s)
```

```text theme={null}
Customers can return any item within 30 days of delivery for a full refund [1].
{'n': 1, 'document_id': 'returns-policy', 'version': 1, 'section': 'Returns policy', 'page': None, 'document_key': '...'}
{'n': 2, 'document_id': 'returns-policy', 'version': 1, 'section': 'Returns policy > Refunds', 'page': None, 'document_key': '...'}
```

To see versions at work, edit `returns-policy.md`, upload it again with the same `document_id`, wait until it is searchable, and ask again: the answer follows the new text and the citation's `version` goes up by one.

## Customize / extend

* **One knowledge base per customer** → upload with `customer_id` and fetch with `sdk.customer.context.fetch(customer_id=...)` on a B2B Instance.
* **Only quotes from documents** → pass `kinds=["passage"]` (`kinds: ['passage']` in TypeScript) to the fetch to leave memories out.
* **Questions that need every match** ("list every policy that mentions travel") → see [Query and navigate documents as an agent](https://docs.maximem.ai/guides/agent-query-and-navigation).
* **Keep it current from a drive** → connect the source in the dashboard instead of uploading by hand.
* **Remove a document** → `sdk.documents.delete(...)` hides it from every fetch at once and can be restored for a while; see [Documents](https://docs.maximem.ai/concepts/documents.md).

## Troubleshooting

**The first question returns nothing**

* The upload is still being processed. Wait for `searchable`, as in step 3.
* Check that the fetch uses the scope the files were uploaded at. Files uploaded with a `user_id` are not found by a client-scope fetch.

**The upload is refused with `UnsupportedFormatError`**

* Documents are not enabled on your Instance, or the format is not one of the supported ones.

**The upload is refused with `InsufficientCreditsForDocumentError`**

* Your balance is below the document's estimate. The error carries `estimate_credits` and `balance_credits` (`estimateCredits` and `balanceCredits` in TypeScript).

**A source has no `document_key`**

* The caller is not allowed to open that original. The citation still names the document, version and section.

**The answer quotes an old version**

* Upload the new file with the same `document_id`, then wait until it is searchable. Until then the previous version is served.

## Related

* **Concepts:** [Documents](https://docs.maximem.ai/concepts/documents.md) · [Citations](https://docs.maximem.ai/concepts/citations.md) · [Memory scopes](https://docs.maximem.ai/concepts/memory-scopes.md)
* **Guides:** [Query and navigate documents as an agent](https://docs.maximem.ai/guides/agent-query-and-navigation) · [Shaping your MACA](https://docs.maximem.ai/guides/configuring-memory.md)
* **Reference:** [`memories.create`](https://docs.maximem.ai/sdk-reference/memories/create)


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