gemini.go 14 KB

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