Skip to content

FinceptTerminal is a modern finance application offering advanced market analytics, investment research, and economic data tools, designed for interactive exploration and data-driven decision-making in a user-friendly environment.

feat(finagent): add PersonaRegistry LRU cache for runtimes

tilakpatel225640981a9dbc
diff --git a/fincept-qt/scripts/agents/finagent_core/persona_registry.py b/fincept-qt/scripts/agents/finagent_core/persona_registry.py
new file mode 100644
index 000000000..fb685aaf2
--- /dev/null
+++ b/fincept-qt/scripts/agents/finagent_core/persona_registry.py
@@ -0,0 +1,72 @@
+"""
+PersonaRegistry — LRU cache of PersonaRuntime instances.
+
+Keyed by (user_id, agent_id). Cap default 8, tunable via
+FINAGENT_RUNTIME_CACHE_SIZE env var. When full, evicts least-recently-used
+runtime and calls its close() before dropping the reference.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from collections import OrderedDict
+from typing import Any, Dict, Tuple
+
+from finagent_core.persona_runtime import PersonaRuntime
+
+logger = logging.getLogger(__name__)
+
+
+class PersonaRegistry:
+ """LRU cache of PersonaRuntime objects."""
+
+ def __init__(self, cap: int = None):
+ if cap is None:
+ try:
+ cap = int(os.getenv("FINAGENT_RUNTIME_CACHE_SIZE", "8"))
+ except ValueError:
+ cap = 8
+ self.cap = max(1, cap)
+ self._items: "OrderedDict[Tuple[str, str], PersonaRuntime]" = OrderedDict()
+
+ def get_or_create(self,
+ user_id: str,
+ agent_id: str,
+ config: Dict[str, Any],
+ api_keys: Dict[str, str]) -> PersonaRuntime:
+ key = (user_id, agent_id)
+ if key in self._items:
+ self._items.move_to_end(key)
+ return self._items[key]
+
+ runtime = PersonaRuntime.build(
+ user_id=user_id,
+ agent_id=agent_id,
+ config=config,
+ api_keys=api_keys,
+ )
+ self._items[key] = runtime
+
+ while len(self._items) > self.cap:
+ evicted_key, evicted_rt = self._items.popitem(last=False)
+ try:
+ evicted_rt.close()
+ except Exception as e:
+ logger.warning(f"Evicting {evicted_key}: close() raised {e}")
+
+ return runtime
+
+ def clear(self) -> None:
+ while self._items:
+ _, rt = self._items.popitem(last=False)
+ try:
+ rt.close()
+ except Exception as e:
+ logger.debug(f"clear(): close() raised {e}")
+
+ def __len__(self) -> int:
+ return len(self._items)
+
+ def __contains__(self, key: Tuple[str, str]) -> bool:
+ return key in self._items
diff --git a/fincept-qt/scripts/agents/finagent_core/tests/test_persona_registry.py b/fincept-qt/scripts/agents/finagent_core/tests/test_persona_registry.py
new file mode 100644
index 000000000..69fdb1268
--- /dev/null
+++ b/fincept-qt/scripts/agents/finagent_core/tests/test_persona_registry.py
@@ -0,0 +1,79 @@
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from finagent_core.persona_registry import PersonaRegistry
+
+
+def _cfg():
+ return {"model": {"provider": "openai", "model_id": "x", "api_key": "k"},
+ "instructions": ""}
+
+
+def test_cap_default_is_8(monkeypatch):
+ monkeypatch.delenv("FINAGENT_RUNTIME_CACHE_SIZE", raising=False)
+ reg = PersonaRegistry()
+ assert reg.cap == 8
+
+
+def test_cap_respects_env(monkeypatch):
+ monkeypatch.setenv("FINAGENT_RUNTIME_CACHE_SIZE", "3")
+ reg = PersonaRegistry()
+ assert reg.cap == 3
+
+
+def test_get_or_create_caches(monkeypatch):
+ reg = PersonaRegistry()
+ with patch("finagent_core.persona_registry.PersonaRuntime") as mock_rt:
+ mock_rt.build.return_value = MagicMock()
+ r1 = reg.get_or_create("u", "a", _cfg(), api_keys={})
+ r2 = reg.get_or_create("u", "a", _cfg(), api_keys={})
+ assert r1 is r2
+ assert mock_rt.build.call_count == 1
+
+
+def test_eviction_calls_close(monkeypatch):
+ monkeypatch.setenv("FINAGENT_RUNTIME_CACHE_SIZE", "2")
+ reg = PersonaRegistry()
+ closed = []
+ def _mk_runtime(user_id, agent_id, config, api_keys):
+ rt = MagicMock()
+ rt.close = lambda a=agent_id: closed.append(a)
+ return rt
+ with patch("finagent_core.persona_registry.PersonaRuntime") as mock_rt:
+ mock_rt.build.side_effect = lambda user_id, agent_id, config, api_keys: _mk_runtime(
+ user_id, agent_id, config, api_keys
+ )
+ reg.get_or_create("u", "a1", _cfg(), api_keys={})
+ reg.get_or_create("u", "a2", _cfg(), api_keys={})
+ reg.get_or_create("u", "a3", _cfg(), api_keys={}) # evicts a1
+ assert closed == ["a1"]
+
+
+def test_access_updates_lru_order(monkeypatch):
+ monkeypatch.setenv("FINAGENT_RUNTIME_CACHE_SIZE", "2")
+ reg = PersonaRegistry()
+ closed = []
+ with patch("finagent_core.persona_registry.PersonaRuntime") as mock_rt:
+ mock_rt.build.side_effect = lambda user_id, agent_id, config, api_keys: MagicMock(
+ close=lambda a=agent_id: closed.append(a)
+ )
+ reg.get_or_create("u", "a1", _cfg(), api_keys={})
+ reg.get_or_create("u", "a2", _cfg(), api_keys={})
+ reg.get_or_create("u", "a1", _cfg(), api_keys={}) # refresh a1 → a2 is now LRU
+ reg.get_or_create("u", "a3", _cfg(), api_keys={}) # evicts a2
+ assert closed == ["a2"]
+
+
+def test_clear_closes_all():
+ reg = PersonaRegistry()
+ closed = []
+ with patch("finagent_core.persona_registry.PersonaRuntime") as mock_rt:
+ mock_rt.build.side_effect = lambda user_id, agent_id, config, api_keys: MagicMock(
+ close=lambda a=agent_id: closed.append(a)
+ )
+ reg.get_or_create("u", "a1", _cfg(), api_keys={})
+ reg.get_or_create("u", "a2", _cfg(), api_keys={})
+ reg.clear()
+ assert set(closed) == {"a1", "a2"}
+ assert len(reg) == 0