1package provider
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "log/slog"
10 "strings"
11 "time"
12
13 "github.com/charmbracelet/catwalk/pkg/catwalk"
14 "github.com/charmbracelet/crush/internal/config"
15 "github.com/charmbracelet/crush/internal/llm/tools"
16 "github.com/charmbracelet/crush/internal/log"
17 "github.com/charmbracelet/crush/internal/message"
18 "github.com/google/uuid"
19 "google.golang.org/genai"
20)
21
22type geminiClient struct {
23 providerOptions providerClientOptions
24 client *genai.Client
25}
26
27type GeminiClient ProviderClient
28
29func newGeminiClient(opts providerClientOptions) GeminiClient {
30 client, err := createGeminiClient(opts)
31 if err != nil {
32 slog.Error("Failed to create Gemini client", "error", err)
33 return nil
34 }
35
36 return &geminiClient{
37 providerOptions: opts,
38 client: client,
39 }
40}
41
42func createGeminiClient(opts providerClientOptions) (*genai.Client, error) {
43 cc := &genai.ClientConfig{
44 APIKey: opts.apiKey,
45 Backend: genai.BackendGeminiAPI,
46 }
47 if config.Get().Options.Debug {
48 cc.HTTPClient = log.NewHTTPClient()
49 }
50 client, err := genai.NewClient(context.Background(), cc)
51 if err != nil {
52 return nil, err
53 }
54 return client, nil
55}
56
57func (g *geminiClient) convertMessages(messages []message.Message) []*genai.Content {
58 var history []*genai.Content
59 for _, msg := range messages {
60 switch msg.Role {
61 case message.User:
62 var parts []*genai.Part
63 parts = append(parts, &genai.Part{Text: msg.Content().String()})
64 for _, binaryContent := range msg.BinaryContent() {
65 imageFormat := strings.Split(binaryContent.MIMEType, "/")
66 parts = append(parts, &genai.Part{InlineData: &genai.Blob{
67 MIMEType: imageFormat[1],
68 Data: binaryContent.Data,
69 }})
70 }
71 history = append(history, &genai.Content{
72 Parts: parts,
73 Role: genai.RoleUser,
74 })
75 case message.Assistant:
76 var assistantParts []*genai.Part
77
78 if msg.Content().String() != "" {
79 assistantParts = append(assistantParts, &genai.Part{Text: msg.Content().String()})
80 }
81
82 if len(msg.ToolCalls()) > 0 {
83 for _, call := range msg.ToolCalls() {
84 if !call.Finished {
85 continue
86 }
87 args, _ := parseJSONToMap(call.Input)
88 assistantParts = append(assistantParts, &genai.Part{
89 FunctionCall: &genai.FunctionCall{
90 Name: call.Name,
91 Args: args,
92 },
93 })
94 }
95 }
96
97 if len(assistantParts) > 0 {
98 history = append(history, &genai.Content{
99 Role: genai.RoleModel,
100 Parts: assistantParts,
101 })
102 }
103
104 case message.Tool:
105 for _, result := range msg.ToolResults() {
106 response := map[string]any{"result": result.Content}
107 parsed, err := parseJSONToMap(result.Content)
108 if err == nil {
109 response = parsed
110 }
111
112 var toolCall message.ToolCall
113 for _, m := range messages {
114 if m.Role == message.Assistant {
115 for _, call := range m.ToolCalls() {
116 if call.ID == result.ToolCallID {
117 toolCall = call
118 break
119 }
120 }
121 }
122 }
123
124 history = append(history, &genai.Content{
125 Parts: []*genai.Part{
126 {
127 FunctionResponse: &genai.FunctionResponse{
128 Name: toolCall.Name,
129 Response: response,
130 },
131 },
132 },
133 Role: genai.RoleModel,
134 })
135 }
136 }
137 }
138
139 return history
140}
141
142func (g *geminiClient) convertTools(tools []tools.BaseTool) []*genai.Tool {
143 geminiTool := &genai.Tool{}
144 geminiTool.FunctionDeclarations = make([]*genai.FunctionDeclaration, 0, len(tools))
145
146 for _, tool := range tools {
147 info := tool.Info()
148 declaration := &genai.FunctionDeclaration{
149 Name: info.Name,
150 Description: info.Description,
151 Parameters: &genai.Schema{
152 Type: genai.TypeObject,
153 Properties: convertSchemaProperties(info.Parameters),
154 Required: info.Required,
155 },
156 }
157
158 geminiTool.FunctionDeclarations = append(geminiTool.FunctionDeclarations, declaration)
159 }
160
161 return []*genai.Tool{geminiTool}
162}
163
164func (g *geminiClient) finishReason(reason genai.FinishReason) message.FinishReason {
165 switch reason {
166 case genai.FinishReasonStop:
167 return message.FinishReasonEndTurn
168 case genai.FinishReasonMaxTokens:
169 return message.FinishReasonMaxTokens
170 default:
171 return message.FinishReasonUnknown
172 }
173}
174
175func (g *geminiClient) send(ctx context.Context, messages []message.Message, tools []tools.BaseTool) (*ProviderResponse, error) {
176 // Convert messages
177 geminiMessages := g.convertMessages(messages)
178 model := g.providerOptions.model(g.providerOptions.modelType)
179 cfg := config.Get()
180
181 modelConfig := cfg.Models[config.SelectedModelTypeLarge]
182 if g.providerOptions.modelType == config.SelectedModelTypeSmall {
183 modelConfig = cfg.Models[config.SelectedModelTypeSmall]
184 }
185
186 maxTokens := model.DefaultMaxTokens
187 if modelConfig.MaxTokens > 0 {
188 maxTokens = modelConfig.MaxTokens
189 }
190 systemMessage := g.providerOptions.systemMessage
191 if g.providerOptions.systemPromptPrefix != "" {
192 systemMessage = g.providerOptions.systemPromptPrefix + "\n" + systemMessage
193 }
194 history := geminiMessages[:len(geminiMessages)-1] // All but last message
195 lastMsg := geminiMessages[len(geminiMessages)-1]
196 config := &genai.GenerateContentConfig{
197 MaxOutputTokens: int32(maxTokens),
198 SystemInstruction: &genai.Content{
199 Parts: []*genai.Part{{Text: systemMessage}},
200 },
201 }
202 config.Tools = g.convertTools(tools)
203 chat, _ := g.client.Chats.Create(ctx, model.ID, config, history)
204
205 attempts := 0
206 for {
207 attempts++
208 var toolCalls []message.ToolCall
209
210 var lastMsgParts []genai.Part
211 for _, part := range lastMsg.Parts {
212 lastMsgParts = append(lastMsgParts, *part)
213 }
214 resp, err := chat.SendMessage(ctx, lastMsgParts...)
215 // If there is an error we are going to see if we can retry the call
216 if err != nil {
217 retry, after, retryErr := g.shouldRetry(attempts, err)
218 if retryErr != nil {
219 return nil, retryErr
220 }
221 if retry {
222 slog.Warn("Retrying due to rate limit", "attempt", attempts, "max_retries", maxRetries, "error", err)
223 select {
224 case <-ctx.Done():
225 return nil, ctx.Err()
226 case <-time.After(time.Duration(after) * time.Millisecond):
227 continue
228 }
229 }
230 return nil, retryErr
231 }
232
233 content := ""
234
235 if len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {
236 for _, part := range resp.Candidates[0].Content.Parts {
237 switch {
238 case part.Text != "":
239 content = string(part.Text)
240 case part.FunctionCall != nil:
241 id := "call_" + uuid.New().String()
242 args, _ := json.Marshal(part.FunctionCall.Args)
243 toolCalls = append(toolCalls, message.ToolCall{
244 ID: id,
245 Name: part.FunctionCall.Name,
246 Input: string(args),
247 Type: "function",
248 Finished: true,
249 })
250 }
251 }
252 }
253 finishReason := message.FinishReasonEndTurn
254 if len(resp.Candidates) > 0 {
255 finishReason = g.finishReason(resp.Candidates[0].FinishReason)
256 }
257 if len(toolCalls) > 0 {
258 finishReason = message.FinishReasonToolUse
259 }
260
261 return &ProviderResponse{
262 Content: content,
263 ToolCalls: toolCalls,
264 Usage: g.usage(resp),
265 FinishReason: finishReason,
266 }, nil
267 }
268}
269
270func (g *geminiClient) stream(ctx context.Context, messages []message.Message, tools []tools.BaseTool) <-chan ProviderEvent {
271 // Convert messages
272 geminiMessages := g.convertMessages(messages)
273
274 model := g.providerOptions.model(g.providerOptions.modelType)
275 cfg := config.Get()
276
277 modelConfig := cfg.Models[config.SelectedModelTypeLarge]
278 if g.providerOptions.modelType == config.SelectedModelTypeSmall {
279 modelConfig = cfg.Models[config.SelectedModelTypeSmall]
280 }
281 maxTokens := model.DefaultMaxTokens
282 if modelConfig.MaxTokens > 0 {
283 maxTokens = modelConfig.MaxTokens
284 }
285
286 // Override max tokens if set in provider options
287 if g.providerOptions.maxTokens > 0 {
288 maxTokens = g.providerOptions.maxTokens
289 }
290 systemMessage := g.providerOptions.systemMessage
291 if g.providerOptions.systemPromptPrefix != "" {
292 systemMessage = g.providerOptions.systemPromptPrefix + "\n" + systemMessage
293 }
294 history := geminiMessages[:len(geminiMessages)-1] // All but last message
295 lastMsg := geminiMessages[len(geminiMessages)-1]
296 config := &genai.GenerateContentConfig{
297 MaxOutputTokens: int32(maxTokens),
298 SystemInstruction: &genai.Content{
299 Parts: []*genai.Part{{Text: systemMessage}},
300 },
301 }
302 config.Tools = g.convertTools(tools)
303 chat, _ := g.client.Chats.Create(ctx, model.ID, config, history)
304
305 attempts := 0
306 eventChan := make(chan ProviderEvent)
307
308 go func() {
309 defer close(eventChan)
310
311 for {
312 attempts++
313
314 currentContent := ""
315 toolCalls := []message.ToolCall{}
316 var finalResp *genai.GenerateContentResponse
317
318 eventChan <- ProviderEvent{Type: EventContentStart}
319
320 var lastMsgParts []genai.Part
321
322 for _, part := range lastMsg.Parts {
323 lastMsgParts = append(lastMsgParts, *part)
324 }
325 for resp, err := range chat.SendMessageStream(ctx, lastMsgParts...) {
326 if err != nil {
327 retry, after, retryErr := g.shouldRetry(attempts, err)
328 if retryErr != nil {
329 eventChan <- ProviderEvent{Type: EventError, Error: retryErr}
330 return
331 }
332 if retry {
333 slog.Warn("Retrying due to rate limit", "attempt", attempts, "max_retries", maxRetries, "error", err)
334 select {
335 case <-ctx.Done():
336 if ctx.Err() != nil {
337 eventChan <- ProviderEvent{Type: EventError, Error: ctx.Err()}
338 }
339
340 return
341 case <-time.After(time.Duration(after) * time.Millisecond):
342 continue
343 }
344 } else {
345 eventChan <- ProviderEvent{Type: EventError, Error: err}
346 return
347 }
348 }
349
350 finalResp = resp
351
352 if len(resp.Candidates) > 0 && resp.Candidates[0].Content != nil {
353 for _, part := range resp.Candidates[0].Content.Parts {
354 switch {
355 case part.Text != "":
356 delta := string(part.Text)
357 if delta != "" {
358 eventChan <- ProviderEvent{
359 Type: EventContentDelta,
360 Content: delta,
361 }
362 currentContent += delta
363 }
364 case part.FunctionCall != nil:
365 id := "call_" + uuid.New().String()
366 args, _ := json.Marshal(part.FunctionCall.Args)
367 newCall := message.ToolCall{
368 ID: id,
369 Name: part.FunctionCall.Name,
370 Input: string(args),
371 Type: "function",
372 Finished: true,
373 }
374
375 isNew := true
376 for _, existing := range toolCalls {
377 if existing.Name == newCall.Name && existing.Input == newCall.Input {
378 isNew = false
379 break
380 }
381 }
382
383 if isNew {
384 toolCalls = append(toolCalls, newCall)
385 }
386 }
387 }
388 }
389 }
390
391 eventChan <- ProviderEvent{Type: EventContentStop}
392
393 if finalResp != nil {
394 finishReason := message.FinishReasonEndTurn
395 if len(finalResp.Candidates) > 0 {
396 finishReason = g.finishReason(finalResp.Candidates[0].FinishReason)
397 }
398 if len(toolCalls) > 0 {
399 finishReason = message.FinishReasonToolUse
400 }
401 eventChan <- ProviderEvent{
402 Type: EventComplete,
403 Response: &ProviderResponse{
404 Content: currentContent,
405 ToolCalls: toolCalls,
406 Usage: g.usage(finalResp),
407 FinishReason: finishReason,
408 },
409 }
410 return
411 }
412 }
413 }()
414
415 return eventChan
416}
417
418func (g *geminiClient) shouldRetry(attempts int, err error) (bool, int64, error) {
419 // Check if error is a rate limit error
420 if attempts > maxRetries {
421 return false, 0, fmt.Errorf("maximum retry attempts reached for rate limit: %d retries", maxRetries)
422 }
423
424 // Gemini doesn't have a standard error type we can check against
425 // So we'll check the error message for rate limit indicators
426 if errors.Is(err, io.EOF) {
427 return false, 0, err
428 }
429
430 errMsg := err.Error()
431 isRateLimit := contains(errMsg, "rate limit", "quota exceeded", "too many requests")
432
433 // Check for token expiration (401 Unauthorized)
434 if contains(errMsg, "unauthorized", "invalid api key", "api key expired") {
435 g.providerOptions.apiKey, err = config.Get().Resolve(g.providerOptions.config.APIKey)
436 if err != nil {
437 return false, 0, fmt.Errorf("failed to resolve API key: %w", err)
438 }
439 g.client, err = createGeminiClient(g.providerOptions)
440 if err != nil {
441 return false, 0, fmt.Errorf("failed to create Gemini client after API key refresh: %w", err)
442 }
443 return true, 0, nil
444 }
445
446 // Check for common rate limit error messages
447
448 if !isRateLimit {
449 return false, 0, err
450 }
451
452 // Calculate backoff with jitter
453 backoffMs := 2000 * (1 << (attempts - 1))
454 jitterMs := int(float64(backoffMs) * 0.2)
455 retryMs := backoffMs + jitterMs
456
457 return true, int64(retryMs), nil
458}
459
460func (g *geminiClient) usage(resp *genai.GenerateContentResponse) TokenUsage {
461 if resp == nil || resp.UsageMetadata == nil {
462 return TokenUsage{}
463 }
464
465 return TokenUsage{
466 InputTokens: int64(resp.UsageMetadata.PromptTokenCount),
467 OutputTokens: int64(resp.UsageMetadata.CandidatesTokenCount),
468 CacheCreationTokens: 0, // Not directly provided by Gemini
469 CacheReadTokens: int64(resp.UsageMetadata.CachedContentTokenCount),
470 }
471}
472
473func (g *geminiClient) Model() catwalk.Model {
474 return g.providerOptions.model(g.providerOptions.modelType)
475}
476
477// Helper functions
478func parseJSONToMap(jsonStr string) (map[string]any, error) {
479 var result map[string]any
480 err := json.Unmarshal([]byte(jsonStr), &result)
481 return result, err
482}
483
484func convertSchemaProperties(parameters map[string]any) map[string]*genai.Schema {
485 properties := make(map[string]*genai.Schema)
486
487 for name, param := range parameters {
488 properties[name] = convertToSchema(param)
489 }
490
491 return properties
492}
493
494func convertToSchema(param any) *genai.Schema {
495 schema := &genai.Schema{Type: genai.TypeString}
496
497 paramMap, ok := param.(map[string]any)
498 if !ok {
499 return schema
500 }
501
502 if desc, ok := paramMap["description"].(string); ok {
503 schema.Description = desc
504 }
505
506 typeVal, hasType := paramMap["type"]
507 if !hasType {
508 return schema
509 }
510
511 typeStr, ok := typeVal.(string)
512 if !ok {
513 return schema
514 }
515
516 schema.Type = mapJSONTypeToGenAI(typeStr)
517
518 switch typeStr {
519 case "array":
520 schema.Items = processArrayItems(paramMap)
521 case "object":
522 if props, ok := paramMap["properties"].(map[string]any); ok {
523 schema.Properties = convertSchemaProperties(props)
524 }
525 }
526
527 return schema
528}
529
530func processArrayItems(paramMap map[string]any) *genai.Schema {
531 items, ok := paramMap["items"].(map[string]any)
532 if !ok {
533 return nil
534 }
535
536 return convertToSchema(items)
537}
538
539func mapJSONTypeToGenAI(jsonType string) genai.Type {
540 switch jsonType {
541 case "string":
542 return genai.TypeString
543 case "number":
544 return genai.TypeNumber
545 case "integer":
546 return genai.TypeInteger
547 case "boolean":
548 return genai.TypeBoolean
549 case "array":
550 return genai.TypeArray
551 case "object":
552 return genai.TypeObject
553 default:
554 return genai.TypeString // Default to string for unknown types
555 }
556}
557
558func contains(s string, substrs ...string) bool {
559 for _, substr := range substrs {
560 if strings.Contains(strings.ToLower(s), strings.ToLower(substr)) {
561 return true
562 }
563 }
564 return false
565}