Say Hello to ChatGPT with Powershell

ChatGPT, Bard, and other AI models are fun. A good way to dig into their capability and limitations are to access them via their API or applications programming interface. From what I’ve seen, many examples of this are in Python. So far, I hadn’t seen much for Powershell…so I thought it would be interesting to say hello to ChatGPT using Powershell.

Like any API, you need to establish an authorization code which identifies you to the API and which allows billing. The authcode essentially serves as a name and password for your call to ChatGPT. First you have to create an account:

Sign Up for OpenAI API

To sign up for the OpenAI API, visit OpenAI’s website and fill out the form. Once your request is approved, you’ll receive an invitation to join the API.

Get an API Key

After you’ve been accepted into the API, you’ll need to generate an API key. To do this, navigate to the API Dashboard and click on the “Generate API Key” button. Your key will be a string of alphanumeric numbers about 48 characters long.

Choose your model

OpenAI has several different models going back from ChatGPT4. Each model is a little different. Some are supposed to be more suitable for things like chatbots, others are better for searching, and of course the graphic model Dall-E generates (argueably horrible) pictures. For purposes of our sample here…. we’ll use the “text-Davinci-03” model which is an earlier version of the ChatGPT3 series.

Powershell Code to Connect:

The Powershell Code uses the PowerShell Invoke-RestMethod cmdlet, and its use is surprisingly similar to other API calls for other services. Here is the full code:

$headers = @{
‘Content-Type’ = ‘application/json’
‘Authorization’ = ‘Bearer yourAPICodeGoesHere12334455’
}

$body = @{
prompt = ‘Hello ChatGPT!’
temperature = 0.7
model = ‘text-davinci-003’
}

$bodyjson= ConvertTo-Json -inputobject $body

$response = Invoke-RestMethod -Uri ‘https://api.openai.com/v1/completions’ `
-Method ‘POST’ `
-Headers $headers `
-Body $bodyjson

 

The prompt parameter specifies the text prompt to send to the model. The temperature parameter controls the “creativity” of the response, with higher values generating more novel responses. The model parameter specifies which model to use – in this case, text-davinci-003.

It works! Run the Powershell script, and you’ll get the following:

‘Hi there! How can I help you today?

API Documentation

You can find more information about the text-davinci-003 model in the OpenAI API documentation. The documentation provides details on the available parameters, example responses, and more.

Payment and Charges

It’s worth noting that to use the OpenAI API, you’ll need to provide a payment method and will be charged an initial $5.00. More information on payment and charges can be found on the API pricing page.

Leave a comment