|
| 1 | +local log = require("zeta.log") |
| 2 | +local curl = require("plenary.curl") |
| 3 | + |
| 4 | +local M = {} |
| 5 | + |
| 6 | +local CLAUDE_API_URL = "https://api.anthropic.com/v1/messages" |
| 7 | +local CLAUDE_API_TOKEN = vim.env.CLAUDE_API_TOKEN |
| 8 | +local SYSTEM_PROMPT_PATH = vim.api.nvim_get_runtime_file("prompt/claude/system-prompt.md", false)[1] |
| 9 | +local USER_PROMPT_PATH = vim.api.nvim_get_runtime_file("prompt/claude/user-prompt.md", false)[1] |
| 10 | + |
| 11 | +---@param body zeta.PredictEditRequestBody |
| 12 | +---@param callback fun(res: zeta.PredictEditResponse) |
| 13 | +function M.request(body, callback) |
| 14 | + local system_prompt = (function() |
| 15 | + local file = assert(io.open(SYSTEM_PROMPT_PATH)) |
| 16 | + local content = file:read("*a") |
| 17 | + file:close() |
| 18 | + return content |
| 19 | + end)() |
| 20 | + local user_prompt_template = (function() |
| 21 | + local file = assert(io.open(USER_PROMPT_PATH)) |
| 22 | + local content = file:read("*a") |
| 23 | + file:close() |
| 24 | + return content |
| 25 | + end)() |
| 26 | + local user_prompt = user_prompt_template |
| 27 | + :gsub("<events>", body.input_events) |
| 28 | + :gsub("<excerpt>", body.input_excerpt) |
| 29 | + local req_body = { |
| 30 | + model="claude-3-5-haiku-20241022", |
| 31 | + max_tokens=1000, |
| 32 | + temperature=0, |
| 33 | + system = system_prompt, |
| 34 | + messages = { |
| 35 | + { |
| 36 | + role = "user", |
| 37 | + content = { |
| 38 | + { type = "text", text = user_prompt }, |
| 39 | + }, |
| 40 | + }, |
| 41 | + { |
| 42 | + role = "assistant", |
| 43 | + content = { |
| 44 | + { type = "text", text = "### Predicted Excerpt:\n\nHere is a modified excerpt including users predicted next edits." }, |
| 45 | + }, |
| 46 | + }, |
| 47 | + }, |
| 48 | + } |
| 49 | + log.debug("claude request body:", req_body) |
| 50 | + curl.post(CLAUDE_API_URL, { |
| 51 | + body = vim.json.encode(req_body), |
| 52 | + headers = { |
| 53 | + ["Content-Type"] = "application/json", |
| 54 | + ["x-api-key"] = CLAUDE_API_TOKEN, |
| 55 | + ["anthropic-version"] = "2023-06-01", |
| 56 | + }, |
| 57 | + callback = function(resp) |
| 58 | + if resp.status ~= 200 then |
| 59 | + return |
| 60 | + end |
| 61 | + local _ok, resp_body = pcall(vim.json.decode, resp.body) |
| 62 | + -- TODO: validate resp_body signature |
| 63 | + callback({ |
| 64 | + request_id = "", |
| 65 | + output_excerpt = resp_body.content[1].text, |
| 66 | + }) |
| 67 | + end |
| 68 | + }) |
| 69 | +end |
| 70 | + |
| 71 | +return M |
0 commit comments