import type { NextApiRequest, NextApiResponse } from 'next';
import { BedrockClient } from '../../../ai/services/bedrock-client';
const client = new BedrockClient();
export const config = {
api: {
bodyParser: true,
responseLimit: false,
},
};
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
const { prompt } = req.body;
if (!prompt) {
return res.status(400).json({ error: 'Prompt is required' });
}
try {
// Set headers for Server-Sent Events
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache, no-transform');
res.setHeader('Connection', 'keep-alive');
const stream = await client.generateText(prompt, {
streaming: true,
temperature: 0.7,
maxTokens: 4096
});
for await (const chunk of stream as AsyncIterable<string>) {
res.write(`data: ${JSON.stringify({ chunk })}\n\n`);
}
res.write('data: [DONE]\n\n');
res.end();
} catch (error) {
console.error('Streaming error:', error);
res.write(`data: ${JSON.stringify({ error: 'Streaming failed' })}\n\n`);
res.end();
}
}