Skip to content

Instantly share code, notes, and snippets.

@dfinke
Created October 7, 2023 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfinke/bd348122436d0ef570fdde76fd9e317c to your computer and use it in GitHub Desktop.
Save dfinke/bd348122436d0ef570fdde76fd9e317c to your computer and use it in GitHub Desktop.
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
}
}
@dfinke
Copy link
Author

dfinke commented Oct 7, 2023

# Example usage of the function
$q = "I had 3 apples, ate one and lost one"
$messages = @(
    @{ Role = "system"; Content = "You are a helpful assistant." }
    @{ Role = "user"; Content = $q }
)


$chatResponse = Get-ChatCompletion -messages $messages
$chatResponse.choices[0].message.content
So, you started with 3 apples, ate one, and lost one. That means you currently have 1 apple left.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment