Skip to content

Instantly share code, notes, and snippets.

@motionharvest
Created December 30, 2025 13:15
Show Gist options
  • Select an option

  • Save motionharvest/c37454df8b7e07d9695368367357434e to your computer and use it in GitHub Desktop.

Select an option

Save motionharvest/c37454df8b7e07d9695368367357434e to your computer and use it in GitHub Desktop.
powershell script that calls the OpenAI endpoint for use with ai_insert.ahk. Requires OPENAI_API_KEY in Environment Variables.
param(
[Parameter(Mandatory=$true)][string]$Prompt,
[string]$Selection = "",
[string]$OutFile = ""
)
$log = Join-Path $PSScriptRoot "ai_call.log"
function Log($msg) {
$ts = (Get-Date).ToString("yyyy-MM-dd HH:mm:ss")
Add-Content -Path $log -Value "$ts $msg"
}
Log "----"
Log "Prompt: $Prompt"
Log "Selection length: $($Selection.Length)"
$apiKey = $env:OPENAI_API_KEY
if (-not $apiKey) {
Log "ERROR: OPENAI_API_KEY env var not found"
exit 0
}
$system = @"
You are an inline insertion engine.
Your output will be inserted directly into an existing document at the caret.
Return ONLY the minimal text that should be inserted.
Do NOT include punctuation unless it is strictly required by syntax.
Do NOT include quotes, explanations, prefixes, suffixes, or formatting.
Do NOT complete sentences.
If the answer is a single token, return only that token.
If multiple tokens are required, return them separated by single spaces only.
Never add trailing punctuation.
"@
$user = if ($Selection -and $Selection.Trim().Length -gt 0) {
@"
User question:
$Prompt
Selected text:
$Selection
"@
} else {
$Prompt
}
$bodyObj = @{
model = "gpt-3.5-turbo"
messages = @(
@{ role = "system"; content = $system },
@{ role = "user"; content = $user }
)
temperature = 0
max_tokens = 120
}
$body = $bodyObj | ConvertTo-Json -Depth 8
Log "Request JSON built"
try {
$resp = Invoke-RestMethod -Uri "https://api.openai.com/v1/chat/completions" -Method Post -Headers @{
Authorization = "Bearer $apiKey"
"Content-Type" = "application/json"
} -Body $body
$text = $resp.choices[0].message.content
if ($null -eq $text) { $text = "" }
$text = ($text -split "`r?`n")[0].Trim()
if ($OutFile -and $OutFile.Trim().Length -gt 0) {
Set-Content -Path $OutFile -Value $text -Encoding utf8 -NoNewline
} else {
Write-Output $text
}
Log "Response: $text"
} catch {
Log "ERROR: $($_.Exception.Message)"
if ($_.ErrorDetails -and $_.ErrorDetails.Message) {
Log "ErrorDetails: $($_.ErrorDetails.Message)"
}
exit 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment