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

Feature: Register OpenAI API key #31

Merged
merged 7 commits into from
Sep 2, 2024

Conversation

sklarfox
Copy link

@sklarfox sklarfox commented Aug 23, 2024

This pull request adds the ability to register an OpenAI API secret using VSCode's SecretStorage API.

It adds one command to the command palette Register OpenAI API Key. You can use that to add/update your API key. It currently only supports OpenAI, but will be updated in the future to support other LLMs.

To retrieve the API key, import the async function getSecret from src/common/vscodeapi.ts. You have to pass it an ExtensionContext object as an argument, along with a string for whichever secret you want (for OpenAI it will be 'OPENAI_API_KEY'). How exactly you get the ExtensionContext object is going to depend on how / where your code is executed.

Summary by CodeRabbit

  • New Features

    • Introduced commands to register both OpenAI and Large Language Model (LLM) API keys within the application.
    • Enhanced functionality for securely managing API keys, including user prompts and storage in secret management.
  • Bug Fixes

    • Improved error handling during command registration to ensure a more robust user experience.
  • Documentation

    • Updated documentation for secrets management commands to enhance user understanding and usability.

Copy link
Contributor

coderabbitai bot commented Aug 23, 2024

Walkthrough

The changes introduce functionality for managing OpenAI and Large Language Model (LLM) API keys within a Visual Studio Code extension. This includes the addition of commands for registering these API keys, securely handling secrets, and enhancing the overall capabilities of the ZenML environment. The updates span multiple files, establishing a structured approach to API key management and secret storage.

Changes

File Change Summary
package.json Added command entries for registering OpenAI and LLM API keys.
src/commands/secrets/cmds.ts Implemented registerOpenAIAPIKey and registerLLMAPIKey functions for secure key management.
src/commands/secrets/registry.ts Defined registerSecretsCommands function to register secrets-related commands.
src/common/vscodeapi.ts Introduced getSecret function for retrieving secrets securely using the provided context.

Poem

🐇✨
In the garden of code, a secret we keep,
An API key tucked away, safe in its sleep.
With a hop and a jump, it’s now easy to find,
ZenML's magic has flourished, oh so kind!
So let’s celebrate changes, both shiny and bright,
A brave little bunny dances in delight!
🌟🥕


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 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 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.

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.
Early access features: disabled

We are currently testing the following features in early access:

  • Anthropic claude-3-5-sonnet for code reviews: Anthropic claims that the new Claude model has stronger code understanding and code generation capabilities than their previous models. Note: Our default code review model was also updated late last week. Please compare the quality of the reviews between the two models by toggling the early access feature.

Note:

  • You can enable or disable early access features from the CodeRabbit UI or by updating the CodeRabbit configuration file.
  • Please join our Discord Community to provide feedback and report issues on the discussion post.

@sklarfox sklarfox marked this pull request as ready for review August 23, 2024 16:51
@strickvl
Copy link
Collaborator

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Aug 23, 2024

Actions performed

Review triggered.

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Outside diff range, codebase verification and nitpick comments (4)
src/commands/secrets/cmds.ts (1)

17-17: Consider removing or addressing TODO comments.

The TODO comment suggests that the retrieval of an API key might not belong in this file. Ensure that the comment is addressed or removed if no longer relevant.

src/commands/secrets/registry.ts (2)

14-15: Consider removing or addressing TODO comments.

The TODO comments suggest that the registration of secrets commands should be moved or adjusted. Ensure that these comments are addressed or removed if no longer relevant.


27-45: Clarify error message for command registration.

The error message in the catch block refers to "pipeline commands," which may not accurately describe the commands being registered. Consider updating the message for clarity.

Apply this diff to clarify the error message:

  } catch (error) {
-   console.error('Error registering pipeline commands:', error);
+   console.error('Error registering secrets commands:', error);
src/common/vscodeapi.ts (1)

74-83: Ensure consistent error handling.

The getSecret function logs an error if the secret is not found but does not return a specific value. Consider returning undefined explicitly for consistency.

Apply this diff to make the return value explicit:

  if (secret === undefined) {
    console.error(`The requested secret with key '${key}' does not exist.`);
-   return;
+   return undefined;
  }
Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 13c257f and a0de734.

Files selected for processing (5)
  • package.json (1 hunks)
  • src/commands/secrets/cmds.ts (1 hunks)
  • src/commands/secrets/registry.ts (1 hunks)
  • src/common/vscodeapi.ts (2 hunks)
  • src/services/ZenExtension.ts (2 hunks)
Additional context used
Path-based instructions (4)
src/commands/secrets/cmds.ts (1)

Pattern **/*.ts: Review the Typescript code for conformity with industry standards and best practices, highlighting any deviations.

src/commands/secrets/registry.ts (1)

Pattern **/*.ts: Review the Typescript code for conformity with industry standards and best practices, highlighting any deviations.

src/common/vscodeapi.ts (1)

Pattern **/*.ts: Review the Typescript code for conformity with industry standards and best practices, highlighting any deviations.

src/services/ZenExtension.ts (1)

Pattern **/*.ts: Review the Typescript code for conformity with industry standards and best practices, highlighting any deviations.

Additional comments not posted (2)
src/services/ZenExtension.ts (1)

20-20: Verify the definition and usage of registerSecretsCommands.

Ensure that the registerSecretsCommands function is correctly defined and utilized within the extension's context.

Run the following script to verify the function's definition and usage:

Also applies to: 77-77

Verification successful

Verification Successful: registerSecretsCommands is correctly defined and used.

The registerSecretsCommands function is defined as an arrow function and exported from src/commands/secrets/registry.ts. It is correctly integrated within the extension's context. No issues found with its definition or usage.

  • File: src/commands/secrets/registry.ts
  • Lines: 27-46
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the definition and usage of `registerSecretsCommands`.

# Test: Search for the function definition. Expect: Correct definition and usage.
ast-grep --lang typescript --pattern 'function registerSecretsCommands($_) { $$$ }'

Length of output: 85


Script:

#!/bin/bash
# Description: Search for alternative patterns for `registerSecretsCommands`.

# Search for `registerSecretsCommands` as an arrow function.
ast-grep --lang typescript --pattern 'const registerSecretsCommands = ($_) => { $$$ }'

# Search for `registerSecretsCommands` as a method within a class.
ast-grep --lang typescript --pattern 'class $_ { $$$ registerSecretsCommands($_) { $$$ } $$$ }'

# Search for `registerSecretsCommands` as a named export.
ast-grep --lang typescript --pattern 'export function registerSecretsCommands($_) { $$$ }'

Length of output: 1649

package.json (1)

302-305: Verify the registration and usage of zenml.registerOpenAIAPIKey.

Ensure that the command is correctly registered and utilized within the extension.

Run the following script to verify the command's registration and usage:

Verification successful

The command zenml.registerOpenAIAPIKey is correctly registered and utilized.

The command is registered in src/commands/secrets/registry.ts and is associated with an asynchronous function call, confirming its proper implementation and usage. No further action is required.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the registration and usage of `zenml.registerOpenAIAPIKey`.

# Test: Search for the command registration. Expect: Correct registration and usage.
rg --type json 'zenml.registerOpenAIAPIKey'

Length of output: 105


Script:

#!/bin/bash
# Description: Search for the implementation and usage of `zenml.registerOpenAIAPIKey` in JavaScript or TypeScript files.

# Test: Search for the command implementation and usage. Expect: Correct implementation and usage.
rg 'zenml.registerOpenAIAPIKey' --type js --type ts -A 5

Length of output: 421

Comment on lines 19 to 40
const registerOpenAIAPIKey = async (context: ExtensionContext) => {
let apiKey = await context.secrets.get('OPENAI_API_KEY');

if (apiKey) {
apiKey = await vscode.window.showInputBox({
prompt: 'OpenAI API Key already exists, enter a new value to update.',
password: true,
});
} else {
apiKey = await vscode.window.showInputBox({
prompt: 'Please enter your OpenAI API key',
password: true,
});
}

if (apiKey === undefined) {
return undefined;
}

await context.secrets.store('OPENAI_API_KEY', apiKey);
vscode.window.showInformationMessage('OpenAI API key stored successfully.');
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper error handling for user input.

Currently, if showInputBox returns undefined, the function returns without storing the API key. Consider handling this case explicitly by showing a message to the user.

Apply this diff to improve user feedback:

  if (apiKey === undefined) {
-   return undefined;
+   vscode.window.showWarningMessage('API key input was canceled.');
+   return;
  }
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
const registerOpenAIAPIKey = async (context: ExtensionContext) => {
let apiKey = await context.secrets.get('OPENAI_API_KEY');
if (apiKey) {
apiKey = await vscode.window.showInputBox({
prompt: 'OpenAI API Key already exists, enter a new value to update.',
password: true,
});
} else {
apiKey = await vscode.window.showInputBox({
prompt: 'Please enter your OpenAI API key',
password: true,
});
}
if (apiKey === undefined) {
return undefined;
}
await context.secrets.store('OPENAI_API_KEY', apiKey);
vscode.window.showInformationMessage('OpenAI API key stored successfully.');
};
const registerOpenAIAPIKey = async (context: ExtensionContext) => {
let apiKey = await context.secrets.get('OPENAI_API_KEY');
if (apiKey) {
apiKey = await vscode.window.showInputBox({
prompt: 'OpenAI API Key already exists, enter a new value to update.',
password: true,
});
} else {
apiKey = await vscode.window.showInputBox({
prompt: 'Please enter your OpenAI API key',
password: true,
});
}
if (apiKey === undefined) {
vscode.window.showWarningMessage('API key input was canceled.');
return;
}
await context.secrets.store('OPENAI_API_KEY', apiKey);
vscode.window.showInformationMessage('OpenAI API key stored successfully.');
};

Copy link
Collaborator

@strickvl strickvl left a comment

Choose a reason for hiding this comment

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

See my comments on slack. This seems good for OpenAI, but we should offer at least the main three providers.

package.json Outdated Show resolved Hide resolved
src/commands/secrets/cmds.ts Outdated Show resolved Hide resolved
src/commands/secrets/cmds.ts Outdated Show resolved Hide resolved
@strickvl strickvl added the enhancement New feature or request label Aug 23, 2024
@sklarfox
Copy link
Author

@strickvl Thanks for the review! I've generalized the function to now also support Anthropic and Gemini on top of OpenAI.

@sklarfox
Copy link
Author

I've made one additional change to the code; I have changed the naming convention for the secrets to prevent collision issues with other extensions. The previous names were {provider}_API_KEY, but this seemed a little generic and could collide with other secrets the the vscode store. The new naming scheme is zenml.{provider}.key, which is similar to other extensions' implementations.

@strickvl
Copy link
Collaborator

strickvl commented Sep 2, 2024

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Sep 2, 2024

Actions performed

Review triggered.

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Outside diff range, codebase verification and nitpick comments (2)
src/commands/secrets/registry.ts (1)

24-43: LGTM with suggestions!

The registerSecretsCommands function is correctly implemented and follows the best practices for registering commands in a VSCode extension. However, consider the following suggestions to improve the function:

  1. Add more error handling and logging to help with debugging and troubleshooting.
  2. Consider using a more descriptive name for the cmd variable in the forEach loop.
  3. Consider adding a comment to explain the purpose of the setContext command.
src/common/vscodeapi.ts (1)

74-83: LGTM with a suggestion!

The getSecret function is well-structured and follows TypeScript best practices. It handles the case when the secret is not found by logging an error and returning undefined.

To improve the code quality and maintainability, consider adding JSDoc comments to document the parameters and return value of the function. Here's an example:

/**
 * Retrieves a secret from the extension context.
 * @param context The extension context.
 * @param key The key of the secret to retrieve.
 * @returns The secret value if found, otherwise `undefined`.
 */
export async function getSecret(context: ExtensionContext, key: string) {
  // ...
}
Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a0de734 and 8f0a4fe.

Files selected for processing (4)
  • package.json (1 hunks)
  • src/commands/secrets/cmds.ts (1 hunks)
  • src/commands/secrets/registry.ts (1 hunks)
  • src/common/vscodeapi.ts (2 hunks)
Additional context used
Path-based instructions (3)
src/commands/secrets/registry.ts (1)

Pattern **/*.ts: Review the Typescript code for conformity with industry standards and best practices, highlighting any deviations.

src/commands/secrets/cmds.ts (1)

Pattern **/*.ts: Review the Typescript code for conformity with industry standards and best practices, highlighting any deviations.

src/common/vscodeapi.ts (1)

Pattern **/*.ts: Review the Typescript code for conformity with industry standards and best practices, highlighting any deviations.

Additional comments not posted (5)
src/commands/secrets/registry.ts (2)

1-12: LGTM!

The copyright and license header is correctly formatted and contains the necessary information.


14-17: LGTM!

The imports are correctly formatted and follow the naming conventions.

src/commands/secrets/cmds.ts (1)

17-58: LGTM!

The registerLLMAPIKey function is well-implemented and follows best practices. It handles different scenarios appropriately, such as:

  • Allowing users to select an LLM provider using VSCode's QuickPick.
  • Handling the case when the user cancels the selection by showing a warning message.
  • Constructing a secret key based on the selected provider.
  • Checking if an API key already exists for the selected provider and prompting the user to update it if it exists.
  • Prompting the user to enter a new API key if one doesn't exist.
  • Handling the case when the user cancels the API key input by showing a warning message.
  • Storing the API key using VSCode's secrets storage and showing a success message.

The function is modular, follows a clear naming convention for variables and the secret key, and handles errors appropriately.

src/common/vscodeapi.ts (1)

21-21: LGTM!

The import statement for ExtensionContext is necessary and approved.

package.json (1)

300-305: LGTM!

The code changes are approved. The command name and title have been generalized as per the previous comment.

@strickvl strickvl merged commit ba17414 into zenml-io:ls-genai-cohort Sep 2, 2024
3 checks passed
@sklarfox sklarfox deleted the feature/openai-api-key branch September 17, 2024 15:08
wyennie pushed a commit to wyennie/vscode-zenml that referenced this pull request Sep 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants