-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
260 lines (226 loc) · 7.11 KB
/
Copy pathmain.go
File metadata and controls
260 lines (226 loc) · 7.11 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log/slog"
"os"
"github.com/17twenty/gemma-cli/env"
"github.com/google/generative-ai-go/genai"
"google.golang.org/api/option"
)
// DefaultSchema represents the default JSON schema when none is provided
var DefaultSchema = map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"urls": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{"type": "string"},
"description": "Array of job URLs extracted from the content",
},
},
"required": []string{"urls"},
}
// Config holds the application configuration
type Config struct {
APIKey string
PromptFile string
Model string
SchemaFile string
OutputFile string
InputFile string
}
func main() {
// Parse command line flags
var (
promptFile = flag.String("prompt", "", "Path to prompt file (required)")
model = flag.String("model", "gemini-1.5-flash", "Model to use (default: gemini-1.5-flash)")
schemaFile = flag.String("schema", "", "Path to JSON schema file (optional)")
outputFile = flag.String("output", "", "Output file path (default: stdout)")
inputFile = flag.String("input", "", "Input file path (required)")
)
flag.Parse()
// Validate required flags
if *promptFile == "" || *inputFile == "" {
fmt.Fprintf(os.Stderr, "Usage: %s -prompt=<prompt.txt> -input=<input.txt> [options]\n", os.Args[0])
fmt.Fprintf(os.Stderr, "\nRequired flags:\n")
fmt.Fprintf(os.Stderr, " -prompt=<file> Path to prompt file\n")
fmt.Fprintf(os.Stderr, " -input=<file> Path to input file\n")
fmt.Fprintf(os.Stderr, "\nOptional flags:\n")
fmt.Fprintf(os.Stderr, " -model=<model> Model to use (default: gemini-1.5-flash)\n")
fmt.Fprintf(os.Stderr, " -schema=<file> Path to JSON schema file\n")
fmt.Fprintf(os.Stderr, " -output=<file> Output file path (default: stdout)\n")
fmt.Fprintf(os.Stderr, "\nEnvironment variables:\n")
fmt.Fprintf(os.Stderr, " GEMINI_API_KEY Google Gemini API key (required)\n")
os.Exit(1)
}
// Get API key from environment
env.LoadFromFile(".env")
apiKey := env.GetAsString("GEMINI_API_KEY")
if apiKey == "" {
fmt.Fprintf(os.Stderr, "Error: GEMINI_API_KEY environment variable is required\n")
os.Exit(1)
}
config := Config{
APIKey: apiKey,
PromptFile: *promptFile,
Model: *model,
SchemaFile: *schemaFile,
OutputFile: *outputFile,
InputFile: *inputFile,
}
if err := run(config); err != nil {
slog.Error("Application error", "error", err)
os.Exit(1)
}
}
func run(config Config) error {
// Read prompt file
promptContent, err := os.ReadFile(config.PromptFile)
if err != nil {
return fmt.Errorf("failed to read prompt file: %w", err)
}
// Read input file
inputContent, err := os.ReadFile(config.InputFile)
if err != nil {
return fmt.Errorf("failed to read input file: %w", err)
}
// Load schema
var schema map[string]interface{}
if config.SchemaFile != "" {
schemaContent, err := os.ReadFile(config.SchemaFile)
if err != nil {
return fmt.Errorf("failed to read schema file: %w", err)
}
if err := json.Unmarshal(schemaContent, &schema); err != nil {
return fmt.Errorf("failed to parse schema file: %w", err)
}
} else {
schema = DefaultSchema
}
// Create Gemini client
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(config.APIKey))
if err != nil {
return fmt.Errorf("failed to create Gemini client: %w", err)
}
defer client.Close()
// Get the model
model := client.GenerativeModel(config.Model)
// Configure the model for JSON output
model.ResponseMIMEType = "application/json"
// Set the response schema by converting the JSON schema to genai.Schema
genaiSchema, err := convertJSONSchemaToGenaiSchema(schema)
if err != nil {
return fmt.Errorf("failed to convert schema: %w", err)
}
model.ResponseSchema = genaiSchema
// Create the full prompt
fullPrompt := fmt.Sprintf("%s\n\nInput:\n%s", string(promptContent), string(inputContent))
// Generate content
resp, err := model.GenerateContent(ctx, genai.Text(fullPrompt))
if err != nil {
return fmt.Errorf("failed to generate content: %w", err)
}
// Extract the response
if len(resp.Candidates) == 0 {
return fmt.Errorf("no response candidates received")
}
var responseText string
for _, part := range resp.Candidates[0].Content.Parts {
if txt, ok := part.(genai.Text); ok {
responseText += string(txt)
}
}
// Parse and format the JSON response
var jsonResponse interface{}
if err := json.Unmarshal([]byte(responseText), &jsonResponse); err != nil {
return fmt.Errorf("failed to parse response as JSON: %w", err)
}
// Format with 2-space indentation
formattedJSON, err := json.MarshalIndent(jsonResponse, "", " ")
if err != nil {
return fmt.Errorf("failed to format JSON response: %w", err)
}
// Write output
if config.OutputFile != "" {
if err := os.WriteFile(config.OutputFile, formattedJSON, 0644); err != nil {
return fmt.Errorf("failed to write output file: %w", err)
}
} else {
fmt.Println(string(formattedJSON))
}
return nil
}
// convertJSONSchemaToGenaiSchema converts a JSON schema map to a genai.Schema
func convertJSONSchemaToGenaiSchema(jsonSchema map[string]interface{}) (*genai.Schema, error) {
schema := &genai.Schema{}
// Set type
if typeStr, ok := jsonSchema["type"].(string); ok {
switch typeStr {
case "object":
schema.Type = genai.TypeObject
case "array":
schema.Type = genai.TypeArray
case "string":
schema.Type = genai.TypeString
case "number":
schema.Type = genai.TypeNumber
case "integer":
schema.Type = genai.TypeInteger
case "boolean":
schema.Type = genai.TypeBoolean
default:
return nil, fmt.Errorf("unsupported type: %s", typeStr)
}
}
// Set description
if desc, ok := jsonSchema["description"].(string); ok {
schema.Description = desc
}
// Set properties for object type
if props, ok := jsonSchema["properties"].(map[string]interface{}); ok {
schema.Properties = make(map[string]*genai.Schema)
for key, prop := range props {
if propMap, ok := prop.(map[string]interface{}); ok {
propSchema, err := convertJSONSchemaToGenaiSchema(propMap)
if err != nil {
return nil, fmt.Errorf("failed to convert property %s: %w", key, err)
}
schema.Properties[key] = propSchema
}
}
}
// Set items for array type
if items, ok := jsonSchema["items"].(map[string]interface{}); ok {
itemSchema, err := convertJSONSchemaToGenaiSchema(items)
if err != nil {
return nil, fmt.Errorf("failed to convert items schema: %w", err)
}
schema.Items = itemSchema
}
// Set required fields
if required, ok := jsonSchema["required"].([]interface{}); ok {
schema.Required = make([]string, len(required))
for i, req := range required {
if reqStr, ok := req.(string); ok {
schema.Required[i] = reqStr
}
}
}
// Set enum values
if enum, ok := jsonSchema["enum"].([]interface{}); ok {
schema.Enum = make([]string, len(enum))
for i, e := range enum {
if eStr, ok := e.(string); ok {
schema.Enum[i] = eStr
}
}
}
// Set format
if format, ok := jsonSchema["format"].(string); ok {
schema.Format = format
}
return schema, nil
}