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

Catch errors when SECRETS is empty or doesnt have the right key #51

Merged
merged 2 commits into from
Jul 28, 2024

Conversation

justyns
Copy link
Owner

@justyns justyns commented Jul 28, 2024

Summary by CodeRabbit

  • New Features

    • Introduced support for the "dall-e" image model in the AI initialization process.
    • Enhanced user experience with clearer error messages for API key retrieval failures.
  • Bug Fixes

    • Improved error handling to prevent silent failures and ensure robust feedback for missing settings and secrets.
  • Tests

    • Added multiple test cases to validate initialization and error handling for image models and missing configurations.

Copy link
Contributor

coderabbitai bot commented Jul 28, 2024

Walkthrough

Walkthrough

The recent updates enhance the initializeOpenAI function to support image models, including a new "dall-e" model, and improve error handling in the API key retrieval process. New test cases have been introduced to ensure robust validation of model configurations and graceful handling of missing settings. These changes significantly bolster the initialization logic, making it more comprehensive and user-friendly while ensuring clear error reporting.

Changes

Files Change Summary
src/init.ts, src/init.test.ts Added support for image models in initializeOpenAI and enhanced error handling for API key retrieval. New test cases validate model settings, handle missing configurations, and ensure appropriate error messaging.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App
    participant Secrets

    User->>App: Call initializeOpenAI()
    App->>Secrets: Read API key
    alt Successful retrieval
        Secrets-->>App: Return API key
        App->>User: Initialization successful
    else Retrieval failed
        Secrets-->>App: Throw error
        App->>App: Log error
        App->>User: Display error message
    end
Loading

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.

@justyns
Copy link
Owner Author

justyns commented Jul 28, 2024

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Jul 28, 2024

Actions performed

Full review triggered.

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 a1f849c and 79cd934.

Files selected for processing (2)
  • src/init.test.ts (2 hunks)
  • src/init.ts (1 hunks)
Additional context used
Path-based instructions (2)
src/init.test.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

src/init.ts (1)

Pattern **/*.ts: Review these typescript files for best practices, readability, and DRY.

Additional comments not posted (7)
src/init.test.ts (6)

95-117: LGTM!

The test case for setting image models correctly is well-structured and covers the necessary assertions.


119-141: LGTM!

The test case for setting embedding models correctly is well-structured and covers the necessary assertions.


143-160: LGTM!

The test case for handling missing settings gracefully is well-structured and covers the necessary assertions.


162-175: LGTM!

The test case for handling an empty API key is well-structured and covers the necessary assertions.


177-190: LGTM!

The test case for handling a missing API secret is well-structured and covers the necessary assertions.


192-207: LGTM!

The test case for handling a non-existent secrets page is well-structured and covers the necessary assertions.

src/init.ts (1)

217-227: LGTM!

The changes to the configureSelectedModel function improve error handling by adding a try-catch block around the API key retrieval logic. This ensures that errors are caught and logged, and a user-friendly error message is provided.

Copy link
Owner Author

Choose a reason for hiding this comment

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

@coderabbitai generate additional tests in this file for src/init.ts

Copy link
Contributor

Choose a reason for hiding this comment

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

@justyns, I've generated additional tests for the initializeOpenAI and configureSelectedModel functions based on their implementations. Here are the new test cases:

import { assertEquals, assertThrowsAsync } from "https://deno.land/[email protected]/assert/mod.ts";
import "./mocks/syscalls.ts";
import { aiSettings, getAndConfigureModel, initializeOpenAI, configureSelectedModel } from "./init.ts";

const settingsPageSample = `
Mock settings, yay
\`\`\`yaml
ai:
  indexEmbeddings: true
  indexEmbeddingsExcludePages:
  - passwords
  indexEmbeddingsExcludeStrings:
  - foo
  chat:
    bakeMessages: false
    customEnrichFunctions:
    - enrichWithURL
  textModels:
    - name: gpt-4o
      provider: openai
      modelName: gpt-4o
    - name: gemini-pro
      modelName: gemini-pro
      provider: gemini
      baseUrl: https://api.gemini.ai/v1
      secretName: GOOGLE_AI_STUDIO_KEY
  imageModels:
    - name: dall-e
      provider: dalle
      modelName: dall-e
  embeddingModels:
    - name: text-embedding-3-small
      provider: openai
    - name: ollama-all-minilm
      modelName: all-minilm
      provider: ollama
      baseUrl: http://localhost:11434
      requireAuth: false
\`\`\`
  `;

const secretsPageSample = `
Mock secrets, yay
\`\`\`yaml
GOOGLE_AI_STUDIO_KEY: foo
OPENAI_API_KEY: bar
\`\`\`
  `;

Deno.test("initializeOpenAI should set the system prompt correctly", async () => {
  try {
    await syscall("mock.setPage", "SETTINGS", settingsPageSample);
    await syscall("mock.setPage", "SECRETS", secretsPageSample);
    await initializeOpenAI();
    assertEquals(
      chatSystemPrompt.role,
      "system",
      "initializeOpenAI did not set the correct system prompt role",
    );
    assertEquals(
      chatSystemPrompt.content.includes("interactive chat session with a user in a markdown-based note-taking tool called SilverBullet"),
      true,
      "initializeOpenAI did not set the correct system prompt content",
    );
  } catch (error) {
    console.error(
      "Error in test 'initializeOpenAI should set the system prompt correctly':",
      error,
    );
    throw error;
  }
});

Deno.test("configureSelectedModel should handle errors during API key retrieval", async () => {
  try {
    const model = {
      name: "test-model",
      provider: "test-provider",
      modelName: "test-model",
      requireAuth: true,
      secretName: "INVALID_SECRET_NAME",
    };
    await syscall("mock.setPage", "SECRETS", secretsPageSample);
    await assertThrowsAsync(
      async () => {
        await configureSelectedModel(model);
      },
      Error,
      "Failed to read the AI API key. Please check the SECRETS page.",
      "configureSelectedModel did not handle errors correctly",
    );
  } catch (error) {
    console.error(
      "Error in test 'configureSelectedModel should handle errors during API key retrieval':",
      error,
    );
    throw error;
  }
});

Deno.test("initializeOpenAI should configure models when multiple models are present", async () => {
  try {
    await syscall("mock.setPage", "SETTINGS", settingsPageSample);
    await syscall("mock.setPage", "SECRETS", secretsPageSample);
    await initializeOpenAI();
    await getAndConfigureModel();
    assertEquals(
      aiSettings.textModels.length,
      2,
      "initializeOpenAI did not configure multiple text models correctly",
    );
    assertEquals(
      aiSettings.imageModels.length,
      1,
      "initializeOpenAI did not configure multiple image models correctly",
    );
    assertEquals(
      aiSettings.embeddingModels.length,
      2,
      "initializeOpenAI did not configure multiple embedding models correctly",
    );
  } catch (error) {
    console.error(
      "Error in test 'initializeOpenAI should configure models when multiple models are present':",
      error,
    );
    throw error;
  }
});

These tests ensure that:

  1. The initializeOpenAI function correctly sets up the system prompt.
  2. The configureSelectedModel function handles errors during API key retrieval.
  3. The initializeOpenAI function correctly configures models when multiple models are present.

Feel free to integrate these tests into your test suite.

Analysis chain
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Fetch the implementation of the initializeOpenAI function and other relevant functions from src/init.ts
ast-grep --lang typescript --pattern $'function initializeOpenAI($_) {
  $$$
}' --pattern $'function getAndConfigureModel($_) {
  $$$
}' --pattern $'async function configureSelectedModel($_) {
  $$$
}' --pattern $'const aiSettings = $_' src/init.ts

Length of output: 413


Script:

#!/bin/bash
# Fetch the implementation of the initializeOpenAI function from src/init.ts
ast-grep --lang typescript --pattern $'function initializeOpenAI($_) {
  $$$
}' src/init.ts

# Fetch the implementation of the getAndConfigureModel function from src/init.ts
ast-grep --lang typescript --pattern $'function getAndConfigureModel($_) {
  $$$
}' src/init.ts

# Fetch the implementation of the configureSelectedModel function from src/init.ts
ast-grep --lang typescript --pattern $'async function configureSelectedModel($_) {
  $$$
}' src/init.ts

# Fetch the declaration of the aiSettings constant from src/init.ts
ast-grep --lang typescript --pattern $'const aiSettings = $_' src/init.ts

Length of output: 4490

@justyns justyns merged commit 5f8332c into main Jul 28, 2024
3 checks passed
@justyns justyns deleted the coderabbit-test branch July 28, 2024 22:36
@coderabbitai coderabbitai bot mentioned this pull request Sep 8, 2024
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