Skip to content

Commit

Permalink
⚡ (openai) Truncate messages sequence automatically if reaching token…
Browse files Browse the repository at this point in the history
… limit
  • Loading branch information
baptisteArno committed May 2, 2023
1 parent 9473563 commit e58016e
Show file tree
Hide file tree
Showing 6 changed files with 73 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ export const TemplatesModal = ({ isOpen, onClose, onTypebotChoose }: Props) => {
borderRightWidth={1}
justify="space-between"
flexShrink={0}
overflowY="scroll"
className="hide-scrollbar"
>
<Stack spacing={5}>
<Stack spacing={2}>
Expand Down
2 changes: 1 addition & 1 deletion apps/builder/src/hooks/useToast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const useToast = () => {
}: Omit<ToastProps, 'onClose'>) => {
toast({
position: 'top-right',
duration: details ? null : undefined,
duration: details && status === 'error' ? null : undefined,
render: ({ onClose }) => (
<Toast
title={title}
Expand Down
11 changes: 6 additions & 5 deletions apps/viewer/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,15 @@
"test:report": "pnpm playwright show-report"
},
"dependencies": {
"@dqbd/tiktoken": "^1.0.7",
"@sentry/nextjs": "7.46.0",
"@trpc/server": "10.18.0",
"@typebot.io/js": "workspace:*",
"@typebot.io/prisma": "workspace:*",
"@typebot.io/react": "workspace:*",
"aws-sdk": "2.1348.0",
"bot-engine": "workspace:*",
"cors": "2.8.5",
"@typebot.io/prisma": "workspace:*",
"google-spreadsheet": "3.3.0",
"got": "12.6.0",
"libphonenumber-js": "1.10.24",
Expand All @@ -39,6 +40,10 @@
"@faire/mjml-react": "3.2.0",
"@paralleldrive/cuid2": "2.2.0",
"@playwright/test": "1.32.1",
"@typebot.io/emails": "workspace:*",
"@typebot.io/lib": "workspace:*",
"@typebot.io/schemas": "workspace:*",
"@typebot.io/tsconfig": "workspace:*",
"@types/cors": "2.8.13",
"@types/google-spreadsheet": "3.3.1",
"@types/node": "18.15.11",
Expand All @@ -48,17 +53,13 @@
"@types/react": "18.0.32",
"@types/sanitize-html": "2.9.0",
"dotenv": "16.0.3",
"@typebot.io/emails": "workspace:*",
"eslint": "8.37.0",
"eslint-config-custom": "workspace:*",
"google-auth-library": "8.7.0",
"@typebot.io/schemas": "workspace:*",
"node-fetch": "3.3.1",
"papaparse": "5.4.1",
"superjson": "1.12.2",
"@typebot.io/tsconfig": "workspace:*",
"typescript": "5.0.3",
"@typebot.io/lib": "workspace:*",
"zod": "3.21.4"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
import {
ChatCompletionOpenAIOptions,
OpenAICredentials,
modelLimit,
} from '@typebot.io/schemas/features/blocks/integrations/openai'
import { OpenAIApi, Configuration, ChatCompletionRequestMessage } from 'openai'
import { isDefined, byId, isNotEmpty, isEmpty } from '@typebot.io/lib'
Expand All @@ -20,6 +21,9 @@ import { updateVariables } from '@/features/variables/updateVariables'
import { parseVariables } from '@/features/variables/parseVariables'
import { saveSuccessLog } from '@/features/logs/saveSuccessLog'
import { parseVariableNumber } from '@/features/variables/parseVariableNumber'
import { encoding_for_model } from '@dqbd/tiktoken'

const minTokenCompletion = 200

export const createChatCompletionOpenAI = async (
state: SessionState,
Expand Down Expand Up @@ -56,7 +60,8 @@ export const createChatCompletionOpenAI = async (
apiKey,
})
const { variablesTransformedToList, messages } = parseMessages(
newSessionState.typebot.variables
newSessionState.typebot.variables,
options.model
)(options.messages)
if (variablesTransformedToList.length > 0)
newSessionState = await updateVariables(state)(variablesTransformedToList)
Expand Down Expand Up @@ -148,16 +153,19 @@ export const createChatCompletionOpenAI = async (
}

const parseMessages =
(variables: Variable[]) =>
(variables: Variable[], model: ChatCompletionOpenAIOptions['model']) =>
(
messages: ChatCompletionOpenAIOptions['messages']
): {
variablesTransformedToList: VariableWithValue[]
messages: ChatCompletionRequestMessage[]
} => {
const variablesTransformedToList: VariableWithValue[] = []
const firstMessagesSequenceIndex = messages.findIndex(
(message) => message.role === 'Messages sequence ✨'
)
const parsedMessages = messages
.flatMap((message) => {
.flatMap((message, index) => {
if (!message.role) return
if (message.role === 'Messages sequence ✨') {
if (
Expand Down Expand Up @@ -189,23 +197,51 @@ const parseMessages =
variable.id === message.content?.assistantMessagesVariableId
)?.value ?? []) as string[]

let allMessages: ChatCompletionRequestMessage[] = []

if (userMessages.length > assistantMessages.length)
return userMessages.flatMap((userMessage, index) => [
allMessages = userMessages.flatMap((userMessage, index) => [
{
role: 'user',
content: userMessage,
},
{ role: 'assistant', content: assistantMessages[index] },
{ role: 'assistant', content: assistantMessages.at(index) ?? '' },
]) satisfies ChatCompletionRequestMessage[]
else {
return assistantMessages.flatMap((assistantMessage, index) => [
{ role: 'assistant', content: assistantMessage },
{
role: 'user',
content: userMessages[index],
},
]) satisfies ChatCompletionRequestMessage[]
allMessages = assistantMessages.flatMap(
(assistantMessage, index) => [
{ role: 'assistant', content: assistantMessage },
{
role: 'user',
content: userMessages.at(index) ?? '',
},
]
) satisfies ChatCompletionRequestMessage[]
}

if (index !== firstMessagesSequenceIndex) return allMessages

const encoder = encoding_for_model(model)
let messagesToSend: ChatCompletionRequestMessage[] = []
let tokenCount = 0

for (let i = allMessages.length - 1; i >= 0; i--) {
const message = allMessages[i]
const tokens = encoder.encode(message.content)

if (
tokenCount + tokens.length - minTokenCompletion >
modelLimit[model]
) {
break
}
tokenCount += tokens.length
messagesToSend = [message, ...messagesToSend]
}

encoder.free()

return messagesToSend
}
return {
role: message.role,
Expand Down
9 changes: 9 additions & 0 deletions packages/schemas/features/blocks/integrations/openai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,15 @@ export const chatCompletionModels = [
'gpt-3.5-turbo-0301',
] as const

export const modelLimit = {
'gpt-3.5-turbo': 4096,
'gpt-3.5-turbo-0301': 4096,
'gpt-4': 8192,
'gpt-4-0314': 8192,
'gpt-4-32k': 32768,
'gpt-4-32k-0314': 32768,
} as const

export const chatCompletionMessageRoles = [
'system',
'user',
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 comments on commit e58016e

@vercel
Copy link

@vercel vercel bot commented on e58016e May 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

docs – ./apps/docs

docs.typebot.io
docs-typebot-io.vercel.app
docs-git-main-typebot-io.vercel.app

@vercel
Copy link

@vercel vercel bot commented on e58016e May 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

viewer-v2 – ./apps/viewer

cadu.uninta.edu.br
chat.hand-made.one
chat.tuanpakya.com
dicanatural.online
test.leadbooster.help
zillabot.saaszilla.co
815639944.21000000.one
83720273.bouclidom.com
aplicacao.bmind.com.br
apply.ansuraniphone.my
bbutton.wpwwakanda.com
bolsamaisbrasil.app.br
bot.ilmuseoaiborghi.it
bot.louismarcondes.com
bot.pratikmandalia.com
bot.t20worldcup.com.au
bot2.mycompany.reviews
bot3.mycompany.reviews
bot4.mycompany.reviews
c23111azqw.nigerias.io
chat.footballmeetup.ie
dieta.barrettamario.it
felipewelington.com.br
form.bridesquadapp.com
form.searchcube.com.sg
gcase.barrettamario.it
help.giversforgood.com
info.clickasuransi.com
kodawariab736.skeep.it
michaeljackson.riku.ai
premium.kandabrand.com
report.gratirabbit.com
resume.gratirabbit.com
83242573.actualizar.xyz
87656003.actualizar.xyz
88152257.actualizar.xyz
91375310.actualizar.xyz
app.youvisitedthis.site
arrivalx2.wpwakanda.com
bot.blackboxtips.com.br
bot.hotelplayarimini.it
bot.upgradesolutions.eu
bots.baptiste-arnaud.fr
help.comebackreward.com
link.venturasuceder.com
mainmenu.diddancing.com
manualhandlingcourse.ie
primitive-shapes.cr8.ai
register.kandabrand.com
sell.sellitwithgary.com
signup.hypemarketing.in
subfooter.wpwakanda.com
survey.hypemarketing.in
rsvp.virtuesocialmedia.com
tarian.theiofoundation.org
ted.meujalecobrasil.com.br
type.dericsoncalari.com.br
bot.pinpointinteractive.com
bot.polychromes-project.com
bot.seidinembroseanchetu.it
chat.semanalimpanome.com.br
designguide.techyscouts.com
liveconvert2.kandalearn.com
poll.mosaicohairboutique.it
presente.empresarias.com.mx
register.algorithmpress.com
sell.sellthemotorhome.co.uk
anamnese.odontopavani.com.br
austin.channelautomation.com
bot.marketingplusmindset.com
bot.seidibergamoseanchetu.it
desabafe.sergiolimajr.com.br
download.venturemarketing.in
piazzatorre.barrettamario.it
type.cookieacademyonline.com
upload.atlasoutfittersk9.com
bot.brigadeirosemdrama.com.br
forms.escoladeautomacao.com.br
onboarding.libertydreamcare.ie
type.talitasouzamarques.com.br
agendamento.sergiolimajr.com.br
anamnese.clinicamegasjdr.com.br
bookings.littlepartymonkeys.com
bot.comercializadoraomicron.com
elevateyourmind.groovepages.com
viewer-v2-typebot-io.vercel.app
yourfeedback.comebackreward.com
bot.cabin-rentals-of-georgia.net
gerador.verificadordehospedes.com
personal-trainer.barrettamario.it
preagendamento.sergiolimajr.com.br
studiotecnicoimmobiliaremerelli.it
download.thailandmicespecialist.com
register.thailandmicespecialist.com
bot.studiotecnicoimmobiliaremerelli.it
pesquisa.escolamodacomproposito.com.br
anamnese.clinicaramosodontologia.com.br
chrome-os-inquiry-system.itschromeos.com
viewer-v2-git-main-typebot-io.vercel.app
main-menu-for-itschromeos.itschromeos.com

@vercel
Copy link

@vercel vercel bot commented on e58016e May 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

builder-v2 – ./apps/builder

builder-v2-typebot-io.vercel.app
builder-v2-git-main-typebot-io.vercel.app
app.typebot.io

@vercel
Copy link

@vercel vercel bot commented on e58016e May 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.