Skip to content

Add support for Anthropic#215

Merged
elie222 merged 11 commits intomainfrom
other-llms
Aug 21, 2024
Merged

Add support for Anthropic#215
elie222 merged 11 commits intomainfrom
other-llms

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Aug 21, 2024

Summary by CodeRabbit

  • New Features

    • Introduced support for multiple AI providers with enhanced configuration options.
    • Added a dynamic selection for AI models based on user input and selected provider.
  • Improvements

    • Streamlined API key handling by standardizing variable names (e.g., openAIApiKey to aiApiKey).
    • Enhanced validation and error handling for AI models and providers.
  • Bug Fixes

    • Resolved inconsistencies in API key usage across various components.
  • Documentation

    • Updated ngrok usage instructions to include a method for maintaining a stable endpoint.
    • Clarified data processing practices by mentioning multiple AI service providers in the privacy documentation.

@vercel
Copy link

vercel bot commented Aug 21, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
inbox-zero ✅ Ready (Inspect) Visit Preview Aug 21, 2024 5:22pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 21, 2024

Warning

Rate limit exceeded

@elie222 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 14 minutes and 0 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 8ad1664 and 83b24c2.

Walkthrough

The recent changes enhance API key management by standardizing the key naming from openAIApiKey to aiApiKey, and adding support for new environment variables relating to Amazon Bedrock. The integration of AI providers is streamlined, allowing for a more flexible and user-friendly experience. Overall, these updates improve maintainability and increase clarity in the documentation and codebase.

Changes

Files Change Summary
.vscode/typescriptreact.code-snippets, apps/web/.env.example Replaced openAIApiKey with aiApiKey; added BEDROCK_ACCESS_KEY, BEDROCK_SECRET_KEY, and BEDROCK_REGION.
apps/web/__tests__/ai-choose-rule.test.ts, apps/web/__tests__/plan.testold.ts Updated tests to use aiApiKey instead of openAIApiKey.
apps/web/app/(app)/premium/config.ts, apps/web/app/(app)/settings/ModelSection.tsx Changed mentions from "OpenAI API key" to "AI API key"; updated components to utilize aiApiKey and introduced aiProvider.
apps/web/app/api/.../*.ts, apps/web/app/user/settings/validation.ts Refined API controllers to leverage aiApiKey and simplified model/provider logic; adjusted validation schema for aiProvider and aiModel.
apps/web/utils/actions/.../*.ts, apps/web/utils/llms/config.ts, apps/web/utils/llms/index.ts Unified function parameters to standardize on aiApiKey; consolidated AI model selection into a single function for better maintainability.
apps/web/prisma/schema.prisma, apps/web/prisma/migrations/... Updated database schema and migrations from openAIApiKey to aiApiKey.
apps/web/package.json, packages/.../package.json Updated dependency versions across packages for improved functionality and security.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI
    participant API
    participant Database

    User->>UI: Input settings
    UI->>API: Submit settings (aiApiKey, aiProvider)
    API->>Database: Save settings (aiApiKey, aiProvider)
    Database-->>API: Confirmation
    API-->>UI: Update success
Loading
sequenceDiagram
    participant User
    participant API
    participant AIService as AI
    participant ModelSelector as MS

    User->>API: Request AI interaction
    API->>MS: Get model based on aiProvider
    MS-->>API: Return selected model
    API->>AI: Call AI service with userAi (aiApiKey, model)
    AI-->>API: Return AI response
    API-->>User: Provide results
Loading

Poem

🐇 In fields of code, where logic blooms,
A key was changed, dispelling glooms.
From OpenAI's grasp to a world anew,
AI's embrace, with skies so blue.
With Bedrock's keys, we hop and cheer,
For every change, a brighter year! 🌱✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

Outside diff range, codebase verification and nitpick comments (3)
apps/web/app/api/user/settings/validation.ts (1)

13-14: Missing entry in modelOptions for Provider.OPEN_AI.

The verification script has identified that there is no corresponding entry in modelOptions for Provider.OPEN_AI, which could lead to runtime errors. Please ensure that all possible values of aiProvider have corresponding entries in modelOptions.

  • Missing modelOptions entry for provider: Provider.OPEN_AI
Analysis chain

Verify the validity of modelOptions[val.aiProvider].

Ensure that modelOptions[val.aiProvider] always returns a valid array to prevent runtime errors.

Run the following script to verify that all possible values of aiProvider have corresponding entries in modelOptions:

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all possible values of `aiProvider` have corresponding entries in `modelOptions`.

# Test: Check for missing entries. Expect: No missing entries.
ast-grep --lang typescript --pattern $'export const providerOptions = $_' | rg -oP '(?<=value: ).*?(?=})' | while read -r provider; do
  if ! rg --type typescript -q "[$provider]:"; then
    echo "Missing modelOptions entry for provider: $provider"
  fi
done

Length of output: 585


Script:

#!/bin/bash
# Description: Verify that all possible values of `aiProvider` have corresponding entries in `modelOptions`.

# Test: Check for missing entries. Expect: No missing entries.
ast-grep --lang typescript --pattern $'export const providerOptions = $_' | rg -oP '(?<=value: ).*?(?=})' | while read -r provider; do
  if ! rg -q "\[$provider\]:"; then
    echo "Missing modelOptions entry for provider: $provider"
  fi
done

Length of output: 301

apps/web/utils/llms/config.ts (1)

27-27: Clarify the comment on line 27.

The comment could be clearer about its context in the UI. Consider specifying that the value is used for display purposes and can represent either the Anthropic or Bedrock service.

Use this diff to clarify the comment:

        value: "claude-3-5-sonnet", // used for display in UI only; can represent either Anthropic or Bedrock
apps/web/app/api/ai/models/route.ts (1)

Line range hint 10-15: Consider renaming getOpenAiModels for clarity.

The function name getOpenAiModels may be misleading as it suggests it only retrieves OpenAI models, while the context now involves multiple AI providers.

Consider renaming the function to something more generic, like getAiModels, to reflect its broader applicability.

 async function getAiModels({ apiKey }: { apiKey: string }) {
   const openai = new OpenAI({ apiKey });

   const models = await openai.models.list();

   return models.data.filter((m) => m.id.startsWith("gpt-"));
 }
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7d10d5a and 31fe1ce.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (41)
  • .vscode/typescriptreact.code-snippets (6 hunks)
  • apps/web/.env.example (1 hunks)
  • apps/web/tests/ai-choose-rule.test.ts (1 hunks)
  • apps/web/tests/plan.testold.ts (3 hunks)
  • apps/web/app/(app)/premium/config.ts (2 hunks)
  • apps/web/app/(app)/settings/ModelSection.tsx (6 hunks)
  • apps/web/app/api/ai/categorise/controller.ts (2 hunks)
  • apps/web/app/api/ai/cold-email/controller.ts (2 hunks)
  • apps/web/app/api/ai/cold-email/route.ts (1 hunks)
  • apps/web/app/api/ai/compose-autocomplete/route.ts (2 hunks)
  • apps/web/app/api/ai/models/route.ts (1 hunks)
  • apps/web/app/api/ai/summarise/controller.ts (2 hunks)
  • apps/web/app/api/google/watch/all/route.ts (2 hunks)
  • apps/web/app/api/google/webhook/group-rule.ts (1 hunks)
  • apps/web/app/api/google/webhook/process-history.ts (5 hunks)
  • apps/web/app/api/google/webhook/static-rule.ts (1 hunks)
  • apps/web/app/api/user/me/route.ts (1 hunks)
  • apps/web/app/api/user/settings/route.ts (1 hunks)
  • apps/web/app/api/user/settings/validation.ts (1 hunks)
  • apps/web/components/PremiumAlert.tsx (3 hunks)
  • apps/web/env.ts (1 hunks)
  • apps/web/package.json (4 hunks)
  • apps/web/prisma/migrations/20240820220244_ai_api_key/migration.sql (1 hunks)
  • apps/web/prisma/schema.prisma (1 hunks)
  • apps/web/utils/actions/ai-rule.ts (4 hunks)
  • apps/web/utils/actions/categorize.ts (3 hunks)
  • apps/web/utils/ai/choose-rule/ai-choose-args.ts (2 hunks)
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts (2 hunks)
  • apps/web/utils/ai/group/create-group.ts (2 hunks)
  • apps/web/utils/ai/rule/create-rule.ts (2 hunks)
  • apps/web/utils/llms/config.ts (1 hunks)
  • apps/web/utils/llms/index.ts (3 hunks)
  • apps/web/utils/llms/types.ts (1 hunks)
  • apps/web/utils/premium/index.ts (1 hunks)
  • apps/web/utils/usage.ts (2 hunks)
  • packages/eslint-config/package.json (1 hunks)
  • packages/loops/package.json (1 hunks)
  • packages/resend/package.json (1 hunks)
  • packages/tinybird-ai-analytics/package.json (1 hunks)
  • packages/tinybird/package.json (1 hunks)
  • turbo.json (2 hunks)
Files skipped from review due to trivial changes (10)
  • .vscode/typescriptreact.code-snippets
  • apps/web/tests/plan.testold.ts
  • apps/web/app/(app)/premium/config.ts
  • apps/web/app/api/google/watch/all/route.ts
  • apps/web/app/api/user/me/route.ts
  • apps/web/components/PremiumAlert.tsx
  • apps/web/prisma/migrations/20240820220244_ai_api_key/migration.sql
  • apps/web/prisma/schema.prisma
  • apps/web/utils/actions/ai-rule.ts
  • apps/web/utils/premium/index.ts
Additional context used
Biome
apps/web/app/api/user/settings/route.ts

[error] 27-30: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

apps/web/utils/llms/index.ts

[error] 31-47: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)


[error] 8-9: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

apps/web/app/(app)/settings/ModelSection.tsx

[error] 85-85: This hook does not specify all of its dependencies: setValue

This dependency is not specified in the hook dependency list.

(lint/correctness/useExhaustiveDependencies)


[error] 85-85: This hook does not specify all of its dependencies: watch

This dependency is not specified in the hook dependency list.

(lint/correctness/useExhaustiveDependencies)

Additional comments not posted (34)
apps/web/utils/llms/types.ts (1)

3-3: LGTM! But verify the usage of aiApiKey.

The change from openAIApiKey to aiApiKey enhances clarity and consistency. Ensure that all references to UserAIFields are updated to use aiApiKey.

Run the following script to verify the usage of aiApiKey:

Verification successful

The usage of aiApiKey is consistent across the codebase.

The change from openAIApiKey to aiApiKey has been successfully propagated throughout the codebase, ensuring clarity and consistency. No issues were found with the usage of aiApiKey.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all references to `UserAIFields` use `aiApiKey`.

# Test: Search for the usage of `UserAIFields`. Expect: Only occurrences of `aiApiKey`.
rg --type typescript -A 3 $'UserAIFields'

Length of output: 75


Script:

#!/bin/bash
# Description: Verify all references to `UserAIFields` use `aiApiKey`.

# Search for the usage of `UserAIFields` and check for `aiApiKey`.
rg 'UserAIFields' -A 3

Length of output: 8767


Script:

#!/bin/bash
# Description: Verify the usage of `aiApiKey` in the codebase.

# Search for the usage of `aiApiKey`.
rg 'aiApiKey'

Length of output: 3745

packages/loops/package.json (2)

9-9: Dependency update approved: @types/node to 22.4.2.

The update may improve type safety and compatibility with newer Node.js features. Ensure compatibility with the existing code.

Run the following script to verify compatibility with the updated @types/node:


6-6: Dependency update approved: loops to ^3.1.1.

The update may introduce new features or bug fixes. Ensure compatibility with the existing code.

Run the following script to verify compatibility with the loops library:

packages/tinybird/package.json (1)

11-11: Dependency update approved: @types/node to 22.4.2.

The update may improve type safety and compatibility with newer Node.js features. Ensure compatibility with the existing code.

Run the following script to verify compatibility with the updated @types/node:

packages/tinybird-ai-analytics/package.json (1)

11-11: Upgrade of @types/node is approved.

The update to version 22.4.2 enhances type safety and compatibility with newer Node.js features.

packages/eslint-config/package.json (1)

15-16: Upgrade of TypeScript ESLint packages is approved.

The updates to @typescript-eslint/parser and @typescript-eslint/eslint-plugin to version 8.2.0 align with the latest improvements in the TypeScript ecosystem.

packages/resend/package.json (2)

17-18: Upgrade of type definitions is approved.

The updates to @types/node and @types/react enhance compatibility with newer versions of Node.js and React.


14-14: Upgrade of resend package requires verification.

The version update from ^3.5.0 to ^4.0.0 may introduce new features or breaking changes. Ensure compatibility with existing code.

Run the following script to verify the usage of the resend package:

apps/web/utils/ai/group/create-group.ts (1)

Line range hint 30-36: Verify the user object structure.

Ensure that the user object contains all necessary properties required by the chatCompletionObject function.

Run the following script to verify the user object structure:

apps/web/app/api/ai/summarise/controller.ts (1)

16-16: Verify the Provider.OPEN_AI constant.

Ensure that the Provider.OPEN_AI constant is correctly defined in the @/utils/llms/config module.

Run the following script to verify the definition of the Provider.OPEN_AI constant:

Verification successful

The Provider.OPEN_AI constant is correctly defined.

The Provider object in apps/web/utils/llms/config.ts includes the OPEN_AI key with the value "openai", confirming that the change to use Provider.OPEN_AI is valid and improves code maintainability.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the definition of the `Provider.OPEN_AI` constant.

# Test: Search for the `Provider` enum or object definition. Expect: It should contain `OPEN_AI`.
ast-grep --lang typescript --pattern $'const Provider = {
  OPEN_AI: $_,
  $$$
}'

Length of output: 286

apps/web/app/api/ai/compose-autocomplete/route.ts (1)

Line range hint 30-35: Verify the user object structure.

Ensure that the user object contains all necessary properties required by the chatCompletionStream function.

Run the following script to verify the user object structure:

apps/web/utils/usage.ts (1)

1-1: LGTM! Using constants for provider names improves maintainability.

The change from a hardcoded string to Provider.OPEN_AI enhances code clarity and reduces potential errors.

Also applies to: 27-27

apps/web/app/api/user/settings/route.ts (1)

17-34: LGTM! The changes enhance flexibility and error handling.

The introduction of aiProvider and getModel improves the handling of multiple AI providers and models.

Also applies to: 39-41

Tools
Biome

[error] 27-30: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

apps/web/utils/ai/choose-rule/ai-choose-rule.ts (1)

3-3: LGTM! Simplifying data handling by passing the user object directly is a good improvement.

The removal of getAiProviderAndModel and direct use of user streamlines the code.

Also applies to: 58-58

apps/web/utils/actions/categorize.ts (1)

37-37: LGTM! But verify the function usage in the codebase.

The code changes are approved. The renaming and direct access to user properties improve clarity and maintainability.

However, ensure that all function calls to categorizeAction and any references to aiApiKey match the new naming convention.

Run the following script to verify the function usage:

Also applies to: 51-53

Verification successful

Function Usage Verification

The categorizeAction function is defined but not used elsewhere in the codebase. The aiApiKey references are consistent with the new naming convention across various files.

  • categorizeAction: Defined in apps/web/utils/actions/categorize.ts but not referenced elsewhere.
  • aiApiKey: Correctly used in multiple files with the new naming convention.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `categorizeAction` and references to `aiApiKey`.

# Test: Search for the function usage and references. Expect: Only occurrences of the new naming convention.
rg --type typescript -A 5 $'categorizeAction'
rg --type typescript -A 5 $'aiApiKey'

Length of output: 151


Script:

#!/bin/bash
# Description: Verify all function calls to `categorizeAction` and references to `aiApiKey`.

# Search for the function usage and references in TypeScript files by extension.
rg --glob '*.ts' -A 5 'categorizeAction'
rg --glob '*.ts' -A 5 'aiApiKey'

Length of output: 12729

apps/web/.env.example (1)

13-15: Environment variables added for Bedrock support.

The addition of BEDROCK_ACCESS_KEY, BEDROCK_SECRET_KEY, and BEDROCK_REGION enhances configuration options for the application.

apps/web/app/api/ai/cold-email/route.ts (1)

40-40: LGTM! But verify the function usage in the codebase.

The code changes are approved. The renaming to aiApiKey aligns with the new naming convention.

However, ensure that all function calls to checkColdEmail and any references to aiApiKey match the new naming convention.

Run the following script to verify the function usage:

Verification successful

Verification Successful: Naming Convention Alignment Confirmed

The renaming to aiApiKey and the usage of checkColdEmail are consistent with the new naming convention across the codebase. No discrepancies were found.

  • checkColdEmail is correctly used in apps/web/app/api/ai/cold-email/route.ts.
  • aiApiKey references are consistently aligned with the new naming convention in multiple files.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `checkColdEmail` and references to `aiApiKey`.

# Test: Search for the function usage and references. Expect: Only occurrences of the new naming convention.
rg --type typescript -A 5 $'checkColdEmail'
rg --type typescript -A 5 $'aiApiKey'

Length of output: 149


Script:

#!/bin/bash
# Description: Verify all function calls to `checkColdEmail` and references to `aiApiKey`.

# Test: Search for the function usage and references. Expect: Only occurrences of the new naming convention.
rg --glob '*.ts' -A 5 'checkColdEmail'
rg --glob '*.ts' -A 5 'aiApiKey'

Length of output: 13053

apps/web/app/api/google/webhook/group-rule.ts (1)

27-27: LGTM! The API key renaming enhances clarity.

The change from openAIApiKey to aiApiKey is consistent with the PR objectives and improves the clarity of the code.

apps/web/utils/ai/rule/create-rule.ts (1)

80-80: LGTM! Streamlined argument structure.

The removal of the getAiProviderAndModel function call and direct use of user improves clarity and reduces complexity.

turbo.json (1)

18-20: LGTM! Added environment variables for BEDROCK.

The addition of BEDROCK_ACCESS_KEY, BEDROCK_SECRET_KEY, and BEDROCK_REGION expands the application's configuration options, enabling integration with additional services.

apps/web/__tests__/ai-choose-rule.test.ts (1)

142-142: LGTM! Renaming openAIApiKey to aiApiKey is consistent with the PR objectives.

The change aligns with the goal of generalizing the API key naming convention.

apps/web/app/api/google/webhook/static-rule.ts (1)

24-24: LGTM! Renaming openAIApiKey to aiApiKey is consistent with the PR objectives.

The change aligns with the goal of generalizing the API key naming convention.

However, ensure that all references to the user object in the codebase are updated to reflect this change.

Run the following script to verify the function usage:

Verification successful

Renaming Verified: All references to openAIApiKey have been updated to aiApiKey.

The codebase consistently uses aiApiKey, confirming that the renaming aligns with the PR objectives. No instances of openAIApiKey were found.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all references to the `user` object reflect the change from `openAIApiKey` to `aiApiKey`.

# Test: Search for the usage of `handleStaticRule`. Expect: Only occurrences of the new parameter structure.
rg --type typescript -A 5 $'handleStaticRule'

Length of output: 79


Script:

#!/bin/bash
# Find all TypeScript files and search for the usage of `handleStaticRule`.
fd --extension ts --exec rg 'handleStaticRule' -A 5

Length of output: 583


Script:

#!/bin/bash
# Search for references to `aiApiKey` and `openAIApiKey` in TypeScript files to verify the update.
fd --extension ts --exec rg 'aiApiKey|openAIApiKey'

Length of output: 1338

apps/web/utils/llms/index.ts (1)

11-11: LGTM! The refactoring to use getModel and userAi improves maintainability.

The changes streamline AI model selection and usage, aligning with the PR objectives.

Also applies to: 54-54, 91-91, 128-128

apps/web/app/api/ai/categorise/controller.ts (1)

82-82: Verify compatibility with chatCompletionObject.

Ensure that the chatCompletionObject function can handle the entire body object as userAi. This change simplifies the data flow but assumes compatibility.

Run the following script to verify the chatCompletionObject function's compatibility:

Verification successful

Compatibility confirmed with chatCompletionObject.

The body object is structured to include UserAIFields, ensuring compatibility with the chatCompletionObject function. The necessary properties are present, confirming that the change is valid.

  • body is typed to include UserAIFields, which contains "aiProvider", "aiModel", and "aiApiKey".
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the `chatCompletionObject` function's compatibility with the new `userAi` parameter.

# Test: Search for the `chatCompletionObject` function definition. Expect: It should handle the `userAi` parameter appropriately.
ast-grep --lang typescript --pattern $'function chatCompletionObject({ userAi, $$$ }) { $$$ }'

Length of output: 95


Script:

#!/bin/bash
# Search for the `chatCompletionObject` function definition in the codebase
rg 'function chatCompletionObject' -A 10

# Additionally, check if `chatCompletionObject` is defined as a variable or constant
rg 'const chatCompletionObject' -A 10
rg 'let chatCompletionObject' -A 10

Length of output: 620


Script:

#!/bin/bash
# Search for the definition of `UserAIFields` to verify its structure
rg 'type UserAIFields' -A 10
rg 'interface UserAIFields' -A 10

Length of output: 173


Script:

#!/bin/bash
# Search for the structure of the `body` object in the controller file
rg 'const body' -A 10 apps/web/app/api/ai/categorise/controller.ts

Length of output: 68


Script:

#!/bin/bash
# Perform a broader search for the `body` object within the controller file to identify its structure
rg 'body' -A 10 apps/web/app/api/ai/categorise/controller.ts

Length of output: 1833

apps/web/app/api/ai/cold-email/controller.ts (1)

68-68: Verify compatibility with chatCompletionObject.

Ensure that the chatCompletionObject function can handle the entire user object as userAi. This change simplifies the data flow but assumes compatibility.

Run the following script to verify the chatCompletionObject function's compatibility:

Verification successful

Compatibility with chatCompletionObject verified.

The user object passed as userAi is compatible with the chatCompletionObject function, as it matches the expected UserAIFields structure, which includes aiProvider, aiModel, and aiApiKey. No further action is required.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the `chatCompletionObject` function's compatibility with the new `userAi` parameter.

# Test: Search for the `chatCompletionObject` function definition. Expect: It should handle the `userAi` parameter appropriately.
ast-grep --lang typescript --pattern $'function chatCompletionObject({ userAi, $$$ }) { $$$ }'

Length of output: 95


Script:

#!/bin/bash
# Description: Locate the `chatCompletionObject` function definition to verify compatibility with the `userAi` parameter.

# Search for the `chatCompletionObject` function definition in the codebase.
rg 'function chatCompletionObject' -A 10

Length of output: 542


Script:

#!/bin/bash
# Description: Locate the definition of `UserAIFields` to verify compatibility with the `user` object.

# Search for the `UserAIFields` type definition in the codebase.
rg 'type UserAIFields' -A 10

Length of output: 137

apps/web/package.json (1)

Line range hint 15-132: Verify compatibility of updated dependencies.

Ensure that the updated dependencies are compatible with the existing codebase and do not introduce breaking changes. Pay special attention to major version changes.

Run the following script to verify the compatibility of updated dependencies:

apps/web/app/(app)/settings/ModelSection.tsx (2)

Line range hint 23-47: LGTM!

The ModelSection component correctly fetches user data and models, and passes the necessary props to ModelSectionForm. The changes align with the shift to a unified API key management approach.


53-57: LGTM!

The getDefaultModel function correctly handles defaulting to Provider.OPEN_AI and returns the first model for the provider.

apps/web/utils/ai/choose-rule/ai-choose-args.ts (1)

126-126: LGTM!

The change to pass the user object as userAi to chatCompletionTools simplifies the function call and enhances maintainability. Ensure that downstream logic correctly handles this encapsulation.

apps/web/env.ts (1)

15-17: LGTM!

The new environment variables for Bedrock services are correctly defined, with optional access and secret keys, and a default region.

apps/web/app/api/google/webhook/process-history.ts (4)

78-78: LGTM! Verify hasAiAccess handling of aiApiKey.

The change is consistent with the renaming of the API key variable.

Ensure that the function hasAiAccess correctly handles the aiApiKey.

Run the following script to verify the function's handling:

Verification successful

Verification Successful: aiApiKey Handling in hasAiAccess

The aiApiKey is correctly used in the logic for determining AI access, replacing the previous openAIApiKey. The boolean expression for hasAiAccess properly checks the conditions for access.

  • The logic for hasAiAccess is implemented as a boolean expression in apps/web/utils/premium/index.ts.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify `hasAiAccess` handling of `aiApiKey`.

# Test: Search for the implementation of `hasAiAccess`. Expect: Correct handling of `aiApiKey`.
ast-grep --lang typescript --pattern $'function hasAiAccess($_, aiApiKey) { $$$ }'

Length of output: 83


Script:

#!/bin/bash
# Search for the `hasAiAccess` function definition in the codebase.
rg 'function hasAiAccess' -A 5

# Search for occurrences of `aiApiKey` in the codebase to understand its usage.
rg 'aiApiKey' -A 5

Length of output: 16370


49-49: Verify consistency of aiApiKey usage.

Ensure that the variable aiApiKey is consistently used throughout the codebase.

Run the following script to verify the usage of aiApiKey:

Verification successful

aiApiKey Usage is Consistent Across the Codebase

The aiApiKey variable is consistently used throughout the codebase, replacing the previous openAIApiKey. This change aligns with the broader context of API key usage in the application.

  • Locations of Usage:
    • apps/web/utils/llms/index.ts
    • apps/web/utils/premium/index.ts
    • apps/web/components/PremiumAlert.tsx
    • apps/web/app/api/google/webhook/process-history.ts
    • Other related files and components

The transition appears to be well-integrated across various modules and components. No inconsistencies were found in the usage of aiApiKey.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of `aiApiKey` across the codebase.

# Test: Search for occurrences of `aiApiKey`. Expect: Consistent usage across files.
rg --type typescript -A 5 $'aiApiKey'

Length of output: 71


Script:

#!/bin/bash
# Description: Verify the usage of `aiApiKey` across the codebase.

# Test: Search for occurrences of `aiApiKey`. Expect: Consistent usage across files.
rg --type ts -A 5 $'aiApiKey'

Length of output: 15748


176-178: LGTM! Verify processHistory handling of AI parameters.

The change simplifies the retrieval of AI-related data.

Ensure that the processHistory function correctly handles aiProvider, aiModel, and aiApiKey.

Run the following script to verify the function's handling:


82-82: LGTM! Verify hasColdEmailAccess handling of aiApiKey.

The change is consistent with the renaming of the API key variable.

Ensure that the function hasColdEmailAccess correctly handles the aiApiKey.

Run the following script to verify the function's handling:

Comment on lines +27 to +30
} else {
// use bedrock if no api key set
return Model.CLAUDE_3_5_SONNET_BEDROCK;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove the unnecessary else clause.

The else clause can be omitted because the previous branch returns early, simplifying the code.

Use this diff to remove the else clause:

      case Provider.ANTHROPIC:
        if (options.aiApiKey) {
          // use anthropic if api key set
          return Model.CLAUDE_3_5_SONNET_ANTHROPIC;
-        } else {
+        }
          // use bedrock if no api key set
          return Model.CLAUDE_3_5_SONNET_BEDROCK;
        }
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
} else {
// use bedrock if no api key set
return Model.CLAUDE_3_5_SONNET_BEDROCK;
}
case Provider.ANTHROPIC:
if (options.aiApiKey) {
// use anthropic if api key set
return Model.CLAUDE_3_5_SONNET_ANTHROPIC;
}
// use bedrock if no api key set
return Model.CLAUDE_3_5_SONNET_BEDROCK;
Tools
Biome

[error] 27-30: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

Comment on lines +8 to +9
import { Model, Provider } from "@/utils/llms/config";
import { UserAIFields } from "@/utils/llms/types";
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize imports: Use import type for type-only imports.

This ensures that types are removed by the transpilers, avoiding unnecessary module loading.

Use this diff to optimize the imports:

-import { Model, Provider } from "@/utils/llms/config";
-import { UserAIFields } from "@/utils/llms/types";
+import type { Model, Provider } from "@/utils/llms/config";
+import type { UserAIFields } from "@/utils/llms/types";
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
import { Model, Provider } from "@/utils/llms/config";
import { UserAIFields } from "@/utils/llms/types";
import type { Model, Provider } from "@/utils/llms/config";
import type { UserAIFields } from "@/utils/llms/types";
Tools
Biome

[error] 8-9: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

Comment on lines 85 to 92
Copy link
Contributor

Choose a reason for hiding this comment

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

Add missing dependencies to useEffect.

The useEffect hook should include setValue and watch as dependencies to ensure it behaves correctly.

Use this diff to fix the dependencies:

 useEffect(() => {
   const aiModel = watch("aiModel");

   // if model not part of provider then switch to default model for provider
   if (!modelOptions[aiProvider].find((o) => o.value === aiModel)) {
     setValue("aiModel", getDefaultModel(aiProvider));
   }
- }, [aiProvider]);
+ }, [aiProvider, setValue, watch]);
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
useEffect(() => {
const aiModel = watch("aiModel");
// if model not part of provider then switch to default model for provider
if (!modelOptions[aiProvider].find((o) => o.value === aiModel)) {
setValue("aiModel", getDefaultModel(aiProvider));
}
}, [aiProvider]);
useEffect(() => {
const aiModel = watch("aiModel");
// if model not part of provider then switch to default model for provider
if (!modelOptions[aiProvider].find((o) => o.value === aiModel)) {
setValue("aiModel", getDefaultModel(aiProvider));
}
}, [aiProvider, setValue, watch]);
Tools
Biome

[error] 85-85: This hook does not specify all of its dependencies: setValue

This dependency is not specified in the hook dependency list.

(lint/correctness/useExhaustiveDependencies)


[error] 85-85: This hook does not specify all of its dependencies: watch

This dependency is not specified in the hook dependency list.

(lint/correctness/useExhaustiveDependencies)

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 31fe1ce and b3529ee.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (3)
  • apps/web/app/(app)/settings/ModelSection.tsx (6 hunks)
  • apps/web/app/api/ai/models/route.ts (2 hunks)
  • apps/web/package.json (4 hunks)
Files skipped from review due to trivial changes (1)
  • apps/web/package.json
Files skipped from review as they are similar to previous changes (2)
  • apps/web/app/(app)/settings/ModelSection.tsx
  • apps/web/app/api/ai/models/route.ts

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

Outside diff range, codebase verification and nitpick comments (1)
apps/web/app/api/ai/summarise/controller.ts (1)

2-3: Optimize imports by using import type.

The imports Provider and UserAIFields are only used as types. Using import type ensures they are removed by the transpiler, optimizing the module loading.

Use this diff to optimize the imports:

-import { Provider } from "@/utils/llms/config";
-import { UserAIFields } from "@/utils/llms/types";
+import type { Provider } from "@/utils/llms/config";
+import type { UserAIFields } from "@/utils/llms/types";
Tools
Biome

[error] 2-3: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b3529ee and c2929c0.

Files selected for processing (7)
  • README.md (1 hunks)
  • apps/web/app/(app)/settings/ModelSection.tsx (6 hunks)
  • apps/web/app/api/ai/summarise/controller.ts (1 hunks)
  • apps/web/app/api/ai/summarise/route.ts (2 hunks)
  • apps/web/app/api/user/settings/route.ts (1 hunks)
  • apps/web/utils/llms/index.ts (3 hunks)
  • apps/web/utils/usage.ts (2 hunks)
Files skipped from review due to trivial changes (1)
  • README.md
Files skipped from review as they are similar to previous changes (1)
  • apps/web/utils/usage.ts
Additional context used
Biome
apps/web/app/api/ai/summarise/controller.ts

[error] 2-3: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

apps/web/app/api/user/settings/route.ts

[error] 27-30: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

apps/web/utils/llms/index.ts

[error] 31-47: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)


[error] 8-9: All these imports are only used as types.

Importing the types with import type ensures that they are removed by the transpilers and avoids loading unnecessary modules.
Safe fix: Use import type.

(lint/style/useImportType)

Additional comments not posted (10)
apps/web/app/api/ai/summarise/controller.ts (1)

7-19: Enhance flexibility by adding userAi parameter.

The addition of the userAi parameter to the summarise function improves its flexibility by allowing user-specific AI configurations. Ensure that all calls to this function are updated to pass the userAi parameter.

apps/web/app/api/ai/summarise/route.ts (2)

34-40: Ensure proper error handling for database query.

The addition of the database query to retrieve user-specific AI configuration details enhances the functionality. Ensure that the database query handles potential exceptions or errors, such as connection issues.


42-42: Update summarise function call with userAi.

The summarise function call is updated to include the userAi parameter, allowing for user-specific AI configurations. Ensure that the userAi object is correctly structured and contains the necessary fields.

apps/web/app/api/user/settings/route.ts (2)

17-34: Remove unnecessary else clause.

The else clause in the getModel function can be omitted because the previous branch returns early, simplifying the code.

Tools
Biome

[error] 27-30: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)


39-41: Enhance flexibility with dynamic AI model selection.

The prisma.user.update call is modified to include the new aiProvider and use the result of the getModel function for the aiModel field. This change improves the logic by dynamically determining the model based on user input.

apps/web/utils/llms/index.ts (3)

54-74: LGTM! Consistent model retrieval logic.

The changes improve consistency and maintainability by centralizing model retrieval logic.


91-111: LGTM! Consistent model retrieval logic.

The changes improve consistency and maintainability by centralizing model retrieval logic.


128-148: LGTM! Consistent model retrieval logic.

The changes improve consistency and maintainability by centralizing model retrieval logic.

apps/web/app/(app)/settings/ModelSection.tsx (2)

Line range hint 23-47: LGTM! Enhanced flexibility with dynamic provider selection.

The changes improve flexibility by allowing dynamic provider selection.


85-92: Add missing dependencies to useEffect.

The useEffect hook should include setValue and watch as dependencies to ensure it behaves correctly.

Use this diff to fix the dependencies:

 useEffect(() => {
   const aiModel = watch("aiModel");

   // if model not part of provider then switch to default model for provider
   if (!modelOptions[aiProvider].find((o) => o.value === aiModel)) {
     setValue("aiModel", getDefaultModel(aiProvider));
- }, [aiProvider]);
+ }, [aiProvider, setValue, watch]);

Likely invalid or redundant comment.

Comment on lines +31 to +47
} else {
if (!env.BEDROCK_ACCESS_KEY)
throw new Error("BEDROCK_ACCESS_KEY is not set");
if (!env.BEDROCK_SECRET_KEY)
throw new Error("BEDROCK_SECRET_KEY is not set");

function getModel(provider: string, model: string, apiKey: string | null) {
if (provider === "openai")
return createOpenAI({ apiKey: apiKey || env.OPENAI_API_KEY })(model);
if (provider === "anthropic")
return createAnthropic({ apiKey: apiKey || env.ANTHROPIC_API_KEY })(model);
const model = aiModel || Model.CLAUDE_3_5_SONNET_BEDROCK;
return {
provider: Provider.ANTHROPIC,
model,
llmModel: createAmazonBedrock({
accessKeyId: env.BEDROCK_ACCESS_KEY,
secretAccessKey: env.BEDROCK_SECRET_KEY,
region: env.BEDROCK_REGION,
})(model),
};
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor: Omit the else clause for cleaner code.

The else clause can be omitted because previous branches break early, improving readability.

Use this diff to refactor the code:

    } else {
      if (!env.BEDROCK_ACCESS_KEY)
        throw new Error("BEDROCK_ACCESS_KEY is not set");
      if (!env.BEDROCK_SECRET_KEY)
        throw new Error("BEDROCK_SECRET_KEY is not set");

      const model = aiModel || Model.CLAUDE_3_5_SONNET_BEDROCK;
      return {
        provider: Provider.ANTHROPIC,
        model,
        llmModel: createAmazonBedrock({
          accessKeyId: env.BEDROCK_ACCESS_KEY,
          secretAccessKey: env.BEDROCK_SECRET_KEY,
          region: env.BEDROCK_REGION,
        })(model),
      };
    }

Committable suggestion was skipped due to low confidence.

Tools
Biome

[error] 31-47: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c2929c0 and 8ad1664.

Files selected for processing (4)
  • apps/web/app/(app)/premium/config.ts (2 hunks)
  • apps/web/app/(landing)/login/LoginForm.tsx (1 hunks)
  • apps/web/app/(landing)/privacy/content.mdx (2 hunks)
  • apps/web/utils/config.ts (1 hunks)
Files skipped from review due to trivial changes (1)
  • apps/web/utils/config.ts
Files skipped from review as they are similar to previous changes (1)
  • apps/web/app/(app)/premium/config.ts
Additional comments not posted (1)
apps/web/app/(landing)/privacy/content.mdx (1)

Line range hint 19-31: Acknowledge improved transparency with Anthropic inclusion.

The addition of Anthropic as a service provider enhances transparency regarding data usage practices. Ensure that user consent and privacy policies are updated to reflect this change, and consider notifying users about the involvement of multiple AI service providers.

This was referenced Nov 1, 2024
@coderabbitai coderabbitai bot mentioned this pull request Nov 15, 2024
This was referenced Nov 22, 2024
@coderabbitai coderabbitai bot mentioned this pull request Jan 9, 2025
This was referenced Jan 16, 2025
@coderabbitai coderabbitai bot mentioned this pull request Jan 31, 2025
@coderabbitai coderabbitai bot mentioned this pull request Mar 1, 2025
@coderabbitai coderabbitai bot mentioned this pull request Jun 4, 2025
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.

1 participant

Comments