2023-06-08 06:31:35 +02:00
const { v4 : uuidv4 } = require ( "uuid" ) ;
const { WorkspaceChats } = require ( "../../models/workspaceChats" ) ;
2023-06-04 04:28:07 +02:00
const { resetMemory } = require ( "./commands/reset" ) ;
2023-06-08 06:31:35 +02:00
const moment = require ( "moment" ) ;
2023-08-04 23:56:27 +02:00
const { getVectorDbClass , getLLMProvider } = require ( "../helpers" ) ;
2023-06-04 04:28:07 +02:00
function convertToChatHistory ( history = [ ] ) {
2023-06-08 06:31:35 +02:00
const formattedHistory = [ ] ;
2023-06-04 04:28:07 +02:00
history . forEach ( ( history ) => {
2023-06-08 06:31:35 +02:00
const { prompt , response , createdAt } = history ;
2023-06-04 04:28:07 +02:00
const data = JSON . parse ( response ) ;
formattedHistory . push ( [
{
2023-06-08 06:31:35 +02:00
role : "user" ,
2023-06-04 04:28:07 +02:00
content : prompt ,
sentAt : moment ( createdAt ) . unix ( ) ,
} ,
{
2023-06-08 06:31:35 +02:00
role : "assistant" ,
2023-06-04 04:28:07 +02:00
content : data . text ,
sources : data . sources || [ ] ,
sentAt : moment ( createdAt ) . unix ( ) ,
} ,
2023-06-08 06:31:35 +02:00
] ) ;
} ) ;
2023-06-04 04:28:07 +02:00
2023-06-08 06:31:35 +02:00
return formattedHistory . flat ( ) ;
2023-06-04 04:28:07 +02:00
}
function convertToPromptHistory ( history = [ ] ) {
2023-06-08 06:31:35 +02:00
const formattedHistory = [ ] ;
2023-06-04 04:28:07 +02:00
history . forEach ( ( history ) => {
2023-06-08 06:31:35 +02:00
const { prompt , response } = history ;
2023-06-04 04:28:07 +02:00
const data = JSON . parse ( response ) ;
formattedHistory . push ( [
2023-06-08 06:31:35 +02:00
{ role : "user" , content : prompt } ,
{ role : "assistant" , content : data . text } ,
] ) ;
} ) ;
return formattedHistory . flat ( ) ;
2023-06-04 04:28:07 +02:00
}
const VALID _COMMANDS = {
2023-06-08 06:31:35 +02:00
"/reset" : resetMemory ,
} ;
2023-06-04 04:28:07 +02:00
function grepCommand ( message ) {
const availableCommands = Object . keys ( VALID _COMMANDS ) ;
for ( let i = 0 ; i < availableCommands . length ; i ++ ) {
const cmd = availableCommands [ i ] ;
const re = new RegExp ( ` ^( ${ cmd } ) ` , "i" ) ;
if ( re . test ( message ) ) {
return cmd ;
}
}
2023-06-08 06:31:35 +02:00
return null ;
2023-06-04 04:28:07 +02:00
}
2023-07-25 19:37:04 +02:00
async function chatWithWorkspace (
workspace ,
message ,
chatMode = "chat" ,
user = null
) {
2023-06-04 04:28:07 +02:00
const uuid = uuidv4 ( ) ;
2023-06-08 06:31:35 +02:00
const command = grepCommand ( message ) ;
2023-06-04 04:28:07 +02:00
if ( ! ! command && Object . keys ( VALID _COMMANDS ) . includes ( command ) ) {
2023-07-25 19:37:04 +02:00
return await VALID _COMMANDS [ command ] ( workspace , message , uuid , user ) ;
2023-06-04 04:28:07 +02:00
}
2023-10-30 23:44:03 +01:00
const LLMConnector = getLLMProvider ( ) ;
const VectorDb = getVectorDbClass ( ) ;
2023-08-04 23:56:27 +02:00
const { safe , reasons = [ ] } = await LLMConnector . isSafe ( message ) ;
2023-06-04 04:28:07 +02:00
if ( ! safe ) {
return {
id : uuid ,
2023-06-08 06:31:35 +02:00
type : "abort" ,
2023-06-04 04:28:07 +02:00
textResponse : null ,
sources : [ ] ,
close : true ,
2023-06-08 06:31:35 +02:00
error : ` This message was moderated and will not be allowed. Violations for ${ reasons . join (
", "
) } found . ` ,
2023-06-04 04:28:07 +02:00
} ;
}
2023-11-01 22:12:27 +01:00
const messageLimit = workspace ? . openAiHistory || 20 ;
2023-06-08 06:31:35 +02:00
const hasVectorizedSpace = await VectorDb . hasNamespace ( workspace . slug ) ;
2023-07-25 19:37:04 +02:00
const embeddingsCount = await VectorDb . namespaceCount ( workspace . slug ) ;
if ( ! hasVectorizedSpace || embeddingsCount === 0 ) {
2024-01-16 18:32:51 +01:00
if ( chatMode === "query" ) {
return {
id : uuid ,
type : "textResponse" ,
sources : [ ] ,
close : true ,
error : null ,
textResponse :
"There is no relevant information in this workspace to answer your query." ,
} ;
}
2023-11-06 22:13:53 +01:00
// If there are no embeddings - chat like a normal LLM chat interface.
return await emptyEmbeddingChat ( {
uuid ,
2023-07-25 19:37:04 +02:00
user ,
2023-11-06 22:13:53 +01:00
message ,
workspace ,
messageLimit ,
LLMConnector ,
2023-06-08 06:31:35 +02:00
} ) ;
2023-11-06 22:13:53 +01:00
}
const { rawHistory , chatHistory } = await recentChatHistory (
user ,
workspace ,
messageLimit ,
chatMode
) ;
const {
contextTexts = [ ] ,
sources = [ ] ,
message : error ,
} = await VectorDb . performSimilaritySearch ( {
namespace : workspace . slug ,
input : message ,
LLMConnector ,
2023-11-07 01:49:29 +01:00
similarityThreshold : workspace ? . similarityThreshold ,
2023-11-06 22:13:53 +01:00
} ) ;
// Failed similarity search.
if ( ! ! error ) {
2023-06-04 04:28:07 +02:00
return {
id : uuid ,
2023-11-06 22:13:53 +01:00
type : "abort" ,
textResponse : null ,
2023-06-04 04:28:07 +02:00
sources : [ ] ,
close : true ,
2023-11-06 22:13:53 +01:00
error ,
2023-06-04 04:28:07 +02:00
} ;
2023-11-06 22:13:53 +01:00
}
2024-01-16 18:32:51 +01:00
// If in query mode and no sources are found, do not
// let the LLM try to hallucinate a response or use general knowledge
if ( chatMode === "query" && sources . length === 0 ) {
return {
id : uuid ,
type : "textResponse" ,
sources : [ ] ,
close : true ,
error : null ,
textResponse :
"There is no relevant information in this workspace to answer your query." ,
} ;
}
2023-11-06 22:13:53 +01:00
// Compress message to ensure prompt passes token limit with room for response
// and build system messages based on inputs and history.
const messages = await LLMConnector . compressMessages (
{
systemPrompt : chatPrompt ( workspace ) ,
userPrompt : message ,
contextTexts ,
2023-06-27 00:08:47 +02:00
chatHistory ,
2023-11-06 22:13:53 +01:00
} ,
rawHistory
) ;
2023-06-04 04:28:07 +02:00
2023-11-06 22:13:53 +01:00
// Send the text completion.
const textResponse = await LLMConnector . getChatCompletion ( messages , {
temperature : workspace ? . openAiTemp ? ? 0.7 ,
} ) ;
if ( ! textResponse ) {
2023-06-04 04:28:07 +02:00
return {
id : uuid ,
2023-11-06 22:13:53 +01:00
type : "abort" ,
textResponse : null ,
sources : [ ] ,
2023-06-04 04:28:07 +02:00
close : true ,
2023-11-06 22:13:53 +01:00
error : "No text completion could be completed with this input." ,
2023-06-04 04:28:07 +02:00
} ;
}
2023-11-06 22:13:53 +01:00
await WorkspaceChats . new ( {
workspaceId : workspace . id ,
prompt : message ,
response : { text : textResponse , sources , type : chatMode } ,
user ,
} ) ;
return {
id : uuid ,
type : "textResponse" ,
close : true ,
textResponse ,
sources ,
error ,
} ;
}
// On query we dont return message history. All other chat modes and when chatting
// with no embeddings we return history.
async function recentChatHistory (
user = null ,
workspace ,
messageLimit = 20 ,
chatMode = null
) {
if ( chatMode === "query" ) return [ ] ;
const rawHistory = (
user
? await WorkspaceChats . forWorkspaceByUser (
workspace . id ,
user . id ,
messageLimit ,
{ id : "desc" }
)
: await WorkspaceChats . forWorkspace ( workspace . id , messageLimit , {
id : "desc" ,
} )
) . reverse ( ) ;
return { rawHistory , chatHistory : convertToPromptHistory ( rawHistory ) } ;
}
async function emptyEmbeddingChat ( {
uuid ,
user ,
message ,
workspace ,
messageLimit ,
LLMConnector ,
} ) {
const { rawHistory , chatHistory } = await recentChatHistory (
user ,
workspace ,
messageLimit
) ;
const textResponse = await LLMConnector . sendChat (
chatHistory ,
message ,
workspace ,
rawHistory
) ;
await WorkspaceChats . new ( {
workspaceId : workspace . id ,
prompt : message ,
response : { text : textResponse , sources : [ ] , type : "chat" } ,
user ,
} ) ;
return {
id : uuid ,
type : "textResponse" ,
sources : [ ] ,
close : true ,
error : null ,
textResponse ,
} ;
2023-06-04 04:28:07 +02:00
}
2023-07-20 20:14:23 +02:00
function chatPrompt ( workspace ) {
return (
workspace ? . openAiPrompt ? ?
"Given the following conversation, relevant context, and a follow up question, reply with an answer to the current question the user is asking. Return only your response to the question given the above information following the users instructions as needed."
) ;
}
2023-06-04 04:28:07 +02:00
module . exports = {
2023-11-14 00:07:30 +01:00
recentChatHistory ,
2023-11-06 22:13:53 +01:00
convertToPromptHistory ,
2023-06-04 04:28:07 +02:00
convertToChatHistory ,
2023-06-08 06:31:35 +02:00
chatWithWorkspace ,
2023-07-20 20:14:23 +02:00
chatPrompt ,
2023-11-14 00:07:30 +01:00
grepCommand ,
VALID _COMMANDS ,
2023-06-08 06:31:35 +02:00
} ;