gemini.go 14 KB

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