As I've been playing, and thinking, more and more about how to best add Chrome AI support to web apps, I came across an interesting use-case that I think could be helpful, and like in my previous examples, be completely ok if it didn't actually work. When I write on the developer blog at Foxit, I make use of WordPress plugin for code samples. This editor has a place for you to both paste in your code, and select the language so the proper highlighter is used:
This works well enough, but it gets a bit annoying to have to constantly keep selecting Python in the dropdown. Ideally the form would use the last language (simple enough via LocalStorage
), but I was curious how well Chrome's Prompt API could handle the task.
To be clear, this is not the same as the Language Detection API which is good for identifying spoken languages. What I wanted was something that could understand programming languages, or code.
I forked one my earlier examples and built a form with a textbox and a simple button to kick off the analyzation. So for example, I pasted in the JavaScript code for the actual Code Pen and analyzed that:
(As a quick aside, after I took this screenshot I was curious if I could disable the spellcheck in the textarea
. Turns out you can as easy as spellcheck="false"
.)
You'll notice it had no problem detecting JavaScript. So I threw in a couple of others tests and was surprised how well it worked:
- It had no trouble with Python
- Or HTML and CSS
- I even took the code from this post and it recognized it as Markdown
- I tried an old Perl CGI script - worked!
- I even tried ActionScript - and it worked!
- ColdFusion? Yep
- PHP? Yep
And how about the ultimate test:
So my demo is fairly simple, just printing out the result, but if I wanted to tie it to something like I said above, you could imagine taking the result, comparing it to the list of options in a dropdown for your editor, and selecting one on a match. (Of course, only do this if the user hasn't selected a language already.)
As for the code, it's pretty close to my other demos so I'll focus on the AI parts, not so much the DOM parts. First, the session:
session = await LanguageModel.create({
initialPrompts: [
{role:'system', content:'You look at a sample of code and try to determine the programming language being used. You will only return the name of the programming language, nothing else.'}
]
And then the call:
let result = await session.prompt([
{
role:"user",
content: [
{ type: "text", value:$input.value }
]
}]);
And that's it. I decided against a JSON schema this time as it was so simple, but that could be done as well to help enforce the "one word" response constraint.
As with my other demos here, you'll need Chrome Canary with the flags enabled and such, or if you are reading this in the future while flying with your S-Tier jetpack, congratulations!
See the Pen Detect Code Language by Raymond Camden (@cfjedimaster) on CodePen.