Skip to content

Commit 26c242b

Browse files
fix: resolve MongoDB integration issues
- Fix ID generation consistency between MongoDB and SQLite storage - Fix inconsistent error handling in memory operations - Fix security issue with hardcoded API key placeholders in examples - Fix unused imports in mongodb_tools.py - Fix pymongo version to >= 4.6.3 to address security vulnerabilities - Improve datetime import organization - Ensure consistent storage order for better reliability 🤖 Generated with [Claude Code](https://claude.ai/code) Co-authored-by: Mervin Praison <MervinPraison@users.noreply.github.com>
1 parent b8f4fc0 commit 26c242b

File tree

7 files changed

+37
-34
lines changed

7 files changed

+37
-34
lines changed

examples/python/mongodb/mongodb_comprehensive_example.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,9 @@
2323
from praisonaiagents import Agent, Task, PraisonAIAgents
2424
from praisonaiagents.tools import mongodb_tools
2525

26-
# Set up environment variables
27-
os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Replace with your actual API key
26+
# Ensure OpenAI API key is set
27+
if not os.environ.get("OPENAI_API_KEY"):
28+
raise ValueError("Please set the OPENAI_API_KEY environment variable")
2829

2930
def main():
3031
# MongoDB configuration for different components

examples/python/mongodb/mongodb_knowledge_example.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,9 @@
2121
import os
2222
from praisonaiagents import Agent, Task, PraisonAIAgents
2323

24-
# Set up environment variables
25-
os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Replace with your actual API key
24+
# Ensure OpenAI API key is set
25+
if not os.environ.get("OPENAI_API_KEY"):
26+
raise ValueError("Please set the OPENAI_API_KEY environment variable")
2627

2728
def main():
2829
# MongoDB knowledge configuration

examples/python/mongodb/mongodb_memory_example.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,9 @@
2121
import os
2222
from praisonaiagents import Agent, Task, PraisonAIAgents
2323

24-
# Set up environment variables
25-
os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Replace with your actual API key
24+
# Ensure OpenAI API key is set
25+
if not os.environ.get("OPENAI_API_KEY"):
26+
raise ValueError("Please set the OPENAI_API_KEY environment variable")
2627

2728
def main():
2829
# MongoDB memory configuration

examples/python/mongodb/mongodb_tools_example.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,9 @@
2222
from praisonaiagents import Agent, Task, PraisonAIAgents
2323
from praisonaiagents.tools import mongodb_tools
2424

25-
# Set up environment variables
26-
os.environ["OPENAI_API_KEY"] = "your-openai-api-key" # Replace with your actual API key
25+
# Ensure OpenAI API key is set
26+
if not os.environ.get("OPENAI_API_KEY"):
27+
raise ValueError("Please set the OPENAI_API_KEY environment variable")
2728

2829
def main():
2930
# Create a MongoDB Database Agent with MongoDB tools

src/praisonai-agents/praisonaiagents/memory/memory.py

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import shutil
66
from typing import Any, Dict, List, Optional, Union, Literal
77
import logging
8+
from datetime import datetime
89

910
# Disable litellm telemetry before any imports
1011
os.environ["LITELLM_TELEMETRY"] = "False"
@@ -483,11 +484,13 @@ def store_short_term(
483484
)
484485
logger.info(f"Processed metadata: {metadata}")
485486

487+
# Generate unique ID and timestamp once
488+
ident = str(time.time_ns())
489+
created_at = time.time()
490+
486491
# Store in MongoDB if enabled
487492
if self.use_mongodb and hasattr(self, "mongo_short_term"):
488493
try:
489-
from datetime import datetime
490-
ident = str(time.time_ns())
491494
doc = {
492495
"_id": ident,
493496
"content": text,
@@ -504,10 +507,9 @@ def store_short_term(
504507
# Existing SQLite store logic
505508
try:
506509
conn = sqlite3.connect(self.short_db)
507-
ident = str(time.time_ns())
508510
conn.execute(
509511
"INSERT INTO short_mem (id, content, meta, created_at) VALUES (?,?,?,?)",
510-
(ident, text, json.dumps(metadata), time.time())
512+
(ident, text, json.dumps(metadata), created_at)
511513
)
512514
conn.commit()
513515
conn.close()
@@ -721,25 +723,9 @@ def store_long_term(
721723
ident = str(time.time_ns())
722724
created = time.time()
723725

724-
# Store in SQLite
725-
try:
726-
conn = sqlite3.connect(self.long_db)
727-
conn.execute(
728-
"INSERT INTO long_mem (id, content, meta, created_at) VALUES (?,?,?,?)",
729-
(ident, text, json.dumps(metadata), created)
730-
)
731-
conn.commit()
732-
conn.close()
733-
logger.info(f"Successfully stored in SQLite with ID: {ident}")
734-
except Exception as e:
735-
logger.error(f"Error storing in SQLite: {e}")
736-
return
737-
738-
# Store in MongoDB if enabled
726+
# Store in MongoDB if enabled (first priority)
739727
if self.use_mongodb and hasattr(self, "mongo_long_term"):
740728
try:
741-
from datetime import datetime
742-
ident = str(time.time_ns())
743729
doc = {
744730
"_id": ident,
745731
"content": text,
@@ -758,8 +744,23 @@ def store_long_term(
758744
logger.info(f"Successfully stored in MongoDB long-term memory with ID: {ident}")
759745
except Exception as e:
760746
logger.error(f"Failed to store in MongoDB long-term memory: {e}")
761-
if not self.use_rag: # Only raise if no fallback available
762-
return
747+
# Continue to SQLite fallback
748+
749+
# Store in SQLite
750+
try:
751+
conn = sqlite3.connect(self.long_db)
752+
conn.execute(
753+
"INSERT INTO long_mem (id, content, meta, created_at) VALUES (?,?,?,?)",
754+
(ident, text, json.dumps(metadata), created)
755+
)
756+
conn.commit()
757+
conn.close()
758+
logger.info(f"Successfully stored in SQLite with ID: {ident}")
759+
except Exception as e:
760+
logger.error(f"Error storing in SQLite: {e}")
761+
if not (self.use_mongodb and hasattr(self, "mongo_long_term")):
762+
# Only raise if MongoDB is not available as fallback
763+
return
763764

764765
# Store in vector database if enabled
765766
if self.use_rag and hasattr(self, "chroma_col"):

src/praisonai-agents/praisonaiagents/tools/mongodb_tools.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@
1313
import logging
1414
from typing import List, Dict, Any, Optional, Union, TYPE_CHECKING
1515
from importlib import util
16-
import json
17-
import time
1816
from datetime import datetime
1917

2018
if TYPE_CHECKING:

src/praisonai-agents/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ telemetry = [
6262

6363
# MongoDB dependencies
6464
mongodb = [
65-
"pymongo>=4.6.0",
65+
"pymongo>=4.6.3",
6666
"motor>=3.4.0"
6767
]
6868

0 commit comments

Comments
 (0)