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

# Smolagents

> Synap memory tools, a step recorder and compacted history for Hugging Face Smolagents.

Give a [Smolagents](https://github.com/huggingface/smolagents) `CodeAgent` or `ToolCallingAgent` persistent memory through Synap. Smolagents keeps its own fixed step log with no pluggable memory backend, so Synap plugs into the extension points it *does* expose: `@tool` functions, `step_callbacks`, the method that builds the model's messages, and static `instructions`.

> [!NOTE]
>
> Requires Python 3.11+ and `smolagents>=1.26`.

## Overview

Surfaces mapped onto Smolagents' own extension points. Adopt only the ones you need.

| Surface | Smolagents extension point | Purpose |
| - | - | - |
| `create_synap_tools` | `@tool` | Explicit `search_memory` / `store_memory` the model can call |
| `synap_step_callbacks` | `step_callbacks` | Report each run to Synap: the turns, tool calls, tool results and reasoning. It also attaches the compacted history |
| `create_synap_recorder` | `step_callbacks={MemoryStep: ...}` | The bare callback behind `synap_step_callbacks`, when you build the mapping yourself |
| `attach_synap_history` | `write_memory_to_messages` | Send the model Synap's compaction in place of the agent's earlier steps |
| `synap_st_instructions` | `CodeAgent(instructions=...)` | Fold Synap's compaction into the agent's instructions once, for an agent with no recorder |

All of them take an already-constructed `MaximemSynapSDK`. Your app owns the SDK and its credentials.

## Setup

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

```bash uv theme={null}
uv add maximem-synap-smolagents smolagents
```

Installing the package also installs `maximem-synap` (0.5.3 or later) and `maximem-synap-integrations-common` (0.2.3 or later). Set `SYNAP_API_KEY` in your environment; `MaximemSynapSDK()` reads it.

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

## Basic integration

Give the agent memory tools it can call. Because `CodeAgent` writes its actions as Python, `search_memory` / `store_memory` compose naturally into the code it generates.

```python theme={null}
import asyncio
from smolagents import CodeAgent, InferenceClientModel
from maximem_synap import MaximemSynapSDK
from synap_smolagents import create_synap_tools

sdk = MaximemSynapSDK()
asyncio.run(sdk.initialize())  # required: without it every Synap call fails

agent = CodeAgent(
    model=InferenceClientModel(),
    tools=create_synap_tools(sdk, user_id="alice", customer_id="acme"),
)
agent.run("What did we decide about the rollout?")
```

## Core concepts

### create\_synap\_tools

Returns `search_memory` and `store_memory` as Smolagents `@tool` functions. `search_memory` reads Synap's long-term layer and returns formatted context; `store_memory` ingests a fact for future recall. Reads degrade to a not-found message; the write raises `SynapIntegrationError` so a failed store is observable.

### synap\_step\_callbacks

`synap_step_callbacks` returns the `step_callbacks` mapping that reports each run to Synap. Pass it straight to the agent:

```python theme={null}
import uuid
from smolagents import CodeAgent, InferenceClientModel
from synap_smolagents import synap_step_callbacks

conversation_id = str(uuid.uuid4())  # one UUID per conversation, reused across runs

agent = CodeAgent(
    model=InferenceClientModel(),
    tools=[],
    step_callbacks=synap_step_callbacks(
        sdk, user_id="alice", conversation_id=conversation_id, customer_id="acme"
    ),
)
agent.run("What did we decide about the rollout?")
```

The callback is registered for `MemoryStep`, the base class of every step, so it receives planning steps, action steps and the final answer. Smolagents calls a callback for the step's class and its base classes, so registering for `ActionStep` alone would skip planning steps and the `FinalAnswerStep`. Use `synap_step_callbacks` and the registration is right by construction.

| Smolagents step | What Synap receives |
| - | - |
| The agent's task | A user turn |
| `PlanningStep.plan`, and each action's `model_output` | A reasoning step |
| `ActionStep.tool_calls` | A tool call for each, with its id and arguments |
| `ActionStep.observations` | A tool result |
| The final answer | An assistant turn |

You do not call `listen()` yourself. The first report opens the gRPC stream. The stream gets up to 10 seconds to open. If it cannot open, the user and assistant turns are written over REST instead, never both, and the stream is tried once more a few seconds later, then no more than once a minute. Reasoning, tool calls and tool results exist only on the stream, so they are dropped while it is down. The REST write and the compaction lookup both need `conversation_id` to be a UUID. A stream you opened yourself is used as is. To keep the recorder on REST, set `SYNAP_AUTO_LISTEN=false`. See [gRPC vs REST](https://docs.maximem.ai/concepts/grpc-vs-rest.md).

Three details to know:

* **The user turn comes from `agent.task`.** Smolagents never passes the task to a step callback, so the recorder reads `agent.task` and reports it once per run, at the end of the first step rather than before it. Pass `report_user_task=False` and write the turn yourself with `record_turn` from `synap_integrations_common` if you need it earlier.
* **Parallel tool calls share one result.** `ToolCallingAgent` merges every tool's output for a step into one `observations` string. A step with a single call reports its result under that call's id. A step with several reports the merged text with no id, because attributing it to one call would be a guess.
* **Tool results leave your process.** A tool result is usually your own customer's data. Synap uses it only as an anticipation hint and never stores it as a long-term memory. Pass `report_tool_results=False` to stop them from being reported.

The turns reach long-term memory through the conversation: Synap extracts from the turns it holds. The recorder does not ingest each step as a separate document unless you pass `ingest_steps=True`, which also extracts the agent's intermediate thoughts and, a second time, its final answer. Leave it off unless you want the step-by-step reasoning remembered.

`create_synap_recorder(sdk, user_id, conversation_id, ...)` returns the bare callback with the same options, for when you build the `step_callbacks` mapping yourself. Register it for `MemoryStep`:

```python theme={null}
from smolagents.memory import MemoryStep
from synap_smolagents import create_synap_recorder

step_callbacks = {
    MemoryStep: create_synap_recorder(
        sdk, user_id="alice", conversation_id=conversation_id
    )
}
```

### Synap's compaction replaces the agent's earlier steps

`write_memory_to_messages` is where Smolagents turns its system prompt and every memory step into the model's messages, and every model call goes through it. `attach_synap_history` wraps it on one agent. Once Synap has compacted the conversation, the model sees the compaction block (in `<synap_conversation_history>` tags), the turns recorded after it, and the current task with its steps, in place of the earlier steps in `agent.memory`. Until then, and whenever Synap cannot answer, the messages pass through untouched. `agent.memory` itself is never edited, and Synap is read once per run, not once per step.

The recorder attaches it for you on the first step it sees (`compact_history=True` is the default). That is after the first step of the first run, because Smolagents has no hook before a model call. To cover the first step of a resumed conversation too, attach it yourself right after you build the agent:

```python theme={null}
from synap_smolagents import attach_synap_history

attach_synap_history(agent, sdk, conversation_id)
```

It is safe to call twice, and returns whether the agent is now wrapped.

### synap\_st\_instructions

Smolagents' `instructions` is a static string, so Synap's compaction is folded into it once at construction, inside `<synap_short_term_context>` tags. Nothing is added until Synap has compacted the conversation. It is a snapshot, so use it only for an agent without the recorder: with the recorder, `attach_synap_history` sends the live compaction and the turns after it, and `instructions` is not needed.

```python theme={null}
from synap_smolagents import synap_st_instructions

agent = CodeAgent(
    model=InferenceClientModel(),
    tools=[],
    instructions=synap_st_instructions(
        sdk, conversation_id=conversation_id,
        instructions="You are a concise, friendly assistant.",
    ),
)
```

`conversation_id` is required. Empty context is a no-op; SDK failures are swallowed by default (`on_error="fallback"`), or set `on_error="raise"` for strict environments.

## Complete example: memory-augmented CodeAgent

```python theme={null}
import asyncio
import uuid
from smolagents import CodeAgent, InferenceClientModel
from maximem_synap import MaximemSynapSDK
from synap_smolagents import create_synap_tools, synap_step_callbacks

sdk = MaximemSynapSDK()
asyncio.run(sdk.initialize())  # required: without it every Synap call fails

conversation_id = str(uuid.uuid4())  # one UUID per conversation

agent = CodeAgent(
    model=InferenceClientModel(),
    tools=create_synap_tools(sdk, user_id="alice", customer_id="acme"),
    instructions="You are a concise, friendly assistant.",
    step_callbacks=synap_step_callbacks(
        sdk, user_id="alice", conversation_id=conversation_id, customer_id="acme"
    ),
)
agent.run("Remind me what plan I'm on and my open ticket.")
```

The tools let the model search and store on demand. The callbacks report the run and, once Synap has compacted the conversation, send the model Synap's compaction instead of the earlier steps.

## Advanced patterns

### Synchronous framework, async SDK

Smolagents runs synchronously and its tools do not support `async`, so every surface bridges to the async Synap SDK internally (via the shared `run_async` helper), on one background loop that stays open for the life of the process. Call `agent.run` as usual; initialize the SDK once with `asyncio.run(sdk.initialize())` (or `await sdk.initialize()` in async code) before the first run.

### Error policy

* **The `search_memory` tool** degrades: a Synap blip returns a not-found message.
* **The `store_memory` tool** raises `SynapIntegrationError` on failure (model-driven, user-initiated).
* **The recorder logs and never raises.** It runs inside the agent loop, in a `finally` with no surrounding try/except, so a raising callback would abort the whole run; a failed report, history lookup or ingest is logged and swallowed, and Smolagents carries on with its own messages.

## Going further

* **Scoping.** `user_id` and `customer_id` flow straight to Synap; per-user isolation and B2C/B2B scope are derived server-side from the ids you pass.

## Next steps

> [card] [SDK: Ingestion](https://docs.maximem.ai/sdk/ingestion.md)
>
> How `memories.create` extraction differs from conversation recording.

> [card] [Integrations overview](https://docs.maximem.ai/integrations/overview.md)
>
> Every framework Synap plugs into.


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