2024-07-10 16:44:39 +00:00
|
|
|
import { type ActionFunctionArgs } from '@remix-run/cloudflare';
|
2024-07-17 18:54:46 +00:00
|
|
|
import { StreamingTextResponse, parseStreamPart } from 'ai';
|
2024-07-24 15:43:32 +00:00
|
|
|
import { streamText } from '~/lib/.server/llm/stream-text';
|
|
|
|
import { stripIndents } from '~/utils/stripIndent';
|
2024-07-10 16:44:39 +00:00
|
|
|
|
|
|
|
const encoder = new TextEncoder();
|
|
|
|
const decoder = new TextDecoder();
|
|
|
|
|
2024-07-29 18:31:45 +00:00
|
|
|
export async function action(args: ActionFunctionArgs) {
|
2024-09-26 16:45:41 +00:00
|
|
|
return enhancerAction(args);
|
2024-07-29 18:31:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function enhancerAction({ context, request }: ActionFunctionArgs) {
|
2024-07-10 16:44:39 +00:00
|
|
|
const { message } = await request.json<{ message: string }>();
|
|
|
|
|
|
|
|
try {
|
2024-07-17 18:54:46 +00:00
|
|
|
const result = await streamText(
|
|
|
|
[
|
2024-07-10 16:44:39 +00:00
|
|
|
{
|
|
|
|
role: 'user',
|
|
|
|
content: stripIndents`
|
2024-07-17 18:54:46 +00:00
|
|
|
I want you to improve the user prompt that is wrapped in \`<original_prompt>\` tags.
|
2024-07-10 16:44:39 +00:00
|
|
|
|
2024-07-17 18:54:46 +00:00
|
|
|
IMPORTANT: Only respond with the improved prompt and nothing else!
|
2024-07-10 16:44:39 +00:00
|
|
|
|
2024-07-17 18:54:46 +00:00
|
|
|
<original_prompt>
|
|
|
|
${message}
|
|
|
|
</original_prompt>
|
|
|
|
`,
|
2024-07-10 16:44:39 +00:00
|
|
|
},
|
2024-07-17 18:54:46 +00:00
|
|
|
],
|
|
|
|
context.cloudflare.env,
|
|
|
|
);
|
2024-07-10 16:44:39 +00:00
|
|
|
|
|
|
|
const transformStream = new TransformStream({
|
|
|
|
transform(chunk, controller) {
|
|
|
|
const processedChunk = decoder
|
|
|
|
.decode(chunk)
|
|
|
|
.split('\n')
|
|
|
|
.filter((line) => line !== '')
|
|
|
|
.map(parseStreamPart)
|
|
|
|
.map((part) => part.value)
|
|
|
|
.join('');
|
|
|
|
|
|
|
|
controller.enqueue(encoder.encode(processedChunk));
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
const transformedStream = result.toAIStream().pipeThrough(transformStream);
|
|
|
|
|
|
|
|
return new StreamingTextResponse(transformedStream);
|
|
|
|
} catch (error) {
|
|
|
|
console.log(error);
|
|
|
|
|
|
|
|
throw new Response(null, {
|
|
|
|
status: 500,
|
|
|
|
statusText: 'Internal Server Error',
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|