php-llm-agent/lib/ResolveActions.function.php
Frederico @ VilaRosa02 436e0e57c5 new version
2025-09-10 11:40:03 +00:00

53 lines
1.8 KiB
PHP

<?php
$actions = [];
class Action {
private $function_name;
private $no_of_args;
private $args_type;
public function setFunctionName(string $s) { $this->function_name = $s; return $this; }
public function setArgumentsTypes(array $a) { $this->args_type = $a; $this->no_of_args = count($a); return $this; }
public function getExpectedNoOfArguments() { return $this->no_of_args; }
public function getFunctionName() { return $this->function_name; }
}
function registerAction(Action $a) { global $actions; $actions[$a->getFunctionName()] = $a; return true;}
// Register all actions available
require_once __DIR__."/actions/index.php";
function ResolveActions(string $text) {
global $actions;
$function_name_regex_format = "@([a-zA-Z_][a-zA-Z0-9_]+)";
$arguments_regex_format = "([\w:\/\.-]+)";
if (preg_match("/$function_name_regex_format( |$)/",$text,$matches)) {
$function_name = $matches[1];
if ( !isset($actions[$function_name]) ||
!function_exists($function_name )) return "[[ Action $function_name not available. ]]";
$action = $actions[$function_name];
// Fetch the arguments
$reg_exp = array_fill(0,$action->getExpectedNoOfArguments(),"([\w:\/\.-]+)");
array_unshift($reg_exp, $function_name_regex_format);
if (!preg_match("/".implode(" ",$reg_exp)."/",$text,$matches))
return "[[ Action $function_name was passed with wrong number of arguemnts. Expected: ".$a->getExpectedNoOfArguments()." ]]";
$full_action_requested_string = $matches[0];
array_shift($matches); // Clip the first whole-string result
array_shift($matches); // Clip the function name
$arguments = $matches;
$actionResult = call_user_func_array($function_name, $arguments);
$text = str_replace($full_action_requested_string,$actionResult,$text);
}
return $text;
}