Created
October 7, 2023 20:24
-
-
Save dfinke/bd348122436d0ef570fdde76fd9e317c to your computer and use it in GitHub Desktop.
This file contains 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
function Get-ChatCompletion { | |
param( | |
$messages, | |
$model = "gpt-3.5-turbo", | |
$functions, | |
$function_call, | |
$temperature = 0.7, | |
$max_tokens, | |
$stop, | |
$top_p = 1.0, | |
$frequency_penalty = 0.0, | |
$presence_penalty = 0.0 | |
) | |
# Check if messages parameter is provided | |
if (-not $messages -or $messages.Length -eq 0) { | |
Write-Error "Please provide a messages array." | |
exit 1 | |
} | |
# Define the API endpoint for chat completions | |
$apiUrl = "https://api.openai.com/v1/chat/completions" | |
# Retrieve API key from environment variable | |
$apiKey = $env:OPENAI_API_KEY | |
if (-not $apiKey) { | |
Write-Error "Please set the OPENAI_API_KEY environment variable." | |
exit 1 | |
} | |
# Create a header with the API key for authorization | |
$headers = @{ | |
"Content-Type" = "application/json" | |
"Authorization" = "Bearer $apiKey" | |
} | |
# Convert messages array to appropriate JSON structure | |
$jsonMessages = $messages | ForEach-Object { | |
@{ | |
role = $_.Role | |
content = $_.Content | |
} | |
} | |
# Define the payload with additional parameters | |
$body = @{ | |
model = $model | |
messages = $jsonMessages | |
temperature = $temperature | |
max_tokens = $max_tokens | |
stop = $stop | |
top_p = $top_p | |
frequency_penalty = $frequency_penalty | |
presence_penalty = $presence_penalty | |
} | |
if ($null -ne $functions) { | |
$body.functions = @($functions) | |
} | |
if ($null -ne $function_call) { | |
$body.function_call = @{name = $function_call } | |
} | |
$jsonBody = $body | ConvertTo-Json -Depth 7 | |
try { | |
# Send POST request to the API with -ErrorVariable to store errors | |
$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Body $jsonBody -Headers $headers -ErrorAction SilentlyContinue -ErrorVariable apiError | |
# Output the response | |
return $response | |
} | |
catch { | |
if ($apiError) { | |
# Write the API error to the error stream | |
Write-Error ($apiError.Message | ConvertFrom-Json).error.message | |
exit 1 | |
} | |
# Write the exception to the error stream | |
Write-Error $_.Exception.Message | |
exit 1 | |
} | |
} |
Author
dfinke
commented
Oct 7, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment