actrone_memory package¶
Subpackages¶
- actrone_memory.benchmark package
- Submodules
- Module contents
- actrone_memory.integrations package
- Submodules
- actrone_memory.integrations.agno module
- actrone_memory.integrations.autogen module
- actrone_memory.integrations.aws_strands module
- actrone_memory.integrations.claude_agent_sdk module
- actrone_memory.integrations.crewai module
- actrone_memory.integrations.dspy module
- actrone_memory.integrations.google_adk module
- actrone_memory.integrations.haystack module
- actrone_memory.integrations.langchain module
- actrone_memory.integrations.langgraph module
- actrone_memory.integrations.llamaindex module
- actrone_memory.integrations.microsoft_agent_framework module
- actrone_memory.integrations.openai_agents module
- actrone_memory.integrations.pydantic_ai module
- actrone_memory.integrations.semantic_kernel module
- actrone_memory.integrations.smolagents module
- Module contents
- Submodules
- actrone_memory.l1 package
- actrone_memory.l2 package
Submodules¶
- actrone_memory.cli module
- actrone_memory.config module
resolve_relevance_threshold()MemoryConfigMemoryConfig.model_configMemoryConfig.backendMemoryConfig.redis_urlMemoryConfig.qdrant_urlMemoryConfig.qdrant_api_keyMemoryConfig.redis_max_connectionsMemoryConfig.redis_socket_timeoutMemoryConfig.redis_socket_connect_timeoutMemoryConfig.qdrant_timeoutMemoryConfig.embedding_providerMemoryConfig.openai_api_keyMemoryConfig.embedding_modelMemoryConfig.embedding_dimensionsMemoryConfig.hashing_dimensionsMemoryConfig.embedding_cache_ttl_secondsMemoryConfig.summarisation_modelMemoryConfig.session_ttl_hoursMemoryConfig.max_session_turnsMemoryConfig.qdrant_collectionMemoryConfig.max_episodic_memoriesMemoryConfig.relevance_thresholdMemoryConfig.relevance_weightMemoryConfig.recency_weightMemoryConfig.hybrid_retrievalMemoryConfig.rerank_enabledMemoryConfig.rerank_modelMemoryConfig.rerank_top_kMemoryConfig.extract_factsMemoryConfig.auto_summariseMemoryConfig.summarise_after_turnsMemoryConfig.summarise_cooldown_secondsMemoryConfig.strict_background_errorsMemoryConfig.shutdown_grace_secondsMemoryConfig.token_counterMemoryConfig.budget_fraction_systemMemoryConfig.budget_fraction_episodicMemoryConfig.budget_fraction_sessionMemoryConfig.budget_fraction_current_turnMemoryConfig.validate_runtime()
- actrone_memory.exceptions module
- actrone_memory.extraction module
- actrone_memory.in_memory module
cosine_similarity()InMemoryStoreInMemoryStore.append_turn()InMemoryStore.get_recent_turns()InMemoryStore.turn_count()InMemoryStore.clear_session()InMemoryStore.get_session_metadata()InMemoryStore.try_acquire_summary_lock()InMemoryStore.upsert()InMemoryStore.search()InMemoryStore.delete()InMemoryStore.delete_agent_memories()InMemoryStore.close()
- actrone_memory.logging module
- actrone_memory.manager module
MemoryManagerMemoryManager.relevance_thresholdMemoryManager.store_turn()MemoryManager.retrieve_context()MemoryManager.inject_memory()MemoryManager.delete_memory()MemoryManager.erase_agent_memories()MemoryManager.clear_session()MemoryManager.search_memories()MemoryManager.get_session_metadata()MemoryManager.get_recent_turns()MemoryManager.extract_memories()MemoryManager.create()MemoryManager.close()
create_memory_manager()
- actrone_memory.metrics module
- actrone_memory.models module
ToolResultMemoryEntryMemoryEntry.idMemoryEntry.agent_idMemoryEntry.session_idMemoryEntry.contentMemoryEntry.content_typeMemoryEntry.embeddingMemoryEntry.importance_scoreMemoryEntry.topic_tagsMemoryEntry.token_countMemoryEntry.timestampMemoryEntry.source_turn_idsMemoryEntry.sourceMemoryEntry.sensitivityMemoryEntry.model_config
TurnRetrievedContextSessionMetadata
- actrone_memory.protocols module
- actrone_memory.recipes module
- actrone_memory.rerank module
- actrone_memory.retrieval module
Module contents¶
actrone-memory, Two-tier persistent memory for AI agents.
Local-first by default: MemoryManager.create() runs with zero external
services and no API key (in-process store, plus the best local embedder
available: in-process ONNX if the onnx extra is installed, then
sentence-transformers, then a dependency-free lexical hashing fallback).
Set backend="redis_qdrant" and an embedding provider for the durable path.
- class actrone_memory.MemoryManager(l1, l2, embedder, config, summariser=None, extractor=None, reranker=None)[source]¶
Bases:
objectTwo-tier persistent agent memory: Redis L1 (hot) + Qdrant L2 (cold semantic).
Do not instantiate directly. Use
MemoryManager.create()or thecreate_memory_manager()context manager.Usage:
mm = await MemoryManager.create() await mm.store_turn(agent_id, session_id, user_msg, assistant_msg) ctx = await mm.retrieve_context(agent_id, session_id, query, token_budget=4096) await mm.close()
Or let
create_memory_manager()close it for you:async with create_memory_manager() as mm: ...
- Parameters:
l1 (L1Store)
l2 (L2Store)
embedder (Embedder)
config (MemoryConfig)
summariser (_Summariser | None)
extractor (FactExtractor | None)
reranker (CrossEncoderReranker | None)
- property relevance_threshold: float¶
The admission threshold applied to long-term memories.
config.relevance_thresholdwhen set, else the embedder’s calibrated threshold, else the library default.
- async store_turn(agent_id, session_id, user_message, assistant_message, tool_results=None)[source]¶
Persist a conversation turn to Redis L1.
Also triggers background summarisation to Qdrant L2 once the session reaches
summarise_after_turnsturns.- Parameters:
agent_id (str) – Unique identifier for the agent (e.g.
"support-bot").session_id (str) – Unique identifier for the conversation session.
user_message (str) – The user’s raw message text.
assistant_message (str) – The agent’s response text.
tool_results (list[ToolResult] | None) – Optional tool call results from this turn.
- Returns:
The turn ID (UUID string).
- Raises:
ValidationError – If any argument fails length or format validation.
StoreConnectionError – If the Redis write fails after retries.
- Return type:
- async retrieve_context(agent_id, session_id, query, token_budget)[source]¶
Fetch relevant context for the next LLM call using the 4-phase pipeline.
Phase 1, Parallel fetch: Redis L1 (recent turns) + Qdrant L2 (semantic search) run concurrently to minimise latency (<50 ms P99).
Phase 2, Budget allocation: the token budget is divided between system prompt, episodic memory, session turns, and the current turn using the fractions in MemoryConfig.
Phase 3, Relevance ranking: Qdrant results are filtered at the configured threshold and re-ranked by
0.7 × cosine_similarity + 0.3 × recency_score.Phase 4, Priority pruning: if results exceed the allocated budget, oldest session turns are dropped first, then lowest-ranked memories. The system-prompt budget is never consumed by this method.
- Parameters:
- Returns:
RetrievedContext with recent_turns, episodic_memories, and budget stats.
- Raises:
TokenBudgetError – If
token_budgetis 0 or negative.ValidationError – If agent_id or session_id are invalid.
StoreConnectionError – If Redis or Qdrant fail after retries.
EmbeddingError – If the embedding call fails after retries.
- Return type:
- async inject_memory(agent_id, content, importance=0.8, session_id='injected', topic_tags=None, source='injected', sensitivity='none')[source]¶
Write a fact directly into L2 long-term memory.
Use this to seed an agent with background knowledge before a conversation starts, e.g. user preferences, company policies, domain facts.
- Parameters:
agent_id (str) – The agent that should have access to this memory.
content (str) – Text of the memory. Write it as a clear, self-contained sentence.
importance (float) – Score from 0.0 to 1.0. Higher values surface this memory more readily. Recommended ≥ 0.8 for facts you always want recalled.
session_id (str) – Label for where this memory came from. Defaults to
"injected".topic_tags (list[str] | None) – Optional keywords describing the memory topic.
source (str) – Provenance attribution, where this fact originated (e.g.
"injected","import:crm","tool:web_search").sensitivity (Literal['none', 'low', 'pii', 'sensitive']) – PII/sensitivity classification for governance and right-to-erasure (
"none"|"low"|"pii"|"sensitive").
- Returns:
The memory ID (UUID). Save this to delete the memory later.
- Raises:
ValidationError – If any argument fails validation.
StoreConnectionError – If the Qdrant write fails after retries.
EmbeddingError – If embedding generation fails after retries.
- Return type:
- async delete_memory(agent_id, memory_id)[source]¶
Permanently remove a memory from Qdrant L2 by ID.
- Parameters:
- Raises:
MemoryNotFoundError – If the memory_id does not exist in Qdrant.
StoreConnectionError – If the Qdrant delete fails after retries.
- Return type:
None
- async erase_agent_memories(agent_id, session_id=None)[source]¶
Local right-to-erasure, irreversibly delete an agent’s long-term memories.
This is the governance seed that graduates to hosted provable erasure: in the OSS library it performs a hard local delete. If
session_idis given, the session’s short-term (L1) turns are cleared too; otherwise only the durable L2 store is wiped (L1 turns are ephemeral and expire on their TTL).- Parameters:
- Raises:
ValidationError – If arguments are invalid.
StoreConnectionError – If the underlying delete fails after retries.
- Return type:
None
- async clear_session(agent_id, session_id)[source]¶
Delete all Redis L1 turns for a session.
Long-term Qdrant memories (summaries, injected facts) are NOT deleted, they persist across sessions by design.
- Raises:
ValidationError – If arguments are invalid.
StoreConnectionError – If the Redis delete fails after retries.
- Parameters:
- Return type:
None
- async search_memories(agent_id, query, limit=10)[source]¶
Semantic search over Qdrant L2 for a given agent.
Results are ranked by the same formula used in
retrieve_context():0.7 × cosine_similarity + 0.3 × recency_score.- Parameters:
- Returns:
List of MemoryEntry objects, sorted by descending relevance score.
- Raises:
ValidationError – If arguments are invalid.
StoreConnectionError – If Qdrant is unreachable.
EmbeddingError – If embedding generation fails.
- Return type:
- async get_session_metadata(agent_id, session_id)[source]¶
Return basic stats about a session (turn count, created_at, last_active).
Returns None if the session does not exist or has expired from Redis.
- Parameters:
- Return type:
SessionMetadata | None
- async get_recent_turns(agent_id, session_id, n=None)[source]¶
Return recent session turns, oldest first, capped at
n.The raw history read that framework memory adapters build on (for example a LangChain
BaseChatMessageHistoryor a LlamaIndex memory), so they do not have to reach into the L1 store directly. Defaults to everything L1 still retains.- Raises:
ValidationError – If arguments are invalid.
StoreConnectionError – If the underlying read fails after retries.
- Parameters:
- Return type:
- async extract_memories(agent_id, session_id, n=None)[source]¶
Extract durable facts from a session’s recent turns and store them.
Turns → atomic facts (
content_type="fact",source="extracted"), each with an LLM-classified sensitivity. This is the “credible beyond turn storage” capability; it is LLM-gated, aFactExtractormust be configured (MemoryConfig.extract_facts=Truewith the OpenAI provider), otherwise aConfigurationErroris raised.- Parameters:
- Returns:
The memory IDs of the stored facts (empty if nothing durable was found).
- Raises:
ConfigurationError – If no fact extractor is configured.
ValidationError – If arguments are invalid.
- Return type:
- async classmethod create(config=None, *, l1=None, l2=None, embedder=None, extractor=None, reranker=None)[source]¶
Build a ready MemoryManager for the configured backend.
The default backend is
"memory", a zero-service, in-process store, and the default embedding provider is"local", which picks the best local embedder available (in-process ONNX, then sentence-transformers, then a dependency-free lexical hashing fallback). Socreate()needs no Redis, no Qdrant, and no API key (parity with the TypeScript on-ramp). Passembedding_provider="hashing"to force the fallback and skip any model download. Setbackend="redis_qdrant"(envACTRONE_BACKEND=redis_qdrant) for the durable, horizontally-scalable production path.Reads configuration from environment variables when config is None.
- Parameters:
config (MemoryConfig | None) – Settings to use. Read from the environment when None.
l1 (L1Store | None) – Custom hot-tier store satisfying the
L1Storeprotocol.l2 (L2Store | None) – Custom long-term store satisfying the
L2Storeprotocol.embedder (Embedder | None) – Custom
Embedder, used instead of the configured provider.extractor (FactExtractor | None) – Custom
FactExtractor, used instead of the OpenAI one the config would build. Lets you extract facts without an OpenAI key.reranker (CrossEncoderReranker | None) – Custom reranker, used instead of the one
rerank_enabledbuilds.
- Return type:
Only Redis and Qdrant adapters ship with this package.
l1/l2are the supported way to run any other engine (pgvector, Weaviate, Valkey, and so on) without constructing the manager by hand: anything satisfying the protocol works. Whatever you inject is used as-is, and the corresponding backend is not built or connected, so injecting both stores never opens a Redis or Qdrant connection. You own the lifecycle of an injected store;close()still calls itsclose().- Raises:
ConfigurationError – If required settings are missing or invalid.
StoreConnectionError – If Redis or Qdrant cannot be reached (
redis_qdrantbackend only).
- Parameters:
config (MemoryConfig | None)
l1 (L1Store | None)
l2 (L2Store | None)
embedder (Embedder | None)
extractor (FactExtractor | None)
reranker (CrossEncoderReranker | None)
- Return type:
- class actrone_memory.MemoryConfig(_case_sensitive=None, _nested_model_default_partial_update=None, _env_prefix=None, _env_prefix_target=None, _env_file=WindowsPath('.'), _env_file_encoding=None, _env_ignore_empty=None, _env_nested_delimiter=None, _env_nested_max_split=None, _env_parse_none_str=None, _env_parse_enums=None, _cli_prog_name=None, _cli_parse_args=None, _cli_settings_source=None, _cli_parse_none_str=None, _cli_hide_none_type=None, _cli_avoid_json=None, _cli_enforce_required=None, _cli_use_class_docs_for_groups=None, _cli_exit_on_error=None, _cli_prefix=None, _cli_flag_prefix_char=None, _cli_implicit_flags=None, _cli_ignore_unknown_args=None, _cli_kebab_case=None, _cli_shortcuts=None, _secrets_dir=None, _build_sources=None, *, backend='memory', redis_url='redis://localhost:6379', qdrant_url='http://localhost:6333', qdrant_api_key=None, redis_max_connections=10, redis_socket_timeout=5.0, redis_socket_connect_timeout=5.0, qdrant_timeout=10.0, embedding_provider='local', openai_api_key=None, embedding_model='text-embedding-3-small', embedding_dimensions=1536, hashing_dimensions=256, embedding_cache_ttl_seconds=604800, summarisation_model='gpt-4o-mini', session_ttl_hours=24, max_session_turns=50, qdrant_collection='agent_memories', max_episodic_memories=500, relevance_threshold=None, relevance_weight=0.7, recency_weight=0.3, hybrid_retrieval=True, rerank_enabled=False, rerank_model='Xenova/ms-marco-MiniLM-L-6-v2', rerank_top_k=20, extract_facts=False, auto_summarise=True, summarise_after_turns=20, summarise_cooldown_seconds=300, strict_background_errors=False, shutdown_grace_seconds=30.0, token_counter='heuristic', budget_fraction_system=0.3, budget_fraction_episodic=0.25, budget_fraction_session=0.35, budget_fraction_current_turn=0.1)[source]¶
Bases:
BaseSettingsAll configuration for actrone-memory.
Values are read from environment variables with the
ACTRONE_prefix. You can also pass values directly when constructing this object.- Required only when
embedding_provider="openai": ACTRONE_OPENAI_API_KEY
All other settings have sensible defaults. The default provider is
"local", a local-first, zero-egress dense embedder that needs no API key (see below).- Parameters:
_case_sensitive (bool | None)
_nested_model_default_partial_update (bool | None)
_env_prefix (str | None)
_env_prefix_target (EnvPrefixTarget | None)
_env_file (DotenvType | None)
_env_file_encoding (str | None)
_env_ignore_empty (bool | None)
_env_nested_delimiter (str | None)
_env_nested_max_split (int | None)
_env_parse_none_str (str | None)
_env_parse_enums (bool | None)
_cli_prog_name (str | None)
_cli_settings_source (CliSettingsSource[Any] | None)
_cli_parse_none_str (str | None)
_cli_hide_none_type (bool | None)
_cli_avoid_json (bool | None)
_cli_enforce_required (bool | None)
_cli_use_class_docs_for_groups (bool | None)
_cli_exit_on_error (bool | None)
_cli_prefix (str | None)
_cli_flag_prefix_char (str | None)
_cli_implicit_flags (bool | Literal['dual', 'toggle'] | None)
_cli_ignore_unknown_args (bool | None)
_cli_kebab_case (bool | Literal['all', 'no_enums'] | None)
_secrets_dir (PathType | None)
_build_sources (tuple[tuple[PydanticBaseSettingsSource, ...], dict[str, Any]] | None)
backend (Literal['memory', 'redis_qdrant'])
redis_url (str)
qdrant_url (str)
qdrant_api_key (SecretStr | None)
redis_max_connections (int)
redis_socket_timeout (float)
redis_socket_connect_timeout (float)
qdrant_timeout (float)
embedding_provider (Literal['openai', 'local', 'hashing'])
openai_api_key (SecretStr | None)
embedding_model (str)
embedding_dimensions (int)
hashing_dimensions (int)
embedding_cache_ttl_seconds (int)
summarisation_model (str)
session_ttl_hours (int)
max_session_turns (int)
qdrant_collection (str)
max_episodic_memories (int)
relevance_threshold (float | None)
relevance_weight (float)
recency_weight (float)
hybrid_retrieval (bool)
rerank_enabled (bool)
rerank_model (str)
rerank_top_k (int)
extract_facts (bool)
auto_summarise (bool)
summarise_after_turns (int)
summarise_cooldown_seconds (int)
strict_background_errors (bool)
shutdown_grace_seconds (float)
token_counter (Literal['heuristic', 'tiktoken'])
budget_fraction_system (float)
budget_fraction_episodic (float)
budget_fraction_session (float)
budget_fraction_current_turn (float)
- model_config = {'arbitrary_types_allowed': True, 'case_sensitive': False, 'cli_avoid_json': False, 'cli_enforce_required': False, 'cli_exit_on_error': True, 'cli_flag_prefix_char': '-', 'cli_hide_none_type': False, 'cli_ignore_unknown_args': False, 'cli_implicit_flags': False, 'cli_kebab_case': False, 'cli_parse_args': None, 'cli_parse_none_str': None, 'cli_prefix': '', 'cli_prog_name': None, 'cli_shortcuts': None, 'cli_use_class_docs_for_groups': False, 'enable_decoding': True, 'env_file': '.env', 'env_file_encoding': None, 'env_ignore_empty': False, 'env_nested_delimiter': None, 'env_nested_max_split': None, 'env_parse_enums': None, 'env_parse_none_str': None, 'env_prefix': 'ACTRONE_', 'env_prefix_target': 'variable', 'extra': 'ignore', 'json_file': None, 'json_file_encoding': None, 'nested_model_default_partial_update': False, 'protected_namespaces': ('model_validate', 'model_dump', 'settings_customise_sources'), 'secrets_dir': None, 'toml_file': None, 'validate_default': True, 'yaml_config_section': None, 'yaml_file': None, 'yaml_file_encoding': None}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- backend: Literal['memory', 'redis_qdrant']¶
- embedding_provider: Literal['openai', 'local', 'hashing']¶
- token_counter: Literal['heuristic', 'tiktoken']¶
- Required only when
- class actrone_memory.MemoryEntry(*, id=<factory>, agent_id, session_id, content, content_type, embedding=None, importance_score=0.5, topic_tags=<factory>, token_count=0, timestamp=<factory>, source_turn_ids=<factory>, source='unknown', sensitivity='none')[source]¶
Bases:
BaseModel- Parameters:
- content_type: ContentType¶
- timestamp: datetime¶
- sensitivity: Sensitivity¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class actrone_memory.RetrievedContext(*, recent_turns, episodic_memories, total_tokens_used, token_budget, retrieval_duration_ms)[source]¶
Bases:
BaseModelOutput of MemoryManager.retrieve_context, ready to inject into an LLM prompt.
- Parameters:
- episodic_memories: list[MemoryEntry]¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class actrone_memory.SessionMetadata(*, agent_id, session_id, turn_count, created_at=None, last_active=None)[source]¶
Bases:
BaseModel- Parameters:
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class actrone_memory.ToolResult(*, tool_name, params, result, success, duration_ms=None)[source]¶
Bases:
BaseModel- Parameters:
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class actrone_memory.Turn(*, id=<factory>, session_id, user_message, assistant_message, tool_results=<factory>, timestamp=<factory>, token_count=0)[source]¶
Bases:
BaseModel- Parameters:
- tool_results: list[ToolResult]¶
- timestamp: datetime¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- actrone_memory.create_memory_manager(config=None)[source]¶
Async context manager that creates and automatically closes a MemoryManager.
Usage:
async with create_memory_manager() as mm: await mm.store_turn(...)
- Parameters:
config (MemoryConfig | None)
- Return type:
- class actrone_memory.InMemoryStore(max_turns=50, *, relevance_weight=0.7, recency_weight=0.3)[source]¶
Bases:
objectZero-dependency, in-process store implementing both memory tiers.
This is the local-first default: it needs no Redis and no Qdrant, so
MemoryManager.create()runs with zero external services, parity with the TypeScriptactrone-memoryon-ramp. Data lives for the lifetime of the process; swap inRedisStore+QdrantStorefor durability and horizontal scale.Concurrency: every method is synchronous internally (no
awaitpoints), so operations are atomic with respect to the asyncio event loop, concurrent background tasks (e.g. summarisation) cannot interleave a partial mutation.- async get_session_metadata(agent_id, session_id)[source]¶
- Parameters:
- Return type:
SessionMetadata | None
- async try_acquire_summary_lock(agent_id, session_id, ttl_seconds)[source]¶
SET-NX-EX equivalent. Returns True for the first caller within a TTL window.
Deduplicates concurrent summarisations within this process and throttles re-summarisation, exactly like the Redis
SET key NX EX ttllock, but scoped to this process (in-memory backends are single-instance by design).
- async upsert(entry)[source]¶
- Parameters:
entry (MemoryEntry)
- Return type:
None
- async search(agent_id, query_embedding, threshold, limit=20, content_types=None, query_text=None)[source]¶
Hybrid relevance search, dense + lexical + recency fused with RRF.
Only memories with embedding cosine ≥
thresholdare admitted; among those, the ranking fuses embedding cosine, BM25 over the content (whenquery_textis given), and recency via Reciprocal Rank Fusion. Withoutquery_text(or with no shared terms) it degrades to the classicrelevance × cosine + recency × recencyblend, matchingQdrantStore.Time complexity: O(n) similarity scoring + O(n log n) rank over the agent’s memories, acceptable for the in-process on-ramp (bounded by
max_episodic_memories).
- actrone_memory.cosine_similarity(a, b)[source]¶
Cosine similarity of two vectors. Returns 0.0 when either is a zero vector.
Tolerates length mismatch by comparing over the shorter prefix, matching the TS
cosineSimilarityhelper so both OSS libs behave identically.
- class actrone_memory.ExtractedFact(*, content, sensitivity='none', topic_tags=<factory>, importance=0.6)[source]¶
Bases:
BaseModelOne atomic fact extracted from conversation, conforming to the shared spec.
- Parameters:
- sensitivity: Sensitivity¶
- model_config = {}¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class actrone_memory.FactExtractor(*args, **kwargs)[source]¶
Bases:
ProtocolSeam for turning conversation text into durable facts (turns → facts).
Implementations are LLM-backed; the library treats extraction as best-effort enrichment (a failure returns no facts and never breaks the write path).
- class actrone_memory.OpenAIFactExtractor(api_key, model='gpt-4o-mini')[source]¶
Bases:
objectLLM fact extractor using OpenAI JSON mode, conforming to the shared spec.
Cost: one cheap completion (e.g. gpt-4o-mini) per extraction call. Extraction is opt-in (
MemoryConfig.extract_facts) precisely because it costs tokens.
- actrone_memory.parse_facts(raw)[source]¶
Parse a model’s JSON response into validated facts, defensively.
Tolerates a bare list or a
{"facts": [...]}envelope, skips malformed entries, clamps oversize content, and bounds the count. Never raises, a completely unparseable response yields[].- Parameters:
raw (str)
- Return type:
- class actrone_memory.Embedder[source]¶
Bases:
ABCAbstract interface all embedding providers must implement.
- abstractmethod async embed_batch(texts)[source]¶
Return embedding vectors for a batch of texts.
The returned list is always the same length as texts.
- property relevance_threshold: float | None¶
The cosine similarity at which this model’s results turn from unrelated to relevant.
Used as the admission threshold when
MemoryConfig.relevance_thresholdis not set. Override it in a custom embedder once you have measured it; the default None means the library default applies.
- class actrone_memory.HashingEmbedder(dimensions=256)[source]¶
Bases:
EmbedderDeterministic, dependency-free hashing embedder (a “hashing vectorizer”).
Hashes words into a fixed-dimension bag-of-words vector and L2-normalises it, so cosine similarity reflects word overlap. This is the zero-dependency, zero-API-key default, parity with the TypeScript
LocalEmbedder, which makes the whole library run fully offline with no model download and no external service. It is not semantically rich (no synonymy); for production recall quality pass anOpenAIEmbedderor the sentence-transformersLocalEmbedder.Deterministic: identical text always yields an identical vector, so no cache is needed.
- Parameters:
dimensions (int)
- property relevance_threshold: float | None¶
The cosine similarity at which this model’s results turn from unrelated to relevant.
Used as the admission threshold when
MemoryConfig.relevance_thresholdis not set. Override it in a custom embedder once you have measured it; the default None means the library default applies.
- class actrone_memory.LocalEmbedder[source]¶
Bases:
Embeddersentence-transformers/all-MiniLM-L6-v2 for offline / free usage (384-dim).
Requires: pip install actrone-memory[local] CPU-bound encoding is offloaded to a thread pool to avoid blocking the event loop.
- property relevance_threshold: float | None¶
The cosine similarity at which this model’s results turn from unrelated to relevant.
Used as the admission threshold when
MemoryConfig.relevance_thresholdis not set. Override it in a custom embedder once you have measured it; the default None means the library default applies.
- class actrone_memory.OpenAIEmbedder(api_key, model='text-embedding-3-small', dimensions=1536)[source]¶
Bases:
EmbedderOpenAI text-embedding-3-small (1536-dim) with automatic retry.
Retries up to 3 times on any exception using exponential backoff with jitter, starting at 1 second and capped at 10 seconds.
- class actrone_memory.L1Store(*args, **kwargs)[source]¶
Bases:
ProtocolHot session tier, recent conversation turns.
Both the Redis-backed
RedisStoreand the dependency-freeInMemoryStorestructurally satisfy this protocol, soMemoryManagerdepends on the seam, not a concrete backend.- async get_session_metadata(agent_id, session_id)[source]¶
- Parameters:
- Return type:
SessionMetadata | None
- class actrone_memory.L2Store(*args, **kwargs)[source]¶
Bases:
ProtocolCold semantic tier, long-term episodic memories.
Implemented by
QdrantStoreand the dependency-freeInMemoryStore.- async upsert(entry)[source]¶
- Parameters:
entry (MemoryEntry)
- Return type:
None
- exception actrone_memory.ActroneMemoryError(message, *, code, details=None)[source]¶
Bases:
ExceptionBase error for all actrone-memory exceptions.
- Every error carries:
code, machine-readable string for programmatic handling (e.g. in logs or alerts) message, human-readable description details, structured dict of context that helps locate the failure
- exception actrone_memory.ConfigurationError(message, details=None)[source]¶
Bases:
ActroneMemoryErrorRaised when required configuration is missing or invalid.
This always means something is wrong with how the library is set up, not a runtime failure. It should cause the application to exit.
- exception actrone_memory.EmbeddingError(message, details=None)[source]¶
Bases:
ActroneMemoryErrorRaised when an embedding provider returns an error or an unexpected response.
- exception actrone_memory.MemoryNotFoundError(memory_id)[source]¶
Bases:
ActroneMemoryErrorRaised when
delete_memory()is called with an ID that does not exist.- Parameters:
memory_id (str)
- Return type:
None
- exception actrone_memory.StoreConnectionError(store, cause, details=None)[source]¶
Bases:
ActroneMemoryErrorRaised when a connection to Redis or Qdrant cannot be established or maintained.
Includes the name of the store that failed and the underlying exception.
- exception actrone_memory.TokenBudgetError(message, details=None)[source]¶
Bases:
ActroneMemoryErrorRaised when
token_budgetis zero or negative inretrieve_context().
- exception actrone_memory.ValidationError(field, message)[source]¶
Bases:
ActroneMemoryErrorRaised when a public method receives an invalid argument at the API boundary.