Skip to content

Commit

Permalink
trying to get response object to work?
Browse files Browse the repository at this point in the history
  • Loading branch information
huynle committed Feb 12, 2024
1 parent 8a53132 commit 36b6003
Show file tree
Hide file tree
Showing 6 changed files with 166 additions and 169 deletions.
144 changes: 40 additions & 104 deletions lua/ogpt/api.lua
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ local Config = require("ogpt.config")
local logger = require("ogpt.common.logger")
local Object = require("ogpt.common.object")
local utils = require("ogpt.utils")
local Response = require("ogpt.response")

local Api = Object("Api")

Expand All @@ -27,11 +28,15 @@ function Api:chat_completions(custom_params, partial_result_fn, should_stop, opt
ctx.model = custom_params.model
utils.log("Request to: " .. _completion_url)
utils.log(params)
local raw_chunks = ""
local state = "START"
-- local raw_chunks = ""
-- local state = "START"
partial_result_fn = vim.schedule_wrap(partial_result_fn)
local response = Response()
response.ctx = ctx
response.rest_params = params
response.partial_result_cb = partial_result_fn

if stream then
-- partial_result_fn = vim.schedule_wrap(partial_result_fn)
local accumulate = {}

self:exec(
Expand All @@ -48,94 +53,26 @@ function Api:chat_completions(custom_params, partial_result_fn, should_stop, opt
function(chunk)
local chunk_og = chunk
table.insert(accumulate, chunk_og)
local content = {
raw = chunk,
accumulate = accumulate,
content = raw_chunks or "",
state = state or "START",
ctx = ctx,
}
ctx, raw_chunks, state = self.provider:process_raw(content, partial_result_fn, opts)
--
-- local ok, json = pcall(vim.json.decode, chunk)
-- if not ok then
-- -- gemini is missing bracket on returns
-- chunk = string.gsub(chunk, "^%[", "")
-- chunk = string.gsub(chunk, "^%,", "")
-- chunk = string.gsub(chunk, "%]$", "")
-- chunk = vim.trim(chunk, "\n")
-- chunk = vim.trim(chunk, "\r")
-- ok, json = pcall(vim.json.decode, chunk)
-- end
--
-- -- if ok then
-- -- vim.print("okay")
-- -- else
-- -- vim.print("not okay")
-- -- end
--
-- if ok then
-- if json.error ~= nil then
-- local error_msg = {
-- "OGPT ERROR:",
-- self.provider.name,
-- vim.inspect(json.error) or "",
-- "Something went wrong.",
-- }
-- table.insert(error_msg, vim.inspect(params))
-- -- local error_msg = "OGPT ERROR: " .. (json.error.message or "Something went wrong")
-- partial_result_fn(table.concat(error_msg, " "), "ERROR", ctx)
-- return
-- end
-- ctx, raw_chunks, state =
-- self.provider:process_line({ json = json, raw = chunk }, ctx, raw_chunks, state, partial_result_fn, opts)
-- return
-- end
--
-- -- openai
-- for line in chunk:gmatch("[^\n]+") do
-- local raw_json = string.gsub(line, "^data:", "")
-- local _ok, _json = pcall(vim.json.decode, raw_json)
-- if _ok then
-- ctx, raw_chunks, state =
-- self.provider:process_line({ json = _json, raw = line }, ctx, raw_chunks, state, partial_result_fn, opts)
-- else
-- ctx, raw_chunks, state = self.provider:process_line(
-- { json = nil, raw = chunk_og },
-- ctx,
-- raw_chunks,
-- state,
-- partial_result_fn,
-- opts
-- )
-- end
-- end
--
-- if not ok then
-- -- if not ok, try to keep process the accumulated stdout
-- table.insert(accumulate, chunk_og)
-- ok, json = pcall(vim.json.decode, table.concat(accumulate, ""))
-- if ok then
-- ctx, raw_chunks, state = self.provider:process_line(
-- { json = json, raw = accumulate },
-- ctx,
-- raw_chunks,
-- state,
-- partial_result_fn,
-- opts
-- )
-- end
-- end
response:add_raw_chunk(chunk)
-- local content = {
-- raw = chunk,
-- accumulate = accumulate,
-- content = raw_chunks or "",
-- state = state or "START",
-- ctx = ctx,
-- params = params,
-- }
self.provider:process_raw(response)
end,
function(_text, _state, _ctx)
partial_result_fn(_text, _state, _ctx)
-- partial_result_fn(_text, _state, _ctx)
-- if opts.on_stop then
-- opts.on_stop()
-- end
end,
should_stop,
function()
partial_result_fn(raw_chunks, "END", ctx)
-- partial_result_fn(raw_chunks, "END", ctx)
-- if opts.on_stop then
-- opts.on_stop()
-- end
Expand Down Expand Up @@ -186,7 +123,7 @@ function Api:make_call(url, params, cb, ctx, raw_chunks, state, opts)
"An Error Occurred, when calling `curl " .. table.concat(curl_args, " ") .. "`",
vim.log.levels.ERROR
)
cb("ERROR: API Error")
cb("ERROR: API Error", "ERROR")
end

local result = table.concat(response:result(), "\n")
Expand Down Expand Up @@ -320,28 +257,27 @@ function Api:exec(cmd, args, on_stdout_chunk, on_complete, should_stop, on_stop)

local handle, err
local function on_stdout_read(_, chunk)
vim.schedule(function()
if chunk then
if should_stop and should_stop() then
if handle ~= nil then
handle:kill(2) -- send SIGINT
pcall(function()
stdout:close()
end)
pcall(function()
stderr:close()
end)
pcall(function()
handle:close()
end)
-- on_stop()
on_complete("", "END")
end
return
if chunk then
-- vim.schedule(function()
if should_stop and should_stop() then
if handle ~= nil then
handle:kill(2) -- send SIGINT
pcall(function()
stdout:close()
end)
pcall(function()
stderr:close()
end)
pcall(function()
handle:close()
end)
-- on_stop()
on_complete("", "END")
end
on_stdout_chunk(chunk)
end
end)
-- end)
on_stdout_chunk(chunk)
end
end

local function on_stderr_read(_, chunk)
Expand Down
70 changes: 34 additions & 36 deletions lua/ogpt/flows/actions/popup/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -103,46 +103,44 @@ function PopupAction:run()
end

function PopupAction:on_result(answer, usage)
vim.schedule(function()
self:set_loading(false)
local lines = utils.split_string_by_line(answer)
local _, start_row, start_col, end_row, end_col = self:get_visual_selection()
local bufnr = self:get_bufnr()
if self.strategy == STRATEGY_PREPEND then
answer = answer .. "\n" .. self:get_selected_text()
vim.api.nvim_buf_set_text(bufnr, start_row - 1, start_col - 1, end_row - 1, end_col, lines)
elseif self.strategy == STRATEGY_APPEND then
answer = self:get_selected_text() .. "\n\n" .. answer .. "\n"
vim.api.nvim_buf_set_text(bufnr, start_row - 1, start_col - 1, end_row - 1, end_col, lines)
elseif self.strategy == STRATEGY_REPLACE then
answer = answer
vim.api.nvim_buf_set_text(bufnr, start_row - 1, start_col - 1, end_row - 1, end_col, lines)
elseif self.strategy == STRATEGY_QUICK_FIX then
if #lines == 1 and lines[1] == "<OK>" then
vim.notify("Your Code looks fine, no issues.", vim.log.levels.INFO)
return
end
self:set_loading(false)
local lines = utils.split_string_by_line(answer)
local _, start_row, start_col, end_row, end_col = self:get_visual_selection()
local bufnr = self:get_bufnr()
if self.strategy == STRATEGY_PREPEND then
answer = answer .. "\n" .. self:get_selected_text()
vim.api.nvim_buf_set_text(bufnr, start_row - 1, start_col - 1, end_row - 1, end_col, lines)
elseif self.strategy == STRATEGY_APPEND then
answer = self:get_selected_text() .. "\n\n" .. answer .. "\n"
vim.api.nvim_buf_set_text(bufnr, start_row - 1, start_col - 1, end_row - 1, end_col, lines)
elseif self.strategy == STRATEGY_REPLACE then
answer = answer
vim.api.nvim_buf_set_text(bufnr, start_row - 1, start_col - 1, end_row - 1, end_col, lines)
elseif self.strategy == STRATEGY_QUICK_FIX then
if #lines == 1 and lines[1] == "<OK>" then
vim.notify("Your Code looks fine, no issues.", vim.log.levels.INFO)
return
end

local entries = {}
for _, line in ipairs(lines) do
local lnum, text = line:match("(%d+):(.*)")
if lnum then
local entry = { filename = vim.fn.expand("%:p"), lnum = tonumber(lnum), text = text }
table.insert(entries, entry)
end
end
if entries then
vim.fn.setqflist(entries)
vim.cmd(Config.options.show_quickfixes_cmd)
local entries = {}
for _, line in ipairs(lines) do
local lnum, text = line:match("(%d+):(.*)")
if lnum then
local entry = { filename = vim.fn.expand("%:p"), lnum = tonumber(lnum), text = text }
table.insert(entries, entry)
end
end

-- set the cursor onto the answer
if self.strategy == STRATEGY_APPEND then
local target_line = end_row + 3
vim.api.nvim_win_set_cursor(0, { target_line, 0 })
if entries then
vim.fn.setqflist(entries)
vim.cmd(Config.options.show_quickfixes_cmd)
end
end)
end

-- set the cursor onto the answer
if self.strategy == STRATEGY_APPEND then
local target_line = end_row + 3
vim.api.nvim_win_set_cursor(0, { target_line, 0 })
end
end

return PopupAction
11 changes: 7 additions & 4 deletions lua/ogpt/flows/chat/base.lua
Original file line number Diff line number Diff line change
Expand Up @@ -221,10 +221,12 @@ function Chat:addAnswer(text, usage)
self:add(ANSWER, text, usage)
end

function Chat:addAnswerPartial(text, state, ctx)
function Chat:addAnswerPartial(response, state)
local text = response.current_text
local ctx = response.ctx
if state == "ERROR" then
self:stopSpinner()
return self:addAnswer(text, {})
-- return self:addAnswer(text, {})
end

local start_line = 0
Expand All @@ -237,6 +239,7 @@ function Chat:addAnswerPartial(text, state, ctx)
-- -- most likely, ended by the using raising the stop flag
-- self:stopSpinner()
elseif state == "END" and text ~= "" then
self:stopSpinner()
local usage = {}
local idx = self.session:add_item({
type = ANSWER,
Expand All @@ -258,12 +261,12 @@ function Chat:addAnswerPartial(text, state, ctx)
idx = idx,
usage = usage or {},
type = ANSWER,
text = text,
text = response:get_total_processed_text(),
lines = lines,
nr_of_lines = nr_of_lines,
start_line = start_line,
end_line = end_line,
context = ctx.context,
context = response:get_context(),
})
self.selectedIndex = self.selectedIndex + 1
vim.api.nvim_buf_set_lines(self.chat_window.bufnr, -1, -1, false, { "", "" })
Expand Down
Loading

0 comments on commit 36b6003

Please sign in to comment.