Skip to content

Commit 777bbc5

Browse files
committed
chore: add decodeError func to make debugging for the llm easier
1 parent 67698fd commit 777bbc5

1 file changed

Lines changed: 24 additions & 1 deletion

File tree

json/json.go

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"bytes"
66
"context"
77
"encoding/json"
8+
"errors"
89
"fmt"
910
"io"
1011

@@ -23,7 +24,11 @@ func Extract() pipe.Handler {
2324
}
2425
blob := extractJSON(data)
2526
if blob == nil {
26-
fmt.Fprintf(w, "Generated JSON is malformed, try again.\n")
27+
fmt.Fprintf(w, "Generated JSON is malformed: no JSON object found, try again.\n")
28+
return nil
29+
}
30+
if msg := decodeError(blob); msg != "" {
31+
fmt.Fprintf(w, "Generated JSON is malformed: %s, try again.\n", msg)
2732
return nil
2833
}
2934
_, err = w.Write(blob)
@@ -50,6 +55,24 @@ func Pretty(w io.Writer) pipe.Handler {
5055
})
5156
}
5257

58+
func decodeError(data []byte) string {
59+
var v any
60+
dec := json.NewDecoder(bytes.NewReader(data))
61+
if err := dec.Decode(&v); err != nil {
62+
var syntaxErr *json.SyntaxError
63+
var typeErr *json.UnmarshalTypeError
64+
switch {
65+
case errors.As(err, &syntaxErr):
66+
return fmt.Sprintf("syntax error at character %d", syntaxErr.Offset)
67+
case errors.As(err, &typeErr):
68+
return fmt.Sprintf("wrong type for field %q", typeErr.Field)
69+
default:
70+
return err.Error()
71+
}
72+
}
73+
return ""
74+
}
75+
5376
func extractJSON(data []byte) []byte {
5477
start := -1
5578
depth := 0

0 commit comments

Comments
 (0)