| 9 | } |
| 10 | |
| 11 | async function chatAction({ context, request }: ActionFunctionArgs) { |
| 12 | const { messages } = await request.json<{ messages: Messages }>(); |
| 13 | |
| 14 | const stream = new SwitchableStream(); |
| 15 | |
| 16 | try { |
| 17 | const options: StreamingOptions = { |
| 18 | toolChoice: 'none', |
| 19 | onFinish: async ({ text: content, finishReason }) => { |
| 20 | if (finishReason !== 'length') { |
| 21 | return stream.close(); |
| 22 | } |
| 23 | |
| 24 | if (stream.switches >= MAX_RESPONSE_SEGMENTS) { |
| 25 | throw Error('Cannot continue message: Maximum segments reached'); |
| 26 | } |
| 27 | |
| 28 | const switchesLeft = MAX_RESPONSE_SEGMENTS - stream.switches; |
| 29 | |
| 30 | console.log(`Reached max token limit (${MAX_TOKENS}): Continuing message (${switchesLeft} switches left)`); |
| 31 | |
| 32 | messages.push({ role: 'assistant', content }); |
| 33 | messages.push({ role: 'user', content: CONTINUE_PROMPT }); |
| 34 | |
| 35 | const result = await streamText(messages, context.cloudflare.env, options); |
| 36 | |
| 37 | return stream.switchSource(result.toAIStream()); |
| 38 | }, |
| 39 | }; |
| 40 | |
| 41 | const result = await streamText(messages, context.cloudflare.env, options); |
| 42 | |
| 43 | stream.switchSource(result.toAIStream()); |
| 44 | |
| 45 | return new Response(stream.readable, { |
| 46 | status: 200, |
| 47 | headers: { |
| 48 | contentType: 'text/plain; charset=utf-8', |
| 49 | }, |
| 50 | }); |
| 51 | } catch (error) { |
| 52 | console.log(error); |
| 53 | |
| 54 | throw new Response(null, { |
| 55 | status: 500, |
| 56 | statusText: 'Internal Server Error', |
| 57 | }); |
| 58 | } |
| 59 | } |