-
-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathproviders.lua
More file actions
388 lines (327 loc) · 10.7 KB
/
providers.lua
File metadata and controls
388 lines (327 loc) · 10.7 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
local utils = require('CopilotChat.utils')
local EDITOR_VERSION = 'Neovim/' .. vim.version().major .. '.' .. vim.version().minor .. '.' .. vim.version().patch
local cached_github_token = nil
local function config_path()
local config = vim.fs.normalize('$XDG_CONFIG_HOME')
if config and vim.uv.fs_stat(config) then
return config
end
if vim.fn.has('win32') > 0 then
config = vim.fs.normalize('$LOCALAPPDATA')
if not config or not vim.uv.fs_stat(config) then
config = vim.fs.normalize('$HOME/AppData/Local')
end
else
config = vim.fs.normalize('$HOME/.config')
end
if config and vim.uv.fs_stat(config) then
return config
end
end
--- Get the github copilot oauth cached token (gu_ token)
---@return string
local function get_github_token()
if cached_github_token then
return cached_github_token
end
-- loading token from the environment only in GitHub Codespaces
local token = os.getenv('GITHUB_TOKEN')
local codespaces = os.getenv('CODESPACES')
if token and codespaces then
cached_github_token = token
return token
end
-- loading token from the file
local config_path = config_path()
if not config_path then
error('Failed to find config path for GitHub token')
end
-- token can be sometimes in apps.json sometimes in hosts.json
local file_paths = {
config_path .. '/github-copilot/hosts.json',
config_path .. '/github-copilot/apps.json',
}
for _, file_path in ipairs(file_paths) do
local file_data = utils.read_file(file_path)
if file_data then
local parsed_data = utils.json_decode(file_data)
if parsed_data then
for key, value in pairs(parsed_data) do
if string.find(key, 'github.com') then
cached_github_token = value.oauth_token
return value.oauth_token
end
end
end
end
end
error('Failed to find GitHub token')
end
---@class CopilotChat.Provider.model
---@field id string
---@field name string
---@field tokenizer string?
---@field max_input_tokens number?
---@field max_output_tokens number?
---@class CopilotChat.Provider.agent
---@field id string
---@field name string
---@field description string?
---@class CopilotChat.Provider.embed
---@field index number
---@field embedding table<number>
---@class CopilotChat.Provider.options
---@field model CopilotChat.Provider.model
---@field agent CopilotChat.Provider.agent?
---@field temperature number?
---@class CopilotChat.Provider.input
---@field role string
---@field content string
---@class CopilotChat.Provider.reference
---@field name string
---@field url string
---@class CopilotChat.Provider.output
---@field content string
---@field finish_reason string?
---@field total_tokens number?
---@field references table<CopilotChat.Provider.reference>?
---@class CopilotChat.Provider
---@field disabled nil|boolean
---@field get_headers nil|fun(self: CopilotChat.Provider):table<string, string>,number?
---@field get_agents nil|fun(self: CopilotChat.Provider, headers:table):table<CopilotChat.Provider.agent>
---@field get_models nil|fun(self: CopilotChat.Provider, headers:table):table<CopilotChat.Provider.model>
---@field embed nil|string|fun(self: CopilotChat.Provider, inputs:table<string>, headers:table):table<CopilotChat.Provider.embed>
---@field prepare_input nil|fun(inputs:table<CopilotChat.Provider.input>, opts:CopilotChat.Provider.options):table
---@field prepare_output nil|fun(output:table, opts:CopilotChat.Provider.options):CopilotChat.Provider.output
---@field get_url nil|fun(self: CopilotChat.Provider, opts:CopilotChat.Provider.options):string
---@type table<string, CopilotChat.Provider>
local M = {}
M.copilot = {
embed = 'copilot_embeddings',
api_base = 'https://api.githubcopilot.com',
get_headers = function(self)
local response, err = utils.curl_get('https://api.github.com/copilot_internal/v2/token', {
json_response = true,
headers = {
['Authorization'] = 'Token ' .. get_github_token(),
},
})
if err then
error(err)
end
if response.body.endpoints and response.body.endpoints.api then
---@diagnostic disable-next-line: inject-field
self.api_base = response.body.endpoints.api
end
return {
['Authorization'] = 'Bearer ' .. response.body.token,
['Editor-Version'] = EDITOR_VERSION,
['Editor-Plugin-Version'] = 'CopilotChat.nvim/*',
['Copilot-Integration-Id'] = 'vscode-chat',
},
response.body.expires_at
end,
get_agents = function(self, headers)
---@diagnostic disable-next-line: undefined-field
local response, err = utils.curl_get(self.api_base .. '/agents', {
json_response = true,
headers = headers,
})
if err then
error(err)
end
return vim.tbl_map(function(agent)
return {
id = agent.slug,
name = agent.name,
description = agent.description,
}
end, response.body.agents)
end,
get_models = function(self, headers)
---@diagnostic disable-next-line: undefined-field
local response, err = utils.curl_get(self.api_base .. '/models', {
json_response = true,
headers = headers,
})
if err then
error(err)
end
local models = vim
.iter(response.body.data)
:filter(function(model)
return model.capabilities.type == 'chat' and not vim.endswith(model.id, 'paygo')
end)
:map(function(model)
return {
id = model.id,
name = model.name,
tokenizer = model.capabilities.tokenizer,
max_input_tokens = model.capabilities.limits.max_prompt_tokens,
max_output_tokens = model.capabilities.limits.max_output_tokens,
policy = not model['policy'] or model['policy']['state'] == 'enabled',
version = model.version,
}
end)
:totable()
local name_map = {}
for _, model in ipairs(models) do
if not name_map[model.name] or model.version > name_map[model.name].version then
name_map[model.name] = model
end
end
models = vim.tbl_values(name_map)
for _, model in ipairs(models) do
if not model.policy then
---@diagnostic disable-next-line: undefined-field
utils.curl_post(self.api_base .. '/models/' .. model.id .. '/policy', {
headers = headers,
json_request = true,
body = { state = 'enabled' },
})
end
end
return models
end,
prepare_input = function(inputs, opts)
local is_o1 = vim.startswith(opts.model.id, 'o1')
inputs = vim.tbl_map(function(input)
if is_o1 then
if input.role == 'system' then
input.role = 'user'
end
end
return input
end, inputs)
local out = {
messages = inputs,
model = opts.model.id,
}
if not is_o1 then
out.n = 1
out.top_p = 1
out.stream = true
out.temperature = opts.temperature
end
if opts.model.max_output_tokens then
out.max_tokens = opts.model.max_output_tokens
end
return out
end,
prepare_output = function(output)
local references = {}
if output.copilot_references then
for _, reference in ipairs(output.copilot_references) do
local metadata = reference.metadata
if metadata and metadata.display_name and metadata.display_url then
table.insert(references, {
name = metadata.display_name,
url = metadata.display_url,
})
end
end
end
local message
if output.choices and #output.choices > 0 then
message = output.choices[1]
else
message = output
end
local content = message.message and message.message.content or message.delta and message.delta.content
local usage = message.usage and message.usage.total_tokens or output.usage and output.usage.total_tokens
local finish_reason = message.finish_reason or message.done_reason or output.finish_reason or output.done_reason
return {
content = content,
finish_reason = finish_reason,
total_tokens = usage,
references = references,
}
end,
get_url = function(self, opts)
if opts.agent then
---@diagnostic disable-next-line: undefined-field
return self.api_base .. '/agents/' .. opts.agent.id .. '?chat'
end
---@diagnostic disable-next-line: undefined-field
return self.api_base .. '/chat/completions'
end,
}
M.github_models = {
embed = 'copilot_embeddings',
get_headers = function(self)
return {
['Authorization'] = 'Bearer ' .. get_github_token(),
['x-ms-useragent'] = EDITOR_VERSION,
['x-ms-user-agent'] = EDITOR_VERSION,
}
end,
get_models = function(self, headers)
local response, err = utils.curl_post('https://api.catalog.azureml.ms/asset-gallery/v1.0/models', {
headers = headers,
json_request = true,
json_response = true,
body = {
filters = {
{ field = 'freePlayground', values = { 'true' }, operator = 'eq' },
{ field = 'labels', values = { 'latest' }, operator = 'eq' },
},
order = {
{ field = 'displayName', direction = 'asc' },
},
},
})
if err then
error(err)
end
return vim
.iter(response.body.summaries)
:filter(function(model)
return vim.tbl_contains(model.inferenceTasks, 'chat-completion')
end)
:map(function(model)
local context_window = model.modelLimits.textLimits.inputContextWindow
local max_output_tokens = model.modelLimits.textLimits.maxOutputTokens
local max_input_tokens = context_window - max_output_tokens
if max_input_tokens <= 0 then
max_output_tokens = 4096
max_input_tokens = context_window - max_output_tokens
end
return {
id = model.name,
name = model.displayName,
tokenizer = 'o200k_base',
max_input_tokens = max_input_tokens,
max_output_tokens = max_output_tokens,
}
end)
:totable()
end,
prepare_input = M.copilot.prepare_input,
prepare_output = M.copilot.prepare_output,
get_url = function(self)
return 'https://models.inference.ai.azure.com/chat/completions'
end,
}
M.copilot_embeddings = {
get_headers = M.copilot.get_headers,
---@diagnostic disable-next-line: undefined-field
api_base = M.copilot.api_base,
embed = function(self, inputs, headers)
---@diagnostic disable-next-line: undefined-field
local response, err = utils.curl_post(self.api_base .. '/embeddings', {
headers = headers,
json_request = true,
json_response = true,
body = {
dimensions = 512,
input = inputs,
model = 'text-embedding-3-small',
},
})
if err then
error(err)
end
return response.body.data
end,
}
return M