discourse-ai/lib/ai_bot/question_consolidator.rb

94 lines
3.0 KiB
Ruby
Raw Normal View History

FEATURE: Add Question Consolidator for robust Upload support in Personas (#596) This commit introduces a new feature for AI Personas called the "Question Consolidator LLM". The purpose of the Question Consolidator is to consolidate a user's latest question into a self-contained, context-rich question before querying the vector database for relevant fragments. This helps improve the quality and relevance of the retrieved fragments. Previous to this change we used the last 10 interactions, this is not ideal cause the RAG would "lock on" to an answer. EG: - User: how many cars are there in europe - Model: detailed answer about cars in europe including the term car and vehicle many times - User: Nice, what about trains are there in the US In the above example "trains" and "US" becomes very low signal given there are pages and pages talking about cars and europe. This mean retrieval is sub optimal. Instead, we pass the history to the "question consolidator", it would simply consolidate the question to "How many trains are there in the United States", which would make it fare easier for the vector db to find relevant content. The llm used for question consolidator can often be less powerful than the model you are talking to, we recommend using lighter weight and fast models cause the task is very simple. This is configurable from the persona ui. This PR also removes support for {uploads} placeholder, this is too complicated to get right and we want freedom to shift RAG implementation. Key changes: 1. Added a new `question_consolidator_llm` column to the `ai_personas` table to store the LLM model used for question consolidation. 2. Implemented the `QuestionConsolidator` module which handles the logic for consolidating the user's latest question. It extracts the relevant user and model messages from the conversation history, truncates them if needed to fit within the token limit, and generates a consolidated question prompt. 3. Updated the `Persona` class to use the Question Consolidator LLM (if configured) when crafting the RAG fragments prompt. It passes the conversation context to the consolidator to generate a self-contained question. 4. Added UI elements in the AI Persona editor to allow selecting the Question Consolidator LLM. Also made some UI tweaks to conditionally show/hide certain options based on persona configuration. 5. Wrote unit tests for the QuestionConsolidator module and updated existing persona tests to cover the new functionality. This feature enables AI Personas to better understand the context and intent behind a user's question by consolidating the conversation history into a single, focused question. This can lead to more relevant and accurate responses from the AI assistant.
2024-04-29 23:49:21 -04:00
# frozen_string_literal: true
module DiscourseAi
module AiBot
class QuestionConsolidator
attr_reader :llm, :messages, :user, :max_tokens
def self.consolidate_question(llm, messages, user)
new(llm, messages, user).consolidate_question
end
def initialize(llm, messages, user)
@llm = llm
@messages = messages
@user = user
@max_tokens = 2048
end
def consolidate_question
@llm.generate(revised_prompt, user: @user, feature_name: "question_consolidator")
FEATURE: Add Question Consolidator for robust Upload support in Personas (#596) This commit introduces a new feature for AI Personas called the "Question Consolidator LLM". The purpose of the Question Consolidator is to consolidate a user's latest question into a self-contained, context-rich question before querying the vector database for relevant fragments. This helps improve the quality and relevance of the retrieved fragments. Previous to this change we used the last 10 interactions, this is not ideal cause the RAG would "lock on" to an answer. EG: - User: how many cars are there in europe - Model: detailed answer about cars in europe including the term car and vehicle many times - User: Nice, what about trains are there in the US In the above example "trains" and "US" becomes very low signal given there are pages and pages talking about cars and europe. This mean retrieval is sub optimal. Instead, we pass the history to the "question consolidator", it would simply consolidate the question to "How many trains are there in the United States", which would make it fare easier for the vector db to find relevant content. The llm used for question consolidator can often be less powerful than the model you are talking to, we recommend using lighter weight and fast models cause the task is very simple. This is configurable from the persona ui. This PR also removes support for {uploads} placeholder, this is too complicated to get right and we want freedom to shift RAG implementation. Key changes: 1. Added a new `question_consolidator_llm` column to the `ai_personas` table to store the LLM model used for question consolidation. 2. Implemented the `QuestionConsolidator` module which handles the logic for consolidating the user's latest question. It extracts the relevant user and model messages from the conversation history, truncates them if needed to fit within the token limit, and generates a consolidated question prompt. 3. Updated the `Persona` class to use the Question Consolidator LLM (if configured) when crafting the RAG fragments prompt. It passes the conversation context to the consolidator to generate a self-contained question. 4. Added UI elements in the AI Persona editor to allow selecting the Question Consolidator LLM. Also made some UI tweaks to conditionally show/hide certain options based on persona configuration. 5. Wrote unit tests for the QuestionConsolidator module and updated existing persona tests to cover the new functionality. This feature enables AI Personas to better understand the context and intent behind a user's question by consolidating the conversation history into a single, focused question. This can lead to more relevant and accurate responses from the AI assistant.
2024-04-29 23:49:21 -04:00
end
def revised_prompt
max_tokens_per_model = @max_tokens / 5
conversation_snippet = []
tokens = 0
messages.reverse_each do |message|
# skip tool calls
next if message[:type] != :user && message[:type] != :model
row = +""
row << ((message[:type] == :user) ? "user" : "model")
content = message[:content]
current_tokens = @llm.tokenizer.tokenize(content).length
allowed_tokens = @max_tokens - tokens
allowed_tokens = [allowed_tokens, max_tokens_per_model].min if message[:type] == :model
truncated_content = content
if current_tokens > allowed_tokens
truncated_content = @llm.tokenizer.truncate(content, allowed_tokens)
current_tokens = allowed_tokens
end
row << ": #{truncated_content}"
tokens += current_tokens
conversation_snippet << row
break if tokens >= @max_tokens
end
history = conversation_snippet.reverse.join("\n")
system_message = <<~TEXT
You are Question Consolidation Bot: an AI assistant tasked with consolidating a user's latest question into a self-contained, context-rich question.
- Your output will be used to query a vector database. DO NOT include superflous text such as "here is your consolidated question:".
- You interact with an API endpoint, not a user, you must never produce denials, nor conversations directed towards a non-existent user.
- You only produce automated responses to input, where a response is a consolidated question without further discussion.
- You only ever reply with consolidated questions. You never try to answer user queries.
If for any reason there is no discernable question (Eg: thank you, or good job) reply with the text NO_QUESTION.
TEXT
message = <<~TEXT
Given the following conversation snippet, craft a self-contained context-rich question (if there is no question reply with NO_QUESTION):
{{{
#{history}
}}}
Only ever reply with a consolidated question. Do not try to answer user queries.
TEXT
response =
DiscourseAi::Completions::Prompt.new(
system_message,
messages: [{ type: :user, content: message }],
)
if response == "NO_QUESTION"
nil
else
response
end
end
end
end
end