Memory¶
ConversationMemory ¶
Bases: ABC
Abstract base class for conversation memory storage.
Source code in packages/ai-parrot/src/parrot/memory/abstract.py
create_history
abstractmethod
async
¶
create_history(user_id: str, session_id: str, metadata: Optional[Dict[str, Any]] = None, chatbot_id: Optional[str] = None) -> ConversationHistory
Create a new conversation history.
Source code in packages/ai-parrot/src/parrot/memory/abstract.py
get_history
abstractmethod
async
¶
get_history(user_id: str, session_id: str, chatbot_id: Optional[str] = None) -> Optional[ConversationHistory]
Get a conversation history.
update_history
abstractmethod
async
¶
add_turn
abstractmethod
async
¶
add_turn(user_id: str, session_id: str, turn: ConversationTurn, chatbot_id: Optional[str] = None) -> None
Add a turn to the conversation.
clear_history
abstractmethod
async
¶
list_sessions
abstractmethod
async
¶
delete_history
abstractmethod
async
¶
Delete a conversation history entirely.
ConversationHistory
dataclass
¶
ConversationHistory(session_id: str, user_id: str, chatbot_id: Optional[str] = None, turns: List[ConversationTurn] = list(), created_at: datetime = datetime.now(), updated_at: datetime = datetime.now(), metadata: Dict[str, Any] = dict())
Manages conversation history for a session - replaces ConversationSession.
add_turn ¶
get_recent_turns ¶
get_messages_for_api ¶
Convert turns to API message format for LLM Model.
Source code in packages/ai-parrot/src/parrot/memory/abstract.py
clear_turns ¶
to_dict ¶
Serialize conversation history to dictionary.
Source code in packages/ai-parrot/src/parrot/memory/abstract.py
from_dict
classmethod
¶
Deserialize conversation history from dictionary.
Source code in packages/ai-parrot/src/parrot/memory/abstract.py
ConversationTurn
dataclass
¶
ConversationTurn(turn_id: str, user_id: str, user_message: str, assistant_response: str, context_used: Optional[str] = None, tools_used: List[str] = list(), timestamp: datetime = datetime.now(), metadata: Dict[str, Any] = dict())
Represents a single turn in a conversation.
to_dict ¶
Serialize turn to dictionary.
Source code in packages/ai-parrot/src/parrot/memory/abstract.py
from_dict
classmethod
¶
Deserialize turn from dictionary.
Source code in packages/ai-parrot/src/parrot/memory/abstract.py
InMemoryConversation ¶
Bases: ConversationMemory
In-memory implementation of conversation memory.
Source code in packages/ai-parrot/src/parrot/memory/mem.py
create_history
async
¶
create_history(user_id: str, session_id: str, metadata: Optional[Dict[str, Any]] = None, chatbot_id: Optional[str] = None) -> ConversationHistory
Create a new conversation history.
Source code in packages/ai-parrot/src/parrot/memory/mem.py
get_history
async
¶
get_history(user_id: str, session_id: str, chatbot_id: Optional[str] = None) -> Optional[ConversationHistory]
Get a conversation history.
Source code in packages/ai-parrot/src/parrot/memory/mem.py
update_history
async
¶
Update a conversation history.
Source code in packages/ai-parrot/src/parrot/memory/mem.py
add_turn
async
¶
add_turn(user_id: str, session_id: str, turn: ConversationTurn, chatbot_id: Optional[str] = None) -> None
Add a turn to the conversation.
Source code in packages/ai-parrot/src/parrot/memory/mem.py
clear_history
async
¶
Clear a conversation history.
Source code in packages/ai-parrot/src/parrot/memory/mem.py
list_sessions
async
¶
List all session IDs for a user.
Source code in packages/ai-parrot/src/parrot/memory/mem.py
delete_history
async
¶
Delete a conversation history entirely.
Source code in packages/ai-parrot/src/parrot/memory/mem.py
RedisConversation ¶
RedisConversation(redis_url: str = None, key_prefix: str = 'conversation', use_hash_storage: bool = True)
Bases: ConversationMemory
Redis-based conversation memory with proper encoding handling.
Source code in packages/ai-parrot/src/parrot/memory/redis.py
create_history
async
¶
create_history(user_id: str, session_id: str, metadata: Optional[Dict[str, Any]] = None, chatbot_id: Optional[str] = None) -> ConversationHistory
Create a new conversation history.
Source code in packages/ai-parrot/src/parrot/memory/redis.py
get_history
async
¶
get_history(user_id: str, session_id: str, chatbot_id: Optional[str] = None) -> Optional[ConversationHistory]
Get a conversation history.
Source code in packages/ai-parrot/src/parrot/memory/redis.py
update_history
async
¶
Update a conversation history.
Source code in packages/ai-parrot/src/parrot/memory/redis.py
add_turn
async
¶
add_turn(user_id: str, session_id: str, turn: ConversationTurn, chatbot_id: Optional[str] = None) -> None
Add a turn to the conversation efficiently.
Source code in packages/ai-parrot/src/parrot/memory/redis.py
clear_history
async
¶
Clear a conversation history.
Source code in packages/ai-parrot/src/parrot/memory/redis.py
list_sessions
async
¶
List all session IDs for a user.
Source code in packages/ai-parrot/src/parrot/memory/redis.py
delete_history
async
¶
Delete a conversation history entirely.
Source code in packages/ai-parrot/src/parrot/memory/redis.py
close
async
¶
ping
async
¶
get_raw_data
async
¶
Get raw data from Redis for debugging.
Source code in packages/ai-parrot/src/parrot/memory/redis.py
debug_conversation
async
¶
debug_conversation(user_id: str, session_id: str, chatbot_id: Optional[str] = None) -> Dict[str, Any]
Debug method to inspect conversation data.
Source code in packages/ai-parrot/src/parrot/memory/redis.py
list_sessions_by_chatbot
async
¶
List all sessions for a specific chatbot.
| PARAMETER | DESCRIPTION |
|---|---|
chatbot_id
|
The chatbot identifier
TYPE:
|
user_id
|
Optional user filter
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
List[str]
|
List of session IDs |
Source code in packages/ai-parrot/src/parrot/memory/redis.py
get_chatbot_stats
async
¶
Get statistics for a specific chatbot.
| RETURNS | DESCRIPTION |
|---|---|
Dict[str, Any]
|
Dictionary with conversation counts, active users, etc. |
Source code in packages/ai-parrot/src/parrot/memory/redis.py
delete_all_chatbot_conversations
async
¶
Delete all conversations for a chatbot.
| PARAMETER | DESCRIPTION |
|---|---|
chatbot_id
|
The chatbot identifier
TYPE:
|
user_id
|
Optional user filter
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of conversations deleted |
Source code in packages/ai-parrot/src/parrot/memory/redis.py
get_chatbot_users
async
¶
Get all users who have interacted with a chatbot.
Source code in packages/ai-parrot/src/parrot/memory/redis.py
FileConversationMemory ¶
Bases: ConversationMemory
File-based implementation of conversation memory.
Source code in packages/ai-parrot/src/parrot/memory/file.py
create_history
async
¶
create_history(user_id: str, session_id: str, metadata: Optional[Dict[str, Any]] = None, chatbot_id: Optional[str] = None) -> ConversationHistory
Create a new conversation history.
Source code in packages/ai-parrot/src/parrot/memory/file.py
get_history
async
¶
get_history(user_id: str, session_id: str, chatbot_id: Optional[str] = None) -> Optional[ConversationHistory]
Get a conversation history.
Source code in packages/ai-parrot/src/parrot/memory/file.py
update_history
async
¶
Update a conversation history.
Source code in packages/ai-parrot/src/parrot/memory/file.py
add_turn
async
¶
add_turn(user_id: str, session_id: str, turn: ConversationTurn, chatbot_id: Optional[str] = None) -> None
Add a turn to the conversation.
Source code in packages/ai-parrot/src/parrot/memory/file.py
clear_history
async
¶
Clear a conversation history.
Source code in packages/ai-parrot/src/parrot/memory/file.py
list_sessions
async
¶
List all session IDs for a user.
Source code in packages/ai-parrot/src/parrot/memory/file.py
delete_history
async
¶
Delete a conversation history entirely.
Source code in packages/ai-parrot/src/parrot/memory/file.py
AnswerMemory ¶
Store and retrieve question/answer interactions by turn identifier.
Source code in packages/ai-parrot/src/parrot/memory/agent.py
store_interaction
async
¶
Persist a question/answer pair under the provided turn identifier.
Source code in packages/ai-parrot/src/parrot/memory/agent.py
get
async
¶
Retrieve a stored interaction by turn identifier.
Source code in packages/ai-parrot/src/parrot/memory/agent.py
EpisodicMemoryMixin ¶
Mixin that adds automatic episodic memory to bots.
Provides hooks that bot implementations call at appropriate points in their ask() flow. The mixin is opt-in — bots that don't inherit it are completely unaffected.
Configuration attributes (override in subclass or set via kwargs): enable_episodic_memory: Master toggle for the mixin. episodic_backend: Backend type ("pgvector" or "faiss"). episodic_dsn: PostgreSQL DSN for PgVector backend. episodic_faiss_path: Persistence path for FAISS backend. episodic_schema: PostgreSQL schema name. episodic_reflection_enabled: Whether to generate reflections. episodic_inject_warnings: Whether to inject failure warnings pre-LLM. episodic_max_warnings: Maximum warnings to inject. episodic_trivial_tools: Tools to skip when recording.
EpisodicMemoryStore ¶
EpisodicMemoryStore(backend: AbstractEpisodeBackend, embedding_provider: EpisodeEmbeddingProvider | None = None, reflection_engine: ReflectionEngine | None = None, redis_cache: EpisodeRedisCache | None = None, default_ttl_days: int = 90, importance_scorer: ImportanceScorer | None = None, recall_strategy: RecallStrategy | None = None)
Main orchestrator for episodic memory operations.
Coordinates a backend (PgVector, FAISS, or RedisVector), an optional embedding provider (sentence-transformers), an optional reflection engine (LLM + heuristic), and an optional Redis cache for fast recent/failure lookups.
Pluggable strategies:
- importance_scorer: When provided, used to compute episode importance
in record_episode() instead of the inline heuristic. Must satisfy
the ImportanceScorer protocol.
- recall_strategy: When provided, used in recall_similar() instead
of calling backend.search_similar() directly. Must satisfy the
RecallStrategy protocol.
When neither is provided, behavior is identical to the pre-FEAT-075 implementation (no breaking changes).
| PARAMETER | DESCRIPTION |
|---|---|
backend
|
Storage backend (PgVector, FAISS, or RedisVector).
TYPE:
|
embedding_provider
|
Optional embedding provider for semantic search.
TYPE:
|
reflection_engine
|
Optional reflection engine for lesson extraction.
TYPE:
|
redis_cache
|
Optional Redis cache for hot episodes.
TYPE:
|
default_ttl_days
|
Default time-to-live for episodes (0 = no expiry).
TYPE:
|
importance_scorer
|
Optional pluggable importance scorer.
TYPE:
|
recall_strategy
|
Optional pluggable recall strategy.
TYPE:
|
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
record_episode
async
¶
record_episode(namespace: MemoryNamespace, situation: str, action_taken: str, outcome: EpisodeOutcome, outcome_details: str | None = None, error_type: str | None = None, error_message: str | None = None, category: EpisodeCategory = EpisodeCategory.TOOL_EXECUTION, importance: int | None = None, related_tools: list[str] | None = None, related_entities: list[str] | None = None, metadata: dict[str, Any] | None = None, generate_reflection: bool = True, ttl_days: int | None = None) -> EpisodicMemory
Record a new episode with auto-enrichment.
Auto-computes importance, generates reflection (if engine available), embeds text for similarity search, stores in backend, and caches.
| PARAMETER | DESCRIPTION |
|---|---|
namespace
|
Scoping dimensions for this episode.
TYPE:
|
situation
|
What the agent was trying to do.
TYPE:
|
action_taken
|
What action was executed.
TYPE:
|
outcome
|
The result classification.
TYPE:
|
outcome_details
|
Additional outcome description.
TYPE:
|
error_type
|
Error category if applicable.
TYPE:
|
error_message
|
Detailed error message.
TYPE:
|
category
|
Episode classification.
TYPE:
|
importance
|
Override auto-computed importance (1-10).
TYPE:
|
related_tools
|
Tools involved in this episode.
TYPE:
|
related_entities
|
Entities referenced.
TYPE:
|
metadata
|
Additional key-value metadata.
TYPE:
|
generate_reflection
|
Whether to generate reflection via engine.
TYPE:
|
ttl_days
|
Override default TTL. 0 = no expiry.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EpisodicMemory
|
The stored EpisodicMemory with all enrichments. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
record_tool_episode
async
¶
record_tool_episode(namespace: MemoryNamespace, tool_name: str, tool_args: dict[str, Any], tool_result: Any, user_query: str | None = None) -> EpisodicMemory
Record an episode from a tool execution.
Extracts episode fields from a ToolResult and delegates to record_episode().
| PARAMETER | DESCRIPTION |
|---|---|
namespace
|
Scoping dimensions.
TYPE:
|
tool_name
|
Name of the tool that was called.
TYPE:
|
tool_args
|
Arguments passed to the tool.
TYPE:
|
tool_result
|
The ToolResult from the tool execution.
TYPE:
|
user_query
|
The original user query that triggered the tool.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
EpisodicMemory
|
The stored episode. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
record_crew_episode
async
¶
record_crew_episode(namespace: MemoryNamespace, crew_result: Any, flow_description: str, per_agent: bool = True) -> list[EpisodicMemory]
Record episodes from a crew execution.
Creates a crew-level episode and optionally per-agent episodes.
| PARAMETER | DESCRIPTION |
|---|---|
namespace
|
Scoping dimensions (should include crew_id).
TYPE:
|
crew_result
|
The result from AgentCrew execution.
TYPE:
|
flow_description
|
Description of the workflow.
TYPE:
|
per_agent
|
If True, create one episode per participating agent.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[EpisodicMemory]
|
List of all created episodes. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
recall_similar
async
¶
recall_similar(query: str, namespace: MemoryNamespace, top_k: int = 5, score_threshold: float = 0.3, category: EpisodeCategory | None = None, include_failures_only: bool = False) -> list[EpisodeSearchResult]
Recall episodes similar to a query.
Embeds the query and performs vector similarity search with namespace filtering.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
Natural language query to search for.
TYPE:
|
namespace
|
Scoping dimensions for filtering.
TYPE:
|
top_k
|
Maximum results.
TYPE:
|
score_threshold
|
Minimum similarity score (0-1).
TYPE:
|
category
|
Optional category filter (applied post-search).
TYPE:
|
include_failures_only
|
If True, only return failure episodes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[EpisodeSearchResult]
|
List of episodes ranked by similarity score. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
get_failure_warnings
async
¶
get_failure_warnings(namespace: MemoryNamespace, current_query: str | None = None, max_warnings: int = 5) -> str
Generate injectable warning text from past failures.
Combines semantically similar failures (if query provided) with recent failures, deduplicates, and formats as text suitable for system prompt injection.
| PARAMETER | DESCRIPTION |
|---|---|
namespace
|
Scoping dimensions.
TYPE:
|
current_query
|
Current user query for semantic matching.
TYPE:
|
max_warnings
|
Maximum number of warnings.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Formatted warning text (empty string if no failures found). |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 | |
get_user_preferences
async
¶
Get user preference episodes.
| PARAMETER | DESCRIPTION |
|---|---|
namespace
|
Must include user_id for meaningful results.
TYPE:
|
limit
|
Maximum preferences to return.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[EpisodicMemory]
|
List of USER_PREFERENCE category episodes. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
get_room_context
async
¶
get_room_context(namespace: MemoryNamespace, limit: int = 10, categories: list[EpisodeCategory] | None = None) -> list[EpisodicMemory]
Get recent episodes for a room.
| PARAMETER | DESCRIPTION |
|---|---|
namespace
|
Must include room_id for room scoping.
TYPE:
|
limit
|
Maximum episodes to return.
TYPE:
|
categories
|
Optional category filter (applied post-retrieval).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
list[EpisodicMemory]
|
List of recent room-scoped episodes. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
cleanup_expired
async
¶
Delete expired episodes from the backend.
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of episodes deleted. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
compact_namespace
async
¶
compact_namespace(namespace: MemoryNamespace, keep_top_n: int = 100, keep_all_failures: bool = True) -> int
Compact a namespace by keeping only the most important episodes.
Retains the top-N episodes by importance score, plus all failure episodes if keep_all_failures is True. Deletes the rest.
| PARAMETER | DESCRIPTION |
|---|---|
namespace
|
The namespace to compact.
TYPE:
|
keep_top_n
|
Number of top episodes to retain.
TYPE:
|
keep_all_failures
|
If True, retain all failure episodes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
int
|
Number of episodes deleted. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
export_episodes
async
¶
Export episodes as JSONL string.
| PARAMETER | DESCRIPTION |
|---|---|
namespace
|
The namespace to export.
TYPE:
|
limit
|
Maximum episodes to export.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
JSONL-formatted string of episodes. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
create_pgvector
async
classmethod
¶
create_pgvector(dsn: str, schema: str = 'parrot_memory', table: str = 'episodic_memory', embedding_provider: EpisodeEmbeddingProvider | None = None, reflection_engine: ReflectionEngine | None = None, redis_cache: EpisodeRedisCache | None = None, recall_strategy: RecallStrategy | None = None, importance_scorer: ImportanceScorer | None = None, **kwargs: Any) -> 'EpisodicMemoryStore'
Create a store with PgVector backend.
| PARAMETER | DESCRIPTION |
|---|---|
dsn
|
PostgreSQL connection string.
TYPE:
|
schema
|
PostgreSQL schema name.
TYPE:
|
table
|
Table name.
TYPE:
|
embedding_provider
|
Optional embedding provider.
TYPE:
|
reflection_engine
|
Optional reflection engine.
TYPE:
|
redis_cache
|
Optional Redis cache.
TYPE:
|
recall_strategy
|
Optional recall strategy.
TYPE:
|
importance_scorer
|
Optional importance scorer.
TYPE:
|
**kwargs
|
Additional kwargs for EpisodicMemoryStore.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
'EpisodicMemoryStore'
|
Configured EpisodicMemoryStore with PgVector backend. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
create_redis_vector
async
classmethod
¶
create_redis_vector(redis_url: str, index_name: str = 'idx:episodes', embedding_dim: int = 384, namespace: MemoryNamespace | None = None, embedding_provider: EpisodeEmbeddingProvider | None = None, reflection_engine: ReflectionEngine | None = None, redis_cache: EpisodeRedisCache | None = None, recall_strategy: RecallStrategy | None = None, importance_scorer: ImportanceScorer | None = None, **kwargs: Any) -> 'EpisodicMemoryStore'
Create a store with RedisVectorBackend.
Requires Redis Stack with RediSearch module enabled.
| PARAMETER | DESCRIPTION |
|---|---|
redis_url
|
Redis connection URL (e.g.,
TYPE:
|
index_name
|
RediSearch index name.
TYPE:
|
embedding_dim
|
Dimension of embedding vectors.
TYPE:
|
namespace
|
Optional namespace for default scoping.
TYPE:
|
embedding_provider
|
Optional embedding provider.
TYPE:
|
reflection_engine
|
Optional reflection engine.
TYPE:
|
redis_cache
|
Optional Redis cache (separate from vector backend).
TYPE:
|
recall_strategy
|
Optional recall strategy.
TYPE:
|
importance_scorer
|
Optional importance scorer.
TYPE:
|
**kwargs
|
Additional kwargs for EpisodicMemoryStore.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
'EpisodicMemoryStore'
|
Configured EpisodicMemoryStore with RedisVectorBackend. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
create_faiss
async
classmethod
¶
create_faiss(persistence_path: str | None = None, dimension: int = 384, max_episodes: int = 10000, embedding_provider: EpisodeEmbeddingProvider | None = None, reflection_engine: ReflectionEngine | None = None, redis_cache: EpisodeRedisCache | None = None, **kwargs: Any) -> 'EpisodicMemoryStore'
Create a store with FAISS backend.
| PARAMETER | DESCRIPTION |
|---|---|
persistence_path
|
Directory for disk persistence (None = in-memory only).
TYPE:
|
dimension
|
Embedding vector dimension.
TYPE:
|
max_episodes
|
Maximum episodes in the FAISS index.
TYPE:
|
embedding_provider
|
Optional embedding provider.
TYPE:
|
reflection_engine
|
Optional reflection engine.
TYPE:
|
redis_cache
|
Optional Redis cache.
TYPE:
|
**kwargs
|
Additional kwargs for EpisodicMemoryStore.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
'EpisodicMemoryStore'
|
Configured EpisodicMemoryStore with FAISS backend. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/store.py
EpisodicMemoryToolkit ¶
Bases: AbstractToolkit
Toolkit exposing episodic memory as agent-callable tools.
Provides three tools for LLM agents: - search_episodic_memory: Semantic search over past experiences. - record_lesson: Explicitly record a lesson for future reference. - get_warnings: Retrieve relevant past failure warnings.
| PARAMETER | DESCRIPTION |
|---|---|
store
|
The EpisodicMemoryStore instance.
TYPE:
|
namespace
|
The namespace scope for all operations.
TYPE:
|
Source code in packages/ai-parrot/src/parrot/memory/episodic/tools.py
search_episodic_memory
async
¶
Search past agent experiences by semantic similarity.
Use this tool to recall what happened in similar past situations, including lessons learned and outcomes.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
What to search for in past experiences.
TYPE:
|
top_k
|
Maximum number of results to return.
TYPE:
|
failures_only
|
If True, only return past failures and mistakes.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Formatted list of relevant past experiences with lessons learned. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/tools.py
record_lesson
async
¶
Explicitly record a lesson learned for future reference.
Use this when you discover something important that should be remembered for similar future situations.
| PARAMETER | DESCRIPTION |
|---|---|
situation
|
What was happening when the lesson was learned.
TYPE:
|
lesson
|
The concise lesson or insight to remember.
TYPE:
|
category
|
Type of lesson (decision, user_preference, workflow_pattern).
TYPE:
|
importance
|
How important this lesson is (1-10, default 5).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Confirmation that the lesson was recorded. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/tools.py
get_warnings
async
¶
Get warnings about past mistakes relevant to the current task.
Use this before attempting actions that might fail, to check if similar attempts have failed before.
| PARAMETER | DESCRIPTION |
|---|---|
context
|
Description of what you're about to do (for relevance matching).
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Formatted warnings about past failures and successful approaches, |
str
|
or a message if no relevant warnings exist. |
Source code in packages/ai-parrot/src/parrot/memory/episodic/tools.py
ContextAssembler ¶
Assembles context from multiple sources within a token budget.
Priority order (highest first): 1. Episodic failure warnings — critical for avoiding past mistakes 2. Relevant skills — applicable knowledge 3. Conversation history — recent turns (truncated from oldest)
Each section gets a weight-based allocation from the total budget. Unused budget from empty sections rolls forward to the next priority.
| PARAMETER | DESCRIPTION |
|---|---|
config
|
Optional MemoryConfig; defaults to MemoryConfig() if omitted.
TYPE:
|
Example
assembler = ContextAssembler(MemoryConfig(max_context_tokens=2000)) ctx = assembler.assemble( episodic_warnings="Don't call X without auth", relevant_skills="Use get_schema tool", conversation="User: hello\nAssistant: hi", ) print(ctx.tokens_used)
Source code in packages/ai-parrot/src/parrot/memory/unified/context.py
assemble ¶
assemble(episodic_warnings: str = '', relevant_skills: str = '', conversation: str = '') -> MemoryContext
Assemble context respecting token budget.
Sections are filled in priority order. Any budget left over from an empty (or smaller-than-allocation) section is carried forward and added to the remaining sections' budgets proportionally.
| PARAMETER | DESCRIPTION |
|---|---|
episodic_warnings
|
Past failure lessons from episodic memory.
TYPE:
|
relevant_skills
|
Applicable skills from the skill registry.
TYPE:
|
conversation
|
Recent conversation turns.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MemoryContext
|
MemoryContext with filled sections and accurate token accounting. |
Source code in packages/ai-parrot/src/parrot/memory/unified/context.py
LongTermMemoryMixin ¶
Single opt-in mixin for long-term memory in any bot/agent.
Provides unified episodic + skill + conversation memory without requiring the bot to manage individual subsystems.
MRO note: place before AbstractBot (or Agent) in the class
definition so this mixin's methods take priority in the resolution order:
class MyAgent(LongTermMemoryMixin, Agent):
enable_long_term_memory = True
Configuration attributes (override in the subclass or via kwargs): enable_long_term_memory: Master toggle — all methods are no-ops when False. episodic_inject_warnings: Retrieve past failure warnings. episodic_auto_record: Record interactions to episodic memory. episodic_max_warnings: Maximum failure warnings per context. skill_inject_context: Retrieve relevant skills into context. skill_auto_extract: Auto-extract skills from successful interactions. skill_expose_tools: Register skill tools with the agent's tool manager. skill_max_context: Maximum skills per context. memory_max_context_tokens: Total token budget for assembled context.
get_memory_context
async
¶
Return assembled memory context as an injectable prompt string.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
Current user query for semantic retrieval.
TYPE:
|
user_id
|
User identifier for conversation history.
TYPE:
|
session_id
|
Session identifier for conversation history.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
Formatted multi-section string ready for system prompt injection, |
str
|
or empty string when memory is disabled or not configured. |
Source code in packages/ai-parrot/src/parrot/memory/unified/mixin.py
MemoryConfig ¶
Bases: BaseModel
Configuration for UnifiedMemoryManager.
Controls which subsystems are enabled, token budget allocation, and per-subsystem limits.
MemoryContext ¶
Bases: BaseModel
Assembled context from all memory subsystems.
Holds the text sections retrieved from episodic memory, skill registry, and conversation history, along with token accounting for budget enforcement.
to_prompt_string ¶
Format as injectable system prompt sections.
Only non-empty sections are included. Each section is wrapped in descriptive XML tags so the LLM can distinguish memory types.
| RETURNS | DESCRIPTION |
|---|---|
str
|
Formatted string ready for injection into a system prompt. |
Source code in packages/ai-parrot/src/parrot/memory/unified/models.py
UnifiedMemoryManager ¶
UnifiedMemoryManager(namespace: MemoryNamespace, conversation_memory: Optional[ConversationMemory] = None, episodic_store: Optional[EpisodicMemoryStore] = None, skill_registry: Optional[Any] = None, config: Optional[MemoryConfig] = None, cross_domain_router: Optional[CrossDomainRouter] = None)
Coordinates episodic memory, skill registry, and conversation memory.
All retrieval in get_context_for_query runs concurrently via
asyncio.gather. Subsystems that are None are silently skipped.
When cross_domain_router is provided, get_context_for_query also
queries episodic memories from relevant agent namespaces identified by the
router. Cross-domain results are labeled and appended to the episodic
warnings text. Cross-domain failures never break the main retrieval flow.
| PARAMETER | DESCRIPTION |
|---|---|
namespace
|
Scoping dimensions for episodic memory queries.
TYPE:
|
conversation_memory
|
Optional conversation history store.
TYPE:
|
episodic_store
|
Optional episodic memory store.
TYPE:
|
skill_registry
|
Optional skill registry (duck-typed via SkillRegistry protocol).
TYPE:
|
config
|
Optional memory configuration; defaults to
TYPE:
|
cross_domain_router
|
Optional router for multi-agent memory sharing.
TYPE:
|
Example
manager = UnifiedMemoryManager( namespace=MemoryNamespace(agent_id="my-agent"), episodic_store=store, cross_domain_router=router, ) ctx = await manager.get_context_for_query("user query", "u1", "s1") prompt += ctx.to_prompt_string()
Source code in packages/ai-parrot/src/parrot/memory/unified/manager.py
configure
async
¶
Initialise all non-None subsystems.
Calls configure(**kwargs) on each subsystem that exposes it.
Subsystems that lack a configure method are silently skipped.
| PARAMETER | DESCRIPTION |
|---|---|
**kwargs
|
Forwarded verbatim to each subsystem's
TYPE:
|
Source code in packages/ai-parrot/src/parrot/memory/unified/manager.py
cleanup
async
¶
Release resources held by all non-None subsystems.
Calls cleanup() on each subsystem that exposes it.
Source code in packages/ai-parrot/src/parrot/memory/unified/manager.py
get_context_for_query
async
¶
Retrieve and assemble context from all memory subsystems.
All three retrieval calls run concurrently via asyncio.gather.
If a subsystem is None or raises an exception its section is
returned as an empty string.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
Current user query — used for semantic similarity search.
TYPE:
|
user_id
|
User identifier for conversation history lookup.
TYPE:
|
session_id
|
Session identifier for conversation history lookup.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
MemoryContext
|
|
Source code in packages/ai-parrot/src/parrot/memory/unified/manager.py
record_interaction
async
¶
record_interaction(query: str, response: Any, tool_calls: list[Any], user_id: str, session_id: str) -> None
Record a completed interaction to episodic and conversation memory.
This method is exception-safe: any error is logged at WARNING level and execution continues. It is designed to be called fire-and-forget after returning a response to the user.
| PARAMETER | DESCRIPTION |
|---|---|
query
|
The user's original query.
TYPE:
|
response
|
The agent's response object (content extracted as str).
TYPE:
|
tool_calls
|
List of tool call objects from the interaction.
TYPE:
|
user_id
|
User identifier.
TYPE:
|
session_id
|
Session identifier.
TYPE:
|