Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(new-adapter): mongo-db adaptor #1427

Merged
merged 16 commits into from
Jan 25, 2025
Merged

Conversation

jobyid
Copy link
Contributor

@jobyid jobyid commented Dec 24, 2024

Added an adaptor which connects to mongo db atlas. Allowing you to store agent data in the cloud. If you have the appropriate tier you can also take advantage of their vector search functionality.
It should have all the same functionality as the other database adaptors.

Relates to:

Adding the option of using MongoDB in the cloud to store you agents data

Risks

Low, adds additional options for database usage

Background

What does this PR do?

Adds the option to store your agents data in MongoDB Atlas, and take advantage of their vector search. I have also updated the .env.example to include the additional variables for the mongo connection. And added to the agent index with functionality to initialise this database if required.

What kind of change is this?

Adding an additional feature

Why are we doing this? Any context or related work?

In my day job we exclusively use mongoDB for our database needs, for commercials and performance reasons. As we want to develop AI Agents, we need to have the mongoDB adaptor. IN the sprit of OpenSource I wanted to make sure it was available for the whole community to use as well.

Documentation changes needed?

A small additional input to the documentation is required to make users aware of the additional functionality and how it can be actioned.
Similar to the Postgres set up just adding in the appropriate connection string to the .env file will action he change to start using MongoDB as the database.

Testing

Where should a reviewer start?

The reviewer will need to have a least a free account with mongoDB atlas, then add the connection string and a Database name to the .env file. After that the agent should run as expected, saving memories as before. The reviewer can verify the saved data inside the MongoDB interface.

Detailed testing steps

  1. Create MongoDB atlas account
  2. Add connection string and Database name to .env file
  3. Run agent
  4. Verify inside MongoDB interface that the collections have formed and data is being stored

Summary by CodeRabbit

Release Notes

  • New Features

    • Added MongoDB database support with a new database adapter
    • Enhanced configuration options for database connections
  • Configuration Updates

    • Updated environment configuration to support MongoDB connection
    • Removed Venice-related configurations
    • Added Hyperbolic logging settings
  • Development Improvements

    • Introduced new package @elizaos/adapter-mongodb
    • Added comprehensive testing infrastructure for MongoDB integration
  • Chores

    • Updated project dependencies
    • Cleaned up unused configuration files

Added an adaptor which connects to mongo db atlas. Allowing you to store agent data in the cloud.
If you have the appropriate tier you can also take advantage of their vector search functionaility.
@odilitime odilitime changed the base branch from main to develop December 25, 2024 00:25
@odilitime odilitime changed the title mongo-db adaptor feat: mongo-db adaptor Dec 25, 2024
@odilitime odilitime added Plugin_new Mark PRs that are a new plugin Needs Testing labels Dec 25, 2024
@wtfsayo wtfsayo self-requested a review January 7, 2025 12:49
packages/adapter-mongodb/src/index.ts Outdated Show resolved Hide resolved
packages/adapter-mongodb/src/index.ts Outdated Show resolved Hide resolved
packages/adapter-mongodb/src/index.ts Outdated Show resolved Hide resolved
packages/adapter-mongodb/src/index.ts Show resolved Hide resolved
Copy link
Contributor

coderabbitai bot commented Jan 21, 2025

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

agent/src/index.ts

Oops! Something went wrong! :(

ESLint: 9.19.0

ESLint couldn't find an eslint.config.(js|mjs|cjs) file.

From ESLint v9.0.0, the default configuration file is now eslint.config.js.
If you are using a .eslintrc.* file, please follow the migration guide
to update your configuration file to the new format:

https://eslint.org/docs/latest/use/configure/migration-guide

If you still have problems after following the migration guide, please stop by
https://eslint.org/chat/help to chat with the team.

Walkthrough

This pull request introduces MongoDB as a new database option for the project, adding a comprehensive MongoDB adapter and updating configuration files. The changes include a new .env.example with MongoDB connection settings, modifications to the agent's database initialization logic, and a complete MongoDB adapter implementation with testing infrastructure. The PR maintains existing database support while providing a new, flexible database connection method.

Changes

File Change Summary
.env.example Added MongoDB connection settings, updated Hyperbolic config, removed Venice config
agent/src/index.ts Modified database initialization to prioritize MongoDB connection
packages/adapter-mongodb/* Added new package with full MongoDB adapter implementation, configuration, and testing files
.gitignore Added .vscode and .zed entries
agent/package.json Added @elizaos/adapter-mongodb dependency

Sequence Diagram

sequenceDiagram
    participant App as Application
    participant Adapter as MongoDB Adapter
    participant MongoDB as MongoDB Database
    
    App->>Adapter: Initialize Database
    Adapter->>MongoDB: Establish Connection
    MongoDB-->>Adapter: Connection Confirmed
    Adapter-->>App: Ready for Operations
    App->>Adapter: Perform CRUD Operations
    Adapter->>MongoDB: Execute Database Commands
    MongoDB-->>Adapter: Return Results
Loading

Possibly related PRs

Poem

🍃 Databases dance, MongoDB arrives
Connections spark, the system thrives
From Supabase to new horizons bright
Adapter's magic takes elegant flight! 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

🧹 Nitpick comments (4)
packages/adapter-mongodb/src/index.ts (2)

20-20: Specify a concrete type for 'database' instead of 'any'

Using any defeats the purpose of TypeScript's type safety. Specify a more precise type for database to improve type safety and code maintainability.

For example:

import { Db } from 'mongodb';

private database: Db;

589-624: Use a standard library for Levenshtein distance calculation

Implementing custom algorithms can introduce unnecessary complexity and potential bugs. Using a well-tested library for Levenshtein distance can improve code readability and maintainability.

For example, you can use the fast-levenshtein package:

import levenshtein from 'fast-levenshtein';

private calculateLevenshteinDistanceOptimized(str1: string, str2: string): number {
    return levenshtein.get(str1, str2);
}
.env.example (2)

413-414: Enhance MongoDB configuration documentation.

Add more descriptive comments to guide users:

-MONGODB_CONNECTION_STRING=  #mongodb connection string
-MONGODB_DATABASE= #name of the database in mongoDB atlas
+MONGODB_CONNECTION_STRING=  # MongoDB Atlas connection string (format: mongodb+srv://<username>:<password>@<cluster>.mongodb.net)
+MONGODB_DATABASE= # Name of the database in MongoDB Atlas (e.g., agent_data)

413-413: Add security note for MongoDB connection string.

The connection string contains sensitive credentials. Consider adding a comment about security best practices.

-MONGODB_CONNECTION_STRING=  #mongodb connection string
+# WARNING: Connection string contains credentials. Never commit actual values to version control.
+MONGODB_CONNECTION_STRING=  # MongoDB Atlas connection string
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8a4b42b and 5eaa272.

📒 Files selected for processing (14)
  • .env.example (2 hunks)
  • .idea/.gitignore (1 hunks)
  • .idea/eliza.iml (1 hunks)
  • .idea/inspectionProfiles/Project_Default.xml (1 hunks)
  • .idea/modules.xml (1 hunks)
  • .idea/prettier.xml (1 hunks)
  • .idea/vcs.xml (1 hunks)
  • agent/src/index.ts (1 hunks)
  • packages/adapter-mongodb/.npmignore (1 hunks)
  • packages/adapter-mongodb/eslint.config.mjs (1 hunks)
  • packages/adapter-mongodb/package.json (1 hunks)
  • packages/adapter-mongodb/src/index.ts (1 hunks)
  • packages/adapter-mongodb/tsconfig.json (1 hunks)
  • packages/adapter-mongodb/tsup.config.ts (1 hunks)
✅ Files skipped from review due to trivial changes (10)
  • .idea/prettier.xml
  • .idea/eliza.iml
  • packages/adapter-mongodb/.npmignore
  • packages/adapter-mongodb/eslint.config.mjs
  • .idea/modules.xml
  • packages/adapter-mongodb/tsconfig.json
  • packages/adapter-mongodb/tsup.config.ts
  • .idea/.gitignore
  • .idea/vcs.xml
  • packages/adapter-mongodb/package.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: integration-tests
🔇 Additional comments (1)
packages/adapter-mongodb/src/index.ts (1)

66-66: ⚠️ Potential issue

Correct 'expireAfterSeconds' value in TTL index

Setting expireAfterSeconds: 0 in the TTL index may not function as intended, as MongoDB requires a positive integer value. To ensure documents expire correctly based on the expiresAt field, you can omit expireAfterSeconds or set it to a positive integer.

Apply this diff to fix the issue:

 { key: { expiresAt: 1 }, options: {
-    expireAfterSeconds: 0
 } }

Likely invalid or redundant comment.

.idea/inspectionProfiles/Project_Default.xml Outdated Show resolved Hide resolved
agent/src/index.ts Show resolved Hide resolved
agent/src/index.ts Outdated Show resolved Hide resolved
agent/src/index.ts Outdated Show resolved Hide resolved
packages/adapter-mongodb/src/index.ts Outdated Show resolved Hide resolved
wtfsayo
wtfsayo previously approved these changes Jan 24, 2025
Copy link
Member

@wtfsayo wtfsayo left a comment

Choose a reason for hiding this comment

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

lgtm

@wtfsayo wtfsayo changed the title feat: mongo-db adaptor feat(new-adapter): mongo-db adaptor Jan 25, 2025
@wtfsayo
Copy link
Member

wtfsayo commented Jan 25, 2025

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jan 25, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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: 3

♻️ Duplicate comments (1)
packages/adapter-mongodb/src/index.ts (1)

474-481: ⚠️ Potential issue

Prevent division by zero in cosineSimilarity
This code can return Infinity or NaN when magnitudeA or magnitudeB is zero. A guard clause can prevent unexpected runtime errors.

     const magnitudeA = Math.sqrt(aArr.reduce((sum, val) => sum + val * val, 0));
     const magnitudeB = Math.sqrt(bArr.reduce((sum, val) => sum + val * val, 0));
+    if (magnitudeA === 0 || magnitudeB === 0) {
+        return 0; // Or any fallback
+    }
     return dotProduct / (magnitudeA * magnitudeB);
🧹 Nitpick comments (6)
packages/adapter-mongodb/src/__tests__/docker-compose.test.yml (2)

12-16: Enhance health check robustness.

Consider adding authentication to the health check command to verify the MongoDB credentials are working.

-      test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
+      test: ["CMD", "mongosh", "--username", "mongodb", "--password", "mongodb", "--eval", "db.adminCommand('ping')"]
🧰 Tools
🪛 yamllint (1.35.1)

[error] 16-16: no new line character at the end of file

(new-line-at-end-of-file)


16-16: Add newline at end of file.

Add a newline character at the end of the file to comply with POSIX standards and fix the linting error.

🧰 Tools
🪛 yamllint (1.35.1)

[error] 16-16: no new line character at the end of file

(new-line-at-end-of-file)

packages/adapter-mongodb/src/index.ts (1)

42-42: Consider using stronger typings instead of any.
Defining private database: Db (from mongodb library) or a more specific interface can improve maintainability.

packages/adapter-mongodb/package.json (2)

10-10: Pin the MongoDB driver version.

Using ^6.3.0 allows minor version updates which could introduce breaking changes. Consider pinning to exact version.

-        "mongodb": "^6.3.0",
+        "mongodb": "6.3.0",

26-26: Add coverage threshold to test script.

The test script doesn't enforce minimum test coverage requirements.

-        "test": "cd src/__tests__ && ./run_tests.sh",
+        "test": "cd src/__tests__ && ./run_tests.sh --coverage --coverageThreshold='{ \"global\": { \"branches\": 80, \"functions\": 80, \"lines\": 80, \"statements\": 80 } }'",
.env.example (1)

19-20: Enhance MongoDB configuration documentation.

The MongoDB configuration entries need better documentation of required format and options.

-MONGODB_CONNECTION_STRING=             #mongodb connection string
-MONGODB_DATABASE=                      #name of the database in mongoDB atlas #default: 'elizaAgent'
+MONGODB_CONNECTION_STRING=             # MongoDB connection string (format: mongodb+srv://<username>:<password>@<cluster>.mongodb.net)
+MONGODB_DATABASE=                      # Name of the database in MongoDB Atlas (default: 'elizaAgent'). Must be alphanumeric and start with a letter.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5eaa272 and d454a70.

📒 Files selected for processing (13)
  • .env.example (4 hunks)
  • .gitignore (1 hunks)
  • .vscode/launch.json (0 hunks)
  • .vscode/settings.json (0 hunks)
  • .vscode/tasks.json (0 hunks)
  • agent/package.json (1 hunks)
  • agent/src/index.ts (4 hunks)
  • packages/adapter-mongodb/package.json (1 hunks)
  • packages/adapter-mongodb/src/__tests__/docker-compose.test.yml (1 hunks)
  • packages/adapter-mongodb/src/__tests__/mongodb-adapter.test.ts (1 hunks)
  • packages/adapter-mongodb/src/__tests__/run_tests.sh (1 hunks)
  • packages/adapter-mongodb/src/index.ts (1 hunks)
  • packages/adapter-mongodb/tsconfig.json (1 hunks)
💤 Files with no reviewable changes (3)
  • .vscode/tasks.json
  • .vscode/launch.json
  • .vscode/settings.json
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🧰 Additional context used
🪛 Biome (1.9.4)
packages/adapter-mongodb/src/index.ts

[error] 1284-1284: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 1335-1335: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 1342-1342: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 1346-1346: Do not add then to an object.

(lint/suspicious/noThenProperty)

🪛 yamllint (1.35.1)
packages/adapter-mongodb/src/__tests__/docker-compose.test.yml

[error] 16-16: no new line character at the end of file

(new-line-at-end-of-file)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: smoke-tests
  • GitHub Check: integration-tests
🔇 Additional comments (6)
packages/adapter-mongodb/src/__tests__/docker-compose.test.yml (1)

1-2: LGTM! Good use of schema validation.

The schema validation and Docker Compose version selection are appropriate.

packages/adapter-mongodb/src/index.ts (1)

1283-1350: Ignore the noThenProperty lint errors on $cond.
These aggregator expressions use MongoDB’s $cond syntax, which legitimately includes then and else. Those lint errors are false positives.

🧰 Tools
🪛 Biome (1.9.4)

[error] 1284-1284: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 1335-1335: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 1342-1342: Do not add then to an object.

(lint/suspicious/noThenProperty)


[error] 1346-1346: Do not add then to an object.

(lint/suspicious/noThenProperty)

packages/adapter-mongodb/src/__tests__/mongodb-adapter.test.ts (1)

6-133: Great test coverage.
These tests validate key features of the MongoDB adapter, ensuring knowledge and cache operations work as intended.

packages/adapter-mongodb/tsconfig.json (1)

1-24: Configuration looks good.
Makes sense to extend the base config, enforcing strict type checks and ES2021 features for this package.

agent/package.json (1)

27-27: LGTM!

The MongoDB adapter dependency is correctly added and follows the workspace pattern.

agent/src/index.ts (1)

516-546: ⚠️ Potential issue

Improve MongoDB initialization and error handling.

The MongoDB initialization has several issues:

  1. The connection is not properly awaited
  2. The error handling could be improved
  3. The connection options should be documented

Apply this diff to fix the issues:

 if (process.env.MONGODB_CONNECTION_STRING) {
     elizaLogger.log("Initializing database on MongoDB Atlas");
     const client = new MongoClient(process.env.MONGODB_CONNECTION_STRING, {
+        // Connection pool settings
         maxPoolSize: 100,
         minPoolSize: 5,
         maxIdleTimeMS: 60000,
+        // Timeout settings
         connectTimeoutMS: 10000,
         serverSelectionTimeoutMS: 5000,
         socketTimeoutMS: 45000,
+        // Performance settings
         compressors: ['zlib'],
         retryWrites: true,
         retryReads: true
     });

     const dbName = process.env.MONGODB_DATABASE || 'elizaAgent';
     const db = new MongoDBDatabaseAdapter(client, dbName);

-    // Test the connection
-    db.init()
-        .then(() => {
-            elizaLogger.success(
-                "Successfully connected to MongoDB Atlas"
-            );
-        })
-        .catch((error) => {
-            elizaLogger.error("Failed to connect to MongoDB Atlas:", error);
-            throw error; // Re-throw to handle it in the calling code
-        });
+    try {
+        // Test the connection
+        await db.init();
+        elizaLogger.success("Successfully connected to MongoDB Atlas");
+    } catch (error) {
+        elizaLogger.error("Failed to connect to MongoDB Atlas:", error);
+        // Close the client on error
+        await client.close();
+        throw error;
+    }

     return db;

Likely invalid or redundant comment.

@wtfsayo wtfsayo enabled auto-merge (squash) January 25, 2025 09:40
@wtfsayo wtfsayo self-requested a review January 25, 2025 09:40
@wtfsayo wtfsayo merged commit fed685f into elizaOS:develop Jan 25, 2025
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Needs Testing Plugin_new Mark PRs that are a new plugin
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants