2024-06-12 02:35:07 -06:00
|
|
|
package toolbox
|
2024-02-21 21:55:38 -07:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
|
2024-06-23 12:57:08 -06:00
|
|
|
toolutil "git.mlow.ca/mlow/lmcli/pkg/agents/toolbox/util"
|
2024-06-12 02:35:07 -06:00
|
|
|
"git.mlow.ca/mlow/lmcli/pkg/api"
|
2024-02-21 21:55:38 -07:00
|
|
|
)
|
|
|
|
|
2024-05-14 17:00:00 -06:00
|
|
|
const READ_FILE_DESCRIPTION = `Retrieve the contents of a text file relative to the current working directory.
|
|
|
|
|
|
|
|
Use the file contents for your own reference in completing your task, they do not need to be shown to the user.
|
2024-02-21 21:55:38 -07:00
|
|
|
|
|
|
|
Each line of the returned content is prefixed with its line number and a tab (\t).
|
|
|
|
|
|
|
|
Example result:
|
|
|
|
{
|
|
|
|
"message": "success",
|
|
|
|
"result": "1\tthe contents\n2\tof the file\n"
|
|
|
|
}`
|
|
|
|
|
2024-06-12 02:35:07 -06:00
|
|
|
var ReadFileTool = api.ToolSpec{
|
2024-02-21 21:55:38 -07:00
|
|
|
Name: "read_file",
|
|
|
|
Description: READ_FILE_DESCRIPTION,
|
2024-06-12 02:35:07 -06:00
|
|
|
Parameters: []api.ToolParameter{
|
2024-02-21 21:55:38 -07:00
|
|
|
{
|
|
|
|
Name: "path",
|
|
|
|
Type: "string",
|
|
|
|
Description: "Path to a file within the current working directory to read.",
|
|
|
|
Required: true,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
|
2024-06-12 02:35:07 -06:00
|
|
|
Impl: func(tool *api.ToolSpec, args map[string]interface{}) (string, error) {
|
2024-02-21 21:55:38 -07:00
|
|
|
tmp, ok := args["path"]
|
|
|
|
if !ok {
|
|
|
|
return "", fmt.Errorf("Path parameter to read_file was not included.")
|
|
|
|
}
|
|
|
|
path, ok := tmp.(string)
|
|
|
|
if !ok {
|
|
|
|
return "", fmt.Errorf("Invalid path in function arguments: %v", tmp)
|
|
|
|
}
|
|
|
|
result := readFile(path)
|
|
|
|
ret, err := result.ToJson()
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("Could not serialize result: %v", err)
|
|
|
|
}
|
|
|
|
return ret, nil
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2024-06-12 02:35:07 -06:00
|
|
|
func readFile(path string) api.CallResult {
|
2024-02-21 21:55:38 -07:00
|
|
|
ok, reason := toolutil.IsPathWithinCWD(path)
|
|
|
|
if !ok {
|
2024-06-12 02:35:07 -06:00
|
|
|
return api.CallResult{Message: reason}
|
2024-02-21 21:55:38 -07:00
|
|
|
}
|
|
|
|
data, err := os.ReadFile(path)
|
|
|
|
if err != nil {
|
2024-06-12 02:35:07 -06:00
|
|
|
return api.CallResult{Message: fmt.Sprintf("Could not read path: %s", err.Error())}
|
2024-02-21 21:55:38 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
lines := strings.Split(string(data), "\n")
|
|
|
|
content := strings.Builder{}
|
|
|
|
for i, line := range lines {
|
|
|
|
content.WriteString(fmt.Sprintf("%d\t%s\n", i+1, line))
|
|
|
|
}
|
|
|
|
|
2024-06-12 02:35:07 -06:00
|
|
|
return api.CallResult{
|
2024-02-21 21:55:38 -07:00
|
|
|
Result: content.String(),
|
|
|
|
}
|
|
|
|
}
|