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

fix: Fix plugin loading from a character.json file #2095

Merged
merged 3 commits into from
Jan 10, 2025

Conversation

treppers
Copy link
Contributor

@treppers treppers commented Jan 10, 2025

Relates to

No specific ticket or issue linked.

Risks

Medium:

•	Plugin loading behavior could fail on some model/plugin combos.  If the plugin isn't listed in the list OR the api key isn't included (i.e. Together for Image Generation).
•	Affects how plugins are included and loaded via the character.json file and a POST via the client.

Background

What does this PR do?

This PR resolves issues and improves functionality for loading plugins in the following ways:
1. Ensures plugins in the plugin array in the character.json file are loaded, regardless if the API key exists in the createAgent function and/or if the plugin is listed in the createAgent list.
2. Adds support for loading plugins via POST settings.
3. Fixes a bug where plugins without a default export for their main function (e.g., video gen, image gen, and web search plugins) fail to load. The fix assumes all plugins are named using the camelCase version of the import name with “Plugin” as a suffix.
4. Load some missing plugins into the package.json

What kind of change is this?

•	Bug Fixes: Resolves plugin loading issues described above.
•	Improvements: Adds support for POST settings and standardizes plugin naming assumptions for broader compatibility.

Documentation changes needed?

Yes:

•	The documentation should be updated to reflect:
1.	The new behavior for plugin loading when added directly to the plugin list.
2.	Details on POST support for plugin loading.
3.	The assumption about plugin naming conventions and export requirements.

Testing

Where should a reviewer start?

•	Start by reviewing the changes made to the createAgent function and the logic for loading plugins.

Detailed testing steps

1.	Add the image generation plugin (@elizaos/plugin-image-generation) to the plugin array in the character.json file. Add a TOGETHER_API_KEY key. Verify that the plugin loads correctly and works with the Together API.
2.	Test loading plugins using the POST method to ensure functionality works as expected.
3.	Test loading plugins with and without a default export for the main function. Ensure that plugins like video gen, image gen, and web search do not `export default` their main plugin function

Discord username

treppers

Summary by CodeRabbit

  • New Features
    • Added two new plugins for video generation and web search.
  • Refactor
    • Improved plugin importing mechanism with enhanced error handling.
    • Streamlined plugin management process in agent initialization.

@odilitime odilitime changed the title Fix plugin loading from a character.json file fix: Fix plugin loading from a character.json file Jan 10, 2025
Copy link
Contributor

coderabbitai bot commented Jan 10, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The pull request introduces two new dependencies for video generation and web search plugins in the agent/package.json file. Simultaneously, the agent/src/index.ts file undergoes a refactoring of plugin handling, with a new handlePluginImporting function replacing the previous isAllStrings function. The changes improve plugin import error management and streamline the plugin loading process for the agent.

Changes

File Change Summary
agent/package.json Added two new dependencies:
- @elizaos/plugin-video-generation
- @elizaos/plugin-web-search
agent/src/index.ts - Removed isAllStrings function
- Added handlePluginImporting async function
- Updated plugin import logic in loadCharacters and startAgent methods

Sequence Diagram

sequenceDiagram
    participant Agent
    participant PluginImporter
    participant Plugins

    Agent->>PluginImporter: Call handlePluginImporting
    PluginImporter->>Plugins: Attempt to import plugins
    alt Import Successful
        Plugins-->>PluginImporter: Return imported plugins
    else Import Failed
        PluginImporter-->>Agent: Return empty array
        PluginImporter->>Agent: Log import errors
    end
Loading

Poem

🐰 Plugins dancing, new and bright,
Importing magic with all my might!
Web search, video - what a treat,
Errors caught, my code's now neat! 🎬🔍
Rabbit's code, forever light! 🌟


🪧 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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ea9d1c0 and 2314e21.

📒 Files selected for processing (2)
  • agent/package.json (1 hunks)
  • agent/src/index.ts (3 hunks)
🔇 Additional comments (4)
agent/src/index.ts (3)

202-204: LGTM! Clean separation of plugin importing logic.

The delegation of plugin importing to a dedicated function improves code organization and maintainability.


790-793: LGTM! Consistent plugin loading implementation.

The integration of handlePluginImporting in startAgent maintains consistency with loadCharacters.


227-227: Add test coverage for handlePluginImporting.

This new function handles critical plugin loading functionality but lacks test coverage. Consider adding tests for:

  • Successful plugin loading
  • Failed plugin imports
  • Empty plugin array handling
  • Invalid plugin format handling

Would you like me to help generate test cases for this functionality?

agent/package.json (1)

62-63: LGTM! Consistent dependency additions.

The new plugin dependencies follow the existing workspace package pattern.

agent/src/index.ts Show resolved Hide resolved
odilitime
odilitime previously approved these changes Jan 10, 2025
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: 1

♻️ Duplicate comments (1)
agent/src/index.ts (1)

230-258: 🛠️ Refactor suggestion

Consider additional improvements to plugin importing.

While the previous review comment covers essential improvements to error handling and type safety, there are additional concerns:

  1. The function returns an empty array [] for failed imports at line 250, which could lead to silent failures in the agent's functionality.
  2. There's no validation that the imported plugins conform to the expected plugin interface.

Additionally, consider adding plugin validation:

 async function handlePluginImporting(plugins: string[]) {
+    interface ElizaPlugin {
+        // Add minimum required plugin interface
+        name?: string;
+        initialize?: () => Promise<void>;
+    }
+
+    function isValidPlugin(plugin: any): plugin is ElizaPlugin {
+        return typeof plugin === 'function' || 
+               (typeof plugin === 'object' && plugin !== null);
+    }
+
     if (plugins.length > 0) {
         elizaLogger.info("Plugins are: ", plugins);
         const importedPlugins = await Promise.all(
             plugins.map(async (plugin) => {
                 try {
                     const importedPlugin = await import(plugin);
                     const functionName =
                         plugin
                             .replace("@elizaos/plugin-", "")
                             .replace(/-./g, (x) => x[1].toUpperCase()) +
                         "Plugin";
-                    return (
-                        importedPlugin.default || importedPlugin[functionName]
-                    );
+                    const pluginFunction = importedPlugin.default || importedPlugin[functionName];
+                    if (!isValidPlugin(pluginFunction)) {
+                        throw new Error(`Invalid plugin format: ${plugin}`);
+                    }
+                    return pluginFunction;
                 } catch (importError) {
                     elizaLogger.error(
                         `Failed to import plugin: ${plugin}`,
                         importError
                     );
-                    return []; // Return null for failed imports
+                    throw importError; // Propagate error to caller
                 }
             })
-        );
+        ).catch(error => {
+            elizaLogger.error('Plugin loading failed:', error);
+            return []; // Return empty array only at top level
+        });
         return importedPlugins;
     } else {
         return [];
     }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2314e21 and 1813bf1.

📒 Files selected for processing (2)
  • agent/package.json (1 hunks)
  • agent/src/index.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • agent/package.json
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: integration-tests
🔇 Additional comments (1)
agent/src/index.ts (1)

799-802: 🛠️ Refactor suggestion

Add error handling for plugin importing in startAgent.

Similar to the loadCharacters function, plugin importing should be wrapped in a try-catch block.

     directClient.startAgent = async (character) => {
-        // Handle plugins
-        character.plugins = await handlePluginImporting(character.plugins);
+        try {
+            character.plugins = await handlePluginImporting(character.plugins);
+        } catch (error) {
+            elizaLogger.error(`Failed to load plugins for character ${character.name}:`, error);
+            // Consider whether to throw or continue with empty plugins array
+            character.plugins = [];
+        }

         // wrap it so we don't have to inject directClient later
         return startAgent(character, directClient);
     };

Likely invalid or redundant comment.

agent/src/index.ts Show resolved Hide resolved
@odilitime odilitime changed the base branch from main to develop January 10, 2025 17:48
@odilitime odilitime enabled auto-merge January 10, 2025 18:01
@odilitime odilitime merged commit a34a9c2 into elizaOS:develop Jan 10, 2025
6 checks passed
@Angelopvtac
Copy link

Hey @odilitime, quite curious, I'm running into this error when loading the image gen plugin into json.


This is what I've got in character JSON

{
"name": "Jowy Bear",
"clients": ["discord"],
"modelProvider": "together",
"settings": {
"secrets": {},
"voice": {
"model": "en_US-hfc_female-medium"
}
},
"plugins": ["@elizaos/plugin-image-generation"],
"bio": [


C:\MyApps\Eliza\eliza\node_modules\better-sqlite3\lib\methods\wrappers.js:5
return this[cppdb].prepare(sql, this, false);
^

TypeError: The database connection is not open
at Database.prepare (C:\MyApps\Eliza\eliza\node_modules\better-sqlite3\lib\methods\wrappers.js:5:21)
at SqliteDatabaseAdapter.getParticipantsForAccount (file:///C:/MyApps/Eliza/eliza/packages/adapter-sqlite/dist/index.js:137:30)
at AgentRuntime.ensureParticipantExists (file:///C:/MyApps/Eliza/eliza/packages/core/dist/index.js:29808:57)
at file:///C:/MyApps/Eliza/eliza/packages/core/dist/index.js:29536:18

Node.js v23.5.0
C:\MyApps\Eliza\eliza\agent:
 ERR_PNPM_RECURSIVE_RUN_FIRST_FAIL  @elizaos/[email protected] start: node --loader ts-node/esm src/index.ts "--isRoot" "--character=characters/jowybear.character.json"
Exit status 1

I'm obviously using together and I noticed that this fix was supposed to clear this.
Do you know what I need to do in order to actually use image gen with together API ?

@daizhengxue
Copy link
Contributor

I also get the same error:
TypeError: The database connection is not open
When I activate my image generation plugin.

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

Successfully merging this pull request may close these issues.

4 participants