Simple PowerShell Script to ask questions and follow-up questions to Chat GPT 4 API

Posted by SysAdmin Tools on

Have you wondered how easy it would be to create a PowerShell script to ask Chat GPT some questions?

A lot of sources may give you a script to ask a single question and most of the time the script does not even work or requires A LOT of modifications.

Why go via the API and not via the website?
Well... queries via the API are not used to train their models. Simple. 




To get started with this, you would off-course need an OpenAI account (https://openai.com)
After you have logged in, create an API key (https://platform.openai.com/api-keys

You will also need some API Credits.
You do not need a Chat GPT Plus subscription to use the API. 

Navigate to https://platform.openai.com/account/billing/overview and click on Add to credit balance and purchase credits.

Once you create your API key, copy it and save it in a secure location to use in the script below.
In the future, if you suspect your key has been compromised, delete it and create a new one. 

The script below builds a conversation history with each question, which is what allows for the follow up questions. 
Simply create a new session or clear the conversation history variable to start fresh by running this command $conversationHistory = @()

############################
$apiKey = "PasteYourAPIKeyHere"
$apiUrl = "https://api.openai.com/v1/chat/completions"

$headers = @{
'Authorization' = "Bearer $apiKey"
'Content-Type' = 'application/json'
}

$conversationHistory = @()

Function GPT-Question ($question) {
$global:conversationHistory += @{
role = 'user'
content = $question
}

$body = @{
model = 'gpt-4'
messages = $conversationHistory
temperature = 1
max_tokens = 256
top_p = 1
frequency_penalty = 0
presence_penalty = 0
} | ConvertTo-Json

$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Headers $headers -Body $body -ContentType 'application/json'

$responseContent = $response.choices[0].message.content
$conversationHistory += @{
role = 'system'
content = $responseContent
}

return $responseContent
}

# Example usage:
# GPT-Question -question "what is the speed of light"
# GPT-Question -question "Can you explain it in more detail?"
############################


You may have to add some formatting to the responses if you want it to start outputting to HTML etc. 

Some of the possible formats are documented here.
https://medium.com/chatgpt-tipps-tricks-hidden-knowledge/a-beginners-guide-to-formatting-output-on-chatgpt-461a9328c9bc

More info here.
https://platform.openai.com/docs/api-reference/introduction




Share this post



← Older Post Newer Post →


Leave a comment

Please note, comments must be approved before they are published.