2024-07-10 16:44:39 +00:00
|
|
|
import { type ActionFunctionArgs } from '@remix-run/cloudflare';
|
2024-07-24 15:43:32 +00:00
|
|
|
import { MAX_RESPONSE_SEGMENTS, MAX_TOKENS } from '~/lib/.server/llm/constants';
|
|
|
|
import { CONTINUE_PROMPT } from '~/lib/.server/llm/prompts';
|
|
|
|
import { streamText, type Messages, type StreamingOptions } from '~/lib/.server/llm/stream-text';
|
|
|
|
import SwitchableStream from '~/lib/.server/llm/switchable-stream';
|
2024-07-10 16:44:39 +00:00
|
|
|
|
2024-07-29 18:31:45 +00:00
|
|
|
export async function action(args: ActionFunctionArgs) {
|
2024-09-26 16:45:41 +00:00
|
|
|
return chatAction(args);
|
2024-07-29 18:31:45 +00:00
|
|
|
}
|
|
|
|
|
2024-09-25 18:54:09 +00:00
|
|
|
async function chatAction({ context, request }: ActionFunctionArgs) {
|
2024-07-17 18:54:46 +00:00
|
|
|
const { messages } = await request.json<{ messages: Messages }>();
|
2024-07-25 15:28:23 +00:00
|
|
|
|
2024-07-19 09:12:55 +00:00
|
|
|
const stream = new SwitchableStream();
|
2024-07-10 16:44:39 +00:00
|
|
|
|
|
|
|
try {
|
2024-07-19 09:12:55 +00:00
|
|
|
const options: StreamingOptions = {
|
|
|
|
toolChoice: 'none',
|
2024-09-25 18:54:09 +00:00
|
|
|
onFinish: async ({ text: content, finishReason }) => {
|
2024-07-19 09:12:55 +00:00
|
|
|
if (finishReason !== 'length') {
|
|
|
|
return stream.close();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (stream.switches >= MAX_RESPONSE_SEGMENTS) {
|
2024-07-22 15:40:28 +00:00
|
|
|
throw Error('Cannot continue message: Maximum segments reached');
|
2024-07-19 09:12:55 +00:00
|
|
|
}
|
|
|
|
|
2024-07-22 15:40:28 +00:00
|
|
|
const switchesLeft = MAX_RESPONSE_SEGMENTS - stream.switches;
|
|
|
|
|
|
|
|
console.log(`Reached max token limit (${MAX_TOKENS}): Continuing message (${switchesLeft} switches left)`);
|
|
|
|
|
2024-07-19 09:12:55 +00:00
|
|
|
messages.push({ role: 'assistant', content });
|
|
|
|
messages.push({ role: 'user', content: CONTINUE_PROMPT });
|
|
|
|
|
|
|
|
const result = await streamText(messages, context.cloudflare.env, options);
|
|
|
|
|
|
|
|
return stream.switchSource(result.toAIStream());
|
|
|
|
},
|
|
|
|
};
|
|
|
|
|
|
|
|
const result = await streamText(messages, context.cloudflare.env, options);
|
|
|
|
|
|
|
|
stream.switchSource(result.toAIStream());
|
|
|
|
|
2024-08-08 15:48:36 +00:00
|
|
|
return new Response(stream.readable, {
|
|
|
|
status: 200,
|
|
|
|
headers: {
|
|
|
|
contentType: 'text/plain; charset=utf-8',
|
|
|
|
},
|
|
|
|
});
|
2024-07-10 16:44:39 +00:00
|
|
|
} catch (error) {
|
|
|
|
console.log(error);
|
|
|
|
|
|
|
|
throw new Response(null, {
|
|
|
|
status: 500,
|
|
|
|
statusText: 'Internal Server Error',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|