|
| 1 | +package builtin |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/base64" |
| 6 | + "encoding/json" |
| 7 | + "fmt" |
| 8 | + "os" |
| 9 | + "unicode/utf8" |
| 10 | + |
| 11 | + "github.com/acorn-io/gptscript/pkg/types" |
| 12 | +) |
| 13 | + |
| 14 | +var Tools = map[string]types.Tool{ |
| 15 | + "sys.read": { |
| 16 | + Description: "Reads the contents of a file", |
| 17 | + Arguments: types.ObjectSchema( |
| 18 | + "filename", "The name of the file to read"), |
| 19 | + BuiltinFunc: func(ctx context.Context, env []string, input string) (string, error) { |
| 20 | + var params struct { |
| 21 | + Filename string `json:"filename,omitempty"` |
| 22 | + } |
| 23 | + if err := json.Unmarshal([]byte(input), ¶ms); err != nil { |
| 24 | + return "", err |
| 25 | + } |
| 26 | + |
| 27 | + log.Debugf("Reading file %s", params.Filename) |
| 28 | + data, err := os.ReadFile(params.Filename) |
| 29 | + if err != nil { |
| 30 | + return "", err |
| 31 | + } |
| 32 | + |
| 33 | + if utf8.Valid(data) { |
| 34 | + return string(data), nil |
| 35 | + } |
| 36 | + return base64.StdEncoding.EncodeToString(data), nil |
| 37 | + }, |
| 38 | + }, |
| 39 | + "sys.write": { |
| 40 | + Description: "Write the contents to a file", |
| 41 | + Arguments: types.ObjectSchema( |
| 42 | + "filename", "The name of the file to write to", |
| 43 | + "content", "The content to write"), |
| 44 | + BuiltinFunc: func(ctx context.Context, env []string, input string) (string, error) { |
| 45 | + var params struct { |
| 46 | + Filename string `json:"filename,omitempty"` |
| 47 | + Content string `json:"content,omitempty"` |
| 48 | + } |
| 49 | + if err := json.Unmarshal([]byte(input), ¶ms); err != nil { |
| 50 | + return "", err |
| 51 | + } |
| 52 | + |
| 53 | + data := []byte(params.Content) |
| 54 | + msg := fmt.Sprintf("Wrote %d bytes to file %s", len(data), params.Filename) |
| 55 | + log.Debugf(msg) |
| 56 | + |
| 57 | + return "", os.WriteFile(params.Filename, data, 0644) |
| 58 | + }, |
| 59 | + }, |
| 60 | +} |
| 61 | + |
| 62 | +func Builtin(name string) (types.Tool, bool) { |
| 63 | + t, ok := Tools[name] |
| 64 | + t.Name = name |
| 65 | + t.ID = name |
| 66 | + t.Instructions = "#!" + name |
| 67 | + return t, ok |
| 68 | +} |
0 commit comments