Skip to content

Instantly share code, notes, and snippets.

@dfinke
Last active November 28, 2022 13:17
Show Gist options
  • Select an option

  • Save dfinke/fd46bf9a335f9c20c756a4d038e431eb to your computer and use it in GitHub Desktop.

Select an option

Save dfinke/fd46bf9a335f9c20c756a4d038e431eb to your computer and use it in GitHub Desktop.
Convert natural language commands into executable PowerShell using OpenAI
<#
Aims to grow the understanding of using OpenAI in PoweShell by providing an example of an implementation and references
#>
function Invoke-OpenAI {
<#
.SYNOPSIS
Convert natural language commands into commands in PowerShell
.EXAMPLE
Invoke-OpenAI "# What's my IP?"
.EXAMPLE
Invoke-OpenAI "# how many processes are running with more than 700 handles?""
.LINK
#>
param(
[Parameter(Mandatory)]
$userQuery,
$maxTokens = 100
)
if(!$env:OpenAIKey) {
$msg = '$env:OpenAIKey is not set'
$msg += 'You need to get one here: https://beta.openai.com/account/api-keys'
throw ($msg -join "`r`n")
}
$url = 'https://api.openai.com/v1/engines/davinci/completions'
$prefix = "<# powershell #>"
$codex_query = '{0} {1}' -f $prefix, $userQuery
$payload = @{
prompt = $codex_query
temperature = 0
max_tokens = $maxTokens
stop = "#"
}
$irmParams = @{
Uri = $url
Method = 'Post'
ContentType = 'application/json'
Headers = @{Authorization = "Bearer $($env:OpenAIKey)" }
Body = $payload | ConvertTo-Json
}
$r = Invoke-RestMethod @irmParams
$r.choices[0].Text.Trim()
}
Set-PSReadLineKeyHandler -Key Ctrl+g `
-BriefDescription NLCLI `
-LongDescription "Calls Codex CLI tool on the current buffer" `
-ScriptBlock {
param($key, $arg)
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
# get response from create_completion function
$output = Invoke-OpenAI $line
# check if output is not null
if ($output -ne $null) {
foreach ($str in $output) {
if ($str -ne $null -and $str -ne "") {
[Microsoft.PowerShell.PSConsoleReadLine]::AddLine()
[Microsoft.PowerShell.PSConsoleReadLine]::Insert($str)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment