Skip to content

Conversation

@MervinPraison
Copy link
Owner

@MervinPraison MervinPraison commented Jul 17, 2025

Implements all three proposed memory agents features from issue #969:

Features Implemented

  1. Session Summaries

    • Automatic conversation summarization every N turns
    • LLM-based summary generation with configurable model
    • Session context inclusion in agent responses
  2. Agentic Memory Management

    • Autonomous memory importance analysis using LLM
    • Agent-driven CRUD operations (remember, update, forget, search)
    • Auto-classification of information importance
  3. Memory References

    • Structured reference metadata with confidence scores
    • Multiple reference formats (inline, footnote, metadata)
    • Enhanced search with reference tracking

Backward Compatibility

  • All existing memory functionality preserved
  • New features are opt-in through configuration
  • No breaking changes to current API
  • Seamless integration with existing agents

Closes #969

Generated with Claude Code


Note

Medium Risk
Adds LLM-driven summarization/classification and introduces update/delete paths that touch both SQLite and ChromaDB, increasing risk of data inconsistency or unexpected external API calls when enabled.

Overview
Adds three opt-in memory-agent capabilities to Memory: session summaries (tracks turns and periodically summarizes via LLM, optionally persisting the summary to long-term memory), agentic memory management (remember with LLM-based importance gating plus update_memory/forget/search_memories), and reference-aware retrieval (search_with_references formats results with inline/footnote/metadata references and optional confidence scores).

Introduces MemoryTools + get_memory_tools for wiring these operations into agent toolchains, exports them from praisonaiagents.memory, and adds two standalone test scripts (test_memory_agents.py, test_memory_basic.py) to exercise the new features and basic/backward-compatible initialization.

Written by Cursor Bugbot for commit 1972767. This will update automatically on new commits. Configure here.

Summary by CodeRabbit

New Features

  • Memory enhancements: Added session-level memory summaries that automatically update after configured conversation turns
  • Agentic memory management: Introduced automatic classification and storage of important facts based on relevance
  • Enhanced search capabilities: Memory search now returns formatted references with confidence scores
  • Memory operations: Added ability to update and delete stored memories
  • Memory tools: Introduced simplified tools for easy integration and memory management operations

…ent, and references

- Add session summary configuration with auto-summarization every N turns
- Implement agentic memory management with auto-classification and confidence thresholds
- Add memory references with inline/footnote/metadata formatting options
- Create MemoryTools class with remember(), update_memory(), forget(), search_memories()
- Maintain full backward compatibility with existing memory functionality
- Add comprehensive test suites for all new features

Resolves #969

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 17, 2025

📝 Walkthrough

Walkthrough

Extends the Memory class with session-level summarization (automatic after N turns), agentic memory management (LLM-powered importance classification), memory references with confidence scores, and introduces MemoryTools utility for agent tool integration. New test files validate all features.

Changes

Cohort / File(s) Summary
Memory API exports
src/praisonai-agents/praisonaiagents/memory/__init__.py
Added public exports for MemoryTools and get_memory_tools to package all; surface-level API change only.
Core memory implementation
src/praisonai-agents/praisonaiagents/memory/memory.py
Added session management (turn tracking, automatic summarization via LLM), agentic memory (LLM-based importance classification for storage decisions), memory reference features (formatted retrieval with confidence scores), and related persistence/vector-store integration logic.
Memory tools wrapper
src/praisonai-agents/praisonaiagents/memory/tools.py
New MemoryTools class wrapping a memory backend; delegates remember, update_memory, forget, search_memories, get_session_summary, and search_with_references operations; includes get_memory_tools factory function.
Test files
src/praisonai-agents/test_memory_agents.py, src/praisonai-agents/test_memory_basic.py
Comprehensive test suites covering session summaries, agentic memory, memory references, MemoryTools operations, agent integration, and backward compatibility validation.

Sequence Diagram(s)

sequenceDiagram
    participant Agent
    participant Memory
    participant LLM
    participant Storage as Storage<br/>(SQLite/Vector)
    
    Agent->>Memory: add_to_session(role, content)
    Memory->>Memory: Increment turn_counter
    alt Turn count reaches update_after_n_turns
        Memory->>Memory: Compose recent turns
        Memory->>LLM: _update_session_summary()
        LLM-->>Memory: Return JSON summary
        Memory->>Memory: Store current_session_summary
        alt include_in_context enabled
            Memory->>Storage: Persist summary to long-term
        end
    end
    
    Agent->>Memory: remember(fact, metadata)
    alt agentic_config enabled
        Memory->>LLM: _classify_importance(fact)
        LLM-->>Memory: Confidence score (0.0-1.0)
        alt confidence > threshold
            Memory->>Storage: Store in long-term memory
        end
    else
        Memory->>Storage: Store in long-term memory
    end
    
    Agent->>Memory: search_with_references(query)
    Memory->>Storage: Search memories
    Storage-->>Memory: Return results
    alt reference_config enabled
        Memory->>Memory: Format references (inline/footnote/metadata)
        Memory->>Memory: Include confidence scores
    end
    Memory-->>Agent: Return dict with content + references
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

Review effort 4/5, Possible security concern

Poem

🐰 Hops excitedly

Sessions now remember turns so fine,
With summaries that grow and shine,
Agents classify what matters most,
References sparkle coast to coast,
Memory tools hop into place—
What wondrous times we now embrace! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: implementation of memory agents with session summaries, agentic management, and enhanced references.
Linked Issues check ✅ Passed The pull request implements all three core objectives from issue #969: session summaries with configurable intervals and LLM model, agentic memory management with auto-classification and CRUD tools, and memory references with multiple format support and confidence scoring.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing the three memory agent features from issue #969; the test files and tool wrapper are supporting implementations for the new functionality.
Docstring Coverage ✅ Passed Docstring coverage is 96.88% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch claude/issue-969-20250717-0012

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary of Changes

Hello @MervinPraison, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the memory capabilities of the PraisonAI agents by introducing advanced features for managing conversational context, intelligently storing and retrieving information, and providing traceable references. The changes are designed to be opt-in and fully backward compatible, allowing for a seamless upgrade path while empowering agents with more sophisticated memory management.

Highlights

  • Session Summaries: Implemented automatic conversation summarization, allowing the system to generate LLM-based summaries every N turns and include session context in agent responses. This enhances the agent's ability to maintain conversational coherence over time.
  • Agentic Memory Management: Introduced autonomous memory importance analysis using an LLM, enabling agents to perform intelligent CRUD operations (remember, update, forget, search) on their long-term memory. This includes auto-classification of information importance to prioritize critical facts.
  • Memory References: Added support for structured reference metadata with confidence scores, allowing for multiple reference formats (inline, footnote, metadata). This provides enhanced search capabilities by linking responses directly to their source memories.
  • Agent Tooling and Integration: Created a dedicated MemoryTools class and get_memory_tools function to expose these new memory functionalities as callable tools for agents, ensuring seamless integration with the existing agent system. New comprehensive test suites have also been added to validate these features and ensure backward compatibility.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces session summaries, agentic memory management, and memory references. The code is well-organized and includes tests. The review highlights a critical issue regarding potential data loss when updating memories, and an opportunity to improve test file maintainability.

Comment on lines +1300 to +1303
c.execute(
"UPDATE long_mem SET content = ?, meta = ? WHERE id = ?",
(new_fact, json.dumps({"updated": True, "updated_at": time.time()}), memory_id)
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The UPDATE statement overwrites the existing metadata. This will cause any pre-existing metadata associated with the memory entry to be lost. To prevent this data loss, fetch the existing metadata, update it, and then write it back.

            # First, fetch existing metadata
            c.execute("SELECT meta FROM long_mem WHERE id = ?", (memory_id,))
            row = c.fetchone()
            if not row:
                return False # Or handle as an error

            existing_meta = json.loads(row[0] or '{}')
            existing_meta.update({"updated": True, "updated_at": time.time()})

            # Then, update the record with the merged metadata
            c.execute(
                "UPDATE long_mem SET content = ?, meta = ? WHERE id = ?",
                (new_fact, json.dumps(existing_meta), memory_id)
            )


self.chroma_col.add(
documents=[new_fact],
metadatas=[{"updated": True, "updated_at": time.time()}],
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Similar to the SQLite update, the metadata for the ChromaDB entry is being overwritten here. When you delete and re-add the document, preserve the original metadata and merge it with the update information to avoid data loss.

                    # get existing metadata
                    existing_metadata = self.chroma_col.get(ids=[memory_id], include=["metadatas"])
                    if existing_metadata and existing_metadata['metadatas']:
                        # Merge existing metadata with new metadata
                        updated_metadata = existing_metadata['metadatas'][0]
                        updated_metadata.update({"updated": True, "updated_at": time.time()})
                    else:
                        updated_metadata = {"updated": True, "updated_at": time.time()}

                    self.chroma_col.add(
                        documents=[new_fact],
                        metadatas=[updated_metadata],
                        ids=[memory_id],
                        embeddings=[embedding]
                    )


# Create an agent with memory tools
memory = Memory(memory_config, verbose=5)
from praisonaiagents.memory.tools import get_memory_tools
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Imports should be at the top of the file to avoid circular dependency issues and improve readability.

from praisonaiagents.memory.tools import get_memory_tools

        agent = Agent(

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Undefined Variable in Conditional Logic

A NameError occurs in the remember() method when agentic memory is enabled but auto-classification is disabled. The importance_score variable is referenced in the metadata update but is only assigned when self.auto_classify is True, causing it to be undefined when self.auto_classify is False.

src/praisonai-agents/praisonaiagents/memory/memory.py#L1268-L1292

# -------------------------------------------------------------------------
def remember(self, fact: str, metadata: Optional[Dict[str, Any]] = None) -> bool:
"""Store important information with agentic classification"""
if not self.agentic_enabled:
# Fallback to regular long-term storage
self.store_long_term(fact, metadata=metadata)
return True
# Auto-classify the importance if enabled
if self.auto_classify:
importance_score = self._classify_importance(fact)
if importance_score < self.confidence_threshold:
self._log_verbose(f"Fact importance {importance_score} below threshold {self.confidence_threshold}")
return False
# Store with agentic metadata
agentic_metadata = metadata or {}
agentic_metadata.update({
"stored_by": "agentic_memory",
"importance_score": importance_score if self.auto_classify else 1.0,
"auto_classified": self.auto_classify
})
self.store_long_term(fact, metadata=agentic_metadata)
return True

Fix in CursorFix in Web


Bug: Metadata Loss and Data Inconsistency

The update_memory method has two issues:

  1. It incorrectly replaces all existing metadata with only update flags in both the SQLite database and ChromaDB, leading to the loss of original metadata (e.g., quality, importance scores).
  2. In ChromaDB, if embedding generation fails after a memory is deleted for an update, the memory is not re-added, causing data inconsistency where the record exists in SQLite but is missing from the vector store.

src/praisonai-agents/praisonaiagents/memory/memory.py#L1299-L1329

c = conn.cursor()
c.execute(
"UPDATE long_mem SET content = ?, meta = ? WHERE id = ?",
(new_fact, json.dumps({"updated": True, "updated_at": time.time()}), memory_id)
)
updated = c.rowcount > 0
conn.commit()
conn.close()
# Update in vector store if available
if self.use_rag and hasattr(self, "chroma_col"):
try:
# ChromaDB doesn't support direct updates, so we delete and re-add
self.chroma_col.delete(ids=[memory_id])
if LITELLM_AVAILABLE:
import litellm
response = litellm.embedding(
model=self.embedding_model,
input=new_fact
)
embedding = response.data[0]["embedding"]
elif OPENAI_AVAILABLE:
from openai import OpenAI
client = OpenAI()
response = client.embeddings.create(
input=new_fact,
model=self.embedding_model
)
embedding = response.data[0].embedding
else:
return updated

Fix in CursorFix in Web


BugBot free trial expires on July 22, 2025
Learn more in the Cursor dashboard.

Was this report helpful? Give feedback by reacting with 👍 or 👎

@MervinPraison
Copy link
Owner Author

@claude review this pull request and do a detailed analysis and fix this if the existing code doesn't have the solution implemented. Making sure it has backward compatibility, no existing features removed. After making those changes, again review the applied changes. Use @web to search if you dont know any information or to find the latest documentation or to find the latest version. Run the code if you think you need to run it to test it. Minimal code change to start with if required any changes.

@github-actions
Copy link
Contributor

github-actions bot commented Jul 17, 2025

Claude encountered an error —— View job


I'll analyze this and get back to you.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Fix all issues with AI agents
In `@src/praisonai-agents/praisonaiagents/memory/memory.py`:
- Around line 1177-1191: The add_to_session method currently does a modulo by
self.update_after_n_turns which will raise ZeroDivisionError if that value is 0;
guard against this by validating/handling zero before the modulo: in
add_to_session (and/or when setting the config) ensure self.update_after_n_turns
is a positive integer (or skip summary logic when it is <= 0) and only call
self._update_session_summary() when update_after_n_turns > 0 and turn_counter %
update_after_n_turns == 0; reference add_to_session, self.update_after_n_turns,
and _update_session_summary when applying the fix.

In `@src/praisonai-agents/test_memory_agents.py`:
- Around line 137-138: The first print call uses an unnecessary f-string prefix
(print(f"\n🔗 Search results with references:")) which triggers Ruff F541;
remove the f prefix and use a regular string literal (print("\n🔗 Search results
with references:")) while keeping the subsequent print that interpolates
result['content'] as an f-string; update the print in test_memory_agents.py
accordingly.
- Around line 242-248: Rename the unused local variable workflow to _workflow
where the PraisonAIAgents instance is created (PraisonAIAgents(...)) to signal
intentional unused value and silence the Ruff F841 warning; update the
assignment line to use _workflow instead of workflow and leave the rest of the
call (agents, tasks, verbose, memory, memory_config) unchanged.

In `@src/praisonai-agents/test_memory_basic.py`:
- Around line 120-128: The local variable "tools" in the test (created via
MemoryTools(memory)) is unused and triggers Ruff F841; rename it to "_tools" to
mark it intentionally unused (replace the assignment "tools =
MemoryTools(memory)" with "_tools = MemoryTools(memory)") so the linter is
satisfied while keeping the instantiation check; leave the subsequent
get_memory_tools call and prints unchanged.
- Around line 41-95: The test creates an unused variable memory and uses
redundant == True comparisons; rename or discard the unused variable (e.g.,
_memory or remove the assignment to memory) and replace boolean-equality asserts
with direct truthiness checks: change assertions on Memory instances
(memory_with_session.session_enabled, memory_with_agentic.agentic_enabled,
memory_with_references.include_references) from "== True" to just the attribute
(e.g., assert memory_with_session.session_enabled) and keep other checks
(update_after_n_turns, confidence_threshold, reference_format, max_references)
as-is; locate these in the test where Memory is constructed (variables memory,
memory_with_session, memory_with_agentic, memory_with_references).

Comment on lines +1177 to +1191
def add_to_session(self, role: str, content: str) -> None:
"""Add a conversation turn to the session history"""
if not self.session_enabled:
return

self.session_history.append({
"role": role,
"content": content,
"timestamp": time.time()
})
self.turn_counter += 1

# Check if we need to update the session summary
if self.turn_counter % self.update_after_n_turns == 0:
self._update_session_summary()
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Guard against update_after_n_turns = 0 to avoid a crash.
Line 1190 performs modulo by self.update_after_n_turns; a config of 0 will raise ZeroDivisionError.

🛡️ Suggested fix
-        if self.turn_counter % self.update_after_n_turns == 0:
+        interval = max(1, self.update_after_n_turns)
+        if self.turn_counter % interval == 0:
             self._update_session_summary()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def add_to_session(self, role: str, content: str) -> None:
"""Add a conversation turn to the session history"""
if not self.session_enabled:
return
self.session_history.append({
"role": role,
"content": content,
"timestamp": time.time()
})
self.turn_counter += 1
# Check if we need to update the session summary
if self.turn_counter % self.update_after_n_turns == 0:
self._update_session_summary()
def add_to_session(self, role: str, content: str) -> None:
"""Add a conversation turn to the session history"""
if not self.session_enabled:
return
self.session_history.append({
"role": role,
"content": content,
"timestamp": time.time()
})
self.turn_counter += 1
# Check if we need to update the session summary
interval = max(1, self.update_after_n_turns)
if self.turn_counter % interval == 0:
self._update_session_summary()
🤖 Prompt for AI Agents
In `@src/praisonai-agents/praisonaiagents/memory/memory.py` around lines 1177 -
1191, The add_to_session method currently does a modulo by
self.update_after_n_turns which will raise ZeroDivisionError if that value is 0;
guard against this by validating/handling zero before the modulo: in
add_to_session (and/or when setting the config) ensure self.update_after_n_turns
is a positive integer (or skip summary logic when it is <= 0) and only call
self._update_session_summary() when update_after_n_turns > 0 and turn_counter %
update_after_n_turns == 0; reference add_to_session, self.update_after_n_turns,
and _update_session_summary when applying the fix.

Comment on lines +137 to +138
print(f"\n🔗 Search results with references:")
print(f"Content: {result['content']}")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Remove the unused f-string prefix.
Line 137 is an f-string without placeholders, which triggers Ruff F541.

🧹 Suggested fix
-    print(f"\n🔗 Search results with references:")
+    print("\n🔗 Search results with references:")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
print(f"\n🔗 Search results with references:")
print(f"Content: {result['content']}")
print("\n🔗 Search results with references:")
print(f"Content: {result['content']}")
🧰 Tools
🪛 Ruff (0.14.14)

[error] 137-137: f-string without any placeholders

Remove extraneous f prefix

(F541)

🤖 Prompt for AI Agents
In `@src/praisonai-agents/test_memory_agents.py` around lines 137 - 138, The first
print call uses an unnecessary f-string prefix (print(f"\n🔗 Search results with
references:")) which triggers Ruff F541; remove the f prefix and use a regular
string literal (print("\n🔗 Search results with references:")) while keeping the
subsequent print that interpolates result['content'] as an f-string; update the
print in test_memory_agents.py accordingly.

Comment on lines +242 to +248
workflow = PraisonAIAgents(
agents=[agent],
tasks=[task],
verbose=1,
memory=True,
memory_config=memory_config
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Avoid unused workflow variable.
Line 242 assigns workflow without use, which triggers Ruff F841. Rename to _workflow to signal intentional unused value.

🧹 Suggested fix
-        workflow = PraisonAIAgents(
+        _workflow = PraisonAIAgents(
             agents=[agent],
             tasks=[task],
             verbose=1,
             memory=True,
             memory_config=memory_config
         )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
workflow = PraisonAIAgents(
agents=[agent],
tasks=[task],
verbose=1,
memory=True,
memory_config=memory_config
)
_workflow = PraisonAIAgents(
agents=[agent],
tasks=[task],
verbose=1,
memory=True,
memory_config=memory_config
)
🧰 Tools
🪛 Ruff (0.14.14)

[error] 242-242: Local variable workflow is assigned to but never used

Remove assignment to unused variable workflow

(F841)

🤖 Prompt for AI Agents
In `@src/praisonai-agents/test_memory_agents.py` around lines 242 - 248, Rename
the unused local variable workflow to _workflow where the PraisonAIAgents
instance is created (PraisonAIAgents(...)) to signal intentional unused value
and silence the Ruff F841 warning; update the assignment line to use _workflow
instead of workflow and leave the rest of the call (agents, tasks, verbose,
memory, memory_config) unchanged.

Comment on lines +41 to +95
memory = Memory(basic_config, verbose=0)
print("✅ Basic memory initialization successful")

# Test session summary configuration
session_config = {
"provider": "rag",
"use_embedding": False,
"session_summary_config": {
"enabled": True,
"update_after_n_turns": 5,
"model": "gpt-4o-mini",
"include_in_context": True
}
}

memory_with_session = Memory(session_config, verbose=0)
print("✅ Session summary configuration successful")
assert memory_with_session.session_enabled == True
assert memory_with_session.update_after_n_turns == 5

# Test agentic memory configuration
agentic_config = {
"provider": "rag",
"use_embedding": False,
"agentic_config": {
"enabled": True,
"auto_classify": True,
"confidence_threshold": 0.7,
"management_model": "gpt-4o"
}
}

memory_with_agentic = Memory(agentic_config, verbose=0)
print("✅ Agentic memory configuration successful")
assert memory_with_agentic.agentic_enabled == True
assert memory_with_agentic.confidence_threshold == 0.7

# Test reference configuration
reference_config = {
"provider": "rag",
"use_embedding": False,
"reference_config": {
"include_references": True,
"reference_format": "inline",
"max_references": 5,
"show_confidence": True
}
}

memory_with_references = Memory(reference_config, verbose=0)
print("✅ Reference configuration successful")
assert memory_with_references.include_references == True
assert memory_with_references.reference_format == "inline"
assert memory_with_references.max_references == 5

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Tidy the lint errors in the initialization test.
Ruff flags unused memory and == True comparisons at Lines 41, 58, 75, and 92.

🧹 Suggested fix
-        memory = Memory(basic_config, verbose=0)
+        _memory = Memory(basic_config, verbose=0)
         print("✅ Basic memory initialization successful")
@@
-        assert memory_with_session.session_enabled == True
+        assert memory_with_session.session_enabled
         assert memory_with_session.update_after_n_turns == 5
@@
-        assert memory_with_agentic.agentic_enabled == True
+        assert memory_with_agentic.agentic_enabled
         assert memory_with_agentic.confidence_threshold == 0.7
@@
-        assert memory_with_references.include_references == True
+        assert memory_with_references.include_references
         assert memory_with_references.reference_format == "inline"
         assert memory_with_references.max_references == 5
🧰 Tools
🪛 Ruff (0.14.14)

[error] 41-41: Local variable memory is assigned to but never used

Remove assignment to unused variable memory

(F841)


[error] 58-58: Avoid equality comparisons to True; use memory_with_session.session_enabled: for truth checks

Replace with memory_with_session.session_enabled

(E712)


[error] 75-75: Avoid equality comparisons to True; use memory_with_agentic.agentic_enabled: for truth checks

Replace with memory_with_agentic.agentic_enabled

(E712)


[error] 92-92: Avoid equality comparisons to True; use memory_with_references.include_references: for truth checks

Replace with memory_with_references.include_references

(E712)

🤖 Prompt for AI Agents
In `@src/praisonai-agents/test_memory_basic.py` around lines 41 - 95, The test
creates an unused variable memory and uses redundant == True comparisons; rename
or discard the unused variable (e.g., _memory or remove the assignment to
memory) and replace boolean-equality asserts with direct truthiness checks:
change assertions on Memory instances (memory_with_session.session_enabled,
memory_with_agentic.agentic_enabled, memory_with_references.include_references)
from "== True" to just the attribute (e.g., assert
memory_with_session.session_enabled) and keep other checks
(update_after_n_turns, confidence_threshold, reference_format, max_references)
as-is; locate these in the test where Memory is constructed (variables memory,
memory_with_session, memory_with_agentic, memory_with_references).

Comment on lines +120 to +128
memory = Memory(config, verbose=0)

# Test MemoryTools class
tools = MemoryTools(memory)
print("✅ MemoryTools class creation successful")

# Test get_memory_tools function
tool_list = get_memory_tools(memory)
print(f"✅ get_memory_tools returned {len(tool_list)} tools")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Avoid unused tools variable.
Line 123 triggers Ruff F841; rename to _tools to mark intentional unused.

🧹 Suggested fix
-        tools = MemoryTools(memory)
+        _tools = MemoryTools(memory)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
memory = Memory(config, verbose=0)
# Test MemoryTools class
tools = MemoryTools(memory)
print("✅ MemoryTools class creation successful")
# Test get_memory_tools function
tool_list = get_memory_tools(memory)
print(f"✅ get_memory_tools returned {len(tool_list)} tools")
memory = Memory(config, verbose=0)
# Test MemoryTools class
_tools = MemoryTools(memory)
print("✅ MemoryTools class creation successful")
# Test get_memory_tools function
tool_list = get_memory_tools(memory)
print(f"✅ get_memory_tools returned {len(tool_list)} tools")
🧰 Tools
🪛 Ruff (0.14.14)

[error] 123-123: Local variable tools is assigned to but never used

Remove assignment to unused variable tools

(F841)

🤖 Prompt for AI Agents
In `@src/praisonai-agents/test_memory_basic.py` around lines 120 - 128, The local
variable "tools" in the test (created via MemoryTools(memory)) is unused and
triggers Ruff F841; rename it to "_tools" to mark it intentionally unused
(replace the assignment "tools = MemoryTools(memory)" with "_tools =
MemoryTools(memory)") so the linter is satisfied while keeping the instantiation
check; leave the subsequent get_memory_tools call and prints unchanged.

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 3 potential issues.

Bugbot Autofix is OFF. To automatically fix reported issues with Cloud Agents, enable Autofix in the Cursor dashboard.

This PR is being reviewed by Cursor Bugbot

Details

You are on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle.

To receive Bugbot reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial.

c = conn.cursor()
c.execute(
"UPDATE long_mem SET content = ?, meta = ? WHERE id = ?",
(new_fact, json.dumps({"updated": True, "updated_at": time.time()}), memory_id)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Memory update discards all existing metadata

High Severity

The update_memory method completely replaces the original metadata with only {"updated": True, "updated_at": time.time()} when updating both SQLite and ChromaDB. This discards all previously stored metadata including stored_by, importance_score, auto_classified, quality scores, and any user-provided metadata. After an update, search_memories filtering by stored_by == "agentic_memory" will no longer find the updated memory, and quality-based filtering will also fail.

Additional Locations (1)

Fix in Cursor Fix in Web

"stored_by": "agentic_memory",
"importance_score": importance_score if self.auto_classify else 1.0,
"auto_classified": self.auto_classify
})
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metadata dictionary mutated affecting caller's object

Medium Severity

The remember method modifies the caller's metadata dictionary in-place when provided. Line 1284 assigns agentic_metadata = metadata or {}, which creates a reference to the original dict (not a copy) when metadata is truthy. The subsequent .update() call mutates this dictionary, adding stored_by, importance_score, and auto_classified keys to the caller's object. This causes unexpected side effects if the caller reuses the metadata dictionary.

Fix in Cursor Fix in Web

embeddings=[embedding]
)
except Exception as e:
self._log_verbose(f"Error updating in ChromaDB: {e}", logging.ERROR)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ChromaDB delete-then-add leaves data inconsistent on failure

Medium Severity

In update_memory, the ChromaDB entry is deleted at line 1312 before attempting to generate a new embedding and re-add it. If embedding generation (lines 1315-1327) or the add operation (line 1331) fails, the exception is caught and logged but the function continues. This leaves the memory deleted from ChromaDB but not re-added, causing ChromaDB and SQLite to become out of sync. The memory will no longer appear in vector-based searches even though it exists in SQLite.

Fix in Cursor Fix in Web

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

memory agents

1 participant