import { OpenAI } from "https://esm.town/v/std/openai";
const openai = new OpenAI();
export default async function(req: Request): Promise<Response> {
if (req.method === "POST") {
const { prompt } = await req.json();
if (!prompt) {
return new Response(JSON.stringify({ message: "Please provide a prompt field in your JSON body" }), {
status: 400,
statusText: "Bad Request",
});
}
try {
const llmResponse = await getLlmResponse(prompt);
return new Response(JSON.stringify({ llmResponse }), {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Content-Type": "application/json",
},
});
} catch (error) {
return new Response(JSON.stringify({ message: error.message }), {
status: 500,
statusText: "Internal Server Error",
});
}
}
if (req.method === "OPTIONS") {
return new Response("", {
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type",
},
});
}
return new Response(JSON.stringify({ message: "Please use POST method" }), {
status: 405,
statusText: "Method Not Allowed",
});
}
async function getLlmResponse(prompt: string) {
const completion = await openai.chat.completions.create({
"messages": [
{ "role": "user", "content": prompt },
],
model: "gpt-3.5-turbo",
max_tokens: 50,
});
return completion.choices[0].message.content;
}