This repository was archived by the owner on Sep 18, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathformat.go
More file actions
99 lines (83 loc) · 2.37 KB
/
format.go
File metadata and controls
99 lines (83 loc) · 2.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package format
import (
"encoding/json"
"fmt"
"strings"
)
// OutputFormat represents the output format type for non-interactive mode
type OutputFormat string
const (
// Text format outputs the AI response as plain text.
Text OutputFormat = "text"
// JSON format outputs the AI response wrapped in a JSON object.
JSON OutputFormat = "json"
)
// String returns the string representation of the OutputFormat
func (f OutputFormat) String() string {
return string(f)
}
// SupportedFormats is a list of all supported output formats as strings
var SupportedFormats = []string{
string(Text),
string(JSON),
}
// Parse converts a string to an OutputFormat
func Parse(s string) (OutputFormat, error) {
s = strings.ToLower(strings.TrimSpace(s))
switch s {
case string(Text):
return Text, nil
case string(JSON):
return JSON, nil
default:
return "", fmt.Errorf("invalid format: %s", s)
}
}
// IsValid checks if the provided format string is supported
func IsValid(s string) bool {
_, err := Parse(s)
return err == nil
}
// GetHelpText returns a formatted string describing all supported formats
func GetHelpText() string {
return fmt.Sprintf(`Supported output formats:
- %s: Plain text output (default)
- %s: Output wrapped in a JSON object`,
Text, JSON)
}
// FormatOutput formats the AI response according to the specified format
func FormatOutput(content string, formatStr string) string {
format, err := Parse(formatStr)
if err != nil {
// Default to text format on error
return content
}
switch format {
case JSON:
return formatAsJSON(content)
case Text:
fallthrough
default:
return content
}
}
// formatAsJSON wraps the content in a simple JSON object
func formatAsJSON(content string) string {
// Use the JSON package to properly escape the content
response := struct {
Response string `json:"response"`
}{
Response: content,
}
jsonBytes, err := json.MarshalIndent(response, "", " ")
if err != nil {
// In case of an error, return a manually formatted JSON
jsonEscaped := strings.ReplaceAll(content, "\\", "\\\\")
jsonEscaped = strings.ReplaceAll(jsonEscaped, "\"", "\\\"")
jsonEscaped = strings.ReplaceAll(jsonEscaped, "\n", "\\n")
jsonEscaped = strings.ReplaceAll(jsonEscaped, "\r", "\\r")
jsonEscaped = strings.ReplaceAll(jsonEscaped, "\t", "\\t")
return fmt.Sprintf("{\n \"response\": \"%s\"\n}", jsonEscaped)
}
return string(jsonBytes)
}