a9838c2100
Under gateway.multiplex_profiles, os.environ holds the DEFAULT profile's .env; a
secondary profile's values exist only in the per-turn secret scope. Every reader
below still read os.environ/os.getenv at call time, so a secondary profile's turn
silently used the default profile's value.
Credentials (F6): FIRECRAWL_API_KEY (read_file hosted OCR), OPENVIKING_API_KEY,
mem0-OSS OPENAI_API_KEY, MODAL_TOKEN_ID/SECRET and BROWSER_USE_API_KEY presence
gates, and the xAI video plugin's os.getenv("XAI_API_KEY") fallback AFTER the
scoped resolver had already missed — the exact fallback-after-miss shape
gateway/AGENTS.md forbids. Deleted, not re-scoped: the resolver is the scope.
Identity / tenant (F7): MEM0_USER_ID/AGENT_ID/HOST/MODE, SUPERMEMORY_CONTAINER_TAG,
RETAINDB_PROJECT, OPENVIKING_ACCOUNT/USER/AGENT (and the whole layered() env
read), HINDSIGHT_BANK_ID/MODE/retain shaping, HERMES_HONCHO_HOST. A raw read
put a secondary profile's memories into the default profile's account/bank/
project/tenant and recalled them back into the default's turns. Each now uses
get_secret with the provider's own per-profile default on a miss.
Endpoints (F8): OPENAI_BASE_URL (aux custom runtime + direct-alias expansion),
XAI_BASE_URL/HERMES_XAI_BASE_URL (aux OAuth), NOUS_INFERENCE_BASE_URL (#65941,
both the aux builder and hermes_cli.auth_nous._nous_inference_env_override),
GATEWAY_PROXY_URL (same UnscopedSecretError-only fallback shape as
GATEWAY_PROXY_KEY three lines below), FIRECRAWL_API_URL, BROWSERBASE_BASE_URL,
SUPERMEMORY/RETAINDB/HONCHO/HINDSIGHT URLs. The keys beside them were already
scoped, so a secondary's key was sent to the default profile's proxy or host.
Targets / display (F11): WEIXIN_HOME_CHANNEL (message posted into the default's
chat), HERMES_LANGUAGE, and agent/i18n's process-wide lru_cache of
display.language — now keyed by HERMES_HOME.
Outbound webhooks: hooks.outbound[].secret_env resolved from os.environ while
the gateway registers each profile's targets inside that profile's scope, so a
secondary's deliveries were signed with the default's secret or left unsigned.
Agent-cache eviction: _spawn_release_thread started a bare threading.Thread, so
commit_memory_session -> provider on_session_end ran with an EMPTY context. The
thread now runs copy_context() and, for the unscoped housekeeping sweep, enters
the owning profile's _profile_runtime_scope resolved from the session key
(agent:<profile>:...). The pressure batch does the same per key.
session_search (#82903): agent/inline_tool_executors.py::_session_search
forwarded every schema argument except `profile`, so a gateway agent could
never select a named profile's store. Forwarded; the ownership-scoping design
in #87779/#87847 is a separate design call and is not attempted here.
Live repro (/tmp/mux_audit/fix-tool-memory-reads/repro.py): 28 FAIL on
origin/main -> 0 FAIL with this change; 10 new invariant tests red on base.
Fixes #82903
Fixes #65941
Fixes #99121
Addresses #87779
Co-authored-by: webtecnica <75556242+webtecnica@users.noreply.github.com>
Co-authored-by: Michael Versluis (Berry) <michael@wve.nl>
67 lines
3.5 KiB
Python
67 lines
3.5 KiB
Python
"""OpenAI-only LLM adapter for Mem0 OSS mode."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
from typing import Dict, List, Optional, Union
|
|
|
|
from mem0.configs.llms.base import BaseLlmConfig
|
|
from mem0.configs.llms.openai import OpenAIConfig
|
|
from mem0.llms.base import LLMBase
|
|
from mem0.llms.openai import OpenAILLM
|
|
|
|
# BaseLlmConfig fields copied into OpenAIConfig; the last two may be absent on older mem0.
|
|
_COPIED_FIELDS = ("model", "temperature", "api_key", "max_tokens", "top_p", "top_k", "enable_vision", "vision_details", "http_client_proxies")
|
|
_OPTIONAL_FIELDS = ("reasoning_effort", "is_reasoning_model")
|
|
|
|
|
|
class DirectOpenAILLM(OpenAILLM):
|
|
"""Use OpenAI credentials and requests regardless of router environment."""
|
|
|
|
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):
|
|
fields = {k: getattr(config, k) for k in _COPIED_FIELDS}
|
|
fields.update({k: getattr(config, k, None) for k in _OPTIONAL_FIELDS})
|
|
config = OpenAIConfig(**fields)
|
|
if not config.model:
|
|
config.model = "gpt-5-mini"
|
|
# 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 picks OpenRouter when OPENROUTER_API_KEY is
|
|
# set); LLMBase still owns validation and supported-parameter filtering.
|
|
LLMBase.__init__(self, config)
|
|
# OPENAI_API_KEY / OPENAI_BASE_URL are profile credentials: read them through the secret
|
|
# scope, never raw os.environ, or a multiplexed secondary's memory extraction runs on the
|
|
# default profile's OpenAI account (and its proxy).
|
|
from agent.secret_scope import get_secret
|
|
api_key = self.config.api_key or get_secret("OPENAI_API_KEY", "")
|
|
if not api_key:
|
|
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=self.config.openai_base_url or get_secret("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):
|
|
params = self._get_supported_params(messages=messages, **kwargs)
|
|
params.update({"model": self.config.model, "messages": messages})
|
|
# 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"], 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:
|
|
try:
|
|
self.config.response_callback(self, response, params)
|
|
except Exception:
|
|
logging.error("Error running Mem0 OpenAI response callback")
|
|
return parsed_response
|