2024-06-12 02:35:07 -06:00
|
|
|
package toolbox
|
2024-02-21 21:55:38 -07:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
|
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
|
|
|
)
|
|
|
|
|
|
|
|
const WRITE_FILE_DESCRIPTION = `Write the provided contents to a file relative to the current working directory.
|
|
|
|
|
|
|
|
Example result:
|
|
|
|
{
|
|
|
|
"message": "success"
|
|
|
|
}`
|
|
|
|
|
2024-06-12 02:35:07 -06:00
|
|
|
var WriteFileTool = api.ToolSpec{
|
2024-02-21 21:55:38 -07:00
|
|
|
Name: "write_file",
|
|
|
|
Description: WRITE_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 write to.",
|
|
|
|
Required: true,
|
|
|
|
},
|
|
|
|
{
|
|
|
|
Name: "content",
|
|
|
|
Type: "string",
|
|
|
|
Description: "The content to write to the file. Overwrites any existing content!",
|
|
|
|
Required: true,
|
|
|
|
},
|
|
|
|
},
|
2024-06-12 02:35:07 -06:00
|
|
|
Impl: func(t *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 write_file was not included.")
|
|
|
|
}
|
|
|
|
path, ok := tmp.(string)
|
|
|
|
if !ok {
|
|
|
|
return "", fmt.Errorf("Invalid path in function arguments: %v", tmp)
|
|
|
|
}
|
|
|
|
tmp, ok = args["content"]
|
|
|
|
if !ok {
|
|
|
|
return "", fmt.Errorf("Content parameter to write_file was not included.")
|
|
|
|
}
|
|
|
|
content, ok := tmp.(string)
|
|
|
|
if !ok {
|
|
|
|
return "", fmt.Errorf("Invalid content in function arguments: %v", tmp)
|
|
|
|
}
|
|
|
|
result := writeFile(path, content)
|
|
|
|
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 writeFile(path string, content 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
|
|
|
}
|
|
|
|
err := os.WriteFile(path, []byte(content), 0644)
|
|
|
|
if err != nil {
|
2024-06-12 02:35:07 -06:00
|
|
|
return api.CallResult{Message: fmt.Sprintf("Could not write to path: %s", err.Error())}
|
2024-02-21 21:55:38 -07:00
|
|
|
}
|
2024-06-12 02:35:07 -06:00
|
|
|
return api.CallResult{}
|
2024-02-21 21:55:38 -07:00
|
|
|
}
|