Skip to content

Commit

Permalink
refactor: function argument parsing using named regex (#4708)
Browse files Browse the repository at this point in the history
Signed-off-by: Maximilian Kenfenheuer <[email protected]>
  • Loading branch information
mKenfenheuer authored Jan 28, 2025
1 parent 91e1ff5 commit b4b67e0
Showing 1 changed file with 27 additions and 28 deletions.
55 changes: 27 additions & 28 deletions pkg/functions/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 len(functionConfig.ArgumentRegex) == 0 {
return functionArguments
}

if functionConfig.ArgumentRegexKey != "" {
agrsRegexKeyName = functionConfig.ArgumentRegexKey
}
if functionConfig.ArgumentRegexValue != "" {
agrsRegexValueName = functionConfig.ArgumentRegexValue
}
// 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)

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]
}
}
agrsRegexKeyName := "key"
agrsRegexValueName := "value"

jsonBytes, _ := json.Marshal(args)
jsonString := string(jsonBytes)
if functionConfig.ArgumentRegexKey != "" {
agrsRegexKeyName = functionConfig.ArgumentRegexKey
}
if functionConfig.ArgumentRegexValue != "" {
agrsRegexValueName = functionConfig.ArgumentRegexValue
}

return jsonString
} else {
return functionArguments
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)
}

0 comments on commit b4b67e0

Please sign in to comment.