#does this shit work with the pages

1 messages · Page 1 of 1 (latest)

fallen rapids
#

import { GoogleGenerativeAI } from '@google/generative-ai';
import { GoogleGenerativeAIStream, Message, StreamingTextResponse } from 'ai';

const genAI = new GoogleGenerativeAI(process.env.GOOGLE_API_KEY || '');

export const config = {
runtime: 'edge',
};

const buildGoogleGenAIPrompt = (messages: Message[]) => ({
contents: messages
.filter(
(message) => message.role === 'user' || message.role === 'assistant'
)
.map((message) => ({
role: message.role === 'user' ? 'user' : 'model',
parts: [{ text: message.content }],
})),
});

export default async function handler(req) {
if (req.method !== 'POST') {
return new Response('Method Not Allowed', { status: 405 });
}

try {
const { messages } = await req.json();
const geminiStream = await genAI
.getGenerativeModel({ model: 'gemini-pro' })
.generateContentStream(buildGoogleGenAIPrompt(messages));

const stream = GoogleGenerativeAIStream(geminiStream);
return new StreamingTextResponse(stream);

} catch (error) {
console.error(error);
return new Response('Internal Server Error', { status: 500 });
}
}