Skip to content

Commit

Permalink
Move our Chrome AI JS code into a JS file instead of rendering that i…
Browse files Browse the repository at this point in the history
…n PHP
  • Loading branch information
dkotter committed Oct 16, 2024
1 parent 6e579c9 commit 9b97859
Show file tree
Hide file tree
Showing 5 changed files with 80 additions and 73 deletions.
55 changes: 3 additions & 52 deletions includes/Classifai/Providers/Browser/ChromeAI.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use WP_Error;

use function Classifai\get_default_prompt;
use function Classifai\sanitize_number_of_responses_field;

class ChromeAI extends Provider {

Expand All @@ -33,14 +32,6 @@ public function __construct( $feature_instance = null ) {
$this->feature_instance = $feature_instance;
}

/**
* Register what we need for the plugin.
*/
public function register() {
// TODO: find a better hook for this.
add_action( 'wp_print_scripts', [ $this, 'output_excerpt_script' ] );
}

/**
* Render the provider fields.
*/
Expand Down Expand Up @@ -71,46 +62,6 @@ public function sanitize_settings( array $new_settings ): array {
return $new_settings;
}

/**
* Output the excerpt script.
*
* This will make a request to the Chrome AI API to generate an excerpt.
*/
public function output_excerpt_script() {
// TODO: ensure this only loads on single admin content.
// TODO: support classic editor.
?>
<script type="text/javascript">
async function classifaiChromeAITextGeneration( prompt = '', content = '' ) {
let result = '';

if ( ! window.ai ) {
return result;
}

const supportsTextGeneration = await window.ai.languageModel.capabilities();

if (
supportsTextGeneration &&
supportsTextGeneration.available === 'readily'
) {
const session = await window.ai.languageModel.create( {
initialPrompts: [
{
role: 'system',
content: prompt,
},
]
} );
result = await session.prompt( `"""${content}"""` );
}

return result;
}
</script>
<?php
}

/**
* Common entry point for all REST endpoints for this provider.
*
Expand Down Expand Up @@ -209,7 +160,7 @@ public function generate_excerpt( int $post_id = 0, array $args = [] ) {
[
'prompt' => 'You will be provided with content delimited by triple quotes. ' . $prompt,
'content' => $this->get_content( $post_id, $excerpt_length, false, $args['content'] ),
'func' => 'classifaiChromeAITextGeneration',
'func' => static::ID,
],
$post_id
);
Expand Down Expand Up @@ -276,7 +227,7 @@ public function generate_title( int $post_id = 0, array $args = [] ) {
[
'prompt' => 'You will be provided with content delimited by triple quotes. ' . $prompt,
'content' => $this->get_content( $post_id, 0, false, $args['content'] ),
'func' => 'classifaiChromeAITextGeneration',
'func' => static::ID,
],
$post_id
);
Expand Down Expand Up @@ -335,7 +286,7 @@ public function resize_content( int $post_id, array $args = array() ) {
[
'prompt' => 'You will be provided with content delimited by triple quotes. ' . $prompt,
'content' => esc_html( $args['content'] ),
'func' => 'classifaiChromeAITextGeneration',
'func' => static::ID,
],
$post_id
);
Expand Down
19 changes: 12 additions & 7 deletions src/js/features/content-resizing/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
/* eslint-disable @wordpress/no-unsafe-wp-apis */
/* eslint-disable no-shadow */
/**
* External Dependencies.
*/
import { registerPlugin } from '@wordpress/plugins';
import {
store as blockEditorStore,
Expand All @@ -23,7 +26,11 @@ import {
} from '@wordpress/wordcount';
import { __, _nx } from '@wordpress/i18n';

/**
* Internal Dependencies.
*/
import { DisableFeatureButton } from '../../components';
import { browserAITextGeneration } from '../../helpers';
import './index.scss';

const aiIconSvg = (
Expand Down Expand Up @@ -256,13 +263,11 @@ const ContentResizingPlugin = () => {
typeof __textArray === 'object' &&
__textArray.hasOwnProperty( 'func' )
) {
const res =
'undefined' !== typeof window[ __textArray.func ]
? await window[ __textArray.func ](
__textArray?.prompt,
__textArray?.content
)
: '';
const res = await browserAITextGeneration(
__textArray.func,
__textArray?.prompt,
__textArray?.content
);
__textArray = [ res.trim() ];
}
} else {
Expand Down
13 changes: 6 additions & 7 deletions src/js/features/excerpt-generation/panel.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import apiFetch from '@wordpress/api-fetch';
* Internal Dependencies.
*/
import { DisableFeatureButton } from '../../components';
import { browserAITextGeneration } from '../../helpers';

/**
* PostExcerpt component.
Expand Down Expand Up @@ -51,13 +52,11 @@ function PostExcerpt( { excerpt, onUpdateExcerpt } ) {
// Support calling a function from the response for browser AI.
if ( typeof res === 'object' ) {
if ( res.hasOwnProperty( 'func' ) ) {
res =
'undefined' !== typeof window[ res.func ]
? await window[ res.func ](
res?.prompt,
res?.content
)
: '';
res = await browserAITextGeneration(
res.func,
res?.prompt,
res?.content
);
} else {
res = '';
}
Expand Down
13 changes: 6 additions & 7 deletions src/js/features/title-generation/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import apiFetch from '@wordpress/api-fetch';
* Internal Dependencies.
*/
import { DisableFeatureButton } from '../../components';
import { browserAITextGeneration } from '../../helpers';

const { classifaiChatGPTData } = window;

Expand Down Expand Up @@ -69,13 +70,11 @@ const TitleGenerationPlugin = () => {
// Support calling a function from the response for browser AI.
if ( typeof res === 'object' ) {
if ( res.hasOwnProperty( 'func' ) ) {
res =
'undefined' !== typeof window[ res.func ]
? await window[ res.func ](
res?.prompt,
res?.content
)
: '';
res = await browserAITextGeneration(
res.func,
res?.prompt,
res?.content
);
res = [ res.trim() ];
} else {
res = [];
Expand Down
53 changes: 53 additions & 0 deletions src/js/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,56 @@ export const handleClick = ( {
}
);
};

/**
* Make a request to a browser AI to generate text.
*
* @param {string} provider Provider to use.
* @param {string} prompt Prompt to send to the API.
* @param {string} content Content to add in addition to the prompt.
*/
export const browserAITextGeneration = async (
provider = '',
prompt = '',
content = ''
) => {
switch ( provider ) {
case 'chrome_ai':
return chromeAITextGeneration( prompt, content );
default:
return '';
}
};

/**
* Make a request to the Chrome AI API to generate text.
*
* @param {string} prompt Prompt to send to the API.
* @param {string} content Content to add in addition to the prompt.
*/
export const chromeAITextGeneration = async ( prompt = '', content = '' ) => {
let result = '';

if ( ! window.ai ) {
return result;
}

const supportsTextGeneration = await window.ai.languageModel.capabilities();

if (
supportsTextGeneration &&
supportsTextGeneration.available === 'readily'
) {
const session = await window.ai.languageModel.create( {
initialPrompts: [
{
role: 'system',
content: prompt,
},
],
} );
result = await session.prompt( `"""${ content }"""` );
}

return result;
};

0 comments on commit 9b97859

Please sign in to comment.