bolt.diy/app/routes/api.enhancer.ts

96 lines
2.7 KiB
TypeScript
Raw Normal View History

2024-07-10 16:44:39 +00:00
import { type ActionFunctionArgs } from '@remix-run/cloudflare';
import { StreamingTextResponse, parseStreamPart } from 'ai';
import { streamText } from '~/lib/.server/llm/stream-text';
import { stripIndents } from '~/utils/stripIndent';
2024-11-12 00:10:54 +00:00
import type { StreamingOptions } from '~/lib/.server/llm/stream-text';
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-11-12 00:10:54 +00:00
const { message, model, provider, apiKeys } = await request.json<{
message: string;
model: string;
provider: string;
apiKeys?: Record<string, string>;
}>();
// Validate 'model' and 'provider' fields
if (!model || typeof model !== 'string') {
throw new Response('Invalid or missing model', {
status: 400,
statusText: 'Bad Request'
});
}
if (!provider || typeof provider !== 'string') {
throw new Response('Invalid or missing provider', {
status: 400,
statusText: 'Bad Request'
});
}
2024-07-10 16:44:39 +00:00
try {
const result = await streamText(
[
2024-07-10 16:44:39 +00:00
{
role: 'user',
2024-11-12 00:10:54 +00:00
content: `[Model: ${model}]\n\n[Provider: ${provider}]\n\n` + stripIndents`
I want you to improve the user prompt that is wrapped in \`<original_prompt>\` tags.
2024-07-10 16:44:39 +00:00
IMPORTANT: Only respond with the improved prompt and nothing else!
2024-07-10 16:44:39 +00:00
<original_prompt>
${message}
</original_prompt>
`,
2024-07-10 16:44:39 +00:00
},
],
context.cloudflare.env,
2024-11-12 00:10:54 +00:00
undefined,
apiKeys
);
2024-07-10 16:44:39 +00:00
const transformStream = new TransformStream({
transform(chunk, controller) {
2024-11-12 00:10:54 +00:00
const text = decoder.decode(chunk);
const lines = text.split('\n').filter(line => line.trim() !== '');
for (const line of lines) {
try {
const parsed = parseStreamPart(line);
if (parsed.type === 'text') {
controller.enqueue(encoder.encode(parsed.value));
}
} catch (e) {
// Skip invalid JSON lines
console.warn('Failed to parse stream part:', line);
}
}
2024-07-10 16:44:39 +00:00
},
});
const transformedStream = result.toAIStream().pipeThrough(transformStream);
return new StreamingTextResponse(transformedStream);
2024-11-12 00:10:54 +00:00
} catch (error: unknown) {
2024-07-10 16:44:39 +00:00
console.log(error);
2024-11-12 00:10:54 +00:00
if (error instanceof Error && error.message?.includes('API key')) {
throw new Response('Invalid or missing API key', {
status: 401,
statusText: 'Unauthorized'
});
}
2024-07-10 16:44:39 +00:00
throw new Response(null, {
status: 500,
statusText: 'Internal Server Error',
});
}
}