Repository navigation
Expand file tree
/
Copy pathmodels.lua
More file actions
82 lines (71 loc) · 1.9 KB
/
Copy pathmodels.lua
File metadata and controls
82 lines (71 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
-- /lua/opencode/models.lua
local M = {
__cache = {
models = nil,
},
}
local url = 'https://models.dev/api.json'
local cache_file = vim.fn.stdpath('cache') .. '/opencode/opencode_models.json'
local curl = require('plenary.curl')
function M.setup()
M.ensure_cache_dir()
M.load()
end
function M.ensure_cache_dir()
local cache_dir = vim.fn.stdpath('cache') .. '/opencode'
if vim.fn.isdirectory(cache_dir) == 0 then
local ok, err = pcall(vim.fn.mkdir, cache_dir, 'p')
if not ok then
error('Failed to create cache directory: ' .. err)
end
end
end
-- Download models.json and write to cache
function M.download_models()
M.ensure_cache_dir()
vim.notify('[Opencode.nvim] Downloading models from ' .. url .. '...', vim.log.levels.INFO)
local result = curl.get(url, { timeout = 10000 })
if result.status ~= 200 or not result.body then
error('Failed to download models.json: HTTP status ' .. tostring(result.status))
end
local ok = vim.fn.writefile({ result.body }, cache_file)
if ok ~= 0 then
error('Failed to write models.json to cache: ' .. cache_file)
end
end
-- Read models.json from cache
function M.read_cache()
local ok, lines = pcall(vim.fn.readfile, cache_file)
if not ok or not lines or #lines == 0 then
return nil
end
return table.concat(lines, '\n')
end
function M.load()
local raw = M.read_cache()
if not raw then
M.download_models()
raw = M.read_cache()
if not raw then
error('Failed to get models.json')
end
end
M.__cache.models = vim.json.decode(raw)
end
function M.update_cache()
M.download_models()
M.load()
end
function M.get_all()
if not M.__cache.models then
M.load()
end
return M.__cache.models
end
function M.get(provider, model)
if not M.__cache.models then
M.load()
end
return M.__cache.models and M.__cache.models[provider] and M.__cache.models[provider].models[model] or nil
end
return M