Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
⚡ (openai) Stream chat completion to avoid serverless timeout (#526)
Closes #520
- Loading branch information
1 parent
6bb6a2b
commit 56364fd
Showing
39 changed files
with
556 additions
and
121 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
103 changes: 103 additions & 0 deletions
103
apps/viewer/src/features/blocks/integrations/openai/getChatCompletionStream.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
import { parseVariableNumber } from '@/features/variables/parseVariableNumber' | ||
import { Connection } from '@planetscale/database' | ||
import { decrypt } from '@typebot.io/lib/api/encryption' | ||
import { | ||
ChatCompletionOpenAIOptions, | ||
OpenAICredentials, | ||
} from '@typebot.io/schemas/features/blocks/integrations/openai' | ||
import { SessionState } from '@typebot.io/schemas/features/chat' | ||
import { | ||
ParsedEvent, | ||
ReconnectInterval, | ||
createParser, | ||
} from 'eventsource-parser' | ||
import type { | ||
ChatCompletionRequestMessage, | ||
CreateChatCompletionRequest, | ||
} from 'openai' | ||
|
||
export const getChatCompletionStream = | ||
(conn: Connection) => | ||
async ( | ||
state: SessionState, | ||
options: ChatCompletionOpenAIOptions, | ||
messages: ChatCompletionRequestMessage[] | ||
) => { | ||
if (!options.credentialsId) return | ||
const credentials = ( | ||
await conn.execute('select data, iv from Credentials where id=?', [ | ||
options.credentialsId, | ||
]) | ||
).rows.at(0) as { data: string; iv: string } | undefined | ||
if (!credentials) { | ||
console.error('Could not find credentials in database') | ||
return | ||
} | ||
const { apiKey } = (await decrypt( | ||
credentials.data, | ||
credentials.iv | ||
)) as OpenAICredentials['data'] | ||
|
||
const temperature = parseVariableNumber(state.typebot.variables)( | ||
options.advancedSettings?.temperature | ||
) | ||
|
||
const encoder = new TextEncoder() | ||
const decoder = new TextDecoder() | ||
|
||
let counter = 0 | ||
|
||
const res = await fetch('https://api.openai.com/v1/chat/completions', { | ||
headers: { | ||
'Content-Type': 'application/json', | ||
Authorization: `Bearer ${apiKey}`, | ||
}, | ||
method: 'POST', | ||
body: JSON.stringify({ | ||
messages, | ||
model: options.model, | ||
temperature, | ||
stream: true, | ||
} satisfies CreateChatCompletionRequest), | ||
}) | ||
|
||
const stream = new ReadableStream({ | ||
async start(controller) { | ||
function onParse(event: ParsedEvent | ReconnectInterval) { | ||
if (event.type === 'event') { | ||
const data = event.data | ||
if (data === '[DONE]') { | ||
controller.close() | ||
return | ||
} | ||
try { | ||
const json = JSON.parse(data) as { | ||
choices: { delta: { content: string } }[] | ||
} | ||
const text = json.choices.at(0)?.delta.content | ||
if (counter < 2 && (text?.match(/\n/) || []).length) { | ||
return | ||
} | ||
const queue = encoder.encode(text) | ||
controller.enqueue(queue) | ||
counter++ | ||
} catch (e) { | ||
controller.error(e) | ||
} | ||
} | ||
} | ||
|
||
// stream response (SSE) from OpenAI may be fragmented into multiple chunks | ||
// this ensures we properly read chunks & invoke an event for each SSE event stream | ||
const parser = createParser(onParse) | ||
|
||
// https://web.dev/streams/#asynchronous-iteration | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
for await (const chunk of res.body as any) { | ||
parser.feed(decoder.decode(chunk)) | ||
} | ||
}, | ||
}) | ||
|
||
return stream | ||
} |
Oops, something went wrong.
56364fd
There was a problem hiding this comment.
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:
landing-page-v2 – ./apps/landing-page
typebot.io
get-typebot.com
www.typebot.io
www.get-typebot.com
landing-page-v2-git-main-typebot-io.vercel.app
landing-page-v2-typebot-io.vercel.app
56364fd
There was a problem hiding this comment.
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
lb.ticketfute.com
ov1.wpwakanda.com
ov2.wpwakanda.com
ov3.wpwakanda.com
support.triplo.ai
viewer.typebot.io
welcome.triplo.ai
1988.bouclidom.com
chatbot.matthesv.de
chatbot.repplai.com
demo.botscientis.us
demo.wemakebots.xyz
hrbot.robomotion.io
inearephones.cr8.ai
kbsub.wpwakanda.com
limitenahora.com.br
live.botscientis.us
mentoria.omelhor.vc
nutrisamirbayde.com
order.maitempah.com
profileadscloud.com
query.forgetsql.com
quest.wpwakanda.com
support.wawplus.com
survey1.digienge.io
surveys.essiell.com
test.botscientis.us
test.getreview.help
test.reventepro.com
typebot.stillio.com
wordsandimagery.com
88584434.therpm.club
92109660.therpm.club
abbonamento.bwell.it
assistent.m-vogel.de
bium.gratirabbit.com
bot.ansuraniphone.my
bot.barrettamario.it
bot.cotemeuplano.com
bot.leadbooster.help
bot.mycompay.reviews
chat.hayurihijab.com
chatbee.agfunnel.com
click.sevenoways.com
connect.growthguy.in
forms.bonanza.design
hello.advergreen.com
kuiz.sistemniaga.com
menu.numero-primo.it
menukb.wpwakanda.com
offer.botscientis.us
sellmycarglasgow.com
talkbot.agfunnel.com
tenorioadvogados.com
uppity.wpwakanda.com
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
open.campus.aalen.university
piazzatorre.barrettamario.it
poll.mosaicohairboutique.com
type.cookieacademyonline.com
upload.atlasoutfittersk9.com
bot.brigadeirosemdrama.com.br
tuttirecepcao.fratucci.com.br
forms.escoladeautomacao.com.br
onboarding.libertydreamcare.ie
recepcao.tutti.fratucci.com.br
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
baleia.testeeventos.progenbr.com
bot.cabin-rentals-of-georgia.net
open.campus.bot.aalen.university
sondaggio.mosaicohairboutique.it
baleia.testegabinete.progenbr.com
gerador.verificadordehospedes.com
personal-trainer.barrettamario.it
sondaggio.mosaicohairboutique.com
preagendamento.sergiolimajr.com.br
studiotecnicoimmobiliaremerelli.it
download.thailandmicespecialist.com
register.thailandmicespecialist.com
bot.studiotecnicoimmobiliaremerelli.it
pesquisa.escolamodacomproposito.com.br
anamnese.clinicaramosodontologia.com.br
gabinete.baleia.formulario.progenbr.com
chrome-os-inquiry-system.itschromeos.com
viewer-v2-git-main-typebot-io.vercel.app
main-menu-for-itschromeos.itschromeos.com
56364fd
There was a problem hiding this comment.
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.vercel.app
docs.typebot.io
docs-git-main-typebot-io.vercel.app
56364fd
There was a problem hiding this comment.
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-git-main-typebot-io.vercel.app
builder-v2-typebot-io.vercel.app
app.typebot.io