Skip to content

Commit

Permalink
fix(copilot): show token output in chat
Browse files Browse the repository at this point in the history
Thanks to @GitMurf for this original PR in #623
  • Loading branch information
olimorris committed Jan 9, 2025
1 parent 6dd3309 commit 6908fd7
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion lua/codecompanion/adapters/copilot.lua
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,17 @@ local function authorize_token()
return _github_token
end

---Prepare data to be parsed as JSON
---@param data string | { body: string }
---@return string
local prepare_data_for_json = function(data)
if type(data) == "table" then
return data.body
end
local find_json_start = string.find(data, "{") or 1
return string.sub(data, find_json_start)
end

---@class Copilot.Adapter: CodeCompanion.Adapter
return {
name = "copilot",
Expand Down Expand Up @@ -166,7 +177,21 @@ return {
return openai.handlers.form_messages(self, messages)
end,
tokens = function(self, data)
return openai.handlers.tokens(self, data)
if data and data ~= "" then
local data_mod = prepare_data_for_json(data)
local ok, json = pcall(vim.json.decode, data_mod, { luanil = { object = true } })

if ok then
if json.usage then
local total_tokens = json.usage.total_tokens or 0
local completion_tokens = json.usage.completion_tokens or 0
local prompt_tokens = json.usage.prompt_tokens or 0
local tokens = total_tokens > 0 and total_tokens or completion_tokens + prompt_tokens
log:trace("Tokens: %s", tokens)
return tokens
end
end
end
end,
chat_output = function(self, data)
return openai.handlers.chat_output(self, data)
Expand Down

0 comments on commit 6908fd7

Please sign in to comment.