php-llm-agent/lib/ParseExpandersIteratorsCompressors.function.php
2025-09-18 15:42:38 +00:00

50 lines
1.4 KiB
PHP

<?php
function ParseExpandersIteratorsCompressors(&$prompt, $stage = "input",$options = []) {
global $debug_level;
$return_array = is_array($prompt);
$processed = false;
$output = [];
$prompt_as_array = is_array($prompt)?$prompt:explode("\n",$prompt);
// 1. LOOP through the lines to find COMMANDS
foreach($prompt_as_array as $line) {
// 1.1 Expand and chunk lines into arrays
if (preg_match("/^<l([0-9]+)/",trim($line),$matches)) {
$output = array_chunk($output,$matches[1]);
$output = array_map(fn($l)=>implode("\n",$l),$output);
$return_array = true;
$processed = true;
continue;
}
// 1.2 Process each chunk
if (preg_match("/^\|\s*(.+)$/",trim($line),$matches)) {
$sys_command = $matches[1];
$processed_output = [];
foreach($output as $i => $chunk) {
if ($debug_level >= 2) echo "-- DEBUG -- : Processing chunk $i of ".count($output)."\n";
$processed_output[] = LlamaCli($chunk,$sys_command,$options);
}
$output = $processed_output;
$processed = true;
$return_array = true;
continue;
}
// 1.3 Compress into text or json
if (preg_match("/^>(json|l)/",trim($line),$matches)) {
if ($matches[1] == "json") $output = json_encode($output);
if ($matches[1] == "l") $output = implode("\n",$output);
$return_array = false;
$processed = true;
continue;
}
$output[] = $line;
}
$prompt = ($return_array?$output:(is_array($output)?implode("\n",$output):$output));
return $processed;
}