2023-05-25 10:32:35 +02:00
|
|
|
import { byId, isDefined } from '@typebot.io/lib'
|
2023-11-13 15:27:36 +01:00
|
|
|
import { ContinueChatResponse, SessionState } from '@typebot.io/schemas'
|
2023-05-25 10:32:35 +02:00
|
|
|
import { ChatCompletionOpenAIOptions } from '@typebot.io/schemas/features/blocks/integrations/openai'
|
|
|
|
import { VariableWithUnknowValue } from '@typebot.io/schemas/features/typebot/variable'
|
2023-12-13 10:22:02 +01:00
|
|
|
import { updateVariablesInSession } from '@typebot.io/variables/updateVariablesInSession'
|
2023-05-25 10:32:35 +02:00
|
|
|
|
|
|
|
export const resumeChatCompletion =
|
|
|
|
(
|
|
|
|
state: SessionState,
|
|
|
|
{
|
|
|
|
outgoingEdgeId,
|
|
|
|
options,
|
2023-07-18 14:31:20 +02:00
|
|
|
logs = [],
|
2023-06-16 16:50:23 +02:00
|
|
|
}: {
|
|
|
|
outgoingEdgeId?: string
|
|
|
|
options: ChatCompletionOpenAIOptions
|
2023-11-13 15:27:36 +01:00
|
|
|
logs?: ContinueChatResponse['logs']
|
2023-06-16 16:50:23 +02:00
|
|
|
}
|
2023-05-25 10:32:35 +02:00
|
|
|
) =>
|
|
|
|
async (message: string, totalTokens?: number) => {
|
|
|
|
let newSessionState = state
|
2023-11-08 15:34:16 +01:00
|
|
|
const newVariables = options.responseMapping?.reduce<
|
2023-05-25 10:32:35 +02:00
|
|
|
VariableWithUnknowValue[]
|
|
|
|
>((newVariables, mapping) => {
|
2023-08-24 07:48:30 +02:00
|
|
|
const { typebot } = newSessionState.typebotsQueue[0]
|
|
|
|
const existingVariable = typebot.variables.find(byId(mapping.variableId))
|
2023-05-25 10:32:35 +02:00
|
|
|
if (!existingVariable) return newVariables
|
|
|
|
if (mapping.valueToExtract === 'Message content') {
|
|
|
|
newVariables.push({
|
|
|
|
...existingVariable,
|
|
|
|
value: Array.isArray(existingVariable.value)
|
|
|
|
? existingVariable.value.concat(message)
|
|
|
|
: message,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
if (mapping.valueToExtract === 'Total tokens' && isDefined(totalTokens)) {
|
|
|
|
newVariables.push({
|
|
|
|
...existingVariable,
|
|
|
|
value: totalTokens,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return newVariables
|
|
|
|
}, [])
|
2023-11-08 15:34:16 +01:00
|
|
|
if (newVariables && newVariables.length > 0)
|
2023-09-20 15:26:52 +02:00
|
|
|
newSessionState = updateVariablesInSession(newSessionState)(newVariables)
|
2023-05-25 10:32:35 +02:00
|
|
|
return {
|
|
|
|
outgoingEdgeId,
|
|
|
|
newSessionState,
|
2023-06-16 16:50:23 +02:00
|
|
|
logs,
|
2023-05-25 10:32:35 +02:00
|
|
|
}
|
|
|
|
}
|