Last active
November 28, 2022 13:17
-
-
Save dfinke/fd46bf9a335f9c20c756a4d038e431eb to your computer and use it in GitHub Desktop.
Convert natural language commands into executable PowerShell using OpenAI
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <# | |
| 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