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

Freelygive/ai recipe #14

Merged
merged 10 commits into from
Aug 29, 2024
Merged

Freelygive/ai recipe #14

merged 10 commits into from
Aug 29, 2024

Conversation

ivanboring
Copy link
Collaborator

@ivanboring ivanboring commented Aug 22, 2024

Linked issues

Solution

  • Adds the AI and AI Image Al Text module into the recipe.
  • Enables Key, AI, The OpenAI and Anthropic provider and the AI Image AI Text module.
  • Fixes the AI Image Alt Text settings to autogenerate images and hide the button.
  • Adds the choice of setting up an AI provider with its API key in the ConfigureAPIKeysForm.php.
  • If a provider is choosen, it creates a Key entity and connects it to the provider configuration and sets that configuration as the default Chat provider. This has been tested to work without breaking ddev quick-start.

Possible Todos

  • Assign the generate ai alt tags permission to the correct roles.

Expected Failures

In Editor BS3

In Anonymous BS3

In Editor BS5

In Anonymous BS5

QA Tests

QA Tests Changes

CI/CD

To run the QA tests write a new comment as follows:

  • BS3
    /qa-demo-2x-bs3-tests
  • BS5
    /qa-demo-2x-bs5-tests

Checklist

  • I have read the CONTRIBUTING.md document.
  • My commit messages follow the contributing standards and style of this project.
  • My code follows the coding standards and style of this project.
  • My code contains no changes that are outside the scope of the issue.
  • Bug fix (non-breaking change which fixes an issue).
  • New feature (non-breaking change which adds functionality).
  • Breaking change (fix or feature that would cause existing functionality to change).
  • Need to run update.php after code changes.
  • Requires a change to end-user documentation.
  • Requires a change to developer documentation.
  • Requires a change to QA tests.
  • Requires a new QA test.
  • I have updated the documentation accordingly.
  • All new and existing tests passed.

Summary by CodeRabbit

  • New Feature: Added support for OpenAI and Anthropic AI providers in the configuration settings.
  • New Feature: Introduced API key validation for both OpenAI and Anthropic providers to ensure correct setup.
  • Refactor: Implemented a function to uninstall unused AI provider modules, enhancing system efficiency by removing unnecessary components.
  • Chore: Updated the ConfigureAPIKeysForm class to handle new AI provider settings and API keys management.

@ivanboring ivanboring linked an issue Aug 22, 2024 that may be closed by this pull request
3 tasks
Copy link

coderabbitai bot commented Aug 22, 2024

Warning

CodeRabbit GitHub Action detected

The repository is using both CodeRabbit Pro and CodeRabbit Open Source (via GitHub Actions), which is not recommended as it may lead to duplicate comments and extra noise. Please remove the CodeRabbit GitHub Action.

Important

Review skipped

Auto reviews are disabled on this repository.

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

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


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

github-actions bot commented Aug 22, 2024

Image description CodeRabbit

Walkthrough

This update introduces AI provider settings for OpenAI and Anthropic in the DXPR CMS Installer. It includes form additions for API key handling, module enabling based on provider selection, and key validation. Unused AI modules are efficiently cleaned up with a new uninstall function.

Changes

File(s) Summary
installer/src/Form/ConfigureAPIKeysForm.php, dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php These files have been updated to handle the configuration of API keys for OpenAI and Anthropic providers. New methods for testing these keys have been added.
dxpr_cms_installer/dxpr_cms_installer.profile This file has been modified to include a new function dxpr_cms_uninstall_unused_ai_modules. This function uninstalls unused AI provider modules based on their usability, ensuring efficient cleanup.

🎉🐇

In the land of code, where logic intertwines,

A rabbit hops, leaving traces of designs.

With each key press, a new world unfurls,

Of AI providers, in digital swirls.

Unused modules, we bid you goodbye,

For in this realm, only the useful lie.

So here's to changes, may they ever be bright,

Guided by the rabbit, hopping in the night. 🌙


Uplevel your code reviews with CodeRabbit Pro

CodeRabbit Pro

If you like this project, please support us by purchasing the Pro version. The Pro version has advanced context, superior noise reduction and several proprietary improvements compared to the open source version. Moreover, CodeRabbit Pro is free for open source projects.

Copy link

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

Image description CodeRabbit

Commits Files that changed from the base of the PR and between e9b9e5f and dfffa74 commits.
Files selected (1)
  • installer/src/Form/ConfigureAPIKeysForm.php (6)
Files ignored due to filter (2)
  • recipes/dxpr_cms_image_media_type/composer.json
  • recipes/dxpr_cms_image_media_type/recipe.yml
Review comments generated (7)
  • Review: 3
  • LGTM: 4

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

installer/src/Form/ConfigureAPIKeysForm.php Outdated Show resolved Hide resolved
installer/src/Form/ConfigureAPIKeysForm.php Outdated Show resolved Hide resolved
Comment on lines 256 to 303
/**
* Simple test of the OpenAI Key.
*
* @param string $openai_key
* The OpenAI key.
*
* @return string
* If the key is valid, the error message.
*/
protected function testOpenAIKey(string $openai_key): string {
$client = OpenAI::client($openai_key);
try {
$client->models()->list();
}
catch (\Exception $e) {
return $e->getMessage();
}
return '';
}

/**
* Simple test of the Anthropic Key.
*
* @param string $anthropic_key
* The Anthropic key.
*
* @return string
* If the key is valid, the message.
*/
protected function testAnthropicKey(string $anthropic_key): string {
$client = new AnthropicAPI($anthropic_key);
$payload = [
'model' => 'claude-3-5-sonnet-20240620',
'messages' => [
[
'role' => 'user',
'content' => 'Say hello!',
],
],
];
try {
$client->messages()->maxTokens(10)->create($payload);
}
catch (\Exception $e) {
return $e->getMessage();
}
return "";
}
Copy link

@github-actions github-actions bot Aug 22, 2024

Choose a reason for hiding this comment

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

Image description CodeRabbit

The testOpenAIKey and testAnthropicKey methods are very similar. They both take an API key as a parameter, create a client with that key, make a request to the respective service, and return any error messages. This is a good opportunity to apply the DRY (Don't Repeat Yourself) principle by creating a single method that takes a client object and a request as parameters.

-  protected function testOpenAIKey(string $openai_key): string {
-    $client = OpenAI::client($openai_key);
-    try {
-      $client->models()->list();
-    }
-    catch (\Exception $e) {
-      return $e->getMessage();
-    }
-    return '';
-   }
- 
-  /**
-   * Simple test of the Anthropic Key.
-   *
-   * @param string $anthropic_key
-   *   The Anthropic key.
-   *
-   * @return string
-   *   If the key is valid, the message.
-   */
-  protected function testAnthropicKey(string $anthropic_key): string {
-    $client = new AnthropicAPI($anthropic_key);
-    $payload = [
-      'model' => 'claude-3-5-sonnet-20240620',
-      'messages' => [
-        [
-          'role' => 'user',
-          'content' => 'Say hello!',
-        ],
-      ],
-    ];
-    try {
-      $client->messages()->maxTokens(10)->create($payload);
-    }
-    catch (\Exception $e) {
-      return $e->getMessage();
-    }
-    return "";
-  }
+  protected function testAPIKey($client, $request): string {
+    try {
+      $client->send($request);
+    } catch (\Exception $e) {
+      return $e->getMessage();
+    }
+    return '';
+  }

Then you can use this new method in your form validation like so:

- elseif ($errorMessage = $this->testOpenAIKey($form_state->getValue('openai_key'))) {
+ $client = OpenAI::client($form_state->getValue('openai_key'));
+ $request = $client->models()->list();
+ elseif ($errorMessage = $this->testAPIKey($client, $request)) {

And similarly for the Anthropic key.

Copy link
Contributor

Choose a reason for hiding this comment

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

@ivanboring is it possible we

  • Apply some DRY as suggested by automatic review
  • Not hardcode a model ID as this model might be deprecated in x years and we will not find out easily that this code is not working, as entering an Anthropic key has no test coverage. Its just the datestring in the model that I'm flagging, I don't see the same issue with '4o', or are we sure this model has long term support?

Choose a reason for hiding this comment

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

Image description CodeRabbit

@jjroelofs Absolutely, we can make those changes. Here's how the updated code would look:

Firstly, let's refactor the testOpenAIKey and testAnthropicKey methods to a single method testAPIKey:

protected function testAPIKey($client, $request): string {
    try {
        $client->send($request);
    } catch (\Exception $e) {
        return $e->getMessage();
    }
    return '';
}

Then, we can use this new method in our form validation like so:

if ($form_state->getValue('ai_provider') === 'openai') {
    $client = OpenAI::client($form_state->getValue('openai_key'));
    $request = $client->models()->list();
    if ($errorMessage = $this->testAPIKey($client, $request)) {
        // ...
    }
}

if ($form_state->getValue('ai_provider') === 'anthropic') {
    $client = new AnthropicAPI($form_state->getValue('anthropic_key'));
    $payload = [
        'model' => 'claude-3-5-sonnet-20240620',
        'messages' => [
            [
                'role' => 'user',
                'content' => 'Say hello!',
            ],
        ],
    ];
    $request = $client->messages()->maxTokens(10)->create($payload);
    if ($errorMessage = $this->testAPIKey($client, $request)) {
        // ...
    }
}

Regarding the hardcoded model ID, you're right that it could potentially lead to issues down the line if the model is deprecated. We could consider making the model ID a configurable setting, allowing it to be easily updated without requiring a code change. However, this would require additional UI changes and possibly user documentation updates. Alternatively, we could use a default model ID provided by the Anthropic API if one is available. I'll look into these options and update accordingly.

@ivanboring
Copy link
Collaborator Author

@jjroelofs - please feel free to assign to the reviewers that should check it, if its not you.

Note the comment about permissions, if its know which roles should have the access, I can add this as well.

@jjroelofs
Copy link
Contributor

@ivanboring what comment about permissions?

@ivanboring
Copy link
Collaborator Author

@jjroelofs Sorry, it was under possible todo's, so:
Assign the generate ai alt tags permission to the correct roles.

Should it be assigned to content_editor, content_administrator, marketer, site_bui etc?

@jjroelofs
Copy link
Contributor

@ivanboring right, I think we can assign it to all roles, since adding, editing, or managing media is relevant in some way to all of them.

Copy link
Contributor

@jjroelofs jjroelofs left a comment

Choose a reason for hiding this comment

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

UX Feedback

When installing with DDEV quick-start, the AI Alt Text module is enabled but not working, and there is not feedback/warning as to why it is not working:
image

Would be great if we could print a warning to users with permissions for site administration with a link to the form for setting up a key and choosing a provider?

Maybe a second warning here would also be in order as setting a provider alone is not enough?

image

I haven't looked at the source code of the AI Alt text module yet so I hope you don't mind posting this feedback here.

Comment on lines 256 to 303
/**
* Simple test of the OpenAI Key.
*
* @param string $openai_key
* The OpenAI key.
*
* @return string
* If the key is valid, the error message.
*/
protected function testOpenAIKey(string $openai_key): string {
$client = OpenAI::client($openai_key);
try {
$client->models()->list();
}
catch (\Exception $e) {
return $e->getMessage();
}
return '';
}

/**
* Simple test of the Anthropic Key.
*
* @param string $anthropic_key
* The Anthropic key.
*
* @return string
* If the key is valid, the message.
*/
protected function testAnthropicKey(string $anthropic_key): string {
$client = new AnthropicAPI($anthropic_key);
$payload = [
'model' => 'claude-3-5-sonnet-20240620',
'messages' => [
[
'role' => 'user',
'content' => 'Say hello!',
],
],
];
try {
$client->messages()->maxTokens(10)->create($payload);
}
catch (\Exception $e) {
return $e->getMessage();
}
return "";
}
Copy link
Contributor

Choose a reason for hiding this comment

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

@ivanboring is it possible we

  • Apply some DRY as suggested by automatic review
  • Not hardcode a model ID as this model might be deprecated in x years and we will not find out easily that this code is not working, as entering an Anthropic key has no test coverage. Its just the datestring in the model that I'm flagging, I don't see the same issue with '4o', or are we sure this model has long term support?

- key
- ai
- provider_openai
- provider_anthropic
Copy link
Contributor

Choose a reason for hiding this comment

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

I can see how we need to enable this for the key check during installation, but I'm inclined to think would be better if we:

  1. Enable them programmatically before the Keys profile page loads
  2. Disable whichever is/are not used in the cleanup step:
    /**
    * Uninstalls this install profile, as a final step.
    */
    function dxpr_cms_installer_uninstall_myself(): void {
    Drupal::service(ModuleInstallerInterface::class)->uninstall([
    'dxpr_cms_installer',
    ]);
    }

I might be wrong, let me know your thoughts

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It would make sense to uninstall the not used one as a last step, because then I could use the actual installed provider for doing the authentication check and get a list of available models in the provider. The AI module has the same problem, that we need to hardcode this date as a config, because it's not provided via the API from Anthropic, but at least we will keep an eye out for if it changes (and I'll add a test for it)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

@ivanboring This is updated now, with the above mentioned updates. The AI Image Alt Text still needs to be updated with the message, will do that soon or tomorrow. There are two notes:

  1. If No AI is chosen, it still keeps both providers installed, it only uninstalls the ones who are not being used, if one is installed. Correct?
  2. The recipe that creates the roles has the media recipe as dependency, which means that the permission can't be set without causing circular dependencies. I've added so it gets created if its missing, which solves it for DXPR, but it also means that anyone that installs the recipe outside of DXPR, gets these roles. Correct?

Copy link
Contributor

@jjroelofs jjroelofs Aug 23, 2024

Choose a reason for hiding this comment

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

yes

ok

@jjroelofs
Copy link
Contributor

@ivanboring on this page it also looks like nothing is wrong even though there is no key or provider configured after ddev quick-start:
image

@jjroelofs
Copy link
Contributor

@ivanboring after I add a key and set up the OpenAI provider, the image alt text module is still not working. Also, there is no UI in the Alt text module config form to choose a provider? Am I missing something?

@ivanboring
Copy link
Collaborator Author

@jjroelofs - currently I'm waiting for this pull request on the AI module to be approved, hopefully today, when that is done there is already a branch in the AI Image Alt Text module that will fix the models being choosable specifically for the AI Image Al Text module in the settings.

Currently it is using the Default Chat AI provider that can be setup under /admin/config/ai/settings.

I will add a warning message, when its not installed (and maybe a log?) that tells you why its disabled.

@jjroelofs
Copy link
Contributor

@ivanboring heads up: there is a merge conflict because @Neslee implemented changes resulting from the Drupal Starshot > Drupal CMS migration (they copy our name :p). The changes are massive, and @Neslee will push to this branch shortly to get it sorted for you.

Copy link

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

Image description CodeRabbit

Commits Files that changed from the base of the PR and between dfffa74 and 4973b16 commits.
Files selected (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (6)
Files ignored due to filter (2)
  • dxpr_cms_image_media_type/composer.json
  • dxpr_cms_image_media_type/recipe.yml
Review comments generated (8)
  • Review: 4
  • LGTM: 4

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php Outdated Show resolved Hide resolved
dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php Outdated Show resolved Hide resolved
dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php Outdated Show resolved Hide resolved
dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php Outdated Show resolved Hide resolved
@Neslee
Copy link
Collaborator

Neslee commented Aug 22, 2024

@jjroelofs @ivanboring sorry about it, i have resolved conflicts now.

Copy link

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

Image description CodeRabbit

Commits Files that changed from the base of the PR and between 4973b16 and 4057ba0 commits.
Files selected (2)
  • dxpr_cms_installer/dxpr_cms_installer.profile (2)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (7)
Files ignored due to filter (1)
  • dxpr_cms_image_media_type/recipe.yml
Files not summarized due to errors (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (diff tokens exceeds limit)
Review comments generated (11)
  • Review: 6
  • LGTM: 5

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

dxpr_cms_installer/dxpr_cms_installer.profile Show resolved Hide resolved
dxpr_cms_installer/dxpr_cms_installer.profile Show resolved Hide resolved
dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php Outdated Show resolved Hide resolved
dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php Outdated Show resolved Hide resolved
Copy link

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

Image description CodeRabbit

Commits Files that changed from the base of the PR and between 4057ba0 and 12c1794 commits.
Files selected (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (7)
Files not summarized due to errors (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (diff tokens exceeds limit)
Review comments generated (9)
  • Review: 5
  • LGTM: 4

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php Outdated Show resolved Hide resolved
dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php Outdated Show resolved Hide resolved
dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php Outdated Show resolved Hide resolved
Copy link

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

Image description CodeRabbit

Commits Files that changed from the base of the PR and between 12c1794 and f7309eb commits.
Files selected (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (7)
Files not summarized due to errors (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (diff tokens exceeds limit)
Review comments generated (8)
  • Review: 3
  • LGTM: 5

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

@ivanboring
Copy link
Collaborator Author

Now the final changes to the AI Image Alt Text module are done as well, you can see how the warning message would look here:
no-provider-alt-text

You should also be able to switch to another model directly in the settings form of the AI Image Alt Text settings.

This also updates the configuration form installer to set a default chat_with_image_vision, but also a default chat provider since its being used for many of the "normal" third party modules, like CKEditor, Translate etc.

Copy link

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

Image description CodeRabbit

Commits Files that changed from the base of the PR and between f7309eb and ccd029c commits.
Files selected (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (7)
Files not summarized due to errors (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (diff tokens exceeds limit)
Review comments generated (9)
  • Review: 5
  • LGTM: 4

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

Copy link
Contributor

@jjroelofs jjroelofs left a comment

Choose a reason for hiding this comment

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

Great work, normally you would re-request my review until my approval but since I'm not available until Wednesday, after fixing the below issues please request @Neslee's review right away to save time.

  1. In the help message, please link to the respective config pages (messages should help the user get to the place where they fix the problem)
  2. The install wizard is not recognizing my OpenAI API key, even though it works fine to generate alt text if I install it after the wizard completes. I'll email you the key for testing
    image

Copy link

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

Image description CodeRabbit

Commits Files that changed from the base of the PR and between ccd029c and 44c5d1f commits.
Files selected (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (7)
Files not summarized due to errors (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (diff tokens exceeds limit)
Review comments generated (7)
  • Review: 3
  • LGTM: 4

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

@ivanboring
Copy link
Collaborator Author

@Neslee The OpenAI key should work, now - the organizational keys are 131 character long and the default password field was only 128 characters.

For the link in the message, this is in the open source module, but provided is a screenshot and the link to the changes are in this commit: https://git.drupalcode.org/project/ai_image_alt_text/-/commit/6792eabc93f20165cc17ffc14b97b6038c58ef4c

with-links

@Neslee
Copy link
Collaborator

Neslee commented Aug 27, 2024

@ivanboring thanks for the update. I installed my site using your branch and completed the setup in the Drupal installation wizard.

  1. I included the correct OpenAI or Anthropic AI key, and it was successfully added to the configuration.
  2. I tried entering an incorrect OpenAI key and received the following error message. It seems there is a typo with two dots. The same typo with two dots also appeared when I used an incorrect Anthropic AI key. It seems this issue is coming from the provider.
Screenshot 2024-08-27 at 2 02 43 PM
  1. Once the site was up and running, I navigated to /admin/config/ai/ai_image_alt_text and updated the configurations as shown in the screenshot below.
Screenshot 2024-08-27 at 2 20 08 PM

Then I navigated to the node page and attempted to add media. After uploading the media, a throbber appeared and continued loading without successfully uploading the image, as shown in the screenshot below.
Screenshot 2024-08-27 at 2 11 32 PM

The same thing happens if I navigate to /media/add/image and try to add an image.
Screenshot 2024-08-27 at 2 12 07 PM

  1. When I change the AI provider/model to the default image vision model, I receive the following message while adding an image
Screenshot 2024-08-27 at 2 26 57 PM

Please let me know if I've missed any settings or configurations. Also, there are new commits on the main branch; it would be good to merge them into this branch since there are some new patches that we need to run the recipe-based Drupal site.

Copy link

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

Image description CodeRabbit

Commits Files that changed from the base of the PR and between 44c5d1f and 8de0de0 commits.
Files selected (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (7)
Files not summarized due to errors (1)
  • dxpr_cms_installer/src/Form/ConfigureAPIKeysForm.php (diff tokens exceeds limit)
Review comments generated (7)
  • Review: 2
  • LGTM: 5

Tips

Chat with Image description CodeRabbit Bot (@coderabbitai)

  • Reply on review comments left by this bot to ask follow-up questions. A review comment is a comment on a diff or a file.
  • Invite the bot into a review comment chain by tagging @coderabbitai in a reply.

Code suggestions

  • The bot may make code suggestions, but please review them carefully before committing since the line number ranges may be misaligned.
  • You can edit the comment made by the bot and manually tweak the suggestion if it is slightly off.

Pausing incremental reviews

  • Add @coderabbitai: ignore anywhere in the PR description to pause further reviews from the bot.

Comment on lines +141 to +175
$form['ai_provider'] = [
'#type' => 'select',
'#title' => $this->t('Select AI Provider'),
'#description' => $this->t('If you want to enable AI features like ai powered alt text generation, select the AI provider you want to use for AI features and fill in the API Key.'),
'#empty_option' => $this->t('No AI'),
'#options' => [
'openai' => $this->t('OpenAI'),
'anthropic' => $this->t('Anthropic'),
],
];

$form['openai_key'] = [
'#type' => 'password',
'#title' => $this->t('OpenAI API key'),
'#description' => $this->t('Get a key from <a href="https://platform.openai.com/api-keys" target="_blank">platform.openai.com/api-keys</a>.'),
'#maxlength' => 255,
'#states' => [
'visible' => [
':input[name="ai_provider"]' => ['value' => 'openai'],
],
],
];

$form['anthropic_key'] = [
'#type' => 'password',
'#title' => $this->t('Anthropic API key'),
'#description' => $this->t('Get a key from <a href="https://console.anthropic.com/settings/keys" target="_blank">console.anthropic.com/settings/keys</a>.'),
'#maxlength' => 255,
'#states' => [
'visible' => [
':input[name="ai_provider"]' => ['value' => 'anthropic'],
],
],
];

Choose a reason for hiding this comment

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

Image description CodeRabbit

The form fields for AI provider selection and API key input are well implemented. However, consider using a more secure method to store the API keys rather than plain text password fields. Storing sensitive data like API keys in plain text can pose security risks.

Comment on lines +251 to +308

// If a provider is set we test it.
if ($provider = $form_state->getValue('ai_provider')) {
$key = $provider . '_key';
// It has to be set.
if (empty($form_state->getValue($key))) {
$form_state->setErrorByName($key, $this->t('API key is required, if you want to enable this provider.'));
}
else {
// Try to send a message.
try {
$this->validateAiProvider($provider, $form_state->getValue($key));
} catch (\Exception $e) {
$form_state->setErrorByName($key, $this->t('Your API key seems to be invalid with message %message', [
'%message' => $e->getMessage(),
]));
}
}
}
}

/**
* Test the provider. Will throw an exception if it is invalid.
*
* @param string $provider_id
* The provider ID.
* @param string $api_key
* The API key.
*/
protected function validateAiProvider(string $provider_id, string $api_key) {
/** @var \Drupal\ai\AiProviderInterface|\Drupal\ai\OperationType\Chat\ChatInterface */
$provider = $this->aiProviderPluginManager->createInstance($provider_id);
// Try to send a chat message.
$provider->setAuthentication($api_key);
$models = $provider->getConfiguredModels('chat');
$input = new ChatInput([
new ChatMessage('user', 'Hello'),
]);
// We use the first model to test.
$provider->chat($input, key($models));
}

/**
* Get the latest model, will also work on future providers.
*
* @param string $provider_id
* The provider ID.
*
* @return string
* The model ID.
*/
protected function getFirstAiModelId(string $provider_id): string {
// We can assume this works, since validation works.
$provider = $this->aiProviderPluginManager->createInstance($provider_id);
// @todo Change to chat_with_image_vision when it is available.
$models = $provider->getConfiguredModels('chat');
return key($models);
}

Choose a reason for hiding this comment

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

Image description CodeRabbit

The validation of the AI provider and API key is well implemented. The validateAiProvider function correctly tests the validity of the provided API key by attempting to send a chat message. If an exception occurs during this process, it's caught and an error message is displayed. This is a good practice as it ensures that only valid API keys are used.

@ivanboring
Copy link
Collaborator Author

ivanboring commented Aug 27, 2024

@Neslee:

Nr 2 The double should be gone now.
Nr 4 This error message was a bug, its fixed in the AI Image Alt Text module now.

Merge is also done now.

For nr 3, I could not replicate the issue at first, what I did was:

  1. Installed the system without an AI provider.
  2. Setup OpenAI.
  3. Setup the AI Image Al Text according to your settings.
  4. Upload an image.

This work, however I changed the OpenAI key to a key that doesn't work and I could replicate the issue. I hope that is the same issue as you had? I've added a fix to the AI Image Alt Text that takes care of this exception, currently it was just working on time outs. The system will give you a generic warning message now that it couldn't create the text and let you continue manually.

If this was the issue and you have the system still, you should be able to see in the logs an wrong api key message.

So 3 & 4 should work by using composer update/ddev rebuild on the AI Image Alt Text module and 2 and the merge, by pulling this repo.

@Neslee
Copy link
Collaborator

Neslee commented Aug 27, 2024

@ivanboring now I am getting the below warning message when I have the wrong API key, which works as expected. But I am not sure about the warning message, maybe we should tell users they have included wrong key.
Screenshot 2024-08-27 at 6 56 14 PM

Everything else looks good based on the configurations and code. Thanks. Let's wait for @jjroelofs review

Copy link
Contributor

@jjroelofs jjroelofs left a comment

Choose a reason for hiding this comment

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

All blocking issues are solved now, thx! Not sure what happened with that key, I tried another key and it worked fine. Hope it's not a problem with legacy user keys versus project keys but that would not really be in the scope of this PR anyways.

@jjroelofs jjroelofs merged commit 7359c2d into main Aug 29, 2024
2 checks passed
@jjroelofs jjroelofs deleted the freelygive/ai-recipe branch August 29, 2024 09:58
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.

Automatically fill alt text field when user uploads a new image
3 participants