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: Primus zkTLS plugin to fully verify agent activities #2086

Merged
merged 28 commits into from
Jan 11, 2025

Conversation

xiangxiecrypto
Copy link
Contributor

Risks

Low

Background

Verifiable agent is emerging and zkTLS is a promising way to enhance transparency and trust for AI Agents. The current solutions focus on the verifiability of LLM inference, but it is not all the behaviour of an agent. In the Eliza framework. LLM is the brain of agent, but it also have actions and external source providers. We aim to make all these activities verifiable.

Recap of zkTLS: zkTLS is a cryptographic protocol that allows third parties to verify the authenticity of TLS transcripts in a privacy-preserving way.

What does this PR do?

This PR introduces the Primus adapter and plugin, enabling verifiability for LLM inference, actions, and interactions with external providers. Different zkTLS modes are provided, including MPC-TLS and Proxy-TLS.

What kind of change is this?

Features

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

In the Eliza framework, an agent consists of three key components: a brain (accessing an LLM), actions (the tasks the
agent performs), and perception (gathering external information from providers). To fully verify agent activities, it's
essential to ensure that the agent's thoughts, actions, and external information requests are all verifiable.

Documentation changes needed?

The documentation in packages/plugin-primus/README.md has been updated, with no further changes needed.

Testing

Where should a reviewer start?

packages/plugin-primus/README.md

Detailed testing steps

Please follow the steps in packages/plugin-primus/README.md.

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Hi @xiangxiecrypto! Welcome to the ai16z community. Thanks for submitting your first pull request; your efforts are helping us accelerate towards AGI. We'll review it shortly. You are now a ai16z contributor!

@wtfsayo wtfsayo self-requested a review January 11, 2025 10:15
wtfsayo
wtfsayo previously approved these changes Jan 11, 2025
@xiangxiecrypto
Copy link
Contributor Author

@wtfsayo thank you for approving the previous version! We just resolved conflict!

@wtfsayo
Copy link
Member

wtfsayo commented Jan 11, 2025

@xiangxiecrypto in-conflict again; can't resolve myself due to your branch perms I think

@xiangxiecrypto
Copy link
Contributor Author

@wtfsayo I‘ve grant you access to the branch, and we resolved the conflicts. Thanks!

@wtfsayo
Copy link
Member

wtfsayo commented Jan 11, 2025

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jan 11, 2025

📝 Walkthrough

Walkthrough

This pull request introduces the @elizaos/plugin-primus, a new plugin for verifiable inference and Twitter interactions within the ElizaOS framework. It adds a workspace dependency for @elizaos/plugin-primus, integrates new clients and adapters for enhanced functionality, and expands the VerifiableInferenceProvider enum. The plugin implements functionality for verified tweet posting and token price retrieval, utilizing Primus' zkTLS protocol to ensure the integrity of agent activities.

Changes

File Change Summary
agent/package.json Added @elizaos/plugin-primus as a workspace dependency
agent/src/index.ts Integrated DirectClient and PrimusAdapter, updated client initialization with Primus support
packages/core/src/types.ts Added RECLAIM and PRIMUS to VerifiableInferenceProvider enum
packages/plugin-primus/ New package with comprehensive implementation of Primus verification plugin
packages/plugin-primus/src/adapter/primusAdapter.ts Implemented PrimusAdapter for text generation and proof verification
packages/plugin-primus/src/actions/postTweetAction.ts Added action for verified tweet posting
packages/plugin-primus/src/providers/ Added providers for token prices and tweet retrieval
packages/plugin-primus/.npmignore Added .npmignore to control package publishing
packages/plugin-primus/README.md Documented plugin functionalities and usage
packages/plugin-primus/package.json Defined package metadata and dependencies
packages/plugin-primus/src/templates.ts Added summarizeTweetTemplate function for tweet formatting
packages/plugin-primus/src/util/ Introduced utility functions for proof generation and verification
packages/plugin-primus/src/util/twitterScraper.ts Implemented TwitterScraper class for Twitter API interactions
packages/plugin-primus/tsconfig.json Created TypeScript configuration for the plugin
packages/plugin-primus/tsup.config.ts Added build configuration for tsup

Finishing Touches

  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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: 11

🧹 Nitpick comments (9)
packages/plugin-primus/src/adapter/primusAdapter.ts (1)

85-85: Use consistent logging with 'elizaLogger'

Replace console.error with elizaLogger.error for consistent logging.

-                console.error("Error in Primus generateText:", error);
+                elizaLogger.error("Error in Primus generateText:", error);
packages/plugin-primus/src/util/twitterScraper.ts (3)

8-8: Remove unnecessary constructor

The empty constructor is unnecessary and can be removed.

-        constructor() {}
🧰 Tools
🪛 Biome (1.9.4)

[error] 8-8: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)


43-183: Avoid using 'any' typecasting

Casting this.scraper to any bypasses type checking. Consider extending or properly typing the Scraper class to avoid using any.


132-132: Correct typo in error messages

Change "illegality" to "illegal" in the error messages.

-                    "Verify attestation failed,data from source is illegality"
+                    "Verify attestation failed, data from source is illegal"

-                    "Verify attestation failed, data from source is illegality"
+                    "Verify attestation failed, data from source is illegal"

Also applies to: 252-252

packages/plugin-primus/src/util/primusUtil.ts (1)

24-24: Remove commented out code

Remove the commented console.log statement.

-    // console.log('requestParam:',requestParam)
packages/plugin-primus/README.md (4)

17-17: Add missing comma

Add a comma after "actions" for better readability.

-An example for verifying actions, such as posting a tweet (this can be extended to any other actions).
+An example for verifying actions, such as posting a tweet (this can be extended to any other actions,).
🧰 Tools
🪛 LanguageTool

[uncategorized] ~17-~17: Possible missing comma found.
Context: ...be extended to any other actions). - An example to verify that the Bitcoin price is acc...

(AI_HYDRA_LEO_MISSING_COMMA)


37-43: Add validation for PrimusOptions interface

Consider adding validation for the attMode field to restrict it to valid values.

 interface PrimusOptions {
     appId: string;
     appSecret: string;
-    attMode: string;
+    attMode: "mpctls" | "proxytls";
     modelProvider?: ModelProviderName;
     token?: string;
 }

93-93: Add return type annotation

The provider's get method should specify its return type for better type safety.

-    get: async (runtime: IAgentRuntime, message: Memory, _state?: State) => {
+    get: async (runtime: IAgentRuntime, message: Memory, _state?: State): Promise<string> => {

159-166: Add environment variable validation steps

Consider adding a section about validating the environment variables and common troubleshooting steps.

Would you like me to generate a validation script and troubleshooting guide section for the README?

🧰 Tools
🪛 Markdownlint (0.37.0)

161-161: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 565f4e7 and 9bf45e0.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (16)
  • agent/package.json (1 hunks)
  • agent/src/index.ts (3 hunks)
  • packages/core/src/types.ts (1 hunks)
  • packages/plugin-primus/.npmignore (1 hunks)
  • packages/plugin-primus/README.md (1 hunks)
  • packages/plugin-primus/package.json (1 hunks)
  • packages/plugin-primus/src/actions/postTweetAction.ts (1 hunks)
  • packages/plugin-primus/src/adapter/primusAdapter.ts (1 hunks)
  • packages/plugin-primus/src/index.ts (1 hunks)
  • packages/plugin-primus/src/providers/tokenPriceProvider.ts (1 hunks)
  • packages/plugin-primus/src/providers/tweetProvider.ts (1 hunks)
  • packages/plugin-primus/src/templates.ts (1 hunks)
  • packages/plugin-primus/src/util/primusUtil.ts (1 hunks)
  • packages/plugin-primus/src/util/twitterScraper.ts (1 hunks)
  • packages/plugin-primus/tsconfig.json (1 hunks)
  • packages/plugin-primus/tsup.config.ts (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • packages/plugin-primus/tsconfig.json
  • packages/plugin-primus/.npmignore
  • packages/plugin-primus/tsup.config.ts
👮 Files not reviewed due to content moderation or server errors (4)
  • packages/core/src/types.ts
  • agent/src/index.ts
  • packages/plugin-primus/package.json
  • packages/plugin-primus/src/actions/postTweetAction.ts
🧰 Additional context used
🪛 LanguageTool
packages/plugin-primus/README.md

[uncategorized] ~17-~17: Possible missing comma found.
Context: ...be extended to any other actions). - An example to verify that the Bitcoin price is acc...

(AI_HYDRA_LEO_MISSING_COMMA)

🪛 Markdownlint (0.37.0)
packages/plugin-primus/README.md

98-98: Column: 20
Hard tabs

(MD010, no-hard-tabs)


161-161: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)

🪛 Biome (1.9.4)
packages/plugin-primus/src/util/twitterScraper.ts

[error] 8-8: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: integration-tests
  • GitHub Check: smoke-tests
🔇 Additional comments (1)
agent/package.json (1)

75-75: LGTM! Dependency added correctly

The new plugin dependency follows the established pattern and is correctly placed.

packages/plugin-primus/src/index.ts Show resolved Hide resolved
packages/plugin-primus/src/templates.ts Outdated Show resolved Hide resolved
packages/plugin-primus/src/providers/tokenPriceProvider.ts Outdated Show resolved Hide resolved
packages/plugin-primus/src/providers/tweetProvider.ts Outdated Show resolved Hide resolved
packages/plugin-primus/src/providers/tweetProvider.ts Outdated Show resolved Hide resolved
packages/plugin-primus/src/util/primusUtil.ts Outdated Show resolved Hide resolved
packages/plugin-primus/src/util/primusUtil.ts Outdated Show resolved Hide resolved
packages/plugin-primus/README.md Outdated Show resolved Hide resolved
@wtfsayo
Copy link
Member

wtfsayo commented Jan 11, 2025

@wtfsayo I‘ve grant you access to the branch, and we resolved the conflicts. Thanks!

nope!!! but do check the ai flagged issues

@xiangxiecrypto
Copy link
Contributor Author

@wtfsayo I‘ve grant you access to the branch, and we resolved the conflicts. Thanks!

nope!!! but do check the ai flagged issues

I think you need to accept the invite. Yeah, we are checking the issues.

@xiangxiecrypto
Copy link
Contributor Author

@wtfsayo I‘ve grant you access to the branch, and we resolved the conflicts. Thanks!

nope!!! but do check the ai flagged issues

We fixed the issues, can you please let the bot review it again? Thanks

@wtfsayo wtfsayo self-requested a review January 11, 2025 14:45
@wtfsayo
Copy link
Member

wtfsayo commented Jan 11, 2025

@coderabbitai review

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 (2)
packages/plugin-primus/src/util/primusUtil.ts (1)

38-42: 🛠️ Refactor suggestion

Add credential validation to verification function

Add environment variable validation.

 export const verifyProof = async (attestation: Attestation): Promise<boolean> => {
+    if (!process.env.PRIMUS_APP_ID || !process.env.PRIMUS_APP_SECRET) {
+        throw new Error('Primus credentials not configured');
+    }
     const zkTLS = new PrimusCoreTLS();
packages/plugin-primus/src/providers/tokenPriceProvider.ts (1)

18-31: 🛠️ Refactor suggestion

Improve type safety and error handling

Replace type assertion and add proper error handling.

     try {
-        const responseData = JSON.parse((attestation as any).data);
+        const responseData = JSON.parse(attestation.data);
+        if (!responseData?.content) {
+            throw new Error('Invalid response format');
+        }
         const price = responseData.content;
🧹 Nitpick comments (10)
packages/plugin-primus/src/providers/tweetProvider.ts (3)

16-19: Remove redundant login verification.

The isLoggedIn() check is redundant since we already handle login failures in the try-catch block above.

-        if (!(await scraperWithPrimus.getScraper().isLoggedIn())) {
-            elizaLogger.error("Failed to login to Twitter");
-            return false;
-        }

27-27: Remove duplicate debug log.

This log message is identical to the one on line 25.

-        elizaLogger.debug(`Fetching tweets for user: ${userName}`);

4-37: Add rate limiting for Twitter API calls.

Consider implementing rate limiting to prevent API abuse and comply with Twitter's usage guidelines.

packages/plugin-primus/README.md (3)

48-49: Make OpenAI endpoint configurable

The endpoint URL should be configurable through environment variables rather than hardcoded.

-    endpoint: "https://api.openapi.com/chat/completions",
+    endpoint: process.env.OPENAI_API_ENDPOINT || "https://api.openapi.com/chat/completions",

157-161: Add version compatibility information

Please specify:

  • Required Node.js version
  • Compatible ElizaOS versions
  • Any other dependencies

98-98: Fix markdown formatting issues

  1. Replace hard tab with spaces in the headers section
  2. Add language specification to the environment variables code block
-    'Accept	': '*/*',
+    'Accept': '*/*',

-```
+```env
 PRIMUS_APP_ID=your_app_id

Also applies to: 167-172

🧰 Tools
🪛 Markdownlint (0.37.0)

98-98: Column: 20
Hard tabs

(MD010, no-hard-tabs)

packages/plugin-primus/src/util/primusUtil.ts (2)

24-24: Remove commented debug code

Remove the commented console.log statement.


25-35: Validate response parse path format

Add validation for the response parse path to ensure it follows JSONPath syntax.

+    if (!responseParsePath.startsWith('$')) {
+        throw new Error('Invalid response parse path format. Must be a valid JSONPath expression');
+    }
     const attestationParams = zkTLS.generateRequestParams(requestParam, [
packages/plugin-primus/src/providers/tokenPriceProvider.ts (2)

9-11: Fix header formatting

Remove the tab character from the Accept header.

     const headers = {
-        'Accept	': '*/*',
+        'Accept': '*/*',
     };

21-27: Consider using a template literal

The multi-line string could be more readable using a template literal.

-            return  `
-            Get BTC price from Binance:
-            BTC: ${price} USDT
-            Time: ${new Date().toUTCString()}
-            POST by eliza #eliza
-            Attested by Primus #primus #zktls
-            `
+            return `Get BTC price from Binance:
+BTC: ${price} USDT
+Time: ${new Date().toUTCString()}
+POST by eliza #eliza
+Attested by Primus #primus #zktls`;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9bf45e0 and d90f838.

📒 Files selected for processing (5)
  • packages/plugin-primus/README.md (1 hunks)
  • packages/plugin-primus/src/providers/tokenPriceProvider.ts (1 hunks)
  • packages/plugin-primus/src/providers/tweetProvider.ts (1 hunks)
  • packages/plugin-primus/src/templates.ts (1 hunks)
  • packages/plugin-primus/src/util/primusUtil.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/plugin-primus/src/templates.ts
🧰 Additional context used
🪛 Markdownlint (0.37.0)
packages/plugin-primus/README.md

98-98: Column: 20
Hard tabs

(MD010, no-hard-tabs)


167-167: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: integration-tests
  • GitHub Check: smoke-tests
🔇 Additional comments (6)
packages/plugin-primus/src/providers/tweetProvider.ts (2)

1-4: LGTM! Clean imports and provider definition.


28-35: Well-implemented error handling for tweet retrieval.

The error handling matches the previously suggested implementation.

packages/plugin-primus/README.md (1)

117-154: Complete the action implementation

The action has several issues that need to be addressed:

  1. Empty examples array
  2. Missing error handling for the tweet posting
  3. Incomplete validate method
packages/plugin-primus/src/util/primusUtil.ts (2)

1-1: LGTM! Clean import with proper types.


3-11: 🛠️ Refactor suggestion

Add environment variable validation and improve type safety

The function should validate environment variables and use stricter types.

+interface RequestHeaders {
+    [key: string]: string;
+}
+
 export const generateProof = async (
     endpoint: string,
     method: string,
-    headers: Record<string, any>,
+    headers: RequestHeaders,
     body: string,
     responseParsePath: string
 ): Promise<Attestation> => {
+    if (!process.env.PRIMUS_APP_ID || !process.env.PRIMUS_APP_SECRET) {
+        throw new Error('Primus credentials not configured');
+    }
     const zkTLS = new PrimusCoreTLS();

Likely invalid or redundant comment.

packages/plugin-primus/src/providers/tokenPriceProvider.ts (1)

1-3: LGTM! Clean imports with proper types.

packages/plugin-primus/README.md Show resolved Hide resolved
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.

5 participants