From b4b67e00bd7b705b1f6497f953ae562d0ea3af64 Mon Sep 17 00:00:00 2001 From: Maximilian Kenfenheuer Date: Tue, 28 Jan 2025 22:58:02 +0100 Subject: [PATCH] refactor: function argument parsing using named regex (#4708) Signed-off-by: Maximilian Kenfenheuer --- pkg/functions/parse.go | 61 +++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 31 deletions(-) diff --git a/pkg/functions/parse.go b/pkg/functions/parse.go index 7b8df91e..50cbb27b 100644 --- a/pkg/functions/parse.go +++ b/pkg/functions/parse.go @@ -331,37 +331,36 @@ func ParseFunctionCall(llmresult string, functionConfig FunctionsConfig) []FuncC } func ParseFunctionCallArgs(functionArguments string, functionConfig FunctionsConfig) string { - if len(functionConfig.ArgumentRegex) > 0 { - // We use named regexes here to extract the function argument key value pairs and convert this to valid json. - // TODO: there might be responses where an object as a value is expected/required. This is currently not handled. - args := make(map[string]string) - - agrsRegexKeyName := "key" - agrsRegexValueName := "value" - - if functionConfig.ArgumentRegexKey != "" { - agrsRegexKeyName = functionConfig.ArgumentRegexKey - } - if functionConfig.ArgumentRegexValue != "" { - agrsRegexValueName = functionConfig.ArgumentRegexValue - } - - for _, r := range functionConfig.ArgumentRegex { - var respRegex = regexp.MustCompile(r) - var nameRange []string = respRegex.SubexpNames() - var keyIndex = slices.Index(nameRange, agrsRegexKeyName) - var valueIndex = slices.Index(nameRange, agrsRegexValueName) - matches := respRegex.FindAllStringSubmatch(functionArguments, -1) - for _, match := range matches { - args[match[keyIndex]] = match[valueIndex] - } - } - - jsonBytes, _ := json.Marshal(args) - jsonString := string(jsonBytes) - - return jsonString - } else { + if len(functionConfig.ArgumentRegex) == 0 { return functionArguments } + + // We use named regexes here to extract the function argument key value pairs and convert this to valid json. + // TODO: there might be responses where an object as a value is expected/required. This is currently not handled. + args := make(map[string]string) + + agrsRegexKeyName := "key" + agrsRegexValueName := "value" + + if functionConfig.ArgumentRegexKey != "" { + agrsRegexKeyName = functionConfig.ArgumentRegexKey + } + if functionConfig.ArgumentRegexValue != "" { + agrsRegexValueName = functionConfig.ArgumentRegexValue + } + + for _, r := range functionConfig.ArgumentRegex { + var respRegex = regexp.MustCompile(r) + var nameRange []string = respRegex.SubexpNames() + var keyIndex = slices.Index(nameRange, agrsRegexKeyName) + var valueIndex = slices.Index(nameRange, agrsRegexValueName) + matches := respRegex.FindAllStringSubmatch(functionArguments, -1) + for _, match := range matches { + args[match[keyIndex]] = match[valueIndex] + } + } + + jsonBytes, _ := json.Marshal(args) + + return string(jsonBytes) }