|
| 1 | +local Utils = require("commit-ai.utils") |
| 2 | +local Job = require('plenary.job') |
| 3 | +local Log = require("commit-ai.log") |
| 4 | +local Common = require("commit-ai.backends.common") |
| 5 | + |
| 6 | +local M = {} |
| 7 | + |
| 8 | +function M.is_available() |
| 9 | + local config = require("commit-ai.config") |
| 10 | + return Utils.get_api_key(config.provider_options.gemini.api_key) and true or false |
| 11 | +end |
| 12 | + |
| 13 | +if not M.is_available() then |
| 14 | + Log.error("Gemini API_KEY is not set") |
| 15 | +end |
| 16 | + |
| 17 | +function M.query_ai(prompt, cb) |
| 18 | + local config = require("commit-ai.config") |
| 19 | + local options = vim.deepcopy(config.provider_options.gemini) |
| 20 | + |
| 21 | + local request_data = { |
| 22 | + contents = { |
| 23 | + { |
| 24 | + parts = { |
| 25 | + { |
| 26 | + text = prompt |
| 27 | + } |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + local tmp_file = os.tmpname() |
| 34 | + local f = io.open(tmp_file, "w") |
| 35 | + if f ~= nil then |
| 36 | + f:write(vim.json.encode(request_data)) |
| 37 | + f:close() |
| 38 | + end |
| 39 | + |
| 40 | + local args = { |
| 41 | + '-X', 'POST', |
| 42 | + string.format( |
| 43 | + 'https://generativelanguage.googleapis.com/v1beta/models/%s:%skey=%s', |
| 44 | + options.model, |
| 45 | + options.stream and 'streamGenerateContent?alt=sse&' or 'generateContent?', |
| 46 | + Utils.get_api_key(options.api_key) |
| 47 | + ), |
| 48 | + '-H', 'Content-Type: application/json', |
| 49 | + '-d', '@' .. tmp_file |
| 50 | + } |
| 51 | + |
| 52 | + |
| 53 | + local new_job = Job:new { |
| 54 | + command = "curl", |
| 55 | + args = args, |
| 56 | + on_exit = vim.schedule_wrap(function(job, exit_code) |
| 57 | + os.remove(tmp_file) |
| 58 | + |
| 59 | + if exit_code ~= 0 then |
| 60 | + Log.error("API request failed with exit code " .. exit_code) |
| 61 | + if cb then cb(nil) end |
| 62 | + return |
| 63 | + end |
| 64 | + |
| 65 | + local result = table.concat(job:result(), "\n") |
| 66 | + |
| 67 | + local success, parsed = pcall(vim.json.decode, result) |
| 68 | + |
| 69 | + if not success then |
| 70 | + Log.error("Failed to parse JSON API response: " .. parsed) |
| 71 | + if cb then cb(nil) end |
| 72 | + return |
| 73 | + end |
| 74 | + |
| 75 | + if cb then cb(parsed) end |
| 76 | + end) |
| 77 | + } |
| 78 | + |
| 79 | + Common.register_job(new_job) |
| 80 | + new_job:start() |
| 81 | + |
| 82 | + return new_job |
| 83 | +end |
| 84 | + |
| 85 | +return M |
0 commit comments