artificial.lv

Atvērtā pirmkoda mākslīgā intelekta aģents

Nevis tikai AI, kas ģenerē kodu — aģents, kas pats instalē rīkus, automatizē pārlūku un izpilda darbu Tavā Windows datorā. Izmēģini jau tagad.

Izmēģini šādi

Programmēt nav jāprot. Pasaki, ko vēlies izdarīt, un aģents pats izdomās, kādus rīkus izmantot, uzrakstīs kodu un izpildīs to Tavā datorā. Tas var arī uzlabot pats sevi: nokopēt savu kodu, uzinstalēt jaunas bibliotēkas un turpināt ar jaunām spējām. Nokopē uzdevumu un ielīmē aģentā.

  1. Izveido mājaslapu

    Pasaki, kādu lapu vēlies. Aģents izveidos failus, dizainu, funkcijas un atvērs rezultātu pārlūkā.

    Izveido man modernu mājaslapu autoservisam latviešu valodā. Saglabā uz Desktop un atver pārlūkā.
  2. Automatizē darbu pārlūkā

    Var uzinstalēt vajadzīgos rīkus, palaist pārlūku un automatizēt darbības internetā.

    Uzinstalē nepieciešamos rīkus un izveido skriptu, kas atver šo mājaslapu, aizpilda formu ar testa datiem un parāda man rezultātu.
  3. Uzlabo pats sevi

    Nokopē savu kodu, modificē un iegūst jaunas spējas — piemēram, pārlūku kā cilvēks.

    Izveido uz Desktop mapīti, nokopē tur pats savu kodu un turpini strādāt ar kopiju. Modificē sevi tā, lai vari apskatīt mājaslapas kā cilvēks — uzinstalē Puppeteer un izmanto to tālāk.
  4. Savāc informāciju no interneta

    Atver vairākas lapas, nolasa datus, salīdzina tos un sagatavo rezultātu.

    Atrodi piecu Latvijas interneta veikalu cenas šim produktam un izveido salīdzinājuma tabulu uz Desktop.
  5. Aizpildi atkārtojošos darbus

    Ja katru dienu pārlūkā jāveic viena un tā pati darbība, aģents uzraksta automatizāciju.

    Izveido programmu, kas atver mūsu administrācijas lapu, ielogojas, atver pasūtījumu sadaļu un saglabā jaunāko pasūtījumu sarakstu.
  6. Izveido rīku uzņēmumam

    Apraksti problēmu parastā valodā — lokāla programma, kalkulators, datu apstrāde vai neliela sistēma.

    Izveido programmu, kurā ievadu klientu, nostrādātās stundas un stundas likmi, un tā sagatavo darba tāmi PDF formātā.
  7. Apstrādā failus

    Meklē, pārsauc, kopē, pārveido un analizē failus Tavā datorā.

    Atrodi visus PDF failus mapē Dokumenti, sakārto tos pa gadiem un pirms pārvietošanas parādi, ko darīsi.
  8. Strādā ar Excel un CSV

    Raksta skriptus datu apstrādei, apvieno Excel/CSV failus un veido pārskatus.

    Apvieno visus Excel (.xlsx) un CSV failus no šīs mapes vienā Excel failā un izveido kopsavilkumu par pārdošanas apjomiem. Ja trūkst rīku Excel lasīšanai, uzinstalē tos.
  9. Pārbaudi datoru

    Administratora tiesības — Windows, procesi, servisi, diski, tīkls un konfigurācija.

    Pārbaudi, kas šobrīd visvairāk noslogo manu datoru, un paskaidro, ko var droši optimizēt.
  10. Uzinstalē nepieciešamo programmatūru

    Ja trūkst rīka, aģents to uzinstalē un izmanto.

    Pārbaudi, vai man ir Node.js un Git. Ja nav, uzinstalē tos un pārbaudi, vai viss strādā.
  11. Izveido automatizāciju no nulles

    Nav obligāti jāzina, kā tehniski atrisināt problēmu — apraksti rezultātu.

    Katru rītu man vajag lejupielādēt failu no mājaslapas, pārsaukt to ar šodienas datumu un ielikt konkrētā mapē. Uztaisi to automātiski.

Ko tas spēj

Viens PowerShell logs ar administratora tiesībām. Tu apraksti rezultātu, kuru vēlies, un AI aģents pats raksta un izpilda nepieciešamās komandas un kodu. Tas nav ieslēgts tikai tajās funkcijās, ar kurām tika lejupielādēts: var nokopēt un modificēt pats savu pirmkodu, uzinstalēt jaunus rīkus un iegūt jaunas spējas darba gaitā — negaidot jaunu artificial.lv versiju.

Tev nav jāzina PowerShell vai programmēšana. Pasaki aģentam, ko gribi panākt, nevis kā to uzprogrammēt.

Izmēģini vienas minūtes laikā

Viens neliels .cmd fails: lejupielādē, palaid ar dubultklikšķi un sāc sarunu. PowerShell komandas pašam nav jāraksta.

  1. Lejupielādē failu Install-artificial-lv-agent.cmd.
  2. Atver to ar dubultklikšķi. Ja Windows parāda brīdinājumu, izvēlies More info un pēc tam Run anyway.
  3. Administratora tiesību pieprasījuma logā nospied Yes. Aģents tiks palaists automātiski.
  4. Vari sarunāties latviski vai angliski — piemēram, Izveido vietni uz Desktop · /model gpt-4o · Esc, S vai Q aptur izpildi.

Pirmkods

Pilnībā atvērts pirmkods. Vari to lasīt, kopēt, modificēt un pielāgot savām vajadzībām. Tas ir tas pats PowerShell AI aģents, kuru lejupielādē instalētājs.

Lejupielādēt .ps1 Skatīt neapstrādāto failu 845 rindas · 32.2 KB · https://artificial.lv/api/v1
#Requires -Version 5.1
<#
.SYNOPSIS
  artificial.lv — ģenerisks Admin AI aģents latviešu valodā (GPT 5.4).

.DESCRIPTION
  Palaid kā Administrator. Tērzē latviski; aģents raksta un izpilda PowerShell,
  var kodēt vietnes/programmas, vadīt datoru, meklēt info tīklā.
  Run: powershell -NoProfile -ExecutionPolicy Bypass -File artificial_agent_lv.ps1
#>
$ErrorActionPreference = 'Continue'
$script:ArtBundled = $true
$script:ArtApiKey = 'sk-art-free'
$script:ArtModel = 'gpt-5.4'
$script:ArtApiBase = 'https://artificial.lv/api/v1'
$script:ArtUserAgent = 'ArtificialAgentLV/1.0'
$script:ArtKnownModels = @()   # filled from GET /models when needed
$script:ArtMaxHistoryMessages = 16   # keep system + last N messages (cuts token cost)
$script:ArtMaxResultChars = 2500     # truncate command output in chat history

Set-StrictMode -Version Latest
# Output UTF-8 for display; do NOT force InputEncoding=UTF8 — that breaks Read-Host with Latvian/special chars on Windows PowerShell 5.1.
try {
    [Console]::OutputEncoding = [Text.Encoding]::UTF8
    $OutputEncoding = [Text.Encoding]::UTF8
    chcp 65001 | Out-Null
} catch {}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

# Reduce accidental console "freeze" (click-select / QuickEdit). Ctrl+S still pauses old consoles — use Esc/S to stop the agent, Ctrl+Q to unfreeze.
try {
    $t = Add-Type -PassThru -Name ArtConsoleMode -Namespace ArtificialLv -MemberDefinition @'
[DllImport("kernel32.dll", SetLastError=true)] public static extern IntPtr GetStdHandle(int n);
[DllImport("kernel32.dll", SetLastError=true)] public static extern bool GetConsoleMode(IntPtr h, out uint mode);
[DllImport("kernel32.dll", SetLastError=true)] public static extern bool SetConsoleMode(IntPtr h, uint mode);
'@ -ErrorAction Stop
    $h = $t::GetStdHandle(-10)
    $mode = [uint32]0
    if ($t::GetConsoleMode($h, [ref]$mode)) {
        $ENABLE_QUICK_EDIT = [uint32]0x0040
        $ENABLE_EXTENDED = [uint32]0x0080
        $newMode = ($mode -bor $ENABLE_EXTENDED) -band (-bnot $ENABLE_QUICK_EDIT)
        [void]$t::SetConsoleMode($h, $newMode)
    }
} catch {}

# --- Admin elevate ---
function Test-IsAdmin {
    $id = [Security.Principal.WindowsIdentity]::GetCurrent()
    $p = New-Object Security.Principal.WindowsPrincipal($id)
    return $p.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Get-ArtSelfPath {
    if ($PSCommandPath) { return $PSCommandPath }
    if ($MyInvocation.MyCommand.Path) { return $MyInvocation.MyCommand.Path }
    return $null
}

function Get-ArtLaunchContext {
    $scriptPath = Get-ArtSelfPath
    $scriptDir = $null
    if ($scriptPath) {
        try { $scriptDir = [IO.Path]::GetDirectoryName($scriptPath) } catch {}
    }
    if (-not $scriptDir -and $PSScriptRoot) { $scriptDir = $PSScriptRoot }
    $cwd = $null
    try { $cwd = (Get-Location -PSProvider FileSystem).Path } catch {
        try { $cwd = [Environment]::CurrentDirectory } catch {}
    }
    return [pscustomobject]@{
        ScriptPath = $scriptPath
        ScriptDir  = $scriptDir
        Cwd        = $cwd
        Desktop    = [Environment]::GetFolderPath('Desktop')
        UserProfile = $env:USERPROFILE
    }
}
if ($env:ARTIFICIAL_AGENT_SMOKE -ne '1' -and -not (Test-IsAdmin)) {
    $self = Get-ArtSelfPath
    if (-not $self) {
        Write-Host 'Nevar atrast aģenta .ps1 ceļu. Palaid ar: powershell -File ceļš\artificial_agent_lv.ps1' -ForegroundColor Red
        Write-Host 'Enter, lai aizvērtu...'
        try { Read-Host | Out-Null } catch {}
        exit 1
    }
    try { Unblock-File -LiteralPath $self -ErrorAction SilentlyContinue } catch {}
    Write-Host 'Pieprasu Administrator tiesības...' -ForegroundColor Yellow
    $psi = New-Object System.Diagnostics.ProcessStartInfo
    $psi.FileName = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
    $psi.Arguments = "-NoProfile -ExecutionPolicy Bypass -File `"$self`""
    $psi.UseShellExecute = $true
    $psi.Verb = 'runas'
    try {
        [Diagnostics.Process]::Start($psi) | Out-Null
    } catch {
        Write-Host 'Nepieciešamas Administrator tiesības (UAC atcelts?).' -ForegroundColor Red
        Write-Host 'Enter, lai aizvērtu...'
        try { Read-Host | Out-Null } catch {}
    }
    exit
}

$script:ArtLaunch = Get-ArtLaunchContext

# --- API client ---
function Get-ArtConfig {
    $model = $script:ArtModel
    if ($env:ARTIFICIAL_MODEL) { $model = $env:ARTIFICIAL_MODEL }
    $apiKey = $script:ArtApiKey
    if ($env:ARTIFICIAL_API_KEY) { $apiKey = $env:ARTIFICIAL_API_KEY }
    $apiBase = $script:ArtApiBase
    if ($env:ARTIFICIAL_API_BASE) { $apiBase = $env:ARTIFICIAL_API_BASE }
    return [pscustomobject]@{
        apiKey  = $apiKey
        model   = $model
        apiBase = $apiBase
    }
}

function Get-ArtModelsFromApi {
    if (-not $script:Config) { $script:Config = Get-ArtConfig }
    $uri = ($script:Config.apiBase.TrimEnd('/')) + '/models'
    $req = [System.Net.HttpWebRequest]::Create($uri)
    $req.Method = 'GET'
    $req.Accept = 'application/json'
    $req.Timeout = 15000
    $req.UserAgent = $script:ArtUserAgent
    if ($script:Config.apiKey) {
        $req.Headers['Authorization'] = 'Bearer ' + $script:Config.apiKey
    }
    $resp = $req.GetResponse()
    try {
        $reader = New-Object System.IO.StreamReader($resp.GetResponseStream(), [Text.Encoding]::UTF8)
        $raw = $reader.ReadToEnd()
        $reader.Close()
    } finally {
        $resp.Close()
    }
    $obj = $raw | ConvertFrom-Json
    $list = @()
    if ($obj -and $obj.data) {
        $list = @($obj.data | ForEach-Object { [string]$_.id } | Where-Object { $_ })
    }
    if ($list.Count -eq 0) {
        throw 'API neatgrieza modeļu sarakstu.'
    }
    $script:ArtKnownModels = $list
    return $list
}

function Set-ArtModel {
    param([Parameter(Mandatory)][string]$Name)
    $n = $Name.Trim()
    if (-not $n) { throw 'Norādi modeli, piem. gpt-4o' }
    $list = @()
    try {
        $list = @(Get-ArtModelsFromApi)
    } catch {
        throw ("Nevar ielādēt modeļus no API: {0}" -f $_.Exception.Message)
    }
    if ($list -notcontains $n) {
        throw "Nezināms modelis '$n'. Atļautie: $($list -join ', ')"
    }
    $script:ArtModel = $n
    if ($script:Config) {
        $script:Config | Add-Member -NotePropertyName model -NotePropertyValue $n -Force
    } else {
        $script:Config = Get-ArtConfig
    }
    return $n
}

function ConvertFrom-ArtAiJson {
    param([Parameter(Mandatory)][string]$Content)
    $text = $Content.Trim()
    if ($text -match '(?s)```(?:json)?\s*(.*?)\s*```') { $text = $Matches[1].Trim() }
    $start = $text.IndexOf('{')
    $end = $text.LastIndexOf('}')
    if ($start -ge 0 -and $end -gt $start) {
        $text = $text.Substring($start, $end - $start + 1)
    }
    return ($text | ConvertFrom-Json)
}

function Truncate-ArtText {
    param([string]$Text, [int]$MaxChars = 2500)
    if ($null -eq $Text) { return '' }
    if ($Text.Length -le $MaxChars) { return $Text }
    return ($Text.Substring(0, $MaxChars) + "`n...[truncated $($Text.Length - $MaxChars) chars]")
}

function Compact-ArtChatMessages {
    if ($null -eq $script:ChatMessages -or $script:ChatMessages.Count -le 1) { return }
    $max = [Math]::Max(4, [int]$script:ArtMaxHistoryMessages)
    if ($script:ChatMessages.Count -le ($max + 1)) { return }
    $keep = New-Object System.Collections.Generic.List[object]
    $keep.Add($script:ChatMessages[0])
    $start = $script:ChatMessages.Count - $max
    for ($i = $start; $i -lt $script:ChatMessages.Count; $i++) {
        $keep.Add($script:ChatMessages[$i])
    }
    $script:ChatMessages = $keep
}

function Format-ArtApiError {
    param(
        [int]$StatusCode = 0,
        [string]$Message = '',
        [string]$Body = ''
    )
    $blob = (($Message) + "`n" + ($Body)).Trim()
    $isQuota = ($StatusCode -eq 429) -or (
        $blob -match '(?i)free tier|spend limit|exhausted|rate_limit|too many requests|insufficient balance|prepaid access'
    )
    if ($isQuota) {
        return @"
Tokenu / bezmaksas limits ir izsmelts.

Papildini bilanci:
  1) Atver https://artificial.lv
  2) Ieiet kontā (Log in)
  3) Nospied «Pirkt API tokenus»

Pēc apmaksas lejupielādē personīgo aģentu no konta (vai iestati ARTIFICIAL_API_KEY ar savu sk-art-u-… atslēgu).
"@.Trim()
    }
    if ($Body) { return "API kļūda: $Message" }
    return "API kļūda: $Message"
}

function Invoke-ArtChat {
    param(
        [Parameter(Mandatory)]$Config,
        [Parameter(Mandatory)][System.Collections.IList]$Messages,
        [string]$Label = 'Domāju'
    )
    $uri = ($Config.apiBase.TrimEnd('/')) + '/chat/completions'
    $bodyObj = @{ model = $Config.model; messages = @($Messages) }
    $json = $bodyObj | ConvertTo-Json -Depth 12
    $bodyBytes = [Text.Encoding]::UTF8.GetBytes($json)
    $raw = $null
    $req = $null
    try {
        $req = [System.Net.HttpWebRequest]::Create($uri)
        $req.Method = 'POST'
        $req.Accept = 'application/json'
        $req.ContentType = 'application/json; charset=utf-8'
        $req.Timeout = 300000
        $req.ReadWriteTimeout = 300000
        $req.UserAgent = $script:ArtUserAgent
        $req.AutomaticDecompression = [System.Net.DecompressionMethods]::GZip -bor [System.Net.DecompressionMethods]::Deflate
        $null = $req.Headers.Add('Authorization', "Bearer $($Config.apiKey)")
        $req.ContentLength = $bodyBytes.Length
        $reqStream = $req.GetRequestStream()
        try { $reqStream.Write($bodyBytes, 0, $bodyBytes.Length) } finally { $reqStream.Close() }

        Write-Host -NoNewline ("  {0}" -f $Label) -ForegroundColor DarkGray
        $sw = [Diagnostics.Stopwatch]::StartNew()
        $ar = $req.BeginGetResponse($null, $null)
        $dots = 0
        while (-not $ar.IsCompleted) {
            if (Test-AgentStopRequested) {
                try { $req.Abort() } catch {}
                Write-Host (" {0}" -f $sw.Elapsed.ToString('mm\:ss')) -ForegroundColor DarkGray
                throw 'ART_CANCELLED'
            }
            Start-Sleep -Milliseconds 120
            $dots++
            if (($dots % 3) -eq 0) {
                try { [Console]::Write('.') } catch { Write-Host -NoNewline '.' }
            }
        }
        Write-Host (" {0}" -f $sw.Elapsed.ToString('mm\:ss')) -ForegroundColor DarkGray

        try {
            $resp = $req.EndGetResponse($ar)
        } catch [System.Net.WebException] {
            if ($_.Exception.Status -eq [System.Net.WebExceptionStatus]::RequestCanceled) {
                throw 'ART_CANCELLED'
            }
            throw
        }
        try {
            $reader = New-Object System.IO.StreamReader($resp.GetResponseStream(), [Text.Encoding]::UTF8, $true)
            try { $raw = $reader.ReadToEnd() } finally { $reader.Close() }
        } finally { $resp.Close() }
    } catch {
        $em = [string]$_.Exception.Message
        if (-not $em) { $em = [string]$_ }
        if ($em -eq 'ART_CANCELLED' -or $em -like '*ART_CANCELLED*') { throw 'ART_CANCELLED' }
        $ex = $_.Exception
        while ($ex.InnerException) { $ex = $ex.InnerException }
        if ($ex -is [System.Net.WebException]) {
            if ($ex.Status -eq [System.Net.WebExceptionStatus]::RequestCanceled) { throw 'ART_CANCELLED' }
            $msg = $ex.Message
            $errBody = ''
            $statusCode = 0
            try {
                if ($ex.Response) {
                    try { $statusCode = [int]$ex.Response.StatusCode } catch {}
                    $er = New-Object System.IO.StreamReader($ex.Response.GetResponseStream(), [Text.Encoding]::UTF8, $true)
                    $errBody = $er.ReadToEnd(); $er.Close()
                    if ($errBody) { $msg += "`n" + $errBody }
                }
            } catch {}
            throw (Format-ArtApiError -StatusCode $statusCode -Message $msg -Body $errBody)
        }
        throw
    }
    if ([string]::IsNullOrWhiteSpace($raw)) { throw 'API atbilde tukša.' }
    $parsed = $null
    try { $parsed = $raw | ConvertFrom-Json } catch {
        throw "API JSON kļūda: $($_.Exception.Message)"
    }
    $choices = @($parsed.choices)
    if ($choices.Count -lt 1) { throw 'API neatdeva choices.' }
    $msgObj = $choices[0].message
    if ($null -eq $msgObj) { throw 'API neatdeva message.' }
    return [string]$msgObj.content
}

# --- Optional shortcuts (aģents var arī rakstīt brīvu PowerShell) ---
$script:ArtActions = [ordered]@{
    pc_overview = @{
        Id = 'pc_overview'; Title = 'PC pārskats'
        Description = 'CPU, RAM, disks, OS — īss statuss'
        Script = {
            $os = Get-CimInstance Win32_OperatingSystem
            $cs = Get-CimInstance Win32_ComputerSystem
            $disk = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID='C:'"
            [pscustomobject]@{
                Dators = $cs.Name
                Lietotajs = $env:USERNAME
                OS = "$($os.Caption) $($os.Version)"
                RAM_GB = [math]::Round($cs.TotalPhysicalMemory / 1GB, 1)
                C_Brivs_GB = if ($disk) { [math]::Round($disk.FreeSpace / 1GB, 1) } else { $null }
                Procesi = @(Get-Process).Count
            } | Format-List | Out-String
        }
    }
    open_url = @{
        Id = 'open_url'; Title = 'Atvērt URL pārlūkā'
        Description = 'Start-Process noklusējuma pārlūkā (piem. https://artificial.lv)'
        Script = {
            $u = $env:ART_OPEN_URL
            if (-not $u) { $u = 'https://artificial.lv' }
            Start-Process $u
            "Atvērts: $u"
        }
    }
    web_get = @{
        Id = 'web_get'; Title = 'Ielādēt tīmekļa lapu (teksts)'
        Description = 'Invoke-WebRequest -UseBasicParsing; URL no $env:ART_WEB_URL'
        Script = {
            $u = $env:ART_WEB_URL
            if (-not $u) { throw 'Iestati $env:ART_WEB_URL' }
            $r = Invoke-WebRequest -Uri $u -UseBasicParsing -TimeoutSec 60
            $t = $r.Content
            if ($t.Length -gt 6000) { $t = $t.Substring(0, 6000) + "`n...(saīsināts)" }
            "Status=$($r.StatusCode) Len=$(@($r.Content).Length)`n$t"
        }
    }
    list_desktop = @{
        Id = 'list_desktop'; Title = 'Darbvirsmas faili'
        Description = 'Parāda Desktop saturu'
        Script = {
            Get-ChildItem -LiteralPath ([Environment]::GetFolderPath('Desktop')) |
                Select-Object Mode, Length, LastWriteTime, Name |
                Format-Table -AutoSize | Out-String
        }
    }
    make_hello_html = @{
        Id = 'make_hello_html'; Title = 'Izveidot hello.html uz Desktop'
        Description = 'Vienkārša HTML piemēra lapa'
        Script = {
            $path = Join-Path ([Environment]::GetFolderPath('Desktop')) 'artificial-hello.html'
            @'
<!DOCTYPE html>
<html lang="lv">
<head>
  <meta charset="utf-8">
  <title>Sveiki no artificial.lv</title>
  <style>
    body{font-family:system-ui;margin:0;min-height:100vh;display:grid;place-items:center;
      background:linear-gradient(145deg,#0f172a,#14532d);color:#ecfdf5}
    h1{font-size:clamp(2rem,6vw,4rem);margin:0}
    p{opacity:.8}
  </style>
</head>
<body>
  <main>
    <h1>Sveiki!</h1>
    <p>Šo lapu izveidoja artificial.lv aģents.</p>
  </main>
</body>
</html>
'@ | Set-Content -Path $path -Encoding UTF8
            Start-Process $path
            "Izveidots un atvērts: $path"
        }
    }
    make_ps_tool = @{
        Id = 'make_ps_tool'; Title = 'Izveidot mazu .ps1 rīku uz Desktop'
        Description = 'Piemērs: Show-DiskFree.ps1'
        Script = {
            $path = Join-Path ([Environment]::GetFolderPath('Desktop')) 'Show-DiskFree.ps1'
            @'
#Requires -Version 5.1
Get-CimInstance Win32_LogicalDisk -Filter "DriveType=3" | ForEach-Object {
  [pscustomobject]@{
    Disks = $_.DeviceID
    Kopā_GB = [math]::Round($_.Size/1GB,1)
    Brīvs_GB = [math]::Round($_.FreeSpace/1GB,1)
    Proc = [math]::Round(100*$_.FreeSpace/[math]::Max($_.Size,1),1)
  }
} | Format-Table -AutoSize
'@ | Set-Content -Path $path -Encoding UTF8
            "Izveidots: $path"
        }
    }
}

function Get-ArtActionCatalogText {
    $lines = @('Īsceļi (action_id) — vari arī rakstīt savu powershell:')
    foreach ($key in $script:ArtActions.Keys) {
        $a = $script:ArtActions[$key]
        $lines += "- $($a.Id): $($a.Title) — $($a.Description)"
    }
    return ($lines -join "`n")
}

function Invoke-ArtAction {
    param([Parameter(Mandatory)][string]$ActionId)
    if (-not $script:ArtActions.Contains($ActionId)) { throw "Nezināms action_id: $ActionId" }
    $action = $script:ArtActions[$ActionId]
    $result = & $action.Script
    return [pscustomobject]@{ Ok = $true; ActionId = $ActionId; Title = $action.Title; Output = [string]$result }
}

function Get-ArtAgentSystemPrompt {
    param([string]$CatalogText)
    $ctx = $script:ArtLaunch
    if (-not $ctx) { $ctx = Get-ArtLaunchContext }
    $locBlock = @"
Palaišanas konteksts (izmanto ceļus, kad raksti failus / lasi aģentu):
- Aģenta .ps1 fails: $($ctx.ScriptPath)
- Aģenta mape (kur palaists): $($ctx.ScriptDir)
- Pašreizējā darba mape (PWD): $($ctx.Cwd)
- Desktop: $($ctx.Desktop)
- Lietotāja profils: $($ctx.UserProfile)
Ja lietotājs saka «šeit» / «šajā mapē» bez ceļa — noklusē uz aģenta mapi ($($ctx.ScriptDir)), nevis tikai Desktop.
"@
    @"
Tu esi artificial.lv — ģenerisks AI aģents ar Windows Administrator tiesībām.
Noklusējuma valoda: latviešu. Atbildi latviski, ja vien lietotājs nepārslēdzas uz citu valodu.
Tu ESI pie tastatūras — NEESI čatbots, kas saka «atver CMD pats». Nekad nesaki, ka tev nav admin tiesību.

$locBlock

Ko tu maki (raksti PowerShell commands[] un izpildi):
1) Dators: procesi, pakalpojumi, diski, tīkls, reģistrs, uzdevumu plānotājs, instalēšana/atinstalēšana, faili/mapes.
2) Programmēšana: izveido HTML/CSS/JS vietnes, Python/Node/C#/PowerShell skriptus, .bat/.ps1 rīkus, saglabā uz Desktop vai kur lietotājs lūdz, palaid/testē.
3) Informācija: Invoke-WebRequest -UseBasicParsing (BEZ ParsedHtml), lejupielāde, API izsaukumi, meklēšana (atver pārlūku vai ielādē URL).
4) Automatizācija: Windows UI (Start-Process), failu pārvaldība, backup, tīrīšana, diagnostika.
5) Pašlabošana: vari lasīt/rediģēt šo aģenta .ps1 failu ($($ctx.ScriptPath)); izmaiņas stājas spēkā pēc restarta.

Labi piemēri (commands[].powershell):
A) Vietne uz Desktop:
`$dir = Join-Path ([Environment]::GetFolderPath('Desktop')) 'mana-lapa'
New-Item -ItemType Directory -Path `$dir -Force | Out-Null
@'
<!DOCTYPE html><html lang="lv"><head><meta charset="utf-8"><title>Mana lapa</title>
<style>body{font-family:Georgia,serif;max-width:40rem;margin:3rem auto;padding:0 1rem}</style>
</head><body><h1>Sveiki</h1><p>Teksts šeit.</p></body></html>
'@ | Set-Content (Join-Path `$dir 'index.html') -Encoding UTF8
Start-Process (Join-Path `$dir 'index.html')
Get-ChildItem `$dir | Format-Table Name,Length | Out-String

B) PC statuss:
Get-CimInstance Win32_OperatingSystem | Select Caption,Version,LastBootUpTime | Format-List | Out-String
Get-Process | Sort CPU -Descending | Select -First 8 Name,CPU,Id | Format-Table | Out-String

C) Meklēt info tīklā (teksts):
`$r = Invoke-WebRequest -Uri 'https://example.com' -UseBasicParsing
`$r.StatusCode; `$r.Content.Substring(0,[Math]::Min(2000,`$r.Content.Length)) | Out-String

D) Mazs rīks:
@'
Write-Host "Šodien: `$(Get-Date -Format 'yyyy-MM-dd HH:mm')"
'@ | Set-Content (Join-Path ([Environment]::GetFolderPath('Desktop')) 'laiks.ps1') -Encoding UTF8

Kā strādā aģenta cilpa:
1) Īsi pasaki latviski, ko dari (message).
2) Ieraksti reālu PowerShell commands[].
3) Nolasi COMMAND RESULT, turpini vai beidz (done=true).
4) Max 3 komandas / gājiens. Vienmēr pipe uz Out-String, ja vajag lasīt rezultātu.
5) Set-StrictMode: NEKAD .Count uz iespējamu vienu objektu — lieto @(`$x).Count.
6) Neizmanto ParsedHtml ar UseBasicParsing.

JSON TIKAI (bez markdown nožogojuma):
{
  "message": "ko tu teiktu lietotājam latviski",
  "commands": [
    {
      "title": "īss nosaukums",
      "powershell": "# tavs skripts",
      "action_id": null,
      "risk": "low"
    }
  ],
  "done": false
}
- Tikai čats / gaidi: commands=[] done=true.
- Restart/shutdown tikai ja lietotājs skaidri lūdz.
- action_id (pēc izvēles) no kataloga; pretējā gadījumā powershell.

$CatalogText
"@
}

# --- UI ---
$script:Config = $null
$script:ChatMessages = New-Object System.Collections.Generic.List[object]
$script:MaxAgentRounds = 12

function Get-ArtLen { param($Value); return @($Value).Count }
function Get-ActionProp {
    param($Action, [string]$Name, $Default = $null)
    $prop = $Action.PSObject.Properties[$Name]
    if ($null -eq $prop) { return $Default }
    return $prop.Value
}

function Write-Sep {
    param([string]$Label = '', [string]$Color = 'DarkGray', [int]$Width = 64)
    if ($Label) {
        $pad = [math]::Max(0, $Width - $Label.Length - 4)
        $left = [math]::Floor($pad / 2)
        $right = $pad - $left
        $line = ('-' * $left) + "[ $Label ]" + ('-' * $right)
        if ($line.Length -lt $Width) { $line += ('-' * ($Width - $line.Length)) }
        Write-Host $line -ForegroundColor $Color
    } else {
        Write-Host ('-' * $Width) -ForegroundColor $Color
    }
}

function Write-Role {
    param([string]$Role, [string]$Text)
    switch ($Role) {
        'assistant' { Write-Host 'AI>  ' -NoNewline -ForegroundColor Green; Write-Host $Text }
        'cmd'       { Write-Host 'CMD> ' -NoNewline -ForegroundColor Magenta; Write-Host $Text }
        'out'       { Write-Host 'OUT> ' -NoNewline -ForegroundColor DarkCyan; Write-Host $Text }
        'error'     { Write-Host 'ERR> ' -NoNewline -ForegroundColor Red; Write-Host $Text }
        default     { Write-Host 'SYS> ' -NoNewline -ForegroundColor DarkYellow; Write-Host $Text }
    }
}

function Clear-ArtKeyBuffer {
    try {
        while ([Console]::KeyAvailable) { $null = [Console]::ReadKey($true) }
    } catch {}
}

function Test-AgentStopRequested {
    try {
        while ([Console]::KeyAvailable) {
            $k = [Console]::ReadKey($true)
            # S / Esc / Q — NOT Ctrl+S (that freezes classic Windows consoles until Ctrl+Q)
            if ($k.Key -eq 'Escape' -or $k.Key -eq 'S' -or $k.Key -eq 'Q') { return $true }
            if ($k.Character -eq 's' -or $k.Character -eq 'S' -or $k.Character -eq 'q' -or $k.Character -eq 'Q') { return $true }
            if ([int]$k.Modifiers -band [ConsoleModifiers]::Control) {
                if ($k.Key -eq 'C') { return $true }
            }
        }
    } catch {}
    return $false
}

function Test-ArtCancelled {
    param($ErrorRecord)
    if ($null -eq $ErrorRecord) { return $false }
    $m = [string]$ErrorRecord.Exception.Message
    if (-not $m) { $m = [string]$ErrorRecord }
    return ($m -eq 'ART_CANCELLED' -or $m -like '*ART_CANCELLED*')
}

function Initialize-ArtChat {
    $catalog = Get-ArtActionCatalogText
    $system = Get-ArtAgentSystemPrompt -CatalogText $catalog
    if ($script:ChatMessages.Count -eq 0) {
        $script:ChatMessages.Add(@{ role = 'system'; content = $system })
    } else {
        $script:ChatMessages[0] = @{ role = 'system'; content = $system }
    }
}

function Invoke-AgentPowerShell {
    param([string]$Title, [string]$Code, [string]$ActionId)
    $title = if ($Title) { $Title } else { 'komanda' }
    Write-Host ''
    Write-Sep -Label 'CMD' -Color 'Magenta'
    Write-Role cmd $title
    try {
        if ($ActionId -and $ActionId -ne 'custom' -and $script:ArtActions.Contains($ActionId)) {
            Write-Host ("  action_id: {0}" -f $ActionId) -ForegroundColor DarkGray
            $result = Invoke-ArtAction -ActionId $ActionId
            $out = [string]$result.Output
        } else {
            if (-not $Code) { throw 'Tukšs powershell un nav action_id.' }
            Write-Sep -Label 'SKRIPTS' -Color 'DarkGray'
            Write-Host $Code -ForegroundColor Gray
            Write-Sep -Color 'DarkGray'
            $out = Invoke-Expression $Code 2>&1 | Out-String
        }
        if ($null -eq $out) { $out = '' }
        $out = [string]$out
        if ($out.Length -gt 8000) { $out = $out.Substring(0, 8000) + "`n...(saīsināts)" }
        if ([string]::IsNullOrWhiteSpace($out)) { $out = '(nav izvades)' }
        Write-Sep -Label 'OUT' -Color 'DarkCyan'
        Write-Role out $out
        Write-Sep -Color 'DarkCyan'
        Write-Host ''
        return [pscustomobject]@{ Ok = $true; Title = $title; Output = $out }
    } catch {
        $err = $_.Exception.Message
        Write-Sep -Label 'ERR' -Color 'Red'
        Write-Role error $err
        Write-Sep -Color 'Red'
        Write-Host ''
        return [pscustomobject]@{ Ok = $false; Title = $title; Output = "ERROR: $err" }
    }
}

function Invoke-AgentLoop {
    param([int]$MaxRounds = 12)
    try {
        if (-not $script:Config) { $script:Config = Get-ArtConfig }
    } catch {
        Write-Role error $_.Exception.Message
        return
    }
    Clear-ArtKeyBuffer

    for ($round = 1; $round -le $MaxRounds; $round++) {
        try {
            if (Test-AgentStopRequested) {
                Write-Role system 'Apturēts. Raksti tālāk.'
                return
            }
            $label = if ($MaxRounds -gt 1) { "Domāju ($round/$MaxRounds)" } else { 'Domāju' }
            Compact-ArtChatMessages
            $raw = Invoke-ArtChat -Config $script:Config -Messages $script:ChatMessages -Label $label
            if ($null -eq $raw) { $raw = '' }
            $raw = [string]$raw
            $script:ChatMessages.Add(@{ role = 'assistant'; content = $raw })

            $parsed = $null
            try { $parsed = ConvertFrom-ArtAiJson -Content $raw } catch { $parsed = $null }
            if (-not $parsed) {
                Write-Role assistant $raw
                Write-Role system 'Atbilde nav JSON — pauzēju. Saki, ko darīt tālāk.'
                return
            }

            $msg = [string](Get-ActionProp $parsed 'message' '')
            if ($msg) { Write-Role assistant $msg }

            $done = $false
            try {
                $doneProp = $parsed.PSObject.Properties['done']
                if ($doneProp -and $null -ne $doneProp.Value) {
                    $done = [System.Convert]::ToBoolean($doneProp.Value)
                }
            } catch { $done = $false }

            $commands = @()
            try {
                $cProp = $parsed.PSObject.Properties['commands']
                if ($cProp -and $null -ne $cProp.Value) { $commands = @($cProp.Value) }
            } catch { $commands = @() }

            if ((Get-ArtLen $commands) -eq 0) { return }

            $resultBlocks = New-Object System.Collections.Generic.List[string]
            foreach ($c in $commands) {
                if (Test-AgentStopRequested) {
                    Write-Role system 'Apturēts pirms nākamās komandas. Raksti tālāk.'
                    return
                }
                $title = [string](Get-ActionProp $c 'title' 'komanda')
                $code = Get-ActionProp $c 'powershell' $null
                if ($null -ne $code) { $code = [string]$code }
                $aid = Get-ActionProp $c 'action_id' $null
                if ($null -ne $aid) { $aid = [string]$aid }

                $exec = Invoke-AgentPowerShell -Title $title -Code $code -ActionId $aid
                $status = if ($exec.Ok) { 'OK' } else { 'KĻŪDA' }
                $histOut = Truncate-ArtText -Text ([string]$exec.Output) -MaxChars $script:ArtMaxResultChars
                $resultBlocks.Add("COMMAND RESULT [$status] $title`n$histOut")
            }

            $follow = ($resultBlocks.ToArray() -join "`n`n")
            if ($done) {
                $script:ChatMessages.Add(@{ role = 'user'; content = "$follow`n(Lietotājs jau saņēma rezultātus. done=true ja beidzi.)" })
                return
            }
            $script:ChatMessages.Add(@{
                role = 'user'
                content = "$follow`nTurpini aģenta cilpu: vēl komandas vai done=true. JSON tikai."
            })
        } catch {
            if (Test-ArtCancelled $_) {
                Write-Role system 'Apturēts (Esc/S/Q). Raksti tālāk.'
                return
            }
            Write-Role error $_.Exception.Message
            Write-Role system 'Gājiens pārtraukts kļūdas dēļ — saki, ko darīt tālāk.'
            return
        }
    }
    Write-Role system 'Sasniegts maksimālais gājienu skaits. Saki, vai turpināt.'
}

function Send-ArtMessage {
    param([string]$Text)
    try {
        if ($null -eq $Text) { return }
        $Text = [string]$Text
        $Text = $Text.Trim()
        if (-not $Text) { return }
        if (-not $script:Config) { $script:Config = Get-ArtConfig }
        if ($null -eq $script:ChatMessages) {
            $script:ChatMessages = New-Object System.Collections.Generic.List[object]
        }
        Initialize-ArtChat
        $script:ChatMessages.Add(@{ role = 'user'; content = $Text })
        Invoke-AgentLoop -MaxRounds $script:MaxAgentRounds
    } catch {
        Write-Role error $_.Exception.Message
        Write-Role system 'Kļūda — saruna turpinās. Mēģini vēlreiz vai /jauns.'
    }
}

# --- boot ---
if ($env:ARTIFICIAL_AGENT_SMOKE -eq '1') {
    try {
        $script:ArtLaunch = Get-ArtLaunchContext
        $script:Config = Get-ArtConfig
        Write-Host "SMOKE_OK model=$($script:Config.model) dir=$($script:ArtLaunch.ScriptDir)"
        exit 0
    } catch {
        Write-Host ("SMOKE_FAIL: {0}" -f $_.Exception.Message)
        exit 1
    }
}

try {
    $script:ArtLaunch = Get-ArtLaunchContext
    $script:Config = Get-ArtConfig
    Initialize-ArtChat
    Write-Role assistant 'Sveiks! Esmu artificial.lv powershell aģents. Ko vēlies paveikt?'
} catch {
    Write-Role error $_.Exception.Message
    Write-Role system 'Palaišana ar kļūdu — vari tomēr rakstīt; API mēģinās vēlreiz.'
}

while ($true) {
    try {
        Clear-ArtKeyBuffer
        Write-Host ''
        Write-Host -NoNewline '> ' -ForegroundColor Cyan
        $line = $null
        try { $line = Read-Host } catch {
            Write-Role error $_.Exception.Message
            continue
        }
        if ($null -eq $line) { break }
        $cmd = [string]$line
        $cmd = $cmd.Trim()
        if (-not $cmd) { continue }

        switch -Regex ($cmd) {
            '^(?i)/?(quit|exit|q|iziet)$' {
                Write-Host 'Uz redzēšanos.'
                exit 0
            }
            '^(?i)/?(help|palidziba|pal[iī]dz[iī]ba)$' {
                Write-Host @"
  Raksti brīvi latviski — aģents izpilda PowerShell.
  /model            Pašreizējais modelis (+ saraksts no API)
  /model gpt-4o     Nomainīt modeli
  /palidziba        Šī palīdzība
  /jauns            Jauna saruna (notīra kontekstu)
  /quit             Iziet
"@ -ForegroundColor DarkGray
                continue
            }
            '^(?i)/?model(\s+(.+))?$' {
                $arg = $Matches[2]
                if (-not $arg) {
                    try {
                        if (-not $script:Config) { $script:Config = Get-ArtConfig }
                        $models = @(Get-ArtModelsFromApi)
                        Write-Role system ("Modelis: {0}  |  pieejamie: {1}" -f $script:Config.model, ($models -join ', '))
                    } catch {
                        Write-Role error $_.Exception.Message
                    }
                } else {
                    try {
                        $m = Set-ArtModel -Name $arg
                        Write-Role system "Modelis iestatīts: $m"
                    } catch {
                        Write-Role error $_.Exception.Message
                    }
                }
                continue
            }
            '^(?i)/?(jauns|new|clear)$' {
                try {
                    $script:ChatMessages = New-Object System.Collections.Generic.List[object]
                    Initialize-ArtChat
                    Write-Role system 'Jauna saruna. Konteksts notīrīts.'
                } catch {
                    Write-Role error $_.Exception.Message
                }
                continue
            }
            default {
                Send-ArtMessage -Text $cmd
            }
        }
    } catch [System.Management.Automation.PipelineStoppedException] {
        Write-Role system 'Pārtraukts (Ctrl+C). Raksti tālāk vai /quit.'
    } catch {
        Write-Role error $_.Exception.Message
        Write-Role system 'Kļūda ievadē/cilpā — turpini rakstīt.'
    }
}

Write-Host ''
Write-Host 'Sesija beigusies. Enter, lai aizvērtu...' -ForegroundColor DarkGray
try { Read-Host | Out-Null } catch {}

Arī API

POST https://artificial.lv/api/v1/chat/completions
Authorization: Bearer sk-art-free

{ "model": "gpt-5.4", "messages": [{"role":"user","content":"Hello"}] }

API statuss

Mini forums

Dalies ar idejām. Konts nav vajadzīgs — izvēlies vārdu. Atver tēmu, lai lasītu un komentētu.

Vēl nav tēmu — esi pirmais.