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

# Semantic Kernel

> Kernel plugin for memory search and storage, plus turn reporting and compacted history for Microsoft Semantic Kernel.

Add persistent, per-user memory to a Semantic Kernel application with a plugin. Both kernel functions (`search_memory` and `store_memory`) are auto-invokable, so the kernel can decide when to query or persist memories on its own. An agent thread and a filter report each turn and tool call to Synap, and send the model Synap's compaction in place of the earlier turns.

> [!NOTE]
>
> Requires Python 3.11+ and Semantic Kernel 1.37 or later.

## Overview

This guide shows how to add Synap to a Semantic Kernel application to build kernels that:

* Recall user-specific facts, preferences, and past conversations
* Persist new information surfaced during a conversation
* Auto-invoke memory functions when the model decides they are relevant
* Send the model Synap's compacted history instead of the earlier turns

| Export | SK interface | Purpose |
| - | - | - |
| `SynapPlugin` | Kernel plugin | Provides `search_memory` and `store_memory` kernel functions |
| `SynapAgentThread` | `ChatHistoryAgentThread` | Reports each user and assistant turn, and sends the model Synap's compaction once there is one |
| `attach_synap_filters` | Kernel filter | Reports each tool call and its result |
| `synap_auto_function_filter` | Filter function | The filter `attach_synap_filters` registers, for when you need the object |
| `SynapChatHistoryReducer` | `ChatHistoryReducer` | A `ChatHistory` whose `reduce()` swaps in Synap's compaction |
| `synap_st_chat_message` | Async factory | Builds a system message that carries Synap's short-term context |

## Setup

Install the package alongside Semantic Kernel:

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

```bash uv theme={null}
uv add maximem-synap-semantic-kernel semantic-kernel
# pip-compatible (existing venv): uv pip install maximem-synap-semantic-kernel semantic-kernel
```

Installing the package also installs `maximem-synap` (0.5.3 or later), `maximem-synap-integrations-common` (0.2.3 or later) and `semantic-kernel` (1.37 or later).

> [!NOTE]
>
> The pip package is `maximem-synap-semantic-kernel`, but the import drops the `maximem-` prefix and uses underscores: `from synap_semantic_kernel import ...`.

Configure your API key. Generate one from the [Synap Dashboard](https://synap.maximem.ai).

```bash .env theme={null}
SYNAP_API_KEY=synap_your_key_here
OPENAI_API_KEY=your-openai-api-key
```

Initialize the SDK once at application startup:

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

sdk = MaximemSynapSDK()
await sdk.initialize()
```

See [SDK Initialization](https://docs.maximem.ai/sdk/initialization.md) for the full lifecycle and configuration options.

## Basic integration

The smallest useful integration adds `SynapPlugin` to a kernel and invokes a prompt that references the plugin's functions:

```python theme={null}
# pip install maximem-synap-semantic-kernel semantic-kernel
from maximem_synap import MaximemSynapSDK
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from synap_semantic_kernel import SynapPlugin

sdk = MaximemSynapSDK()
await sdk.initialize()

kernel = Kernel()
kernel.add_service(OpenAIChatCompletion(service_id="default"))

kernel.add_plugin(
    SynapPlugin(sdk=sdk, user_id="alice", customer_id="acme"),
    plugin_name="synap",
)

result = await kernel.invoke_prompt(
    "{{synap.search_memory query='project priorities'}} What are my top priorities?"
)
```

The scoping triple (`user_id`, optional `customer_id`) is bound when you construct the plugin. The kernel functions only ever see `query`, `content`, and other model-supplied parameters. This prevents prompts (or prompt injections) from spoofing scope.

For automatic invocation (the kernel chooses when to call memory functions), enable auto function calling. See "Auto function calling" below.

***

## Core concepts

### SynapPlugin

`SynapPlugin` is a regular Semantic Kernel plugin class with `@kernel_function` annotated methods. Adding it to the kernel registers both functions under the plugin name you choose:

```python theme={null}
from synap_semantic_kernel import SynapPlugin

plugin = SynapPlugin(
    sdk=sdk,
    user_id="alice",
    customer_id="acme",   # optional, required for B2B instances
)

kernel.add_plugin(plugin, plugin_name="synap")
```

After registration, the kernel can invoke the two functions through prompt templating, manual invocation, or auto function calling.

> [!NOTE]
>
> The same function has two spellings. In prompt templates and manual invocation it is `synap.search_memory` (plugin, dot, function). In auto function calling, the name the model sees and must call is `synap-search_memory` (plugin, hyphen, function), so any instruction that tells the model which tool to use has to use the hyphenated form. The same applies to `synap-store_memory`.

### search\_memory

Function signature exposed to the kernel:

```text theme={null}
search_memory(query: str) -> str
```

Runs an accurate-mode fetch scoped to the bound user and customer, and returns the formatted context as a string suitable for direct interpolation into prompt templates. When nothing matches it returns `"No relevant memories found."`. **Search failures surface**: an SDK error is logged and raised as `SynapIntegrationError`.

### store\_memory

Function signature exposed to the kernel:

```text theme={null}
store_memory(content: str) -> str
```

Returns `"Memory stored (ingestion_id: ...)"` on success. **Store failures surface explicitly**: the function raises `SynapIntegrationError` so the kernel (and caller) know if persistence failed.

***

## Complete example: chat function with auto-invoked memory

The following kernel auto-invokes `synap-search_memory` and `synap-store_memory` whenever the model decides they are relevant. The application just adds messages to a `ChatHistory` and the kernel handles the rest:

```python theme={null}
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.contents import ChatHistory
from synap_semantic_kernel import SynapPlugin


def build_kernel(sdk, user_id: str, customer_id: str | None = None) -> Kernel:
    kernel = Kernel()
    kernel.add_service(OpenAIChatCompletion(service_id="default"))
    kernel.add_plugin(
        SynapPlugin(sdk=sdk, user_id=user_id, customer_id=customer_id),
        plugin_name="synap",
    )
    return kernel


async def chat(kernel: Kernel, history: ChatHistory, message: str) -> str:
    settings = kernel.get_prompt_execution_settings_from_service_id("default")
    settings.function_choice_behavior = FunctionChoiceBehavior.Auto()

    history.add_user_message(message)

    chat_service = kernel.get_service("default")
    response = await chat_service.get_chat_message_content(
        chat_history=history,
        settings=settings,
        kernel=kernel,
    )
    history.add_message(response)
    return str(response)


# Usage
kernel = build_kernel(sdk, user_id="alice", customer_id="acme")
history = ChatHistory(system_message=(
    "You are a personal assistant. Call synap-search_memory before answering "
    "questions about the user. Call synap-store_memory when they share a new fact."
))

await chat(kernel, history, "I just upgraded to the Pro plan.")
reply = await chat(kernel, history, "What plan am I on?")
# → "You're on the Pro plan."
```

Three things to notice in this pattern:

1. **`FunctionChoiceBehavior.Auto()` lets the model drive memory.** No prompt-template plumbing; the model calls the right function when it's the right time.
2. **Scope is per-kernel.** `build_kernel(...)` constructs a fresh kernel per user so concurrent requests cannot bleed scope.
3. **The system message is the policy.** Tell the model when to search and when to store; the plugin just enforces it.

***

## Advanced patterns

### Multi-tenant scoping

`SynapPlugin` accepts the standard scoping triple: `user_id` (required), `customer_id` (B2B instances only), optional `conversation_id`. `customer_id` is required on B2B Synap instances and **not accepted** on B2C (single-tenant) ones, where a call carrying it is rejected with HTTP 400. See [Memory Scopes](https://docs.maximem.ai/concepts/memory-scopes.md).

```python theme={null}
# User-scoped only
plugin = SynapPlugin(sdk=sdk, user_id="alice")

# Organization-scoped (user sees org-shared memories too)
plugin = SynapPlugin(sdk=sdk, user_id="alice", customer_id="acme-corp")
```

For multi-tenant services, build the plugin (and kernel) per request rather than sharing one across users.

### Prompt-template invocation

Outside of auto function calling, you can interpolate plugin calls directly in prompt templates:

```python theme={null}
result = await kernel.invoke_prompt(
    "Context: {{synap.search_memory query='dietary preferences'}}\n"
    "Question: What should I order for dinner?"
)
```

This pattern is useful when you want deterministic recall (the function *always* runs) rather than letting the model decide.

### Report turns and use Synap's compaction

The plugin gives the model tools. To report the conversation itself, and to send the model Synap's compaction, use `SynapAgentThread` and `attach_synap_filters` with a `ChatCompletionAgent`:

```python theme={null}
from semantic_kernel.agents import ChatCompletionAgent
from synap_semantic_kernel import SynapAgentThread, SynapPlugin, attach_synap_filters

kernel = build_kernel(sdk, user_id="alice", customer_id="acme")
attach_synap_filters(
    kernel, sdk, conversation_id=conversation_id, user_id="alice", customer_id="acme",
)

agent = ChatCompletionAgent(
    kernel=kernel,
    name="Assistant",
    instructions="You are a personal assistant.",
)
thread = SynapAgentThread(
    sdk, conversation_id=conversation_id, user_id="alice", customer_id="acme",
)

reply = await agent.get_response(messages="Where is my order?", thread=thread)

# Ends the Synap session for this conversation as well.
await thread.delete()
```

`conversation_id` and `user_id` are required on the thread and on the filter. Use the same ids on both so the turns and the tool calls land in one conversation. Make `conversation_id` a UUID: Synap rejects any other value when it reads the compacted conversation.

* **Turns.** The thread reports each user and assistant message. A message that carries a tool call is one lap of the function-calling loop, not the end of the turn, so it is not reported as a turn.
* **Tool calls and results.** The filter reports the call before the tool runs and the result after, with the same call id, so anticipation sees what the agent did. A tool result is usually your own customer's data and it leaves your process.
* **Compaction.** The agent reads its history through the thread. Once Synap has compacted the conversation, the model is sent Synap's compaction block (in `<synap_conversation_history>` tags) and the turns after it, in place of every turn before the current one. The current turn is untouched. Before the first compaction, or if Synap cannot answer, the model is sent Semantic Kernel's own messages. Semantic Kernel's own reducers stay in place as the fallback.

You do not call `listen()`. The first turn opens the real-time stream. If it cannot open, each turn is written over REST instead, never both; tool calls and reasoning exist only on the stream and are dropped in that case. Set `SYNAP_AUTO_LISTEN=false` to stay on REST, or open the stream yourself and the integration uses it as is. See [gRPC vs REST](https://docs.maximem.ai/concepts/grpc-vs-rest.md#framework-integrations).

By default the thread's history is a `SynapChatHistoryReducer`, which Synap's compaction replaces turns in. If you pass your own `chat_history` to `SynapAgentThread`, it stays as it is: the model is still sent Synap's compaction in place of the earlier turns, but your history is not rewritten. Outside an agent thread, call `await history.reduce()` on a `SynapChatHistoryReducer` before each model call to get the same replacement.

### Add the compaction to a system message

`synap_st_chat_message` is the lighter option for a plain chat-completion loop. It returns an async factory that builds a system message from Synap's short-term context and your own prompt:

```python theme={null}
import uuid
from semantic_kernel.contents import ChatHistory
from synap_semantic_kernel import synap_st_chat_message

conversation_id = str(uuid.uuid4())

get_system_message = synap_st_chat_message(
    sdk, conversation_id, system="You are a helpful agent.",
)

history = ChatHistory()
system_message = await get_system_message(history)
if system_message is not None:
    history.add_message(system_message)
history.add_user_message("Where is my order?")
```

The factory fetches Synap's short-term context for the conversation, which includes the recent turns, wraps it in `<synap_short_term_context>` tags and places it above your `system` text. Pass the history you are about to send: when it already holds user or assistant turns, the factory returns only your `system` text, so the turns are not sent twice. That makes it the right fit for a loop that starts from an empty history, for example after a restart. `conversation_id` is required and must be a UUID.

### Failure semantics

The plugin and the reporting pieces fail differently:

* **The plugin raises.** `search_memory` and `store_memory` log the error and raise `SynapIntegrationError`, so a failed search is never mistaken for an empty memory and a failed store is never mistaken for a stored one.
* **Reporting never raises.** `SynapAgentThread` updates the thread's own history first and then reports, so a Synap problem cannot cost you a message. The filter and the reducer log and carry on.
* **No compaction, or an error, leaves the history alone.** The model is sent the messages Semantic Kernel built.
* **`synap_st_chat_message` falls back by default.** On an SDK error it returns your `system` text. Pass `on_error="raise"` to get `SynapIntegrationError` instead.

***

## Going further

* [Patterns overview](https://docs.maximem.ai/patterns/overview.md): reusable memory patterns across frameworks.
* [Cookbook overview](https://docs.maximem.ai/cookbook/overview.md): end-to-end worked examples.

***

## Next steps

> [card] [Microsoft Agent Framework](https://docs.maximem.ai/integrations/microsoft-agent.md)
>
> Context and history providers for MAF agents.

> [card] [OpenAI Agents](https://docs.maximem.ai/integrations/openai-agents.md)
>
> Function tools for the OpenAI Agents SDK.

> [card] [Context Fetch](https://docs.maximem.ai/sdk/context-fetch.md)
>
> The retrieval API behind `search_memory`: modes, scopes, and response shapes.

> [card] [Memory Scopes](https://docs.maximem.ai/concepts/memory-scopes.md)
>
> How `user_id` and `customer_id` interact across reads and writes.


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