Private/Helpers.ps1
|
# Private helper functions for PowerCraft.AI #region Provider Configuration $script:Providers = @{ openai = @{ ChatEndpoint = 'https://api.openai.com/v1/chat/completions' ResponsesEndpoint = 'https://api.openai.com/v1/responses' ModelsEndpoint = 'https://api.openai.com/v1/models' SecretName = 'openai' EnvVars = @('OPENAI_API_KEY') DefaultModel = 'gpt-5.5' } gemini = @{ ChatEndpoint = 'https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent' ModelsEndpoint = 'https://generativelanguage.googleapis.com/v1beta/models' SecretName = 'gemini' EnvVars = @('GEMINI_API_KEY', 'GOOGLE_API_KEY') DefaultModel = 'gemini-3.5-flash' } anthropic = @{ MessagesEndpoint = 'https://api.anthropic.com/v1/messages' ModelsEndpoint = 'https://api.anthropic.com/v1/models' SecretName = 'anthropic' EnvVars = @('ANTHROPIC_API_KEY') DefaultModel = 'claude-opus-4-8' } } #endregion #region Key Resolution # What the secret store said when it could not be read: each is passed on once a session. $script:StoreProblemsSaid = [System.Collections.Generic.HashSet[string]]::new() function Resolve-PCApiKey { <# .SYNOPSIS The API key of a provider: its environment variable, then the PowerCraft.Secrets store. .DESCRIPTION The environment is read here and not left to PowerCraft.Secrets. Version 1 of that module answers Get-PCSecret from the environment before its store. Version 2 reads its store only, and which variable holds a key is for the module that uses the key to say. Read here, the order is the same with either version: a variable that is set wins, and the store is not asked. #> [CmdletBinding()] param( [Parameter(Mandatory)][string]$Provider ) $config = $script:Providers[$Provider] foreach ($variable in $config.EnvVars) { $value = [Environment]::GetEnvironmentVariable($variable) if ($value) { return $value } } if (Get-Command Get-PCSecret -ErrorAction SilentlyContinue) { try { $key = Get-PCSecret -Name $config.SecretName -ErrorAction Stop } catch { # A store that is there and cannot be read, such as a PowerCraft.Secrets 2 store # that is locked on this machine. It is said once, in the store's own words, and # does not take away a provider whose key is in the environment. $problem = "$_" if ($script:StoreProblemsSaid.Add($problem)) { Write-Warning "PowerCraft.AI: the secret store could not be read, so only keys in the environment are used. $problem" } $key = $null } if ($key) { return $key } } return $null } #endregion #region Provider Request Functions function Invoke-PCOpenAIRequest { [CmdletBinding()] param( [Parameter(Mandatory)][string]$ApiKey, [Parameter(Mandatory)][string]$Model, [Parameter(Mandatory)][array]$Messages, [int]$MaxTokens = 4096, [double]$Temperature = 0.3, [switch]$JsonMode, [switch]$WebSearch, [int]$TimeoutSec = 120 ) $headers = @{ 'Authorization' = "Bearer $ApiKey" 'Content-Type' = 'application/json' } $isResponsesAPI = $Model -match '^(gpt-5|o[1-9])' if ($isResponsesAPI) { # Responses API for reasoning models $systemMsg = ($Messages | Where-Object { $_.role -eq 'system' } | ForEach-Object { $_.content }) -join "`n" $userMsg = ($Messages | Where-Object { $_.role -eq 'user' } | ForEach-Object { $_.content }) -join "`n" $combinedInput = if ($systemMsg) { "$systemMsg`n`n$userMsg" } else { $userMsg } $body = @{ model = $Model input = $combinedInput } if ($WebSearch) { $body.tools = @(@{ type = 'web_search_preview' }) } if ($JsonMode -and -not $WebSearch) { $body.text = @{ format = @{ type = 'json_object' } } } $response = Invoke-RestMethod ` -Uri $script:Providers.openai.ResponsesEndpoint ` -Method POST ` -Headers $headers ` -Body ($body | ConvertTo-Json -Depth 20) ` -TimeoutSec $TimeoutSec $messageOutput = $response.output | Where-Object { $_.type -eq 'message' } | Select-Object -First 1 if ($messageOutput -and $messageOutput.content) { $textContent = $messageOutput.content | Where-Object { $_.type -eq 'output_text' } | Select-Object -First 1 if ($textContent) { return $textContent.text.Trim() } } throw 'No output_text found in OpenAI Responses API response' } else { # Standard Chat Completions API $body = @{ model = $Model messages = $Messages max_tokens = $MaxTokens temperature = $Temperature } if ($JsonMode) { $body.response_format = @{ type = 'json_object' } } $response = Invoke-RestMethod ` -Uri $script:Providers.openai.ChatEndpoint ` -Method POST ` -Headers $headers ` -Body ($body | ConvertTo-Json -Depth 20) ` -TimeoutSec $TimeoutSec return $response.choices[0].message.content.Trim() } } function Invoke-PCGeminiRequest { [CmdletBinding()] param( [Parameter(Mandatory)][string]$ApiKey, [Parameter(Mandatory)][string]$Model, [Parameter(Mandatory)][array]$Messages, [int]$MaxTokens = 4096, [double]$Temperature = 0.3, [switch]$JsonMode, [int]$TimeoutSec = 120 ) $endpoint = $script:Providers.gemini.ChatEndpoint -replace '\{model\}', $Model $uri = "${endpoint}?key=$ApiKey" $systemInstruction = $null $contents = @() foreach ($msg in $Messages) { if ($msg.role -eq 'system') { $systemInstruction = @{ parts = @(@{ text = $msg.content }) } } elseif ($msg.role -eq 'user') { $contents += @{ role = 'user'; parts = @(@{ text = $msg.content }) } } elseif ($msg.role -eq 'assistant') { $contents += @{ role = 'model'; parts = @(@{ text = $msg.content }) } } } $body = @{ contents = $contents generationConfig = @{ temperature = $Temperature maxOutputTokens = $MaxTokens } } if ($systemInstruction) { $body.systemInstruction = $systemInstruction } if ($JsonMode) { $body.generationConfig.responseMimeType = 'application/json' } $response = Invoke-RestMethod ` -Uri $uri ` -Method POST ` -Headers @{ 'Content-Type' = 'application/json' } ` -Body ($body | ConvertTo-Json -Depth 20) ` -TimeoutSec $TimeoutSec if ($response.candidates -and $response.candidates[0].content.parts) { $text = ($response.candidates[0].content.parts | ForEach-Object { $_.text }) -join '' return $text.Trim() } throw 'No content found in Gemini response' } function Invoke-PCAnthropicRequest { [CmdletBinding()] param( [Parameter(Mandatory)][string]$ApiKey, [Parameter(Mandatory)][string]$Model, [Parameter(Mandatory)][array]$Messages, [int]$MaxTokens = 4096, [double]$Temperature = 0.3, [switch]$JsonMode, [int]$TimeoutSec = 120 ) $headers = @{ 'x-api-key' = $ApiKey 'anthropic-version' = '2023-06-01' 'Content-Type' = 'application/json' } $systemContent = $null $apiMessages = @() foreach ($msg in $Messages) { if ($msg.role -eq 'system') { $systemContent = $msg.content } else { $apiMessages += @{ role = $msg.role; content = $msg.content } } } $body = @{ model = $Model max_tokens = $MaxTokens messages = $apiMessages } if ($systemContent) { $body.system = $systemContent } # Some models (e.g. opus-4-7+) deprecate temperature; only include if supported $noTempModels = @('claude-opus-4-7', 'claude-opus-4-8', 'claude-fable-5') if ($Temperature -ne 1.0 -and $Model -notin $noTempModels) { $body.temperature = $Temperature } $response = Invoke-RestMethod ` -Uri $script:Providers.anthropic.MessagesEndpoint ` -Method POST ` -Headers $headers ` -Body ($body | ConvertTo-Json -Depth 20) ` -TimeoutSec $TimeoutSec $textBlocks = $response.content | Where-Object { $_.type -eq 'text' } if ($textBlocks) { return ($textBlocks | ForEach-Object { $_.text }) -join '' } throw 'No text content found in Anthropic response' } #endregion |