functions/LemonAI-StartAISession.ps1

function LemonAI-StartAISession($session_port=11434){
    try {
        $AIJob=(Get-Job -Name "aisess-$session_port" -ErrorAction SilentlyContinue)
        if($AIJob){
            if($AIJob.State -eq "Completed"){
                Remove-Job $AIJob
                $AIJob=$false
            }
        }
        if($AIJob){return $AIJob}
        else {
            $newSess=(Start-Job -Name "aisess-$session_port" -ArgumentList $session_port -ScriptBlock {
                $session_port = $args[0]
                try {
                    [System.Environment]::SetEnvironmentVariable("OLLAMA_HOST","127.0.0.1:$session_port")
                    Write-Output "safepass"
                    ollama serve
                }catch {
                    Write-Output "unsafepass"
                    if($_.Exception.Message -like "*'ollama' is not recognized*"){
                        Write-Error -Exception "Ollama is not installed." -Message "You must use the 'LemonAI-OllamaInstall' command for first time use. Executing now..."
                        #LemonAI-OllamaInstall
                    }
                    else {Write-Output "Error: $_.Exception.Message"}
                }
            })
            while(-not $newSess.ChildJobs[0].Output[0]){ Start-Sleep -Milliseconds 300 }
            Start-Sleep -Seconds 1
            if($newSess.ChildJobs[0].Error){
                if($newSess.ChildJobs[0].Error[0].Exception.Message -eq "Ollama is not installed."){
                    Write-Error $newSess.ChildJobs[0].Error[0]
                    LemonAI-OllamaInstall
                    return $null
                }
                
            }
            return $newSess
        }
    }
    catch {
        Write-Output "Error: $_.Exception.Message"
    }
}