We eat lunch together as a company, and we’ve been talking a lot about AI lately. Yesterday ChatGPT came up in the discussion, and someone mentioned it had the ability to describe what your code was doing. So I decided to add that functionality to my installation of Understand. Since Understand was designed as a platform more than an IDE, it was pretty easy. Here’s how I did it. (If you don’t care about my journey of discovery and just want the script, you can get it here.)
First, I needed to create a free account on openai.com and create an API key. That took about 2 minutes.
I then added that API key as an environment variable named OPENAI_API_KEY on my system to be consistent with OpenAPI’s methods.
OpenAPI’s documentation is excellent, so it only took another few minutes to find an example of what I was after – a quick way to explain what a given function is doing. Disclaimer, it’s actually using their code-davinci-002 engine instead of the ChatGPT engine, but the more precise the better IMHO.
Let’s get this running in Python first, then figure out how to integrate it into Understand:
Assuming Python3 is already installed on your system, run `pip install openai` to install their libraries.
I added a couple of lines to their sample script to actually output the results, but it pretty much just worked.
I have several different ways I could integrate this into Understand; I’m going to add it as a custom User Tool.
Adding the User Tool
User tools are an easy way to call an external script or action from Understand. Here’s how I set this one up:
I give it a title, specify my Python directory, then set the path to my script. My plan is to send whatever code is selected to OpenAI, so I set the Input to Selected Text, and I want the output to go to the command capture window, so I set that accordingly. The “Add to” section at the bottom determines where the option will show up. I like the right-click menu, so I’m just going to select Context Menu. Now I have the option when I right-click on a selection.
Now I need to get my script to read the highlighted code Understand is sending in. By default, the input command only reads one line of text. I’m sure there’s a better way, but I’m relatively new at Python. This loop seems to do the trick:
I used OpenAI’s playground to experiment with what settings worked best for me (don’t forget the View Code button in the upper right corner). I add those settings to my script.
And I run it again in Understand. Viola! It’s working!
Now I never have to comment my code again–our AI overlords will do it for me!!!
Oh, wait, maybe not. A few minutes later, unbound recursion rears its ugly head again!
Curses! So maybe the robots aren’t ready to take over the world yet…thankfully. But I do think this tool may prove handy. If you think it might be useful, you can download it from our Plugin repository.
Let us know if you end up using this or have any other ideas to extend Understand.