PSMD.OpenAI.psm1

$script:ModuleRoot = $PSScriptRoot
$script:ModuleVersion = (Import-PowerShellDataFile -Path "$($script:ModuleRoot)\PSMD.OpenAI.psd1").ModuleVersion

# Detect whether at some level dotsourcing was enforced
$script:doDotSource = Get-PSFConfigValue -FullName PSMD.OpenAI.Import.DoDotSource -Fallback $false
if ($PSMD_OpenAI_dotsourcemodule) { $script:doDotSource = $true }

<#
Note on Resolve-Path:
All paths are sent through Resolve-Path/Resolve-PSFPath in order to convert them to the correct path separator.
This allows ignoring path separators throughout the import sequence, which could otherwise cause trouble depending on OS.
Resolve-Path can only be used for paths that already exist, Resolve-PSFPath can accept that the last leaf my not exist.
This is important when testing for paths.
#>


# Detect whether at some level loading individual module files, rather than the compiled module was enforced
$importIndividualFiles = Get-PSFConfigValue -FullName PSMD.OpenAI.Import.IndividualFiles -Fallback $false
if ($PSMD_OpenAI_importIndividualFiles) { $importIndividualFiles = $true }
if (Test-Path (Resolve-PSFPath -Path "$($script:ModuleRoot)\..\.git" -SingleItem -NewChild)) { $importIndividualFiles = $true }
if ("<was compiled>" -eq '<was not compiled>') { $importIndividualFiles = $true }
    
function Import-ModuleFile
{
    <#
        .SYNOPSIS
            Loads files into the module on module import.
         
        .DESCRIPTION
            This helper function is used during module initialization.
            It should always be dotsourced itself, in order to proper function.
             
            This provides a central location to react to files being imported, if later desired
         
        .PARAMETER Path
            The path to the file to load
         
        .EXAMPLE
            PS C:\> . Import-ModuleFile -File $function.FullName
     
            Imports the file stored in $function according to import policy
    #>

    [CmdletBinding()]
    Param (
        [string]
        $Path
    )
    
    $resolvedPath = $ExecutionContext.SessionState.Path.GetResolvedPSPathFromPSPath($Path).ProviderPath
    if ($doDotSource) { . $resolvedPath }
    else { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText($resolvedPath))), $null, $null) }
}

#region Load individual files
if ($importIndividualFiles)
{
    # Execute Preimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\preimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # Import all internal functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Import all public functions
    foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Filter "*.ps1" -Recurse -ErrorAction Ignore))
    {
        . Import-ModuleFile -Path $function.FullName
    }
    
    # Execute Postimport actions
    foreach ($path in (& "$ModuleRoot\internal\scripts\postimport.ps1")) {
        . Import-ModuleFile -Path $path
    }
    
    # End it here, do not load compiled code below
    return
}
#endregion Load individual files

#region Load compiled code
<#
This file loads the strings documents from the respective language folders.
This allows localizing messages and errors.
Load psd1 language files for each language you wish to support.
Partial translations are acceptable - when missing a current language message,
it will fallback to English or another available language.
#>

Import-PSFLocalizedString -Path "$($script:ModuleRoot)\en-us\*.psd1" -Module 'PSMD.OpenAI' -Language 'en-US'

function Add-OaiHelp {
<#
.SYNOPSIS
    Adds help to the provided function, if needed.
 
.DESCRIPTION
    Adds help to the provided function, if needed.
    If the command already has ANY help, no action will be taken.
 
.PARAMETER Component
    Function definitions as parsed from the Read-ReAstComponent command.
 
.EXAMPLE
    PS C:\> Read-ReAstComponent -Path "C:\Temp\MyScript.ps1" -Select FunctionDefinitionAst | Add-OaiHelp | Write-ReAstComponent
     
    Reads all function definitions from 'C:\Temp\MyScript.ps1' and adds help to them if needed.
#>

    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline = $true)]
        [Refactor.Component.AstResult[]]
        $Component
    )
    process {
        :main foreach ($componentObject in $Component) {
            if ($componentObject.Ast.GetHelpContent()) {
                $componentObject
                continue
            }

            $textToScan = Resolve-FunctionCode -Ast $componentObject.Ast
            $attempt = 0
            while ($attempt -lt 3) {
                $helpResult = $null
                try { $helpResult = Get-PsmdOaiHelp -Code $textToScan -ErrorAction Stop }
                catch {
                    $PSCmdlet.WriteError($_)
                    $componentObject
                    continue main
                }

                if (-not $helpResult) { $attempt++; continue }
                $insertIndex = $componentObject.Text.IndexOf("`n",$componentObject.Text.IndexOf("{"))
                $newText = $componentObject.Text.SubString(0, $insertIndex), "`n", $helpResult.Help.Trim(), $componentObject.Text.SubString($insertIndex) -join ""
                if (Test-ReSyntax -Code $newText) { break }
                $attempt++
            }
            if ($attempt -lt 3) {
                $componentObject.NewText = $newText
            }
            $componentObject
        }
    }
}

function Assert-OpenAIConnection {
<#
    .SYNOPSIS
        Checks to make sure that a connection to OpenAI is established prior to running the calling command.
 
    .DESCRIPTION
        The Assert-OpenAIConnection function will check to see if a connection to OpenAI has been established before running the calling command.
        If a valid connection has not been established, the function will throw a terminating error.
 
    .PARAMETER Cmdlet
        The $PSCmdlet variable of the calling command.
        Used to throw a terminating error in the context of the caller, making this helper function invisible to the user.
 
    .EXAMPLE
        PS C:> Assert-OpenAIConnection -Cmdlet $PSCmdlet
 
        Checks to make sure that a connection to OpenAI is established prior to running the calling command.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        $Cmdlet
    )

    if ($script:token -and $script:token.Type -ne 'Empty') { return }

    $record = [PSFramework.Meta.PsfErrorRecord]::new(
        'Not connected to OpenAI! Call Connect-PsmdOpenAI first.',
        [System.Management.Automation.ErrorCategory]::InvalidOperation,
        'Not Connected'
    )
    $Cmdlet.ThrowTerminatingError($record)
}

function Invoke-OpenAIRequest {
<#
    .SYNOPSIS
        Executes an OpenAI request.
 
    .DESCRIPTION
        Executes an OpenAI request.
 
    .PARAMETER Body
        The actual request payload to send.
 
    .PARAMETER Type
        The type of OpenAI request to invoke.
        Defaults to ’completions’.
         
    .EXAMPLE
        PS C:\> Invoke-OpenAIRequest -Body @{ prompt = $prompt; max_tokens = 2000 }
 
        Sends the query in $prompt, expecting no more than 2000 tokens in the response.
#>

    [CmdletBinding()]
    param (
        $Body,

        [string]
        $Type = 'completions'
    )

    begin {
        Assert-OpenAIConnection -Cmdlet $PSCmdlet
    }
    process {
        $url = 'https://{0}.openai.azure.com/openai/deployments/{1}/{2}?api-version={3}' -f $script:token.Resource, $script:token.Deployment, $Type, $script:token.ApiVersion
        try { Invoke-RestMethod -Method 'Post' -Uri $url -Headers $script:token.GetHeader() -Body ($Body | ConvertTo-Json -Compress) -ErrorAction Stop }
        catch { throw }
    }
}

function Measure-TokenCount {
<#
    .SYNOPSIS
        Gets the total token count by calculating the average token length and dividing it by four.
 
    .DESCRIPTION
        The Measure-TokenCount function calculates the total token count of a string by dividing the length of the string by 4 and then rounding it.
 
    .PARAMETER Code
        The Code that is used to calculate the total token count of the given string.
 
    .EXAMPLE
        PS C:\> Measure-TokenCount -Code "Write-Host 'Hello, world!'"
 
        This command calculates the total token count of the string "Write-Host 'Hello, world!'" (7).
#>

    [OutputType([int])]
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Code
    )

    $Code -split "(?<=\s)" | ForEach-Object {
        $div = $_.Length / 4
        $rounded = [math]::Round(($_.Length / 4), [System.MidpointRounding]::ToNegativeInfinity)
        if ($div -gt $rounded) { $rounded + 1 }
        else { $rounded }
    } | Measure-Object -Sum | ForEach-Object Sum
}

function New-Token {
<#
    .SYNOPSIS
        Creates a new token object for a given resource and deployment.
 
    .DESCRIPTION
        Creates a new token object for a given resource and deployment.
        A token object is repsonsible for generating the authentication header for OpenAI API requests.
 
        Depending on just how we are connected, this might require renewing session tokens.
 
    .PARAMETER Resource
        The name of the resource for the token
 
    .PARAMETER Deployment
        The name of the deployment for the token
 
    .PARAMETER Empty
        If the token should be empty
 
    .PARAMETER ApiKey
        The ApiKey that will be used to create a token
 
    .PARAMETER ApiVersion
        The API version that will be used for the request.
        Defaults to 2022-12-01
 
    .EXAMPLE
        PS C:\> New-Token -Resource 'user_data' -Deployment 'test-production' -ApiKey $ApiKey
 
        Creates a new ApiKey token with the specified resource and deployment, as well as the ApiKey supplied.
#>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseShouldProcessForStateChangingFunctions", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "")]
    [CmdletBinding()]
    param (
        [string]
        $Resource,

        [string]
        $Deployment,

        [Parameter(Mandatory = $true, ParameterSetName = 'Empty')]
        [switch]
        $Empty,

        [Parameter(Mandatory = $true, ParameterSetName = 'Token')]
        [SecureString]
        $ApiKey,

        [string]
        $ApiVersion = '2022-12-01'
    )

    $data = @{
        Created    = Get-Date
        Type       = 'Empty'
        Resource   = $Resource
        Deployment = $Deployment
        ApiVersion = $ApiVersion
    }
    

    switch ($PSCmdlet.ParameterSetName) {
        'Empty' {
            $object = [PSCustomObject]$data
            Add-Member -InputObject $object -MemberType ScriptMethod -Name GetHeader -Value { @{} }
            return $object
        }
        'Token' {
            $data.ApiKey = $ApiKey
            $data.Type = 'ApiKey'
            $object = [PSCustomObject]$data
            Add-Member -InputObject $object -MemberType ScriptMethod -Name GetHeader -Value {
                @{
                    'api-key' = [PSCredential]::new("whatever", $this.ApiKey).GetNetworkCredential().Password
                    'Content-Type' = 'application/json'
                }
            }
            return $object
        }
        default {
            throw "Not Implemented!"
        }
    }
}

function Resolve-FunctionCode {
<#
    .SYNOPSIS
        Resolves the function code to send to OpenAI based on the provided PowerShell AST object
 
    .DESCRIPTION
        Resolves the function code to send to OpenAI based on the provided PowerShell AST object.
        It ensures the total token count is below the limit given, truncating code parts as needed.
 
    .PARAMETER Ast
        The PowerShell AST object representing the function code.
 
    .PARAMETER TokenLimit
        The maximum token count to be allowed.
        Defaults to: 3000
 
    .EXAMPLE
        PS C:\> Resolve-FunctionCode -Ast $ast
 
        Returns the text value of the function AST provided, as should be sent to OpenAI
#>

    [OutputType([string])]
    [CmdletBinding()]
    param (
        [System.Management.Automation.Language.FunctionDefinitionAst]
        $Ast,

        [int]
        $TokenLimit = 3000
    )

    if ((Measure-TokenCount -Code $Ast.Extent.Text) -lt $TokenLimit) {
        return $Ast.Extent.Text | Set-String -OldValue '\s+' -NewValue ' '
    }

    $keyWord = 'function'
    if ($Ast.IsFilter) { $keyWord = 'filter' }
    if ($Ast.IsWorkflow) { $keyWord = 'workflow' }

    $textHeader = @(
        '{0} {1} {{' -f $keyWord, $Ast.Name
    ) + @(
        $Ast.Body.ParamBlock.Attributes.Extent.Text | Split-String "`n" | Set-String "^\s+" | Join-String "`n"
    ) + @(
        $Ast.Body.ParamBlock.Extent.Text | Split-String "`n" | Set-String "^\s+" | Join-String "`n"
    )

    $beginBlock = ''
    if ($Ast.Body.BeginBlock) {
        $beginBlock = @"
begin {
$($Ast.Body.BeginBlock.Statements.Extent.Text | Split-String "`n" | Set-String "^\s+" | Join-String "`n")
}
"@

    }
    $processBlock = ''
    if ($Ast.Body.ProcessBlock) {
        $processBlock = @"
process {
$($Ast.Body.ProcessBlock.Statements.Extent.Text | Split-String "`n" | Set-String "^\s+" | Join-String "`n")
}
"@

    }
    $endBlock = ''
    if ($Ast.Body.EndBlock) {
        $endBlock = @"
end {
$($Ast.Body.EndBlock.Statements.Extent.Text | Split-String "`n" | Set-String "^\s+" | Join-String "`n")
}
"@

    }

    $cases = @(
        @($textHeader) + @($beginBlock) + @($processBlock) + @($endBlock) + @('}') | Join-String "`n"
        @($textHeader) + @($beginBlock) + @($processBlock) + @('}') | Join-String "`n"
        @($textHeader) + @($processBlock) + @('}') | Join-String "`n"
    )

    foreach ($case in $cases) {
        if ((Measure-TokenCount -Code $case) -lt $TokenLimit) {
            return $case | Set-String -OldValue '\s+' -NewValue ' '
        }
    }

    $lines = $processBlock -split "`n"
    foreach ($index in 0..$lines.Count) {
        $newProcess = $lines[0..($lines.Count - 1 - $index)]
        $newText = @($textHeader) + @($newProcess) + @('}') | Join-String "`n"
        if ((Measure-TokenCount -Code $newText) -lt $TokenLimit) {
            return $newText | Set-String -OldValue '\s+' -NewValue ' '
        }
    }

    throw "Unable to generate a scanable function code with $TokenLimit tokens. This usually only happens when the param block is too large to accomodate anything else. Param block size: $($Ast.Body.ParamBlock.Extent.Text.Length)"
}

function Add-PsmdOaiFunctionHelp {
<#
    .SYNOPSIS
        Adds PowerShell Comment-Based Help to function definitions in a script file.
 
    .DESCRIPTION
        Adds PowerShell Comment-Based Help to function definitions in a script file.
        Reads the script file, parses the syntax trees of the function definitions, and adds the Comment-Based Help.
        The script file is updated with the help included.
 
    .PARAMETER Path
        Specifies the path to the script file to read.
 
    .PARAMETER OutPath
        The folder-path where to write the results to.
        If specified, input files will not be modified.
 
    .PARAMETER PassThru
        Return the result objects.
        By default, files are updated silently.
 
    .PARAMETER Backup
        Whether to create a backup of the file before modifying it.
 
    .PARAMETER EnableException
        This parameters disables user-friendly warnings and enables the throwing of exceptions.
        This is less user friendly, but allows catching exceptions in calling scripts.
 
    .PARAMETER WhatIf
        If this switch is enabled, no actions are performed but informational messages will be displayed that explain what would happen if the command were to run.
     
    .PARAMETER Confirm
        If this switch is enabled, you will be prompted for confirmation before executing any operations that change state.
 
    .EXAMPLE
        PS C:\> Add-PsmdOaiFunctionHelp -Path C:\Scripts\test.ps1
 
        The script file located at C:\Scripts\test.ps1 is modified to include Comment-Based Help for each function definition.
 
#>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "")]
    [CmdletBinding(SupportsShouldProcess = $true, DefaultParameterSetName = 'default')]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('FullName')]
        [string[]]
        $Path,

        [Parameter(ParameterSetName = 'outpath')]
        [string]
        $OutPath,

        [switch]
        $PassThru,

        [Parameter(ParameterSetName = 'inplace')]
        [switch]
        $Backup,

        [switch]
        $EnableException
    )

    begin {
        $param = @{
            PassThru = $PassThru
        }
        if ($OutPath) { $param.OutPath = $OutPath }
        if ($Backup) { $param.Backup = $Backup }
    }
    process {
        foreach ($pathEntry in $Path) {
            Invoke-PSFProtectedCommand -ActionString 'Add-PsmdOaiFunctionHelp.Path.Resolving' -ActionStringValues $pathEntry -Target $pathEntry -ScriptBlock {
                $resolvedPaths = Resolve-PSFPath -Path $pathEntry -Provider FileSystem
            } -EnableException $EnableException -PSCmdlet $PSCmdlet -Continue

            foreach ($resolvedPath in $resolvedPaths) {
                $fsItem = Get-Item -LiteralPath $resolvedPath
                if ($fsItem.PSIsContainer) { continue }

                if (Test-ReSyntax -LiteralPath $fsItem.FullName -Not) {
                    Stop-PSFFunction -String 'Add-PsmdOaiFunctionHelp.Error.Syntax' -StringValues $fsItem.FullName -EnableException $EnableException -Cmdlet $PSCmdlet -Continue -Target $fsItem
                }

                $scriptParts = Read-ReAstComponent -LiteralPath $fsItem.FullName -Select FunctionDefinitionAst
                if (-not $scriptParts) { continue }
                $scriptParts | Where-Object Type -EQ FunctionDefinitionAst | Add-OaiHelp
                Invoke-PSFProtectedCommand -ActionString 'Add-PsmdOaiFunctionHelp.Converting' -ActionStringValues $fsItem.Name -Target $fsItem -ScriptBlock {
                    Write-ReAstComponent @param -Components $scriptParts
                } -EnableException $EnableException -PSCmdlet $PSCmdlet -Continue
            }
        }
    }
}

function Connect-PsmdOpenAI {
<#
    .SYNOPSIS
        Creates a connection to an OpenAI resource.
 
    .DESCRIPTION
        Creates a connection to an OpenAI resource.
 
    .PARAMETER Resource
        The resource name of the OpenAI resource.
 
    .PARAMETER Deployment
        The name of the specific deployment within the resource to use.
 
    .PARAMETER ApiKey
        The API key required for authentication.
 
    .PARAMETER Identity
        Use the current MSI account to connect to the OpenAI resource.
        Not implemented yet.
 
    .PARAMETER User
        Connect as the current Azure User.
        Not implemented yet.
 
    .PARAMETER DynamicKey
        While connecting as the current identity, use that access to dynamically retrieve the ApiKey and then continue using the ApiKey.
        Not implemented yet.
 
    .PARAMETER ApiVersion
        The version of the API to use.
        Default is 2022-12-01.
 
    .EXAMPLE
        PS C:\> Connect-PsmdOpenAI -Resource "resourcename" -Deployment "mydeployment" -ApiKey $key
 
        Creates a connection to an Azure Cognitive Services OpenAI resource using an API key.
#>

    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSReviewUnusedParameter", "")]
    [CmdletBinding(DefaultParameterSetName = 'User')]
    param (
        [string]
        $Resource = (Get-PSFConfigValue -FullName 'PSMD.OpenAI.Default.Resource'),

        [Parameter(Mandatory = $true)]
        [string]
        $Deployment = (Get-PSFConfigValue -FullName 'PSMD.OpenAI.Default.Resource'),

        [Parameter(ParameterSetName = 'Token')]
        $ApiKey,

        [Parameter(ParameterSetName = 'MSI')]
        [switch]
        $Identity,

        [Parameter(ParameterSetName = 'User')]
        [switch]
        $User,

        [Parameter(ParameterSetName = 'DynamicKey')]
        [switch]
        $DynamicKey,

        [string]
        $ApiVersion = '2022-12-01'
    )

    begin {
        if (-not $Resource) { Stop-PSFFunction -String 'Connect-PsmdOpenAI.NoResource' -EnableException $true -Cmdlet $PSCmdlet }
        if (-not $Deployment) { Stop-PSFFunction -String 'Connect-PsmdOpenAI.NoDeployment' -EnableException $true -Cmdlet $PSCmdlet }
    }
    Process {
        switch ($PSCmdlet.ParameterSetName) {
            'Token' {
                if ($ApiKey -is [securestring]) { $secret = $ApiKey }
                elseif ($ApiKey -is [PSCredential]) { $secret = $ApiKey.Password}
                else { $secret = $ApiKey | ConvertTo-SecureString -AsPlainText -Force }
                $script:token = New-Token -Resource $Resource -Deployment $Deployment -ApiKey $secret -ApiVersion $ApiVersion
            }
            default {
                throw "Not Implemented Yet"
            }
        }
<#
        If ($ManagedIdentity -eq $true) {
            "managed"
            try {
                Connect-AzAccount -Identity
 
                $MyTokenRequest = Get-AzAccessToken -ResourceUrl "https://cognitiveservices.azure.com"
                $MyToken = $MyTokenRequest.token
                If (!$MyToken) {
                    Write-Warning "Failed to get API access token!"
                    Exit 1
                }
                $Global:MyHeader = @{"Authorization" = "Bearer $MyToken" }
            }
            catch [System.Exception] {
                Write-Warning "Failed to get Access Token, Error message: $($_.Exception.Message)"; break
            }
 
        }
        If ($User -eq $true) {
            "USER"
            try {
                Connect-AzAccount
 
                $MyTokenRequest = Get-AzAccessToken -ResourceUrl "https://cognitiveservices.azure.com"
                $MyToken = $MyTokenRequest.token
                If (!$MyToken) {
                    Write-Warning "Failed to get API access token!"
                    Exit 1
                }
                $Global:MyHeader = @{"Authorization" = "Bearer $MyToken" }
            }
            catch [System.Exception] {
                Write-Warning "Failed to get Access Token, Error message: $($_.Exception.Message)"; break
            }
        }
        If ($APIkey) {
            "APIKEY"
            $Global:MyHeader = @{"api-key" = $apikey }
        }
        #>

    }
}

function Get-PsmdOaiCompletion {
<#
.SYNOPSIS
    Gets completion suggestions from the OpenAI-driven Autocomplete model
 
.DESCRIPTION
    Invokes the OpenAI Autocomplete model for the specified prompt and returns choices.
 
.PARAMETER Prompt
    The prompt to pass to the OpenAI Autocomplete model.
 
.PARAMETER MaxTokens
    The maximum amount of tokens to return.
    The sent token plus the expected result must not be above 4097!
 
.PARAMETER Raw
    Returns the raw response object instead of the just the choices.
 
.EXAMPLE
    PS C:\> Get-PsmdOaiCompletion -Prompt "The quick "
 
    Returns completion suggestons for the input prompt "The quick " as strings.
 
.EXAMPLE
    PS C:\> Get-PsmdOaiCompletion -Prompt "The quick " -Raw
     
    Returns the raw response object from the OpenAI Autocomplete model.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]
        $Prompt,

        [int]
        $MaxTokens = 1000,

        [switch]
        $Raw
    )

    begin {
        Assert-OpenAIConnection -Cmdlet $PSCmdlet
    }
    process {
        $body = @{
            prompt     = $Prompt
            max_tokens = $MaxTokens
        }
        try { $results = Invoke-OpenAIRequest -Body $body -ErrorAction Stop }
        catch { throw }

        if ($Raw) { return $results }
        $results.choices.text
    }
}

function Get-PsmdOaiHelp {
<#
    .SYNOPSIS
        Get help from the OpenAI Service for given code or command.
 
    .DESCRIPTION
        Get help from the OpenAI Service for given code or command.
 
    .PARAMETER Command
        The command for which help is being requested
 
    .PARAMETER Code
        The code for which help is being requested
 
    .EXAMPLE
        PS C:\> Get-PsmdOaiHelp -Command mkdir
 
        Gets the help for the mkdir command from the OpenAI service.
 
    .EXAMPLE
        PS C:\> Get-PsmdOaiHelp -Code $sourceCode
 
        Gets the help for the command specified in the code from the OpenAI service.
#>

    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, ParameterSetName = 'Command')]
        [string]
        $Command,
        
        [Parameter(Mandatory = $true, ParameterSetName = 'Code')]
        [string]
        $Code
    )

    begin {
        Assert-OpenAIConnection -Cmdlet $PSCmdlet

        $basePrompt = @'
Write the help for the following PowerShell Function in the PowerShell Comment Based Help format.
 
{0}
'@

    }
    process {
        if ($Code) {
            $tokenCount = Measure-TokenCount -Code ($basePrompt -f $Code)
            try { $help = Get-PsmdOaiCompletion -MaxTokens (4097 - $tokenCount - 200) -Prompt ($basePrompt -f $Code) -ErrorAction Stop }
            catch {
                $PSCmdlet.WriteError($_)
                return
            }
            [PSCustomObject]@{
                Command = ''
                Code = $Code
                Help = $help
            }
        }

        if ($Command) {
            foreach ($commandObject in Get-Command -Name $Command) {
                $commandText = @"
function $($commandObject.Name) {
$($commandObject.Definition)
}
"@

                $tokenCount = Measure-TokenCount -Code ($basePrompt -f $commandText)
                try { $help = Get-PsmdOaiCompletion -MaxTokens (4097 - $tokenCount - 200) -Prompt ($basePrompt -f $commandText) -ErrorAction Stop }
                catch {
                    $PSCmdlet.WriteError($_)
                    continue
                }
                [PSCustomObject]@{
                    Command = $commandObject.Name
                    Code = $Code
                    Help = $help
                }
            }
        }
    }
}

<#
This is an example configuration file
 
By default, it is enough to have a single one of them,
however if you have enough configuration settings to justify having multiple copies of it,
feel totally free to split them into multiple files.
#>


<#
# Example Configuration
Set-PSFConfig -Module 'PSMD.OpenAI' -Name 'Example.Setting' -Value 10 -Initialize -Validation 'integer' -Handler { } -Description "Example configuration setting. Your module can then use the setting using 'Get-PSFConfigValue'"
#>


Set-PSFConfig -Module 'PSMD.OpenAI' -Name 'Import.DoDotSource' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be dotsourced on import. By default, the files of this module are read as string value and invoked, which is faster but worse on debugging."
Set-PSFConfig -Module 'PSMD.OpenAI' -Name 'Import.IndividualFiles' -Value $false -Initialize -Validation 'bool' -Description "Whether the module files should be imported individually. During the module build, all module code is compiled into few files, which are imported instead by default. Loading the compiled versions is faster, using the individual files is easier for debugging and testing out adjustments."

Set-PSFConfig -Module 'PSMD.OpenAI' -Name 'Default.Resource' -Value '' -Initialize -Validation string -Description "The default OpenAI resource to connect to."
Set-PSFConfig -Module 'PSMD.OpenAI' -Name 'Default.Deployment' -Value '' -Initialize -Validation string -Description "The default OpenAI deployment to connect to."

<#
Stored scriptblocks are available in [PsfValidateScript()] attributes.
This makes it easier to centrally provide the same scriptblock multiple times,
without having to maintain it in separate locations.
 
It also prevents lengthy validation scriptblocks from making your parameter block
hard to read.
 
Set-PSFScriptblock -Name 'PSMD.OpenAI.ScriptBlockName' -Scriptblock {
     
}
#>


<#
# Example:
Register-PSFTeppScriptblock -Name "PSMD.OpenAI.alcohol" -ScriptBlock { 'Beer','Mead','Whiskey','Wine','Vodka','Rum (3y)', 'Rum (5y)', 'Rum (7y)' }
#>


<#
# Example:
Register-PSFTeppArgumentCompleter -Command Get-Alcohol -Parameter Type -Name PSMD.OpenAI.alcohol
#>


# The connected token. Should implement automatic token refresh and the .GetHeader() method
$script:token = New-Token -Empty

New-PSFLicense -Product 'PSMD.OpenAI' -Manufacturer 'Friedrich Weinmann' -ProductVersion $script:ModuleVersion -ProductType Module -Name MIT -Version "1.0.0.0" -Date (Get-Date "2023-04-12") -Text @"
Copyright (c) 2023 Friedrich Weinmann
 
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
 
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
 
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"@

#endregion Load compiled code