fix(openai): user and assistant roles should be alternating (#859)

This commit is contained in:
yetone 2024-11-17 03:49:02 +08:00 committed by GitHub
parent ff85b9c1e2
commit 9891b03656
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 25 additions and 6 deletions

View File

@ -19,12 +19,15 @@ M.parse_messages = function(opts)
vim.iter(opts.messages):each(function(message) vim.iter(opts.messages):each(function(message)
local role = message.role local role = message.role
if role == prev_role then if role == prev_role then
if role == "user" then if role == M.role_map["user"] then
table.insert(contents, { role = "model", parts = { table.insert(
{ text = "Ok, I understand." }, contents,
} }) { role = M.role_map["assistant"], parts = {
{ text = "Ok, I understand." },
} }
)
else else
table.insert(contents, { role = "user", parts = { table.insert(contents, { role = M.role_map["user"], parts = {
{ text = "Ok" }, { text = "Ok" },
} }) } })
end end

View File

@ -85,7 +85,23 @@ M.parse_messages = function(opts)
messages[#messages].content = message_content messages[#messages].content = message_content
end end
return messages local final_messages = {}
local prev_role = nil
vim.iter(messages):each(function(message)
local role = message.role
if role == prev_role then
if role == M.role_map["user"] then
table.insert(final_messages, { role = M.role_map["assistant"], content = "Ok, I understand." })
else
table.insert(final_messages, { role = M.role_map["user"], content = "Ok" })
end
end
prev_role = role
table.insert(final_messages, { role = M.role_map[role] or role, content = message.content })
end)
return final_messages
end end
M.parse_response = function(data_stream, _, opts) M.parse_response = function(data_stream, _, opts)