Skip to content

The agent that grows with you

refactor(plugins/memory): mem0 — table-driven setup prompts, tool dispatch, compact backend

Teknium87a450145c6b
diff --git a/plugins/memory/mem0/__init__.py b/plugins/memory/mem0/__init__.py
index ea871c44cc4..9bd5a9ca496 100644
--- a/plugins/memory/mem0/__init__.py
+++ b/plugins/memory/mem0/__init__.py
@@ -1,33 +1,12 @@
"""Mem0 memory plugin — MemoryProvider interface.
-Server-side LLM fact extraction, semantic search, and automatic deduplication
-via the Mem0 Platform API (cloud) or OSS (self-hosted) via Memory.
-
-Original PR #2933 by kartik-mem0, adapted to MemoryProvider ABC.
-
-Configuration
--------------
-Secret (lives in $HERMES_HOME/.env or the environment):
- MEM0_API_KEY — Mem0 Platform API key (required for platform mode)
- MEM0_HOST — Base URL of a self-hosted Mem0 server. When set, the
- plugin talks to that server directly over HTTP
- (X-API-Key auth) instead of the cloud API.
-
-Behavioral settings (live in $HERMES_HOME/mem0.json, set via `hermes memory
-setup`):
- mode — Backend mode: "platform" (default) or "oss"
- host — Self-hosted Mem0 server URL (alt: MEM0_HOST env var).
- When set, routes to the self-hosted HTTP backend.
- user_id — Canonical user identifier. When set, it is applied
- uniformly across every gateway (CLI, Telegram, Slack,
- Discord, …) so the same human gets one merged memory
- store. When unset, the gateway-native id (e.g. Telegram
- numeric id, Discord snowflake) is used instead.
- agent_id — Agent identifier (default: hermes)
-
-The matching MEM0_MODE / MEM0_USER_ID / MEM0_AGENT_ID environment variables are
-still read as a backward-compatible fallback, but mem0.json is the canonical
-home for these non-secret settings.
+Server-side LLM fact extraction, semantic search and deduplication via the Mem0
+Platform API (cloud), a self-hosted Mem0 server (MEM0_HOST, HTTP), or OSS Memory.
+Secrets live in $HERMES_HOME/.env (MEM0_API_KEY, MEM0_HOST); behavioral settings
+in $HERMES_HOME/mem0.json via `hermes memory setup`: mode ("platform"|"oss"), host,
+user_id (canonical id across every gateway so one human gets one merged store;
+unset → gateway-native id), agent_id. MEM0_MODE/MEM0_USER_ID/MEM0_AGENT_ID env
+vars remain a backward-compatible fallback.
"""
from __future__ import annotations
@@ -38,6 +17,7 @@ import logging
import os
import threading
import time
+from pathlib import Path
from typing import Any, Dict, List
from agent.memory_provider import MemoryProvider
@@ -46,44 +26,36 @@ from tools.registry import tool_error
logger = logging.getLogger(__name__)
-# Circuit breaker: after this many consecutive failures, pause API calls
-# for _BREAKER_COOLDOWN_SECS to avoid hammering a down server.
-_BREAKER_THRESHOLD = 5
-_BREAKER_COOLDOWN_SECS = 120
-_PREFETCH_WAIT_SECS = 3
-
+# Circuit breaker: after _BREAKER_THRESHOLD consecutive failures, pause API
+# calls for _BREAKER_COOLDOWN_SECS to avoid hammering a down server.
+_BREAKER_THRESHOLD, _BREAKER_COOLDOWN_SECS, _PREFETCH_WAIT_SECS = 5, 120, 3
_CLIENT_ERROR_TYPES = ("MemoryNotFoundError", "ValidationError")
-
-# Sentinel returned when neither MEM0_USER_ID nor a gateway-native id is
-# available. Treated as "no operator-configured user_id" by initialize() so
-# that legacy mem0.json files written by the setup wizard (which historically
-# wrote this exact placeholder) still allow gateway-native ids to flow
-# through instead of silently overriding them with the placeholder.
+# Placeholder user_id. initialize() treats it as "no operator-configured user_id"
+# so legacy mem0.json files written by the wizard don't override gateway-native ids.
_DEFAULT_USER_ID = "hermes-user"
def _is_client_error(exc: Exception) -> bool:
"""True for user-caused errors (bad ID, not found) that should NOT trip circuit breaker."""
- etype = type(exc).__name__
- if etype in _CLIENT_ERROR_TYPES:
- return True
err_str = str(exc).lower()
- return "404" in err_str or "not found" in err_str or "valid uuid" in err_str
+ return type(exc).__name__ in _CLIENT_ERROR_TYPES or any(s in err_str for s in ("404", "not found", "valid uuid"))
-# ---------------------------------------------------------------------------
-# Config
-# ---------------------------------------------------------------------------
+def _read_mem0_json(config_path: Path) -> dict:
+ """Best-effort read of mem0.json; missing/corrupt file -> {}."""
+ if config_path.exists():
+ try:
+ return json.loads(config_path.read_text(encoding="utf-8"))
+ except Exception:
+ pass
+ return {}
-def _load_config() -> dict:
- """Load config from env vars, with $HERMES_HOME/mem0.json overrides.
- Environment variables provide defaults; mem0.json (if present) overrides
- individual keys. This avoids a silent failure when the JSON file exists
- but is missing fields like ``api_key`` that the user set in ``.env``.
- """
+def _load_config() -> dict:
+ """Env vars provide defaults; $HERMES_HOME/mem0.json overrides individual keys.
+ Layering avoids a silent failure when the JSON file exists but lacks fields
+ like ``api_key`` that the user set in ``.env``."""
from hermes_constants import get_hermes_home
-
config = {
"mode": os.environ.get("MEM0_MODE", "platform"),
"api_key": get_secret("MEM0_API_KEY", ""),
@@ -91,22 +63,12 @@ def _load_config() -> dict:
"agent_id": os.environ.get("MEM0_AGENT_ID", "hermes"),
"oss": {},
}
- # Only carry user_id when the operator explicitly configured one (env or
- # mem0.json). An absent key tells initialize() to fall back to the
- # gateway-native id from kwargs instead of overriding it with a placeholder.
- env_user_id = os.environ.get("MEM0_USER_ID")
- if env_user_id:
- config["user_id"] = env_user_id
-
- config_path = get_hermes_home() / "mem0.json"
- if config_path.exists():
- try:
- file_cfg = json.loads(config_path.read_text(encoding="utf-8"))
- config.update({k: v for k, v in file_cfg.items()
- if v is not None and v != ""})
- except Exception:
- pass
-
+ # Only carry user_id when explicitly configured so initialize() can fall
+ # back to the gateway-native id.
+ if os.environ.get("MEM0_USER_ID"):
+ config["user_id"] = os.environ["MEM0_USER_ID"]
+ file_cfg = _read_mem0_json(get_hermes_home() / "mem0.json")
+ config.update({k: v for k, v in file_cfg.items() if v is not None and v != ""})
return config
@@ -114,77 +76,58 @@ def _load_config() -> dict:
# Tool schemas
# ---------------------------------------------------------------------------
-SEARCH_SCHEMA = {
- "name": "mem0_search",
- "description": (
- "Search the user's memories by meaning; returns facts ranked by "
- "relevance. Use this before answering any question that may depend on "
- "what you know about the user (preferences, facts, history, people, "
- "projects, past decisions). For multi-part or multi-hop questions, "
- "call it several times — vary the wording and run follow-up searches "
- "on what earlier results reveal; one search is rarely enough."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "query": {"type": "string", "description": "What to search for."},
- "top_k": {"type": "integer", "description": "Max results (default: 10, max: 50)."},
- "rerank": {"type": "boolean", "description": "Rerank results for relevance (default: false, platform mode only)."},
- },
- "required": ["query"],
- },
-}
-
-ADD_SCHEMA = {
- "name": "mem0_add",
- "description": (
- "Store a durable fact about the user, verbatim (no LLM extraction). "
- "Call this the moment the user states a lasting preference, correction, "
- "decision, or personal detail worth recalling on future turns — don't "
- "wait to be asked to remember. Skip transient chit-chat and facts you've "
- "already stored."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "content": {"type": "string", "description": "The fact to store."},
- },
- "required": ["content"],
- },
-}
-
-UPDATE_SCHEMA = {
- "name": "mem0_update",
- "description": (
- "Replace the text of an existing memory by its ID (take the ID from a "
- "mem0_search result). Use when a stored fact has changed "
- "or was wrong — correct it in place instead of adding a duplicate."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "memory_id": {"type": "string", "description": "Memory UUID to update."},
- "text": {"type": "string", "description": "New text content."},
- },
- "required": ["memory_id", "text"],
- },
-}
-
-DELETE_SCHEMA = {
- "name": "mem0_delete",
- "description": (
- "Delete a memory by its ID (take the ID from a mem0_search "
- "result). Use when a stored fact is obsolete or the user asks you to "
- "forget it; prefer mem0_update if the fact merely changed."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "memory_id": {"type": "string", "description": "Memory UUID to delete."},
- },
- "required": ["memory_id"],
+def _schema(name: str, description: str, properties: dict, required: list[str]) -> dict:
+ return {"name": name, "description": description, "parameters": {"type": "object", "properties": properties, "required": required}}
+
+
+def _param(type_: str, description: str) -> dict:
+ return {"type": type_, "description": description}
+
+
+SEARCH_SCHEMA = _schema(
+ "mem0_search",
+ "Search the user's memories by meaning; returns facts ranked by "
+ "relevance. Use this before answering any question that may depend on "
+ "what you know about the user (preferences, facts, history, people, "
+ "projects, past decisions). For multi-part or multi-hop questions, "
+ "call it several times — vary the wording and run follow-up searches "
+ "on what earlier results reveal; one search is rarely enough.",
+ {
+ "query": _param("string", "What to search for."),
+ "top_k": _param("integer", "Max results (default: 10, max: 50)."),
+ "rerank": _param("boolean", "Rerank results for relevance (default: false, platform mode only)."),
},
-}
+ ["query"],
+)
+
+ADD_SCHEMA = _schema(
+ "mem0_add",
+ "Store a durable fact about the user, verbatim (no LLM extraction). "
+ "Call this the moment the user states a lasting preference, correction, "
+ "decision, or personal detail worth recalling on future turns — don't "
+ "wait to be asked to remember. Skip transient chit-chat and facts you've "
+ "already stored.",
+ {"content": _param("string", "The fact to store.")},
+ ["content"],
+)
+
+UPDATE_SCHEMA = _schema(
+ "mem0_update",
+ "Replace the text of an existing memory by its ID (take the ID from a "
+ "mem0_search result). Use when a stored fact has changed "
+ "or was wrong — correct it in place instead of adding a duplicate.",
+ {"memory_id": _param("string", "Memory UUID to update."), "text": _param("string", "New text content.")},
+ ["memory_id", "text"],
+)
+
+DELETE_SCHEMA = _schema(
+ "mem0_delete",
+ "Delete a memory by its ID (take the ID from a mem0_search "
+ "result). Use when a stored fact is obsolete or the user asks you to "
+ "forget it; prefer mem0_update if the fact merely changed.",
+ {"memory_id": _param("string", "Memory UUID to delete.")},
+ ["memory_id"],
+)
# ---------------------------------------------------------------------------
@@ -192,33 +135,19 @@ DELETE_SCHEMA = {
# ---------------------------------------------------------------------------
class Mem0MemoryProvider(MemoryProvider):
- """Mem0 memory with server-side extraction and semantic search.
-
- Supports Platform API (cloud) and OSS (self-hosted) modes via MEM0_MODE.
- """
+ """Mem0 memory with server-side extraction and semantic search (platform, self-hosted or OSS)."""
def __init__(self):
- self._config = None
- self._backend = None
- self._mode = "platform"
- self._api_key = ""
- self._host = ""
- self._user_id = _DEFAULT_USER_ID
- self._agent_id = "hermes"
+ self._config = self._backend = None
+ self._mode, self._api_key, self._host = "platform", "", ""
+ self._user_id, self._agent_id = _DEFAULT_USER_ID, "hermes"
self._rerank_default = False
self._channel = "cli" # gateway channel name (cli/telegram/discord/...)
- self._sync_thread = None
- self._prefetch_thread = None
- self._prefetch_query = ""
- self._prefetch_result = ""
- self._prefetch_done = False
- # Circuit breaker state
- self._consecutive_failures = 0
- self._breaker_open_until = 0.0
- self._breaker_lock = threading.Lock()
- self._sync_lock = threading.Lock()
- self._prefetch_lock = threading.Lock()
- self._atexit_registered = False
+ self._sync_thread = self._prefetch_thread = None
+ self._prefetch_query = self._prefetch_result = ""
+ self._prefetch_done = self._atexit_registered = False
+ self._consecutive_failures, self._breaker_open_until = 0, 0.0 # circuit breaker state
+ self._breaker_lock, self._sync_lock, self._prefetch_lock = threading.Lock(), threading.Lock(), threading.Lock()
@property
def name(self) -> str:
@@ -226,32 +155,22 @@ class Mem0MemoryProvider(MemoryProvider):
def is_available(self) -> bool:
cfg = _load_config()
- mode = cfg.get("mode", "platform")
- if mode == "oss":
+ if cfg.get("mode", "platform") == "oss":
return bool(cfg.get("oss", {}).get("vector_store"))
# Platform needs an api_key; self-hosted needs a host (api_key optional
# when the server runs with AUTH_DISABLED).
return bool(cfg.get("api_key") or cfg.get("host"))
def save_config(self, values, hermes_home):
- """Write config to $HERMES_HOME/mem0.json."""
- import json
- from pathlib import Path
+ """Merge-write config to $HERMES_HOME/mem0.json."""
+ from utils import atomic_json_write
config_path = Path(hermes_home) / "mem0.json"
- existing = {}
- if config_path.exists():
- try:
- existing = json.loads(config_path.read_text(encoding="utf-8"))
- except Exception:
- pass
+ existing = _read_mem0_json(config_path)
existing.update(values)
- from utils import atomic_json_write
atomic_json_write(config_path, existing, mode=0o600)
def get_config_schema(self):
- cfg = _load_config()
- mode = cfg.get("mode", "platform")
- api_key_required = mode != "oss"
+ api_key_required = _load_config().get("mode", "platform") != "oss"
return [
{"key": "api_key", "description": "Mem0 Platform API key", "secret": True, "required": api_key_required, "env_var": "MEM0_API_KEY", "url": "https://app.mem0.ai"},
{"key": "host", "description": "Self-hosted Mem0 server URL (leave blank for cloud)", "required": False, "env_var": "MEM0_HOST"},
@@ -264,17 +183,17 @@ class Mem0MemoryProvider(MemoryProvider):
from ._setup import post_setup
post_setup(hermes_home, config)
+ def _vs_provider(self, default: str) -> str:
+ """Configured OSS vector-store provider name (for error hints)."""
+ return self._config.get("oss", {}).get("vector_store", {}).get("provider", default)
+
def _create_backend(self):
- # Lazy-install the mem0 SDK on demand before either backend imports
- # it. ensure() honors security.allow_lazy_installs (default true) and,
- # on a sealed Docker venv, redirects the install to the durable
- # target. On failure we fall through so the import inside the backend
- # produces the canonical error, captured below.
+ # Lazy-install the mem0 SDK before either backend imports it. ensure() honors
+ # security.allow_lazy_installs and redirects sealed Docker venvs to the durable
+ # target; on failure the backend import raises the canonical error, captured below.
try:
from tools.lazy_deps import ensure as _lazy_ensure
_lazy_ensure("memory.mem0", prompt=False)
- except ImportError:
- pass
except Exception:
pass
try:
@@ -306,8 +225,7 @@ class Mem0MemoryProvider(MemoryProvider):
if self._mode == "oss":
err_str = str(exc).lower()
if "connection" in err_str or "refused" in err_str or "timeout" in err_str:
- vs = self._config.get("oss", {}).get("vector_store", {})
- msg += f" (check that {vs.get('provider', 'vector store')} is running)"
+ msg += f" (check that {self._vs_provider('vector store')} is running)"
return msg
def _record_success(self):
@@ -316,18 +234,12 @@ class Mem0MemoryProvider(MemoryProvider):
def _record_failure(self):
with self._breaker_lock:
- self._consecutive_failures += 1
- count = self._consecutive_failures
- if count >= _BREAKER_THRESHOLD:
+ self._consecutive_failures = count = self._consecutive_failures + 1
+ tripped = count >= _BREAKER_THRESHOLD
+ if tripped:
self._breaker_open_until = time.monotonic() + _BREAKER_COOLDOWN_SECS
- else:
- count = 0
- if count >= _BREAKER_THRESHOLD:
- hint = ""
- if self._mode == "oss":
- vs = self._config.get("oss", {}).get("vector_store", {})
- provider = vs.get("provider", "unknown")
- hint = f" Check that your {provider} vector store is running and reachable."
+ if tripped:
+ hint = f" Check that your {self._vs_provider('unknown')} vector store is running and reachable." if self._mode == "oss" else ""
logger.warning(
"Mem0 circuit breaker tripped after %d consecutive failures. "
"Pausing API calls for %ds.%s",
@@ -339,30 +251,16 @@ class Mem0MemoryProvider(MemoryProvider):
self._mode = self._config.get("mode", "platform")
self._api_key = self._config.get("api_key", "")
self._host = self._config.get("host", "")
- # Resolution order for user_id:
- # 1. Operator-configured MEM0_USER_ID (env or $HERMES_HOME/mem0.json) —
- # the canonical principal, applied across every gateway so the same
- # human gets one merged memory store.
- # 2. Gateway-native id from kwargs (Telegram numeric id, Discord
- # snowflake, etc.) — preserves per-platform isolation when no
- # override is configured.
- # 3. Hardcoded fallback _DEFAULT_USER_ID (CLI with no auth).
- # The literal _DEFAULT_USER_ID string is treated as unset so users who
- # ran the setup wizard with the suggested default still get gateway-
- # native ids instead of being silently bucketed together.
+ # user_id precedence: operator-configured (env/mem0.json) > gateway-native id
+ # from kwargs > _DEFAULT_USER_ID. The literal placeholder counts as unset so
+ # wizard users still get gateway-native ids instead of being bucketed together.
configured = self._config.get("user_id")
- if configured == _DEFAULT_USER_ID:
- configured = None
- self._user_id = configured or kwargs.get("user_id") or _DEFAULT_USER_ID
+ self._user_id = (None if configured == _DEFAULT_USER_ID else configured) or kwargs.get("user_id") or _DEFAULT_USER_ID
self._agent_id = self._config.get("agent_id", "hermes")
- # Persisted rerank preference (setup wizard / mem0.json). Used as the
- # DEFAULT for mem0_search when the model doesn't pass ``rerank``
- # explicitly; per-call args still win. Platform-only feature — other
- # backends accept-and-ignore the flag.
+ # Persisted rerank preference: DEFAULT for mem0_search when the model doesn't
+ # pass ``rerank``; per-call args win. Platform-only; other backends ignore it.
_rr = self._config.get("rerank", False)
- self._rerank_default = (
- _rr.lower() in ("true", "1", "yes") if isinstance(_rr, str) else bool(_rr)
- )
+ self._rerank_default = _rr.lower() in ("true", "1", "yes") if isinstance(_rr, str) else bool(_rr)
self._channel = kwargs.get("platform") or "cli"
self._backend = self._create_backend()
if self._backend and not self._atexit_registered:
@@ -370,30 +268,18 @@ class Mem0MemoryProvider(MemoryProvider):
self._atexit_registered = True
def _read_filters(self) -> Dict[str, Any]:
- # Scoped to user_id only — by design — so recall surfaces memories
- # written from any gateway/agent under this principal. Writes attach
- # agent_id (and metadata.channel) so per-agent / per-channel views are
- # still possible at query time when needed; reads default to the wider
- # cross-agent recall.
+ # Scoped to user_id only — by design — so recall surfaces memories from any
+ # gateway/agent under this principal; writes attach agent_id and metadata.channel
+ # (dashboard per-channel filtering) so narrower views remain possible at query time.
return {"user_id": self._user_id}
def _write_metadata(self) -> Dict[str, Any]:
- # Tag every write with the gateway channel so the dashboard can offer
- # per-channel filtered views without coupling identity to the channel.
return {"channel": self._channel} if self._channel else {}
def system_prompt_block(self) -> str:
- # Mirror the precedence in _create_backend (oss > host > platform) so
- # the label always names the backend that actually runs. Checking
- # ``host`` first here would mislabel an ``oss``+``host`` config as
- # self-hosted HTTP even though OSS wins the routing.
- if self._mode == "oss":
- mode_label = "OSS (self-hosted)"
- elif self._host:
- mode_label = "self-hosted (HTTP API)"
- else:
- mode_label = "platform (cloud API)"
- # Rerank is a Mem0 Platform feature only.
+ # Mirror _create_backend precedence (oss > host > platform) so the label names
+ # the backend that actually runs. Rerank is a Mem0 Platform feature only.
+ mode_label = "OSS (self-hosted)" if self._mode == "oss" else "self-hosted (HTTP API)" if self._host else "platform (cloud API)"
rerank_note = " Rerank is available on search." if (self._mode == "platform" and not self._host) else ""
return (
"# Mem0 Memory\n"
@@ -418,31 +304,25 @@ class Mem0MemoryProvider(MemoryProvider):
with self._prefetch_lock:
if self._prefetch_query != query or not self._prefetch_done:
return None
- result = self._prefetch_result
- self._prefetch_result = ""
- self._prefetch_done = False
+ result, self._prefetch_result, self._prefetch_done = self._prefetch_result, "", False
return result
def _start_prefetch(self, query: str) -> None:
- if not query or self._backend is None or self._is_breaker_open():
- return
backend = self._backend
+ if not query or backend is None or self._is_breaker_open():
+ return
with self._prefetch_lock:
- if self._prefetch_query == query:
- if self._prefetch_done:
- return
- if self._prefetch_thread and self._prefetch_thread.is_alive():
- return
- self._prefetch_query = query
- self._prefetch_result = ""
- self._prefetch_done = False
+ # Same query already answered or still in flight: don't restart it.
+ if self._prefetch_query == query and (
+ self._prefetch_done or (self._prefetch_thread and self._prefetch_thread.is_alive())
+ ):
+ return
+ self._prefetch_query, self._prefetch_result, self._prefetch_done = query, "", False
def _run():
body = ""
try:
- results = backend.search(
- query, filters=self._read_filters(), top_k=10, rerank=False,
- )
+ results = backend.search(query, filters=self._read_filters(), top_k=10, rerank=False)
lines = [r.get("memory", "") for r in (results or []) if r.get("memory")]
if lines:
body = "## Mem0 Memory\n" + "\n".join(f"- {l}" for l in lines)
@@ -470,11 +350,8 @@ class Mem0MemoryProvider(MemoryProvider):
thread = self._prefetch_thread if self._prefetch_query == query else None
if thread:
thread.join(timeout=_PREFETCH_WAIT_SECS)
- cached = self._consume_prefetch_result(query)
- if cached is not None:
- return cached
# Slow backend: skip injection; mem0_search tool remains the backstop.
- return ""
+ return self._consume_prefetch_result(query) or ""
def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:
"""Send the turn to Mem0 for server-side fact extraction (non-blocking)."""
@@ -486,17 +363,8 @@ class Mem0MemoryProvider(MemoryProvider):
if backend is None:
return
try:
- messages = [
- {"role": "user", "content": user_content},
- {"role": "assistant", "content": assistant_content},
- ]
- backend.add(
- messages,
- user_id=self._user_id,
- agent_id=self._agent_id,
- infer=True,
- metadata=self._write_metadata(),
- )
+ messages = [{"role": "user", "content": user_content}, {"role": "assistant", "content": assistant_content}]
+ backend.add(messages, user_id=self._user_id, agent_id=self._agent_id, infer=True, metadata=self._write_metadata())
self._record_success()
except Exception as e:
self._record_failure()
@@ -514,99 +382,86 @@ class Mem0MemoryProvider(MemoryProvider):
def get_tool_schemas(self) -> List[Dict[str, Any]]:
return [SEARCH_SCHEMA, ADD_SCHEMA, UPDATE_SCHEMA, DELETE_SCHEMA]
+ # -- tool handlers -------------------------------------------------------
+
+ def _tool_search(self, args: dict) -> str:
+ query = args.get("query", "")
+ if not query:
+ return tool_error("Missing required parameter: query")
+ try:
+ top_k = max(1, min(int(args.get("top_k", 10)), 50))
+ rerank_raw = args.get("rerank", self._rerank_default)
+ rerank = rerank_raw.lower() not in ("false", "0", "no") if isinstance(rerank_raw, str) else bool(rerank_raw)
+ results = self._backend.search(query, filters=self._read_filters(), top_k=top_k, rerank=rerank)
+ self._record_success()
+ if not results:
+ return json.dumps({"result": "No relevant memories found."})
+ items = [{"id": r.get("id"), "memory": r.get("memory", ""), "score": r.get("score", 0)} for r in results]
+ return json.dumps({"results": items, "count": len(items)})
+ except Exception as e:
+ if not _is_client_error(e):
+ self._record_failure()
+ return tool_error(self._format_error("Search failed", e))
+
+ def _tool_add(self, args: dict) -> str:
+ content = args.get("content", "")
+ if not content:
+ return tool_error("Missing required parameter: content")
+ try:
+ result = self._backend.add(
+ [{"role": "user", "content": content}],
+ user_id=self._user_id, agent_id=self._agent_id, infer=False, metadata=self._write_metadata(),
+ )
+ self._record_success()
+ event_id = result.get("event_id") if isinstance(result, dict) else None
+ # Cloud add is async (server-side extraction); OSS and self-hosted store synchronously.
+ msg = "Fact stored." if (self._mode == "oss" or self._host) else "Fact queued for storage."
+ return json.dumps({"result": msg, "event_id": event_id})
+ except Exception as e:
+ self._record_failure()
+ return tool_error(self._format_error("Failed to store", e))
+
+ def _tool_by_id(self, args: dict, required: tuple[str, ...], label: str, method: str) -> str:
+ """Shared update/delete shape: required-param check, then backend.<method>(*values)."""
+ values = [args.get(k, "") for k in required]
+ for k, v in zip(required, values):
+ if not v:
+ return tool_error(f"Missing required parameter: {k}")
+ try:
+ result = getattr(self._backend, method)(*values)
+ self._record_success()
+ return json.dumps(result)
+ except Exception as e:
+ if _is_client_error(e):
+ return tool_error(f"Memory not found: {values[0]}")
+ self._record_failure()
+ return tool_error(self._format_error(label, e))
+
+ def _tool_update(self, args: dict) -> str:
+ return self._tool_by_id(args, ("memory_id", "text"), "Update failed", "update")
+
+ def _tool_delete(self, args: dict) -> str:
+ return self._tool_by_id(args, ("memory_id",), "Delete failed", "delete")
+
+ _TOOL_HANDLERS = {
+ "mem0_search": _tool_search,
+ "mem0_add": _tool_add,
+ "mem0_update": _tool_update,
+ "mem0_delete": _tool_delete,
+ }
+
def handle_tool_call(self, tool_name: str, args: dict, **kwargs) -> str:
if self._backend is None:
err = getattr(self, "_init_error", "unknown error")
- hint = ""
- if self._mode == "oss":
- vs = self._config.get("oss", {}).get("vector_store", {})
- provider = vs.get("provider", "vector store")
- hint = f" Check that {provider} is running and reachable."
+ hint = f" Check that {self._vs_provider('vector store')} is running and reachable." if self._mode == "oss" else ""
return json.dumps({"error": f"Mem0 backend not initialized: {err}.{hint}"})
-
if self._is_breaker_open():
- msg = "Mem0 temporarily unavailable (multiple consecutive failures). Will retry automatically."
- if self._mode == "oss":
- vs = self._config.get("oss", {}).get("vector_store", {})
- msg += f" Check that your {vs.get('provider', 'vector store')} is running."
- return json.dumps({"error": msg})
-
- if tool_name == "mem0_search":
- query = args.get("query", "")
- if not query:
- return tool_error("Missing required parameter: query")
- try:
- top_k = max(1, min(int(args.get("top_k", 10)), 50))
- rerank_raw = args.get("rerank", getattr(self, "_rerank_default", False))
- if isinstance(rerank_raw, str):
- rerank = rerank_raw.lower() not in ("false", "0", "no")
- else:
- rerank = bool(rerank_raw)
- results = self._backend.search(query, filters=self._read_filters(), top_k=top_k, rerank=rerank)
- self._record_success()
- if not results:
- return json.dumps({"result": "No relevant memories found."})
- items = [{"id": r.get("id"), "memory": r.get("memory", ""),
- "score": r.get("score", 0)} for r in results]
- return json.dumps({"results": items, "count": len(items)})
- except Exception as e:
- if not _is_client_error(e):
- self._record_failure()
- return tool_error(self._format_error("Search failed", e))
-
- elif tool_name == "mem0_add":
- content = args.get("content", "")
- if not content:
- return tool_error("Missing required parameter: content")
- try:
- result = self._backend.add(
- [{"role": "user", "content": content}],
- user_id=self._user_id,
- agent_id=self._agent_id,
- infer=False,
- metadata=self._write_metadata(),
- )
- self._record_success()
- event_id = result.get("event_id") if isinstance(result, dict) else None
- # Cloud add is async (server-side extraction); OSS and self-hosted store synchronously.
- msg = "Fact stored." if (self._mode == "oss" or self._host) else "Fact queued for storage."
- return json.dumps({"result": msg, "event_id": event_id})
- except Exception as e:
- self._record_failure()
- return tool_error(self._format_error("Failed to store", e))
-
- elif tool_name == "mem0_update":
- memory_id = args.get("memory_id", "")
- text = args.get("text", "")
- if not memory_id:
- return tool_error("Missing required parameter: memory_id")
- if not text:
- return tool_error("Missing required parameter: text")
- try:
- result = self._backend.update(memory_id, text)
- self._record_success()
- return json.dumps(result)
- except Exception as e:
- if _is_client_error(e):
- return tool_error(f"Memory not found: {memory_id}")
- self._record_failure()
- return tool_error(self._format_error("Update failed", e))
-
- elif tool_name == "mem0_delete":
- memory_id = args.get("memory_id", "")
- if not memory_id:
- return tool_error("Missing required parameter: memory_id")
- try:
- result = self._backend.delete(memory_id)
- self._record_success()
- return json.dumps(result)
- except Exception as e:
- if _is_client_error(e):
- return tool_error(f"Memory not found: {memory_id}")
- self._record_failure()
- return tool_error(self._format_error("Delete failed", e))
-
- return tool_error(f"Unknown tool: {tool_name}")
+ hint = f" Check that your {self._vs_provider('vector store')} is running." if self._mode == "oss" else ""
+ return json.dumps({"error": f"Mem0 temporarily unavailable (multiple consecutive failures). Will retry automatically.{hint}"})
+ handler = self._TOOL_HANDLERS.get(tool_name)
+ if handler is None:
+ return tool_error(f"Unknown tool: {tool_name}")
+ return handler(self, args)
def _shutdown_backend(self):
try:
diff --git a/plugins/memory/mem0/_backend.py b/plugins/memory/mem0/_backend.py
index 09da2078158..930214958a1 100644
--- a/plugins/memory/mem0/_backend.py
+++ b/plugins/memory/mem0/_backend.py
@@ -6,46 +6,51 @@ from abc import ABC, abstractmethod
from typing import Any
+def _add_kwargs(user_id: str, agent_id: str, infer: bool, metadata: dict | None) -> dict[str, Any]:
+ kwargs: dict[str, Any] = {"user_id": user_id, "agent_id": agent_id, "infer": infer}
+ if metadata:
+ kwargs["metadata"] = metadata
+ return kwargs
+
+
+def _unwrap_results(response: Any) -> list:
+ """Normalize API response — extract results list from dict or pass through."""
+ if isinstance(response, dict):
+ return response.get("results", [])
+ return response if isinstance(response, list) else []
+
+
class Mem0Backend(ABC):
- """Unified interface over Platform (MemoryClient) and OSS (Memory) backends."""
+ """Unified interface over Platform (MemoryClient), self-hosted (HTTP) and OSS (Memory) backends.
+
+ update()/delete() are template methods: subclasses implement the raw
+ ``_update``/``_delete`` calls and the base wraps the uniform result dict.
+ """
@abstractmethod
- def search(self, query: str, *, filters: dict, top_k: int = 10, rerank: bool = False) -> list[dict]:
- ...
+ def search(self, query: str, *, filters: dict, top_k: int = 10, rerank: bool = False) -> list[dict]: ...
@abstractmethod
- def add(
- self,
- messages: list,
- *,
- user_id: str,
- agent_id: str,
- infer: bool = False,
- metadata: dict | None = None,
- ) -> dict:
- ...
+ def add(self, messages: list, *, user_id: str, agent_id: str, infer: bool = False, metadata: dict | None = None) -> dict: ...
@abstractmethod
- def update(self, memory_id: str, text: str) -> dict:
- ...
+ def _update(self, memory_id: str, text: str) -> None: ...
@abstractmethod
+ def _delete(self, memory_id: str) -> None: ...
+
+ def update(self, memory_id: str, text: str) -> dict:
+ self._update(memory_id, text)
+ return {"result": "Memory updated.", "memory_id": memory_id}
+
def delete(self, memory_id: str) -> dict:
- ...
+ self._delete(memory_id)
+ return {"result": "Memory deleted.", "memory_id": memory_id}
def close(self) -> None:
pass
-def _unwrap_results(response: Any) -> list:
- """Normalize API response — extract results list from dict or pass through."""
- if isinstance(response, dict):
- return response.get("results", [])
- if isinstance(response, list):
- return response
- return []
-
-
class PlatformBackend(Mem0Backend):
"""Wraps mem0.MemoryClient for Mem0 Platform (cloud API)."""
@@ -54,41 +59,24 @@ class PlatformBackend(Mem0Backend):
self._client = MemoryClient(api_key=api_key)
def search(self, query: str, *, filters: dict, top_k: int = 10, rerank: bool = False) -> list[dict]:
- response = self._client.search(query, filters=filters, top_k=top_k, rerank=rerank)
- return _unwrap_results(response)
-
- def add(
- self,
- messages: list,
- *,
- user_id: str,
- agent_id: str,
- infer: bool = False,
- metadata: dict | None = None,
- ) -> dict:
- kwargs: dict[str, Any] = {"user_id": user_id, "agent_id": agent_id, "infer": infer}
- if metadata:
- kwargs["metadata"] = metadata
- return self._client.add(messages, **kwargs)
+ return _unwrap_results(self._client.search(query, filters=filters, top_k=top_k, rerank=rerank))
- def update(self, memory_id: str, text: str) -> dict:
+ def add(self, messages: list, *, user_id: str, agent_id: str, infer: bool = False, metadata: dict | None = None) -> dict:
+ return self._client.add(messages, **_add_kwargs(user_id, agent_id, infer, metadata))
+
+ def _update(self, memory_id: str, text: str) -> None:
self._client.update(memory_id=memory_id, text=text)
- return {"result": "Memory updated.", "memory_id": memory_id}
- def delete(self, memory_id: str) -> dict:
+ def _delete(self, memory_id: str) -> None:
self._client.delete(memory_id=memory_id)
- return {"result": "Memory deleted.", "memory_id": memory_id}
class SelfHostedBackend(Mem0Backend):
"""Direct HTTP backend for a self-hosted Mem0 server (the FastAPI ``server/``).
- mem0.MemoryClient can't be reused for self-hosted: it is hardwired to the
- cloud API — ``Authorization: Token`` auth and a ``GET /v1/ping/`` validation
- call in ``__init__`` that the self-hosted server does not expose (it would
- 404 before any real request). This client talks to that server directly,
- using its actual contract: ``X-API-Key`` auth and the ``/memories`` /
- ``/search`` routes.
+ mem0.MemoryClient is hardwired to the cloud API (``Authorization: Token`` auth,
+ ``GET /v1/ping/`` in ``__init__``) so it can't be reused here; this speaks the
+ server's real contract: ``X-API-Key`` auth and the ``/memories`` / ``/search`` routes.
"""
def __init__(self, api_key: str, host: str, transport=None):
@@ -97,14 +85,11 @@ class SelfHostedBackend(Mem0Backend):
headers = {"Content-Type": "application/json"}
if api_key:
headers["X-API-Key"] = api_key # omitted only for AUTH_DISABLED servers
- # Connect-level retries smooth over transient blips so a single
- # dropped SYN doesn't count toward the provider failure breaker.
- # ``transport`` is injectable for tests (httpx.MockTransport).
- if transport is None:
- transport = httpx.HTTPTransport(retries=2)
+ # Connect-level retries keep a single dropped SYN from counting toward the
+ # provider failure breaker. ``transport`` is injectable for tests.
self._client = httpx.Client(
base_url=host.rstrip("/"), headers=headers, timeout=30.0,
- transport=transport,
+ transport=transport or httpx.HTTPTransport(retries=2),
)
def _json(self, method: str, path: str, **kwargs) -> Any:
@@ -113,38 +98,21 @@ class SelfHostedBackend(Mem0Backend):
return resp.json() if resp.content else {}
def search(self, query: str, *, filters: dict, top_k: int = 10, rerank: bool = False) -> list[dict]:
- # rerank is a platform-only feature; the self-hosted /search ignores it.
+ # rerank is platform-only; the self-hosted /search ignores it.
body: dict[str, Any] = {"query": query, "top_k": top_k}
if filters:
body["filters"] = filters # user_id belongs in filters (top-level is deprecated)
return _unwrap_results(self._json("POST", "/search", json=body))
- def add(
- self,
- messages: list,
- *,
- user_id: str,
- agent_id: str,
- infer: bool = False,
- metadata: dict | None = None,
- ) -> dict:
- body: dict[str, Any] = {
- "messages": messages,
- "user_id": user_id,
- "agent_id": agent_id,
- "infer": infer,
- }
- if metadata:
- body["metadata"] = metadata
+ def add(self, messages: list, *, user_id: str, agent_id: str, infer: bool = False, metadata: dict | None = None) -> dict:
+ body: dict[str, Any] = {"messages": messages, **_add_kwargs(user_id, agent_id, infer, metadata)}
return self._json("POST", "/memories", json=body)
- def update(self, memory_id: str, text: str) -> dict:
+ def _update(self, memory_id: str, text: str) -> None:
self._json("PUT", f"/memories/{memory_id}", json={"text": text})
- return {"result": "Memory updated.", "memory_id": memory_id}
- def delete(self, memory_id: str) -> dict:
+ def _delete(self, memory_id: str) -> None:
self._json("DELETE", f"/memories/{memory_id}")
- return {"result": "Memory deleted.", "memory_id": memory_id}
def close(self) -> None:
try:
@@ -169,14 +137,8 @@ def _register_direct_openai_provider() -> None:
"mem0 LlmFactory does not support the provider registration required "
"for the Hermes OpenAI OSS backend"
)
-
- registration = (_DIRECT_OPENAI_CLASS_PATH, OpenAIConfig)
- if provider_map.get(_DIRECT_OPENAI_PROVIDER) != registration:
- register_provider(
- _DIRECT_OPENAI_PROVIDER,
- _DIRECT_OPENAI_CLASS_PATH,
- OpenAIConfig,
- )
+ if provider_map.get(_DIRECT_OPENAI_PROVIDER) != (_DIRECT_OPENAI_CLASS_PATH, OpenAIConfig):
+ register_provider(_DIRECT_OPENAI_PROVIDER, _DIRECT_OPENAI_CLASS_PATH, OpenAIConfig)
class OSSBackend(Mem0Backend):
@@ -185,6 +147,7 @@ class OSSBackend(Mem0Backend):
def __init__(self, oss_config: dict):
import os
from mem0 import Memory
+ from ._oss_providers import EMBEDDER_PROVIDERS, KNOWN_DIMS, LLM_PROVIDERS
def _provider_block(name: str) -> dict:
block = dict(oss_config[name])
@@ -192,12 +155,8 @@ class OSSBackend(Mem0Backend):
provider_config = dict(block.get("config", {}))
legacy_base = provider_config.pop("api_base", None)
if legacy_base:
- from ._oss_providers import EMBEDDER_PROVIDERS, LLM_PROVIDERS
-
- provider_def = (
- LLM_PROVIDERS if name == "llm" else EMBEDDER_PROVIDERS
- ).get(provider, {})
- canonical_key = provider_def.get("base_url_key")
+ registry = LLM_PROVIDERS if name == "llm" else EMBEDDER_PROVIDERS
+ canonical_key = registry.get(provider, {}).get("base_url_key")
if canonical_key:
provider_config.setdefault(canonical_key, legacy_base)
block["config"] = provider_config
@@ -205,22 +164,14 @@ class OSSBackend(Mem0Backend):
vector_store = dict(oss_config["vector_store"])
vs_config = dict(vector_store.get("config", {}))
-
if "path" in vs_config:
vs_config["path"] = os.path.expanduser(vs_config["path"])
embedder_config = oss_config.get("embedder", {}).get("config", {})
- dims = embedder_config.get("embedding_dims")
- if not dims:
- from ._oss_providers import KNOWN_DIMS
- model = embedder_config.get("model", "")
- dims = KNOWN_DIMS.get(model)
+ dims = embedder_config.get("embedding_dims") or KNOWN_DIMS.get(embedder_config.get("model", ""))
if dims:
vs_config["embedding_model_dims"] = dims
- self._recreate_collection_if_dims_changed(
- vector_store.get("provider", "qdrant"), vs_config, dims,
- )
-
+ self._recreate_collection_if_dims_changed(vector_store.get("provider", "qdrant"), vs_config, dims)
vector_store["config"] = vs_config
config = {
@@ -230,12 +181,10 @@ class OSSBackend(Mem0Backend):
"version": "v1.1",
}
if str(config["llm"].get("provider") or "").strip().lower() == "openai":
- # mem0 validates LlmConfig.provider before its factory lookup, so
- # first build the supported OpenAI config and only then swap the
- # provider on that validated in-memory object.
+ # mem0 validates LlmConfig.provider before its factory lookup: build the
+ # supported OpenAI config first, then swap the provider on the validated object.
_register_direct_openai_provider()
from mem0.configs.base import MemoryConfig
-
memory_config = MemoryConfig(**config)
try:
memory_config.llm.provider = _DIRECT_OPENAI_PROVIDER
@@ -252,11 +201,10 @@ class OSSBackend(Mem0Backend):
def _recreate_collection_if_dims_changed(provider: str, vs_config: dict, expected_dims: int) -> None:
"""Delete stale vector collection when embedding dimensions change."""
collection_name = vs_config.get("collection_name", "mem0")
- if provider == "qdrant":
- try:
+ try:
+ if provider == "qdrant":
from qdrant_client import QdrantClient
- path = vs_config.get("path")
- url = vs_config.get("url")
+ path, url = vs_config.get("path"), vs_config.get("url")
if path:
client = QdrantClient(path=path)
elif url:
@@ -266,30 +214,19 @@ class OSSBackend(Mem0Backend):
try:
if not client.collection_exists(collection_name):
return
- info = client.get_collection(collection_name)
- vectors = info.config.params.vectors
- # Named-vector collections expose a dict; unnamed expose an object with .size.
+ vectors = client.get_collection(collection_name).config.params.vectors
+ # Named-vector collections expose a dict; unnamed expose an object with .size.
if isinstance(vectors, dict):
- first = next(iter(vectors.values()), None)
- current_dims = first.size if first else None
- else:
- current_dims = getattr(vectors, "size", None)
+ vectors = next(iter(vectors.values()), None)
+ current_dims = getattr(vectors, "size", None)
if current_dims is not None and current_dims != expected_dims:
client.delete_collection(collection_name)
finally:
client.close()
- except Exception:
- pass
- elif provider == "pgvector":
- try:
+ elif provider == "pgvector":
import psycopg2
from psycopg2 import sql as pgsql
- conn_params = {}
- for k in ("host", "port", "user", "password", "dbname"):
- if vs_config.get(k):
- conn_params[k] = vs_config[k]
- if vs_config.get("sslmode"):
- conn_params["sslmode"] = vs_config["sslmode"]
+ conn_params = {k: vs_config[k] for k in ("host", "port", "user", "password", "dbname", "sslmode") if vs_config.get(k)}
conn = psycopg2.connect(**conn_params)
conn.autocommit = True
try:
@@ -302,41 +239,25 @@ class OSSBackend(Mem0Backend):
)
row = cur.fetchone()
if row and row[0] > 0 and row[0] != expected_dims:
- cur.execute(pgsql.SQL("DROP TABLE IF EXISTS {}").format(
- pgsql.Identifier(collection_name)
- ))
+ cur.execute(pgsql.SQL("DROP TABLE IF EXISTS {}").format(pgsql.Identifier(collection_name)))
finally:
cur.close()
finally:
conn.close()
- except Exception:
- pass
+ except Exception:
+ pass
def search(self, query: str, *, filters: dict, top_k: int = 10, rerank: bool = False) -> list[dict]:
- response = self._memory.search(query, filters=filters, top_k=top_k)
- return _unwrap_results(response)
-
- def add(
- self,
- messages: list,
- *,
- user_id: str,
- agent_id: str,
- infer: bool = False,
- metadata: dict | None = None,
- ) -> dict:
- kwargs: dict[str, Any] = {"user_id": user_id, "agent_id": agent_id, "infer": infer}
- if metadata:
- kwargs["metadata"] = metadata
- return self._memory.add(messages, **kwargs)
+ return _unwrap_results(self._memory.search(query, filters=filters, top_k=top_k))
- def update(self, memory_id: str, text: str) -> dict:
+ def add(self, messages: list, *, user_id: str, agent_id: str, infer: bool = False, metadata: dict | None = None) -> dict:
+ return self._memory.add(messages, **_add_kwargs(user_id, agent_id, infer, metadata))
+
+ def _update(self, memory_id: str, text: str) -> None:
self._memory.update(memory_id, data=text)
- return {"result": "Memory updated.", "memory_id": memory_id}
- def delete(self, memory_id: str) -> dict:
+ def _delete(self, memory_id: str) -> None:
self._memory.delete(memory_id)
- return {"result": "Memory deleted.", "memory_id": memory_id}
def close(self):
try:
diff --git a/plugins/memory/mem0/_openai_llm.py b/plugins/memory/mem0/_openai_llm.py
index d61ab511c9c..64d1fe63123 100644
--- a/plugins/memory/mem0/_openai_llm.py
+++ b/plugins/memory/mem0/_openai_llm.py
@@ -15,24 +15,16 @@ from mem0.llms.openai import OpenAILLM
class DirectOpenAILLM(OpenAILLM):
"""Use OpenAI credentials and requests regardless of router environment."""
- def __init__(
- self,
- config: Optional[Union[BaseLlmConfig, OpenAIConfig, Dict]] = None,
- ):
+ def __init__(self, config: Optional[Union[BaseLlmConfig, OpenAIConfig, Dict]] = None):
if config is None:
config = OpenAIConfig()
elif isinstance(config, dict):
config = OpenAIConfig(**config)
elif isinstance(config, BaseLlmConfig) and not isinstance(config, OpenAIConfig):
config = OpenAIConfig(
- model=config.model,
- temperature=config.temperature,
- api_key=config.api_key,
- max_tokens=config.max_tokens,
- top_p=config.top_p,
- top_k=config.top_k,
- enable_vision=config.enable_vision,
- vision_details=config.vision_details,
+ model=config.model, temperature=config.temperature, api_key=config.api_key,
+ max_tokens=config.max_tokens, top_p=config.top_p, top_k=config.top_k,
+ enable_vision=config.enable_vision, vision_details=config.vision_details,
reasoning_effort=getattr(config, "reasoning_effort", None),
http_client_proxies=config.http_client_proxies,
is_reasoning_model=getattr(config, "is_reasoning_model", None),
@@ -40,56 +32,34 @@ class DirectOpenAILLM(OpenAILLM):
if not config.model:
config.model = "gpt-5-mini"
-
- # Older, partial, and manually edited configs may predate the setup
- # marker. Keep the exact default model safe at runtime without
- # overriding an explicit user choice or changing the persisted config.
+ # Configs predating the setup marker: keep the default model reasoning-safe
+ # without overriding an explicit user choice.
if config.model == "gpt-5-mini" and config.is_reasoning_model is None:
config.is_reasoning_model = True
-
- # Bypass OpenAILLM.__init__: it intentionally selects OpenRouter when
- # OPENROUTER_API_KEY is present. LLMBase still owns validation and
- # supported-parameter filtering for parity with Mem0's implementation.
+ # Bypass OpenAILLM.__init__ (it picks OpenRouter when OPENROUTER_API_KEY is
+ # set); LLMBase still owns validation and supported-parameter filtering.
LLMBase.__init__(self, config)
api_key = self.config.api_key or os.getenv("OPENAI_API_KEY")
if not api_key:
- raise ValueError(
- "OpenAI API key is required for the Hermes Mem0 OSS provider"
- )
-
- base_url = (
- self.config.openai_base_url
- or os.getenv("OPENAI_BASE_URL")
- or "https://api.openai.com/v1"
- )
-
+ raise ValueError("OpenAI API key is required for the Hermes Mem0 OSS provider")
from openai import OpenAI
-
- self.client = OpenAI(api_key=api_key, base_url=base_url)
+ self.client = OpenAI(api_key=api_key, base_url=self.config.openai_base_url or os.getenv("OPENAI_BASE_URL") or "https://api.openai.com/v1")
def generate_response(
- self,
- messages: List[Dict[str, str]],
- response_format=None,
- tools: Optional[List[Dict]] = None,
- tool_choice: str = "auto",
- **kwargs,
+ self, messages: List[Dict[str, str]], response_format=None,
+ tools: Optional[List[Dict]] = None, tool_choice: str = "auto", **kwargs,
):
params = self._get_supported_params(messages=messages, **kwargs)
params.update({"model": self.config.model, "messages": messages})
-
- # OpenRouter-only fields are deliberately not added here. ``store`` is
- # opt-in so OpenAI-compatible endpoints do not receive unknown fields.
+ # No OpenRouter-only fields; ``store`` is opt-in so OpenAI-compatible
+ # endpoints never receive unknown fields.
if self.config.store is not None:
params["store"] = self.config.store
-
if response_format:
params["response_format"] = response_format
if tools:
- params["tools"] = tools
- params["tool_choice"] = tool_choice
-
+ params["tools"], params["tool_choice"] = tools, tool_choice
response = self.client.chat.completions.create(**params)
parsed_response = self._parse_response(response, tools)
if self.config.response_callback:
diff --git a/plugins/memory/mem0/_oss_providers.py b/plugins/memory/mem0/_oss_providers.py
index 3eb96e04c6b..69ead2009be 100644
--- a/plugins/memory/mem0/_oss_providers.py
+++ b/plugins/memory/mem0/_oss_providers.py
@@ -7,39 +7,23 @@ from typing import Any
LLM_PROVIDERS: dict[str, dict[str, Any]] = {
"openai": {
- "label": "OpenAI",
- "needs_key": True,
- "env_var": "OPENAI_API_KEY",
- "default_model": "gpt-5-mini",
- "base_url_key": "openai_base_url",
+ "label": "OpenAI", "needs_key": True, "env_var": "OPENAI_API_KEY",
+ "default_model": "gpt-5-mini", "base_url_key": "openai_base_url",
},
"ollama": {
- "label": "Ollama (local)",
- "needs_key": False,
- "default_model": "llama3.1:8b",
- "default_url": "http://localhost:11434",
- "base_url_key": "ollama_base_url",
- "pip_dep": "ollama",
+ "label": "Ollama (local)", "needs_key": False, "default_model": "llama3.1:8b",
+ "default_url": "http://localhost:11434", "base_url_key": "ollama_base_url", "pip_dep": "ollama",
},
}
EMBEDDER_PROVIDERS: dict[str, dict[str, Any]] = {
"openai": {
- "label": "OpenAI",
- "needs_key": True,
- "env_var": "OPENAI_API_KEY",
- "default_model": "text-embedding-3-small",
- "base_url_key": "openai_base_url",
- "dims": 1536,
+ "label": "OpenAI", "needs_key": True, "env_var": "OPENAI_API_KEY",
+ "default_model": "text-embedding-3-small", "base_url_key": "openai_base_url", "dims": 1536,
},
"ollama": {
- "label": "Ollama (local)",
- "needs_key": False,
- "default_model": "nomic-embed-text",
- "default_url": "http://localhost:11434",
- "base_url_key": "ollama_base_url",
- "dims": 768,
- "pip_dep": "ollama",
+ "label": "Ollama (local)", "needs_key": False, "default_model": "nomic-embed-text",
+ "default_url": "http://localhost:11434", "base_url_key": "ollama_base_url", "dims": 768, "pip_dep": "ollama",
},
}
@@ -57,32 +41,23 @@ VECTOR_PROVIDERS: dict[str, dict[str, Any]] = {
}
KNOWN_DIMS: dict[str, int] = {
- "text-embedding-3-small": 1536,
- "text-embedding-3-large": 3072,
- "text-embedding-ada-002": 1536,
- "nomic-embed-text": 768,
+ "text-embedding-3-small": 1536, "text-embedding-3-large": 3072, "text-embedding-ada-002": 1536, "nomic-embed-text": 768,
}
+SECTION_REGISTRIES = (("llm", LLM_PROVIDERS), ("embedder", EMBEDDER_PROVIDERS), ("vector_store", VECTOR_PROVIDERS))
+
def validate_oss_config(oss_config: dict) -> list[str]:
"""Validate an OSS config dict. Returns list of error strings (empty = valid)."""
errors: list[str] = []
-
- for section, registry in [("llm", LLM_PROVIDERS), ("embedder", EMBEDDER_PROVIDERS),
- ("vector_store", VECTOR_PROVIDERS)]:
+ for section, registry in SECTION_REGISTRIES:
block = oss_config.get(section)
if not block or not isinstance(block, dict):
errors.append(f"Missing required section: {section}")
- continue
- provider_id = block.get("provider", "")
- if provider_id not in registry:
- valid = ", ".join(registry.keys())
- errors.append(f"Unknown {section} provider '{provider_id}'. Valid: {valid}")
+ elif block.get("provider", "") not in registry:
+ errors.append(f"Unknown {section} provider '{block.get('provider', '')}'. Valid: {', '.join(registry.keys())}")
vs = oss_config.get("vector_store", {})
- if vs.get("provider") == "pgvector":
- cfg = vs.get("config", {})
- if not cfg.get("user"):
- errors.append("PGVector requires 'user' in vector_store.config")
-
+ if vs.get("provider") == "pgvector" and not vs.get("config", {}).get("user"):
+ errors.append("PGVector requires 'user' in vector_store.config")
return errors
diff --git a/plugins/memory/mem0/_setup.py b/plugins/memory/mem0/_setup.py
index 7c68c81d4ec..40ff7813732 100644
--- a/plugins/memory/mem0/_setup.py
+++ b/plugins/memory/mem0/_setup.py
@@ -9,108 +9,112 @@ import shutil
import socket
import subprocess
import sys
+import time
+import urllib.error
import urllib.request
from pathlib import Path
from typing import Any
-from hermes_constants import get_hermes_home
+from hermes_constants import get_hermes_home # noqa: F401 — patched by tests
-from ._oss_providers import (
- LLM_PROVIDERS,
- EMBEDDER_PROVIDERS,
- VECTOR_PROVIDERS,
- KNOWN_DIMS,
- validate_oss_config,
-)
+from . import _read_mem0_json
+from ._oss_providers import EMBEDDER_PROVIDERS, KNOWN_DIMS, LLM_PROVIDERS, SECTION_REGISTRIES, VECTOR_PROVIDERS, validate_oss_config
def _curses_select(title: str, items: list[tuple[str, str]], default: int = 0) -> int:
"""Interactive single-select with arrow keys."""
from hermes_cli.curses_ui import curses_radiolist
- display_items = [
- f"{label} {desc}" if desc else label
- for label, desc in items
- ]
- return curses_radiolist(title, display_items, selected=default, cancel_returns=default)
+ return curses_radiolist(title, [f"{label} {desc}" if desc else label for label, desc in items], selected=default, cancel_returns=default)
def _prompt(label: str, default: str | None = None, secret: bool = False) -> str:
"""Prompt for a value with optional default and secret masking."""
- suffix = f" [{default}]" if default else ""
- if secret:
- sys.stdout.write(f" {label}{suffix}: ")
- sys.stdout.flush()
- if sys.stdin.isatty():
- val = getpass.getpass(prompt="")
- else:
- val = sys.stdin.readline().strip()
- else:
- sys.stdout.write(f" {label}{suffix}: ")
- sys.stdout.flush()
- val = sys.stdin.readline().strip()
+ sys.stdout.write(f" {label}{f' [{default}]' if default else ''}: ")
+ sys.stdout.flush()
+ val = getpass.getpass(prompt="") if secret and sys.stdin.isatty() else sys.stdin.readline().strip()
return val or (default or "")
-def has_oss_flags() -> bool:
- """Check if OSS-related flags are present in sys.argv."""
- flags = parse_flags(sys.argv[1:])
- if flags["mode"] == "oss":
- return True
- if any(flags.get(k) for k in ("oss_llm_key", "oss_vector_path", "oss_vector_url")):
- return True
- return False
+def _input(label: str, default: str) -> str:
+ """input() with a bracketed default shown and applied on blank."""
+ return input(f" {label} [{default}]: ").strip() or default
+
+
+def _masked(secret: str) -> str:
+ return f"...{secret[-4:]}" if len(secret) > 4 else "set"
+
+
+def _http_get(url: str, path: str, timeout: int):
+ return urllib.request.urlopen(urllib.request.Request(f"{url.rstrip('/')}{path}", method="GET"), timeout=timeout)
+
+
+def _prompt_api_key(label: str, env_var: str, hermes_home: str) -> str:
+ """Prompt for API key, showing masked existing value if found."""
+ existing = os.environ.get(env_var, "")
+ env_path = Path(hermes_home) / ".env"
+ if not existing and env_path.exists():
+ # utf-8-sig: a Notepad BOM on line 1 would otherwise defeat the key match.
+ for line in env_path.read_text(encoding="utf-8-sig", errors="replace").splitlines():
+ if line.startswith(f"{env_var}="):
+ existing = line.split("=", 1)[1].strip()
+ break
+ hint = f" (current: {_masked(existing)}, blank to keep)" if existing else ""
+ return getpass.getpass(f" {label} API key{hint}: ").strip()
+
+
+def _api_key_writes(flags: dict, label: str, *, url: str | None = None, fresh_label: str | None = None) -> dict[str, str]:
+ """MEM0_API_KEY for .env: from --api-key, else prompt (masking any key already in the environment)."""
+ if flags.get("api_key"):
+ return {"MEM0_API_KEY": flags["api_key"]}
+ existing = os.environ.get("MEM0_API_KEY", "")
+ if existing:
+ val = _prompt(f"{label} (current: {_masked(existing)}, blank to keep)", secret=True)
+ else:
+ if url:
+ print(f" Get yours at {url}")
+ val = _prompt(fresh_label or label, secret=True)
+ return {"MEM0_API_KEY": val} if val else {}
+
+
+def _print_dry_run(summary: str, env_writes: dict, check=None) -> None:
+ print(f"\n [dry-run] Would save config: {summary}")
+ if env_writes:
+ print(" [dry-run] Would write API key to .env")
+ if check:
+ check()
+ print(" [dry-run] No files written.\n")
+
+
+def _print_saved(label: str, env_writes: dict, key_line: str, server: str | None = None) -> None:
+ print(f"\n Memory provider: {label}")
+ if server:
+ print(f" Server: {server}")
+ print(" Activation saved to config.yaml")
+ print(" Provider config saved")
+ if env_writes:
+ print(f" {key_line}")
+ print("\n Start a new session to activate.\n")
+
+
+_FLAG_KEYS = (
+ "mode", "api_key", "host",
+ "oss_llm", "oss_llm_key", "oss_llm_model", "oss_llm_url",
+ "oss_embedder", "oss_embedder_key", "oss_embedder_model", "oss_embedder_url",
+ "oss_vector", "oss_vector_path", "oss_vector_url", "oss_vector_host",
+ "oss_vector_port", "oss_vector_user", "oss_vector_password", "oss_vector_dbname",
+ "user_id",
+)
+_FLAG_DEFAULTS = {"oss_llm": "openai", "oss_embedder": "openai", "oss_vector": "qdrant"}
+# --oss-vector-<key> flags accepted per vector store (also the pgvector key order).
+_VECTOR_FLAG_KEYS = {"qdrant": ("path", "url"), "pgvector": ("host", "port", "user", "password", "dbname")}
def parse_flags(argv: list[str] | None = None) -> dict[str, str]:
"""Parse CLI flags from argv. Returns dict of flag values."""
args = argv if argv is not None else sys.argv[1:]
- flags: dict[str, str] = {
- "mode": "",
- "api_key": "",
- "host": "",
- "oss_llm": "openai",
- "oss_llm_key": "",
- "oss_llm_model": "",
- "oss_llm_url": "",
- "oss_embedder": "openai",
- "oss_embedder_key": "",
- "oss_embedder_model": "",
- "oss_embedder_url": "",
- "oss_vector": "qdrant",
- "oss_vector_path": "",
- "oss_vector_url": "",
- "oss_vector_host": "",
- "oss_vector_port": "",
- "oss_vector_user": "",
- "oss_vector_password": "",
- "oss_vector_dbname": "",
- "user_id": "",
- "dry_run": False,
- }
-
- flag_map = {
- "--mode": "mode",
- "--api-key": "api_key",
- "--host": "host",
- "--oss-llm": "oss_llm",
- "--oss-llm-key": "oss_llm_key",
- "--oss-llm-model": "oss_llm_model",
- "--oss-llm-url": "oss_llm_url",
- "--oss-embedder": "oss_embedder",
- "--oss-embedder-key": "oss_embedder_key",
- "--oss-embedder-model": "oss_embedder_model",
- "--oss-embedder-url": "oss_embedder_url",
- "--oss-vector": "oss_vector",
- "--oss-vector-path": "oss_vector_path",
- "--oss-vector-url": "oss_vector_url",
- "--oss-vector-host": "oss_vector_host",
- "--oss-vector-port": "oss_vector_port",
- "--oss-vector-user": "oss_vector_user",
- "--oss-vector-password": "oss_vector_password",
- "--oss-vector-dbname": "oss_vector_dbname",
- "--user-id": "user_id",
- }
-
+ flags: dict[str, Any] = {k: _FLAG_DEFAULTS.get(k, "") for k in _FLAG_KEYS}
+ flags["dry_run"] = False
+ flag_map = {"--" + k.replace("_", "-"): k for k in _FLAG_KEYS}
i = 0
while i < len(args):
if args[i] == "--dry-run":
@@ -121,57 +125,40 @@ def parse_flags(argv: list[str] | None = None) -> dict[str, str]:
i += 2
else:
i += 1
-
return flags
+def _model_block(flags: dict, registry: dict, prefix: str) -> tuple[str, dict, dict[str, Any]]:
+ """Resolve (provider_id, provider_def, config) for an LLM/embedder section from flags."""
+ pid = flags.get(prefix, "openai")
+ pdef = registry[pid]
+ model = flags.get(f"{prefix}_model") or pdef["default_model"]
+ cfg: dict[str, Any] = {"model": model}
+ url = flags.get(f"{prefix}_url") or pdef.get("default_url")
+ if url and pdef.get("base_url_key"):
+ cfg[pdef["base_url_key"]] = url
+ return pid, pdef, cfg
+
+
def build_oss_config(flags: dict[str, str]) -> tuple[dict, dict[str, str]]:
- """Build OSS config dict + env_writes from parsed flags.
-
- Returns (oss_config, env_writes) where oss_config goes into mem0.json
- and env_writes maps env var names to secret values for .env.
- """
- llm_id = flags.get("oss_llm", "openai")
- llm_def = LLM_PROVIDERS[llm_id]
- llm_model = flags.get("oss_llm_model") or llm_def["default_model"]
- llm_config: dict[str, Any] = {"model": llm_model}
- if llm_id == "openai" and llm_model == "gpt-5-mini":
+ """Build (oss_config for mem0.json, env_writes of secrets for .env) from parsed flags."""
+ llm_id, llm_def, llm_config = _model_block(flags, LLM_PROVIDERS, "oss_llm")
+ if llm_id == "openai" and llm_config["model"] == "gpt-5-mini":
llm_config["is_reasoning_model"] = True
- llm_url = flags.get("oss_llm_url") or llm_def.get("default_url")
- if llm_url and llm_def.get("base_url_key"):
- llm_config[llm_def["base_url_key"]] = llm_url
-
- embedder_id = flags.get("oss_embedder", "openai")
- embedder_def = EMBEDDER_PROVIDERS[embedder_id]
- embedder_model = flags.get("oss_embedder_model") or embedder_def["default_model"]
- embedder_config: dict[str, Any] = {"model": embedder_model}
- embedder_url = flags.get("oss_embedder_url") or embedder_def.get("default_url")
- if embedder_url and embedder_def.get("base_url_key"):
- embedder_config[embedder_def["base_url_key"]] = embedder_url
- dims = KNOWN_DIMS.get(embedder_model)
+
+ embedder_id, embedder_def, embedder_config = _model_block(flags, EMBEDDER_PROVIDERS, "oss_embedder")
+ dims = KNOWN_DIMS.get(embedder_config["model"])
if dims:
embedder_config["embedding_dims"] = dims
vector_id = flags.get("oss_vector", "qdrant")
- vector_def = VECTOR_PROVIDERS[vector_id]
- vector_config = dict(vector_def["default_config"])
- if vector_id == "qdrant":
- if flags.get("oss_vector_path"):
- vector_config["path"] = flags["oss_vector_path"]
- if flags.get("oss_vector_url"):
- vector_config.pop("path", None)
- vector_config["url"] = flags["oss_vector_url"]
- elif vector_id == "pgvector":
- if flags.get("oss_vector_host"):
- vector_config["host"] = flags["oss_vector_host"]
- if flags.get("oss_vector_port"):
- vector_config["port"] = int(flags["oss_vector_port"])
- if flags.get("oss_vector_user"):
- vector_config["user"] = flags["oss_vector_user"]
- if flags.get("oss_vector_password"):
- vector_config["password"] = flags["oss_vector_password"]
- if flags.get("oss_vector_dbname"):
- vector_config["dbname"] = flags["oss_vector_dbname"]
+ vector_config = dict(VECTOR_PROVIDERS[vector_id]["default_config"])
+ for key in _VECTOR_FLAG_KEYS.get(vector_id, ()):
+ val = flags.get(f"oss_vector_{key}")
+ if val:
+ vector_config[key] = int(val) if key == "port" else val
+ if "url" in vector_config:
+ vector_config.pop("path", None) # a remote Qdrant URL replaces local storage
oss_config = {
"llm": {"provider": llm_id, "config": llm_config},
@@ -182,141 +169,84 @@ def build_oss_config(flags: dict[str, str]) -> tuple[dict, dict[str, str]]:
env_writes: dict[str, str] = {}
if llm_def.get("needs_key") and flags.get("oss_llm_key"):
env_writes[llm_def["env_var"]] = flags["oss_llm_key"]
- if embedder_def.get("needs_key") and flags.get("oss_embedder_key"):
- env_writes[embedder_def["env_var"]] = flags["oss_embedder_key"]
- elif embedder_def.get("needs_key") and embedder_id == llm_id and flags.get("oss_llm_key"):
- env_writes[embedder_def["env_var"]] = flags["oss_llm_key"]
-
+ if embedder_def.get("needs_key"):
+ # An embedder sharing the LLM's provider reuses the LLM key when no embedder key was given.
+ key = flags.get("oss_embedder_key") or (flags.get("oss_llm_key") if embedder_id == llm_id else "")
+ if key:
+ env_writes[embedder_def["env_var"]] = key
return oss_config, env_writes
def _write_env(env_path: Path, env_writes: dict[str, str]) -> None:
"""Append or update env vars in .env file."""
env_path.parent.mkdir(parents=True, exist_ok=True)
- existing_lines: list[str] = []
- if env_path.exists():
- # Read as UTF-8 (BOM-tolerant), matching the canonical .env readers in
- # hermes_cli/config.py. read_text() with no encoding falls back to the
- # system locale (cp1252/GBK on Windows): it mangles or crashes on
- # non-ASCII values while copying existing lines through, and a BOM'd
- # first line would fail the key match and get duplicated.
- existing_lines = env_path.read_text(
- encoding="utf-8-sig"
- ).splitlines()
-
+ # utf-8-sig like the canonical .env readers: locale decoding (cp1252/GBK) mangles
+ # non-ASCII values, and a BOM'd first line would miss the key match and get duplicated.
+ existing_lines = env_path.read_text(encoding="utf-8-sig").splitlines() if env_path.exists() else []
updated_keys: set[str] = set()
new_lines: list[str] = []
for line in existing_lines:
- key_match = line.split("=", 1)[0].strip() if "=" in line and not line.startswith("#") else None
- if key_match and key_match in env_writes:
- new_lines.append(f"{key_match}={env_writes[key_match]}")
- updated_keys.add(key_match)
- else:
- new_lines.append(line)
- for k, v in env_writes.items():
- if k not in updated_keys:
- new_lines.append(f"{k}={v}")
-
+ key = line.split("=", 1)[0].strip() if "=" in line and not line.startswith("#") else None
+ if key and key in env_writes:
+ updated_keys.add(key)
+ line = f"{key}={env_writes[key]}"
+ new_lines.append(line)
+ new_lines += [f"{k}={v}" for k, v in env_writes.items() if k not in updated_keys]
env_path.write_text("\n".join(new_lines) + "\n", encoding="utf-8")
def _save_mem0_json(hermes_home: str, data: dict) -> None:
"""Merge-write to mem0.json."""
config_path = Path(hermes_home) / "mem0.json"
- existing = {}
- if config_path.exists():
- try:
- existing = json.loads(config_path.read_text(encoding="utf-8"))
- except Exception:
- pass
+ existing = _read_mem0_json(config_path)
existing.update(data)
config_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")
-def _setup_platform(hermes_home: str, config: dict, flags: dict[str, str]) -> None:
- """Platform mode setup — uses the framework's schema-based flow.
-
- Delegates to the same code path the framework uses when post_setup
- doesn't exist, preserving the original platform onboarding experience.
- """
- schema = [
- {"key": "api_key", "description": "Mem0 Platform API key", "secret": True, "required": True, "env_var": "MEM0_API_KEY", "url": "https://app.mem0.ai"},
- {"key": "user_id", "description": "User identifier", "default": "hermes-user"},
- {"key": "agent_id", "description": "Agent identifier", "default": "hermes"},
- {"key": "rerank", "description": "Enable reranking for recall", "default": "false", "choices": ["true", "false"]},
- ]
-
- existing_config = {}
- config_path = Path(hermes_home) / "mem0.json"
- if config_path.exists():
- try:
- existing_config = json.loads(config_path.read_text(encoding="utf-8"))
- except Exception:
- pass
+def _activate_provider(config: dict) -> None:
+ """Point config.yaml's memory.provider at mem0."""
+ from hermes_cli.config import save_config
+ config["memory"]["provider"] = "mem0"
+ save_config(config)
- provider_config = dict(existing_config)
- env_writes: dict[str, str] = {}
- print("\n Configuring mem0:\n")
+def _persist_provider_config(hermes_home: str, config: dict, provider_config: dict, env_writes: dict[str, str]) -> None:
+ """Shared platform/self-hosted tail: activate, write mem0.json (0600), then .env."""
+ _activate_provider(config)
+ from plugins.memory.mem0 import Mem0MemoryProvider
+ Mem0MemoryProvider().save_config(provider_config, hermes_home)
+ if env_writes:
+ _write_env(Path(hermes_home) / ".env", env_writes)
- for field in schema:
- key = field["key"]
- desc = field.get("description", key)
- default = field.get("default")
- is_secret = field.get("secret", False)
- choices = field.get("choices")
- env_var = field.get("env_var")
- url = field.get("url")
-
- if flags.get("api_key") and key == "api_key":
- env_writes["MEM0_API_KEY"] = flags["api_key"]
- continue
- if choices and not is_secret:
- choice_items = [(c, "") for c in choices]
- current = provider_config.get(key, default)
- current_idx = 0
- if current and str(current).lower() in choices:
- current_idx = choices.index(str(current).lower())
- sel = _curses_select(f" {desc}", choice_items, default=current_idx)
- provider_config[key] = choices[sel]
- elif is_secret:
- existing = os.environ.get(env_var, "") if env_var else ""
- if existing:
- masked = f"...{existing[-4:]}" if len(existing) > 4 else "set"
- val = _prompt(f"{desc} (current: {masked}, blank to keep)", secret=True)
- else:
- if url:
- print(f" Get yours at {url}")
- val = _prompt(desc, secret=True)
- if val and env_var:
- env_writes[env_var] = val
- else:
- current = provider_config.get(key)
- effective_default = current or default
- val = _prompt(desc, default=str(effective_default) if effective_default else None)
- if val:
- provider_config[key] = val
+def _setup_platform(hermes_home: str, config: dict, flags: dict[str, str]) -> None:
+ """Platform mode setup — prompts for API key (secret -> .env), user/agent ids and rerank (-> mem0.json)."""
+ provider_config = _read_mem0_json(Path(hermes_home) / "mem0.json")
+
+ print("\n Configuring mem0:\n")
+
+ env_writes = _api_key_writes(flags, "Mem0 Platform API key", url="https://app.mem0.ai")
+ for key, desc, default in (("user_id", "User identifier", "hermes-user"), ("agent_id", "Agent identifier", "hermes")):
+ val = _prompt(desc, default=str(provider_config.get(key) or default))
+ if val:
+ provider_config[key] = val
+ choices = ["true", "false"]
+ current = provider_config.get("rerank", "false")
+ current_idx = choices.index(str(current).lower()) if current and str(current).lower() in choices else 0
+ sel = _curses_select(" Enable reranking for recall", [(c, "") for c in choices], default=current_idx)
+ provider_config["rerank"] = choices[sel]
if flags.get("dry_run"):
- print(f"\n [dry-run] Would save config: {provider_config}")
- if env_writes:
- print(" [dry-run] Would write API key to .env")
- print(" [dry-run] No files written.\n")
+ _print_dry_run(str(provider_config), env_writes)
return
provider_config["mode"] = "platform"
- # Clear any stale self-hosted host: routing checks ``host`` before platform
- # (see _create_backend), so leaving it would silently keep routing to the
- # self-hosted server even though the user just chose platform mode. Set it
- # to "" rather than pop() — save_config merges into the existing mem0.json
- # (existing.update), so a popped key would survive; an empty value overwrites
- # it and reads as falsy at routing time.
+ # Routing checks ``host`` before platform (_create_backend), so a stale
+ # self-hosted host must be cleared. Set "" rather than pop(): save_config
+ # merges into the existing mem0.json, so a popped key would survive.
provider_config["host"] = ""
- # The json-file clear above can't help when the host comes from the
- # environment: _load_config() seeds ``host`` from MEM0_HOST, and the
- # docs tell self-hosted users to put MEM0_HOST in ~/.hermes/.env. Warn
- # so the user knows platform mode won't take effect until it's removed.
+ # _load_config() also seeds ``host`` from MEM0_HOST (docs tell self-hosted
+ # users to put it in .env); the file clear can't help there, so warn.
if os.environ.get("MEM0_HOST", "").strip():
print(
"\n ⚠ MEM0_HOST is set in your environment "
@@ -325,33 +255,14 @@ def _setup_platform(hermes_home: str, config: dict, flags: dict[str, str]) -> No
"routing to the self-hosted server."
)
- from hermes_cli.config import save_config
- config["memory"]["provider"] = "mem0"
- save_config(config)
-
- from plugins.memory.mem0 import Mem0MemoryProvider
- provider = Mem0MemoryProvider()
- provider.save_config(provider_config, hermes_home)
-
- if env_writes:
- _write_env(Path(hermes_home) / ".env", env_writes)
-
- print("\n Memory provider: mem0")
- print(" Activation saved to config.yaml")
- print(" Provider config saved")
- if env_writes:
- print(" API keys saved to .env")
- print("\n Start a new session to activate.\n")
+ _persist_provider_config(hermes_home, config, provider_config, env_writes)
+ _print_saved("mem0", env_writes, "API keys saved to .env")
def _check_selfhosted_server(host: str) -> None:
"""Best-effort reachability check for a self-hosted Mem0 server (non-fatal)."""
- import urllib.error
- import urllib.request as _urlreq
-
try:
- req = _urlreq.Request(f"{host.rstrip('/')}/docs", method="GET")
- _urlreq.urlopen(req, timeout=5)
+ _http_get(host, "/docs", 5)
print(f" ✓ Mem0 server reachable at {host}")
except urllib.error.HTTPError:
# Any HTTP response (401/403/404) still means something is listening.
@@ -361,160 +272,84 @@ def _check_selfhosted_server(host: str) -> None:
def _setup_selfhosted(hermes_home: str, config: dict, flags: dict[str, str]) -> None:
- """Self-hosted mode setup — point at an existing Mem0 dashboard server.
-
- For users already running the Dockerized Mem0 FastAPI server: stores the
- server URL (behavioral -> mem0.json) and an optional API key
- (secret -> .env as MEM0_API_KEY).
- """
- existing_config = {}
- config_path = Path(hermes_home) / "mem0.json"
- if config_path.exists():
- try:
- existing_config = json.loads(config_path.read_text(encoding="utf-8"))
- except Exception:
- pass
-
- provider_config = dict(existing_config)
+ """Self-hosted mode — point at an existing Mem0 server: URL -> mem0.json, key -> .env (MEM0_API_KEY)."""
+ provider_config = _read_mem0_json(Path(hermes_home) / "mem0.json")
print("\n Configuring mem0 (self-hosted server):\n")
- host = flags.get("host") or _prompt(
- "Mem0 server URL (e.g. http://localhost:8888)",
- default=provider_config.get("host") or None,
- )
+ host = flags.get("host") or _prompt("Mem0 server URL (e.g. http://localhost:8888)", default=provider_config.get("host") or None)
if not host:
print(" Error: a server URL is required for self-hosted mode.", file=sys.stderr)
return
host = host.rstrip("/")
- env_writes: dict[str, str] = {}
- if flags.get("api_key"):
- env_writes["MEM0_API_KEY"] = flags["api_key"]
- else:
- existing_key = os.environ.get("MEM0_API_KEY", "")
- if existing_key:
- masked = f"...{existing_key[-4:]}" if len(existing_key) > 4 else "set"
- val = _prompt(f"Server API key (current: {masked}, blank to keep)", secret=True)
- else:
- val = _prompt("Server API key (blank if AUTH_DISABLED)", secret=True)
- if val:
- env_writes["MEM0_API_KEY"] = val
-
- user_id = flags.get("user_id") or _prompt(
- "User identifier", default=provider_config.get("user_id") or "hermes-user"
- )
+ env_writes = _api_key_writes(flags, "Server API key", fresh_label="Server API key (blank if AUTH_DISABLED)")
+ user_id = flags.get("user_id") or _prompt("User identifier", default=provider_config.get("user_id") or "hermes-user")
agent_id = _prompt("Agent identifier", default=provider_config.get("agent_id") or "hermes")
if flags.get("dry_run"):
- print(f"\n [dry-run] Would save config: host={host}, user_id={user_id}, agent_id={agent_id}")
- if env_writes:
- print(" [dry-run] Would write API key to .env")
- _check_selfhosted_server(host)
- print(" [dry-run] No files written.\n")
+ _print_dry_run(f"host={host}, user_id={user_id}, agent_id={agent_id}", env_writes, lambda: _check_selfhosted_server(host))
return
- provider_config["mode"] = "platform" # routing: oss > host > platform; host wins
- provider_config["host"] = host
- provider_config["user_id"] = user_id
- provider_config["agent_id"] = agent_id
+ provider_config.update(mode="platform", host=host, user_id=user_id, agent_id=agent_id) # routing: oss > host > platform
+ _persist_provider_config(hermes_home, config, provider_config, env_writes)
- from hermes_cli.config import save_config
- config["memory"]["provider"] = "mem0"
- save_config(config)
+ _check_selfhosted_server(host)
+ _print_saved("mem0 (self-hosted)", env_writes, "API key saved to .env", server=host)
- from plugins.memory.mem0 import Mem0MemoryProvider
- provider = Mem0MemoryProvider()
- provider.save_config(provider_config, hermes_home)
+def _print_oss_summary(oss_config: dict, env_writes: dict, dry_run: bool = False) -> None:
+ llm, emb = oss_config["llm"], oss_config["embedder"]
+ w = 0 if dry_run else 9 # final summary column-aligns the labels
+ print("\n [dry-run] OSS config would be:" if dry_run else "\n ✓ Mem0 configured (OSS mode)")
+ print(f" {'LLM:':<{w}} {llm['provider']} ({llm['config'].get('model', '')})")
+ print(f" {'Embedder:':<{w}} {emb['provider']} ({emb['config'].get('model', '')})")
+ print(f" {'Vector:':<{w}} {oss_config['vector_store']['provider']}")
+ if dry_run:
+ if env_writes:
+ print(f" Env vars: {', '.join(env_writes.keys())}")
+ return
if env_writes:
- _write_env(Path(hermes_home) / ".env", env_writes)
+ print(" API keys saved to .env")
+ print(" Config saved to mem0.json")
+ print(" Provider set in config.yaml")
+ print("\n Start a new session to activate.\n")
- _check_selfhosted_server(host)
- print("\n Memory provider: mem0 (self-hosted)")
- print(f" Server: {host}")
- print(" Activation saved to config.yaml")
- print(" Provider config saved")
+
+def _finish_oss(
+ hermes_home: str, config: dict, oss_config: dict, env_writes: dict[str, str],
+ user_id: str, agent_id: str, pgvector_config: dict | None = None,
+) -> None:
+ """Shared OSS tail: write secrets + mem0.json, install deps, activate, check, summarize."""
if env_writes:
- print(" API key saved to .env")
- print("\n Start a new session to activate.\n")
+ _write_env(Path(hermes_home) / ".env", env_writes)
+ _save_mem0_json(hermes_home, {"mode": "oss", "user_id": user_id, "agent_id": agent_id, "oss": oss_config})
+ _install_provider_deps(oss_config["llm"]["provider"], oss_config["embedder"]["provider"], oss_config["vector_store"]["provider"])
+ if pgvector_config:
+ _ensure_pgvector_extension(pgvector_config)
+ _activate_provider(config)
+ _run_connectivity_checks(oss_config)
+ _print_oss_summary(oss_config, env_writes)
def _setup_oss(hermes_home: str, config: dict, flags: dict[str, str]) -> None:
- """OSS mode setup — build config from flags or interactive prompts.
-
- Non-interactive when --mode was set explicitly via flags (post_setup already
- resolved mode). Interactive only when mode was chosen via curses picker.
- """
+ """OSS mode — non-interactive when --mode was given, otherwise curses pickers."""
if not flags.get("_mode_from_flag"):
_setup_oss_interactive(hermes_home, config)
return
-
oss_config, env_writes = build_oss_config(flags)
errors = validate_oss_config(oss_config)
if errors:
for e in errors:
print(f" Error: {e}", file=sys.stderr)
sys.exit(1)
-
- user_id = flags.get("user_id") or os.getenv("USER", "hermes-user")
-
- llm_id = oss_config["llm"]["provider"]
- embedder_id = oss_config["embedder"]["provider"]
- vector_id = oss_config["vector_store"]["provider"]
-
if flags.get("dry_run"):
- print("\n [dry-run] OSS config would be:")
- print(f" LLM: {oss_config['llm']['provider']} ({oss_config['llm']['config'].get('model', '')})")
- print(f" Embedder: {oss_config['embedder']['provider']} ({oss_config['embedder']['config'].get('model', '')})")
- print(f" Vector: {vector_id}")
- if env_writes:
- print(f" Env vars: {', '.join(env_writes.keys())}")
+ _print_oss_summary(oss_config, env_writes, dry_run=True)
_run_connectivity_checks(oss_config)
print(" [dry-run] No files written.\n")
return
- if env_writes:
- _write_env(Path(hermes_home) / ".env", env_writes)
- _save_mem0_json(hermes_home, {"mode": "oss", "user_id": user_id, "agent_id": "hermes", "oss": oss_config})
-
- _install_provider_deps(llm_id, embedder_id, vector_id)
-
- from hermes_cli.config import save_config
- config["memory"]["provider"] = "mem0"
- save_config(config)
-
- _run_connectivity_checks(oss_config)
- print("\n ✓ Mem0 configured (OSS mode)")
- print(f" LLM: {oss_config['llm']['provider']} ({oss_config['llm']['config'].get('model', '')})")
- print(f" Embedder: {oss_config['embedder']['provider']} ({oss_config['embedder']['config'].get('model', '')})")
- print(f" Vector: {vector_id}")
- if env_writes:
- print(" API keys saved to .env")
- print(" Config saved to mem0.json")
- print(" Provider set in config.yaml")
- print("\n Start a new session to activate.\n")
-
-
-def _prompt_api_key(label: str, env_var: str, hermes_home: str) -> str:
- """Prompt for API key, showing masked existing value if found."""
- existing = os.environ.get(env_var, "")
- if not existing:
- env_path = Path(hermes_home) / ".env"
- if env_path.exists():
- # BOM-tolerant read matching the canonical .env readers in
- # hermes_cli/config.py; a Notepad BOM on the first line would
- # otherwise defeat the startswith() key match below.
- for line in env_path.read_text(
- encoding="utf-8-sig", errors="replace"
- ).splitlines():
- if line.startswith(f"{env_var}="):
- existing = line.split("=", 1)[1].strip()
- break
- if existing:
- masked = f"...{existing[-4:]}" if len(existing) > 4 else "set"
- return getpass.getpass(f" {label} API key (current: {masked}, blank to keep): ").strip()
- return getpass.getpass(f" {label} API key: ").strip()
+ _finish_oss(hermes_home, config, oss_config, env_writes, flags.get("user_id") or os.getenv("USER", "hermes-user"), "hermes")
_PGVECTOR_CONTAINER = "hermes-pgvector"
@@ -522,154 +357,110 @@ _PGVECTOR_IMAGE = "pgvector/pgvector:pg17"
_PGVECTOR_PASSWORD = "hermes"
-def _ensure_pgvector(host: str = "localhost", port: int = 5432) -> dict | None:
- """Ensure pgvector is reachable; offer Docker setup if not.
+def _docker(*args: str, timeout: int, **kwargs) -> subprocess.CompletedProcess:
+ return subprocess.run(["docker", *args], capture_output=True, timeout=timeout, stdin=subprocess.DEVNULL, **kwargs)
+
- Returns updated vector_config dict if Docker was started, None otherwise.
- """
- ok, _ = _check_pgvector(host, port)
- if ok:
+def _ensure_pgvector(host: str = "localhost", port: int = 5432) -> dict | None:
+ """Ensure pgvector is reachable; offer Docker setup if not. Returns the Docker
+ container's vector_config if one was started, None otherwise."""
+ if _check_pgvector(host, port)[0]:
print(f" ✓ PostgreSQL reachable at {host}:{port}")
return None
print(f" PostgreSQL not reachable at {host}:{port}")
+ if not shutil.which("docker"):
+ print(" Docker not found. Install Docker to auto-start pgvector,\n or run PostgreSQL with pgvector manually.")
+ return None
- # Check if our container already exists but is stopped
- if shutil.which("docker"):
- try:
- result = subprocess.run(
- ["docker", "inspect", _PGVECTOR_CONTAINER, "--format", "{{.State.Status}}"],
- capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=10, stdin=subprocess.DEVNULL,
- )
- if result.returncode == 0 and "exited" in result.stdout:
- print(f" Found stopped container '{_PGVECTOR_CONTAINER}', restarting...")
- subprocess.run(["docker", "start", _PGVECTOR_CONTAINER],
- capture_output=True, timeout=15,
- stdin=subprocess.DEVNULL)
- _wait_for_port(host, port, timeout=15)
- ok, _ = _check_pgvector(host, port)
- if ok:
- print(" ✓ PostgreSQL container restarted")
- return None
- except Exception:
- pass
+ # Restart our own container if it exists but is stopped.
+ try:
+ result = _docker("inspect", _PGVECTOR_CONTAINER, "--format", "{{.State.Status}}",
+ timeout=10, text=True, encoding='utf-8', errors='replace')
+ if result.returncode == 0 and "exited" in result.stdout:
+ print(f" Found stopped container '{_PGVECTOR_CONTAINER}', restarting...")
+ _docker("start", _PGVECTOR_CONTAINER, timeout=15)
+ _wait_for_port(host, port, timeout=15)
+ if _check_pgvector(host, port)[0]:
+ print(" ✓ PostgreSQL container restarted")
+ return None
+ except Exception:
+ pass
- answer = input(" Start pgvector via Docker? [Y/n]: ").strip().lower()
- if answer in ("", "y", "yes"):
- return _start_pgvector_docker(host, port)
- else:
- print(" Skipping Docker setup. Make sure PostgreSQL with pgvector is running.")
- return None
- else:
- print(" Docker not found. Install Docker to auto-start pgvector,")
- print(" or run PostgreSQL with pgvector manually.")
- return None
+ if input(" Start pgvector via Docker? [Y/n]: ").strip().lower() in ("", "y", "yes"):
+ return _start_pgvector_docker(host, port)
+ print(" Skipping Docker setup. Make sure PostgreSQL with pgvector is running.")
+ return None
def _start_pgvector_docker(host: str, port: int) -> dict | None:
"""Pull and start pgvector Docker container."""
try:
print(f" Pulling {_PGVECTOR_IMAGE}...")
- subprocess.run(["docker", "pull", _PGVECTOR_IMAGE],
- capture_output=True, timeout=120,
- stdin=subprocess.DEVNULL)
-
- # Remove existing container if present
- subprocess.run(["docker", "rm", "-f", _PGVECTOR_CONTAINER],
- capture_output=True, timeout=10,
- stdin=subprocess.DEVNULL)
-
+ _docker("pull", _PGVECTOR_IMAGE, timeout=120)
+ _docker("rm", "-f", _PGVECTOR_CONTAINER, timeout=10) # remove existing container if present
print(f" Starting container '{_PGVECTOR_CONTAINER}' on port {port}...")
- subprocess.run([
- "docker", "run", "-d",
- "--name", _PGVECTOR_CONTAINER,
+ _docker(
+ "run", "-d", "--name", _PGVECTOR_CONTAINER,
"-e", f"POSTGRES_PASSWORD={_PGVECTOR_PASSWORD}",
- "-p", f"{port}:5432",
- _PGVECTOR_IMAGE,
- ], capture_output=True, timeout=30, check=True, stdin=subprocess.DEVNULL)
-
+ "-p", f"{port}:5432", _PGVECTOR_IMAGE,
+ timeout=30, check=True,
+ )
_wait_for_port(host, port, timeout=20)
- ok, _ = _check_pgvector(host, port)
- if ok:
+ if _check_pgvector(host, port)[0]:
print(f" ✓ pgvector running on {host}:{port}")
- return {
- "host": host, "port": port,
- "user": "postgres", "password": _PGVECTOR_PASSWORD,
- "dbname": "postgres",
- }
else:
- print(" Warning: Container started but PostgreSQL not yet accepting connections.")
- print(" It may need a few more seconds. Config will be saved; retry later.")
- return {
- "host": host, "port": port,
- "user": "postgres", "password": _PGVECTOR_PASSWORD,
- "dbname": "postgres",
- }
+ print(" Warning: Container started but PostgreSQL not yet accepting connections.\n"
+ " It may need a few more seconds. Config will be saved; retry later.")
+ return {"host": host, "port": port, "user": "postgres", "password": _PGVECTOR_PASSWORD, "dbname": "postgres"}
except subprocess.CalledProcessError as e:
print(f" Failed to start Docker container: {e}")
- return None
except Exception as e:
print(f" Docker error: {e}")
- return None
+ return None
def _ensure_ollama(models: list[str]) -> bool:
- """Ensure Ollama is running and required models are pulled.
-
- Returns True if Ollama is ready, False if user needs to handle it manually.
- """
+ """Ensure Ollama is running and required models are pulled. Returns False when
+ the user must handle it manually."""
url = "http://localhost:11434"
ollama_bin = shutil.which("ollama")
- ok, _ = _check_ollama(url)
-
+ ok = _check_ollama(url)[0]
if not ok:
- if ollama_bin:
- print(" Ollama installed but not running. Starting...")
- try:
- subprocess.Popen(
- [ollama_bin, "serve"],
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
- )
- _wait_for_port("localhost", 11434, timeout=10)
- ok, _ = _check_ollama(url)
- if ok:
- print(" ✓ Ollama started")
- except Exception as e:
- print(f" Could not start Ollama: {e}")
- else:
- print(" Ollama not found. Install it:")
- print(" curl -fsSL https://ollama.com/install.sh | sh")
- print(" Or on macOS: brew install ollama")
+ if not ollama_bin:
+ print(" Ollama not found. Install it:\n curl -fsSL https://ollama.com/install.sh | sh\n"
+ " Or on macOS: brew install ollama")
return False
-
+ print(" Ollama installed but not running. Starting...")
+ try:
+ subprocess.Popen([ollama_bin, "serve"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ _wait_for_port("localhost", 11434, timeout=10)
+ ok = _check_ollama(url)[0]
+ if ok:
+ print(" ✓ Ollama started")
+ except Exception as e:
+ print(f" Could not start Ollama: {e}")
if not ok:
print(" Warning: Ollama not reachable. Models cannot be pulled.")
return False
- # Pull required models
for model in models:
if _ollama_has_model(url, model):
print(f" ✓ Model '{model}' available")
- else:
- print(f" Pulling '{model}'... (this may take a few minutes)")
- try:
- subprocess.run([ollama_bin or "ollama", "pull", model], timeout=600,
- stdin=subprocess.DEVNULL)
- print(f" ✓ Model '{model}' pulled")
- except Exception as e:
- print(f" Warning: Could not pull '{model}': {e}")
- print(f" Run manually: ollama pull {model}")
-
+ continue
+ print(f" Pulling '{model}'... (this may take a few minutes)")
+ try:
+ subprocess.run([ollama_bin or "ollama", "pull", model], timeout=600, stdin=subprocess.DEVNULL)
+ print(f" ✓ Model '{model}' pulled")
+ except Exception as e:
+ print(f" Warning: Could not pull '{model}': {e}\n Run manually: ollama pull {model}")
return True
def _ollama_has_model(url: str, model: str) -> bool:
"""Check if Ollama already has a model pulled."""
try:
- req = urllib.request.Request(f"{url}/api/tags", method="GET")
- resp = urllib.request.urlopen(req, timeout=5)
- data = json.loads(resp.read())
- names = [m.get("name", "") for m in data.get("models", [])]
+ names = [m.get("name", "") for m in json.loads(_http_get(url, "/api/tags", 5).read()).get("models", [])]
base_model = model.split(":")[0]
return any(model in n or base_model in n for n in names)
except Exception:
@@ -682,20 +473,13 @@ def _ensure_pgvector_extension(pg_config: dict) -> None:
import psycopg2
except ImportError:
return
- conn_params = {
- "host": pg_config.get("host", "localhost"),
- "port": pg_config.get("port", 5432),
- "user": pg_config.get("user", "postgres"),
- "dbname": pg_config.get("dbname", "postgres"),
- }
+ conn_params = {k: pg_config.get(k, d) for k, d in (("host", "localhost"), ("port", 5432), ("user", "postgres"), ("dbname", "postgres"))}
if pg_config.get("password"):
conn_params["password"] = pg_config["password"]
try:
conn = psycopg2.connect(**conn_params)
conn.autocommit = True
- cur = conn.cursor()
- cur.execute("CREATE EXTENSION IF NOT EXISTS vector")
- cur.close()
+ conn.cursor().execute("CREATE EXTENSION IF NOT EXISTS vector")
conn.close()
print(" ✓ pgvector extension enabled")
except Exception as e:
@@ -704,12 +488,10 @@ def _ensure_pgvector_extension(pg_config: dict) -> None:
def _wait_for_port(host: str, port: int, timeout: int = 15) -> None:
"""Wait until a TCP port is accepting connections."""
- import time
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
- sock = socket.create_connection((host, port), timeout=1)
- sock.close()
+ socket.create_connection((host, port), timeout=1).close()
return
except OSError:
time.sleep(0.5)
@@ -717,68 +499,54 @@ def _wait_for_port(host: str, port: int, timeout: int = 15) -> None:
def _provider_description(v: dict) -> str:
"""Description for LLM/embedder picker: model + URL if applicable."""
- model = v.get("default_model", "")
- url = v.get("default_url")
- if url:
- return f"{model} ({url})"
- return model
+ model, url = v.get("default_model", ""), v.get("default_url")
+ return f"{model} ({url})" if url else model
def _vector_description(pid: str, v: dict) -> str:
cfg = v.get("default_config", {})
if pid == "qdrant":
return cfg.get("path", "local storage")
- if pid == "pgvector":
- return f"{cfg.get('host', 'localhost')}:{cfg.get('port', 5432)}"
- return pid
+ return f"{cfg.get('host', 'localhost')}:{cfg.get('port', 5432)}" if pid == "pgvector" else pid
+
+
+def _configure_model_provider(
+ kind: str, registry: dict, hermes_home: str, env_writes: dict[str, str], llm: tuple[str, dict] | None = None,
+) -> tuple[str, dict, str, str | None]:
+ """Pick an LLM/embedder provider, collect its key, and (for Ollama) model + URL.
+ Returns (id, definition, model, url). For the embedder (``llm`` given), a provider
+ shared with the LLM reuses the LLM key instead of prompting again."""
+ items = [(v["label"], _provider_description(v)) for v in registry.values()]
+ pid = list(registry)[_curses_select(f"{kind} Provider", items, 0)]
+ pdef = registry[pid]
+ model, url = pdef["default_model"], pdef.get("default_url")
+ if pdef["needs_key"]:
+ if llm is None or pid != llm[0]:
+ label = pdef["label"] if llm is None else f"{pdef['label']} embedder"
+ key = _prompt_api_key(label, pdef["env_var"], hermes_home)
+ if key:
+ env_writes[pdef["env_var"]] = key
+ elif llm[1].get("env_var") in env_writes:
+ env_writes[pdef["env_var"]] = env_writes[llm[1]["env_var"]]
+ if pid == "ollama":
+ model = _input(f"{kind} model", pdef["default_model"])
+ url = _input("Ollama URL", pdef["default_url"])
+ return pid, pdef, model, url
def _setup_oss_interactive(hermes_home: str, config: dict) -> None:
"""Interactive OSS setup using curses pickers."""
- llm_items = [(v["label"], _provider_description(v)) for pid, v in LLM_PROVIDERS.items()]
- llm_idx = _curses_select("LLM Provider", llm_items, 0)
- llm_id = list(LLM_PROVIDERS.keys())[llm_idx]
- llm_def = LLM_PROVIDERS[llm_id]
-
env_writes: dict[str, str] = {}
- llm_model = llm_def["default_model"]
- llm_url = llm_def.get("default_url")
- if llm_def["needs_key"]:
- key = _prompt_api_key(llm_def["label"], llm_def["env_var"], hermes_home)
- if key:
- env_writes[llm_def["env_var"]] = key
- if llm_id == "ollama":
- llm_model = input(f" LLM model [{llm_def['default_model']}]: ").strip() or llm_def["default_model"]
- llm_url = input(f" Ollama URL [{llm_def['default_url']}]: ").strip() or llm_def["default_url"]
-
- embedder_items = [(v["label"], _provider_description(v)) for pid, v in EMBEDDER_PROVIDERS.items()]
- embedder_idx = _curses_select("Embedder Provider", embedder_items, 0)
- embedder_id = list(EMBEDDER_PROVIDERS.keys())[embedder_idx]
- embedder_def = EMBEDDER_PROVIDERS[embedder_id]
-
- embedder_model = embedder_def["default_model"]
- embedder_url = embedder_def.get("default_url")
- if embedder_def["needs_key"] and embedder_id != llm_id:
- key = _prompt_api_key(f"{embedder_def['label']} embedder", embedder_def["env_var"], hermes_home)
- if key:
- env_writes[embedder_def["env_var"]] = key
- elif embedder_def["needs_key"] and embedder_id == llm_id:
- if llm_def.get("env_var") in env_writes:
- env_writes[embedder_def["env_var"]] = env_writes[llm_def["env_var"]]
- if embedder_id == "ollama":
- embedder_model = input(f" Embedder model [{embedder_def['default_model']}]: ").strip() or embedder_def["default_model"]
- embedder_url = input(f" Ollama URL [{embedder_def['default_url']}]: ").strip() or embedder_def["default_url"]
+ llm_id, llm_def, llm_model, llm_url = _configure_model_provider("LLM", LLM_PROVIDERS, hermes_home, env_writes)
+ embedder_id, _, embedder_model, embedder_url = _configure_model_provider(
+ "Embedder", EMBEDDER_PROVIDERS, hermes_home, env_writes, llm=(llm_id, llm_def),
+ )
vector_items = [(v["label"], _vector_description(pid, v)) for pid, v in VECTOR_PROVIDERS.items()]
- vector_idx = _curses_select("Vector Store", vector_items, 0)
- vector_id = list(VECTOR_PROVIDERS.keys())[vector_idx]
+ vector_id = list(VECTOR_PROVIDERS)[_curses_select("Vector Store", vector_items, 0)]
# Auto-setup: ensure Ollama is running and models are pulled
- ollama_models = []
- if llm_id == "ollama":
- ollama_models.append(llm_model)
- if embedder_id == "ollama":
- ollama_models.append(embedder_model)
+ ollama_models = [m for pid, m in ((llm_id, llm_model), (embedder_id, embedder_model)) if pid == "ollama"]
if ollama_models:
_ensure_ollama(ollama_models)
@@ -787,88 +555,46 @@ def _setup_oss_interactive(hermes_home: str, config: dict) -> None:
if vector_id == "pgvector":
pgvector_config = _ensure_pgvector()
if not pgvector_config:
- # Native PostgreSQL — prompt for connection details
- default_user = os.getenv("USER", "postgres")
- pg_user = input(f" PostgreSQL user [{default_user}]: ").strip() or default_user
- pg_host = input(" PostgreSQL host [localhost]: ").strip() or "localhost"
- pg_port = input(" PostgreSQL port [5432]: ").strip() or "5432"
- pg_dbname = input(" PostgreSQL database [postgres]: ").strip() or "postgres"
+ # Native PostgreSQL — prompt for connection details (user first, matching the historical order)
+ pg = {k: _input(f"PostgreSQL {label}", d) for k, label, d in (
+ ("user", "user", os.getenv("USER", "postgres")), ("host", "host", "localhost"),
+ ("port", "port", "5432"), ("dbname", "database", "postgres"))}
pg_password = getpass.getpass(" PostgreSQL password (blank if none): ").strip()
- pgvector_config = {
- "host": pg_host, "port": int(pg_port),
- "user": pg_user, "dbname": pg_dbname,
- }
+ pgvector_config = {"host": pg["host"], "port": int(pg["port"]), "user": pg["user"], "dbname": pg["dbname"]}
if pg_password:
pgvector_config["password"] = pg_password
- user_id = input(f" User ID [{os.getenv('USER', 'hermes-user')}]: ").strip()
- user_id = user_id or os.getenv("USER", "hermes-user")
-
- agent_id = input(" Agent ID [hermes]: ").strip()
- agent_id = agent_id or "hermes"
+ user_id = _input("User ID", os.getenv("USER", "hermes-user"))
+ agent_id = _input("Agent ID", "hermes")
flags = {
- "oss_llm": llm_id,
+ "oss_llm": llm_id, "oss_llm_model": llm_model, "oss_llm_url": llm_url or "",
"oss_llm_key": env_writes.get(llm_def["env_var"], "") if llm_def.get("env_var") else "",
- "oss_llm_model": llm_model,
- "oss_llm_url": llm_url or "",
- "oss_embedder": embedder_id,
- "oss_embedder_model": embedder_model,
- "oss_embedder_url": embedder_url or "",
- "oss_vector": vector_id,
- "user_id": user_id,
+ "oss_embedder": embedder_id, "oss_embedder_model": embedder_model, "oss_embedder_url": embedder_url or "",
+ "oss_vector": vector_id, "user_id": user_id,
}
-
if pgvector_config:
- flags["oss_vector_host"] = pgvector_config["host"]
- flags["oss_vector_port"] = str(pgvector_config["port"])
- flags["oss_vector_user"] = pgvector_config["user"]
- if pgvector_config.get("password"):
- flags["oss_vector_password"] = pgvector_config["password"]
- flags["oss_vector_dbname"] = pgvector_config["dbname"]
+ for key in ("host", "port", "user", "password", "dbname"):
+ if pgvector_config.get(key):
+ flags[f"oss_vector_{key}"] = str(pgvector_config[key])
oss_config, _ = build_oss_config(flags)
-
- if env_writes:
- _write_env(Path(hermes_home) / ".env", env_writes)
- _save_mem0_json(hermes_home, {"mode": "oss", "user_id": user_id, "agent_id": agent_id, "oss": oss_config})
-
- _install_provider_deps(llm_id, embedder_id, vector_id)
-
- if vector_id == "pgvector" and pgvector_config:
- _ensure_pgvector_extension(pgvector_config)
-
- from hermes_cli.config import save_config
- config["memory"]["provider"] = "mem0"
- save_config(config)
-
- _run_connectivity_checks(oss_config)
- print("\n ✓ Mem0 configured (OSS mode)")
- print(f" LLM: {oss_config['llm']['provider']} ({oss_config['llm']['config'].get('model', '')})")
- print(f" Embedder: {oss_config['embedder']['provider']} ({oss_config['embedder']['config'].get('model', '')})")
- print(f" Vector: {vector_id}")
- if env_writes:
- print(" API keys saved to .env")
- print(" Config saved to mem0.json")
- print(" Provider set in config.yaml")
- print("\n Start a new session to activate.\n")
+ _finish_oss(hermes_home, config, oss_config, env_writes, user_id, agent_id, pgvector_config)
def _install_provider_deps(llm_id: str, embedder_id: str, vector_id: str) -> None:
"""Install all optional pip deps for selected providers."""
- deps: set[str] = set()
- for registry, pid in [(LLM_PROVIDERS, llm_id), (EMBEDDER_PROVIDERS, embedder_id),
- (VECTOR_PROVIDERS, vector_id)]:
- dep = registry.get(pid, {}).get("pip_dep")
- if dep:
- deps.add(dep)
+ deps = {
+ registry[pid]["pip_dep"]
+ for (_, registry), pid in zip(SECTION_REGISTRIES, (llm_id, embedder_id, vector_id))
+ if registry.get(pid, {}).get("pip_dep")
+ }
for dep in sorted(deps):
try:
print(f" Installing {dep}...")
# Environment-aware install: sealed hosted venvs redirect to the
- # durable data-volume target instead of /opt/hermes (NS-605).
+ # durable data-volume target instead of /opt/hermes.
from tools.lazy_deps import install_specs
-
outcome = install_specs([dep], timeout=60)
if outcome.ok:
print(f" ✓ Installed {dep}")
@@ -885,8 +611,7 @@ def _install_provider_deps(llm_id: str, embedder_id: str, vector_id: str) -> Non
def _check_qdrant_path(path: str) -> tuple[bool, str]:
"""Check that qdrant local storage parent dir is writable."""
- p = Path(path).expanduser()
- parent = p.parent
+ parent = Path(path).expanduser().parent
try:
parent.mkdir(parents=True, exist_ok=True)
return True, f"Directory writable: {parent}"
@@ -897,8 +622,7 @@ def _check_qdrant_path(path: str) -> tuple[bool, str]:
def _check_ollama(url: str) -> tuple[bool, str]:
"""Check Ollama is reachable via /api/tags."""
try:
- req = urllib.request.Request(f"{url.rstrip('/')}/api/tags", method="GET")
- urllib.request.urlopen(req, timeout=3)
+ _http_get(url, "/api/tags", 3)
return True, "Ollama reachable"
except Exception as e:
return False, f"Ollama not reachable at {url}: {e}"
@@ -907,41 +631,37 @@ def _check_ollama(url: str) -> tuple[bool, str]:
def _check_pgvector(host: str, port: int) -> tuple[bool, str]:
"""Check PGVector via TCP socket."""
try:
- sock = socket.create_connection((host, port), timeout=3)
- sock.close()
+ socket.create_connection((host, port), timeout=3).close()
return True, f"PGVector reachable at {host}:{port}"
except Exception as e:
return False, f"PGVector not reachable at {host}:{port}: {e}"
+def _warn_unless(check: tuple[bool, str]) -> None:
+ ok, msg = check
+ if not ok:
+ print(f" Warning: {msg}")
+
+
def _run_connectivity_checks(oss_config: dict) -> None:
"""Run connectivity checks and print warnings."""
vs = oss_config.get("vector_store", {})
+ cfg = vs.get("config", {})
if vs.get("provider") == "qdrant":
- path = vs.get("config", {}).get("path")
- url = vs.get("config", {}).get("url")
+ path, url = cfg.get("path"), cfg.get("url")
if path:
- ok, msg = _check_qdrant_path(path)
- if not ok:
- print(f" Warning: {msg}")
+ _warn_unless(_check_qdrant_path(path))
elif url:
try:
- req = urllib.request.Request(f"{url.rstrip('/')}/healthz", method="GET")
- urllib.request.urlopen(req, timeout=3)
+ _http_get(url, "/healthz", 3)
except Exception as e:
print(f" Warning: Qdrant not reachable at {url}: {e}")
elif vs.get("provider") == "pgvector":
- cfg = vs.get("config", {})
- ok, msg = _check_pgvector(cfg.get("host", "localhost"), cfg.get("port", 5432))
- if not ok:
- print(f" Warning: {msg}")
+ _warn_unless(_check_pgvector(cfg.get("host", "localhost"), cfg.get("port", 5432)))
llm = oss_config.get("llm", {})
if llm.get("provider") == "ollama":
- url = llm.get("config", {}).get("ollama_base_url", "http://localhost:11434")
- ok, msg = _check_ollama(url)
- if not ok:
- print(f" Warning: {msg}")
+ _warn_unless(_check_ollama(llm.get("config", {}).get("ollama_base_url", "http://localhost:11434")))
def _check_min_dep_version() -> None:
@@ -949,55 +669,36 @@ def _check_min_dep_version() -> None:
try:
import mem0
installed_ver = getattr(mem0, "__version__", None)
- if not installed_ver:
- return
- installed_parts = tuple(int(x) for x in installed_ver.split(".")[:3])
- required_parts = (2, 0, 7)
- if installed_parts < required_parts:
- req_str = ".".join(str(x) for x in required_parts)
- print(f"\n ⚠ mem0ai {installed_ver} installed but >={req_str} required.")
- print(f" Run: uv pip install --python {sys.executable} 'mem0ai>={req_str}'")
- except ImportError:
- pass
+ if installed_ver and tuple(int(x) for x in installed_ver.split(".")[:3]) < (2, 0, 7):
+ print(f"\n ⚠ mem0ai {installed_ver} installed but >=2.0.7 required.\n"
+ f" Run: uv pip install --python {sys.executable} 'mem0ai>=2.0.7'")
except Exception:
pass
-def post_setup(hermes_home: str, config: dict) -> None:
- """Entry point called by hermes memory setup framework.
+_MODE_HANDLERS = {
+ "oss": _setup_oss,
+ "selfhosted": _setup_selfhosted,
+ "self-hosted": _setup_selfhosted,
+ "platform": _setup_platform,
+}
+# Interactive picker order: Platform, Self-hosted server, Open Source.
+_MODE_ITEMS = [
+ ("Platform", "Mem0 Cloud API (lightweight, just needs an API key)"),
+ ("Self-hosted server", "Connect to an existing self-hosted Mem0 server (Docker/FastAPI)"),
+ ("Open Source", "Run Mem0 locally (self-hosted LLM + vector store)"),
+]
+_MODE_PICKER = (_setup_platform, _setup_selfhosted, _setup_oss)
+
- Routes on --mode (platform / selfhosted / oss); with no flag it shows an
- interactive picker with all three modes. Platform keeps the framework's
- original schema-based onboarding; selfhosted points at an existing Mem0
- server; oss builds a local SDK config.
- """
+def post_setup(hermes_home: str, config: dict) -> None:
+ """Entry point called by hermes memory setup framework. Routes on --mode
+ (platform / selfhosted / oss); with no flag shows a picker. OSS is
+ non-interactive only when the mode came from the flag."""
_check_min_dep_version()
flags = parse_flags(sys.argv[1:])
-
- if flags["mode"] == "oss":
- flags["_mode_from_flag"] = True
- _setup_oss(hermes_home, config, flags)
- return
-
- if flags["mode"] in ("selfhosted", "self-hosted"):
- _setup_selfhosted(hermes_home, config, flags)
- return
-
- if flags["mode"] == "platform":
- _setup_platform(hermes_home, config, flags)
- return
-
- # No --mode flag: show interactive picker
- mode_items = [
- ("Platform", "Mem0 Cloud API (lightweight, just needs an API key)"),
- ("Self-hosted server", "Connect to an existing self-hosted Mem0 server (Docker/FastAPI)"),
- ("Open Source", "Run Mem0 locally (self-hosted LLM + vector store)"),
- ]
- mode_idx = _curses_select(" Select mode", mode_items, 0)
- if mode_idx == 1:
- _setup_selfhosted(hermes_home, config, flags)
- elif mode_idx == 2:
- flags["_mode_from_flag"] = False
- _setup_oss(hermes_home, config, flags)
- else:
- _setup_platform(hermes_home, config, flags)
+ handler = _MODE_HANDLERS.get(flags["mode"])
+ flags["_mode_from_flag"] = handler is not None
+ if handler is None:
+ handler = _MODE_PICKER[_curses_select(" Select mode", _MODE_ITEMS, 0)]
+ handler(hermes_home, config, flags)