2023-10-30 10:56:33 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module DiscourseAi
|
|
|
|
module AiHelper
|
|
|
|
class ChatThreadTitler
|
|
|
|
def initialize(thread)
|
|
|
|
@thread = thread
|
|
|
|
end
|
|
|
|
|
|
|
|
def suggested_title
|
2024-02-07 13:05:50 -05:00
|
|
|
@thread.then { thread_content(_1) }.then { call_llm(_1) }.then { cleanup(_1) }
|
|
|
|
end
|
|
|
|
|
|
|
|
def call_llm(thread_content)
|
2023-11-27 07:33:31 -05:00
|
|
|
return nil if thread_content.blank?
|
2023-10-30 10:56:33 -04:00
|
|
|
|
2024-02-07 13:05:50 -05:00
|
|
|
chat = "<input>\n#{thread_content}\n</input>"
|
2023-10-30 10:56:33 -04:00
|
|
|
|
2024-02-07 13:05:50 -05:00
|
|
|
prompt =
|
|
|
|
DiscourseAi::Completions::Prompt.new(
|
|
|
|
<<~TEXT.strip,
|
|
|
|
I want you to act as a title generator for chat between users. I will provide you with the chat transcription,
|
|
|
|
and you will generate a single attention-grabbing title. Please keep the title concise and under 15 words
|
|
|
|
and ensure that the meaning is maintained. The title will utilize the same language type of the chat.
|
|
|
|
I want you to only reply the suggested title and nothing else, do not write explanations.
|
2024-02-09 12:49:28 -05:00
|
|
|
You will find the chat between <input></input> XML tags. Return the suggested title between <title> tags.
|
2024-02-07 13:05:50 -05:00
|
|
|
TEXT
|
|
|
|
messages: [{ type: :user, content: chat, id: "User" }],
|
2023-11-27 11:03:24 -05:00
|
|
|
)
|
|
|
|
|
2024-02-07 13:05:50 -05:00
|
|
|
DiscourseAi::Completions::Llm.proxy(SiteSetting.ai_helper_model).generate(
|
|
|
|
prompt,
|
|
|
|
user: Discourse.system_user,
|
2024-02-09 12:49:28 -05:00
|
|
|
stop_sequences: ["</input>"],
|
2024-02-07 13:05:50 -05:00
|
|
|
)
|
|
|
|
end
|
2023-11-27 11:03:24 -05:00
|
|
|
|
2024-02-07 13:05:50 -05:00
|
|
|
def cleanup(title)
|
2024-02-09 12:49:28 -05:00
|
|
|
(Nokogiri::HTML5.fragment(title).at("title")&.text || title)
|
|
|
|
.split("\n")
|
|
|
|
.first
|
|
|
|
.then { _1.match?(/^("|')(.*)("|')$/) ? _1[1..-2] : _1 }
|
|
|
|
.truncate(100, separator: " ")
|
2024-02-07 13:05:50 -05:00
|
|
|
end
|
2023-11-27 11:03:24 -05:00
|
|
|
|
2024-02-07 13:05:50 -05:00
|
|
|
def thread_content(thread)
|
|
|
|
# TODO: Replace me by a proper API call
|
2023-11-27 11:03:24 -05:00
|
|
|
thread
|
|
|
|
.chat_messages
|
|
|
|
.joins(:user)
|
|
|
|
.pluck(:username, :message)
|
|
|
|
.map { |username, message| "#{username}: #{message}" }
|
|
|
|
.join("\n")
|
|
|
|
end
|
2024-02-07 13:05:50 -05:00
|
|
|
|
|
|
|
attr_reader :thread
|
2023-10-30 10:56:33 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|