87 lines
4.6 KiB
TypeScript
87 lines
4.6 KiB
TypeScript
// This file should be placed in the `api` directory (e.g., `api/generate-plan.ts`)
|
|
// Vercel automatically deploys files in the /api directory as Serverless Functions.
|
|
|
|
// Using the Vercel Edge-compatible Request and Response
|
|
export default async function handler(request: Request) {
|
|
if (request.method !== 'POST') {
|
|
return new Response(`Method ${request.method} Not Allowed`, { status: 405, headers: { 'Allow': 'POST' } });
|
|
}
|
|
|
|
try {
|
|
const { goal } = await request.json();
|
|
|
|
if (!goal || typeof goal !== 'string') {
|
|
return new Response(JSON.stringify({ error: 'Goal is required and must be a string.' }), { status: 400, headers: { 'Content-Type': 'application/json' } });
|
|
}
|
|
|
|
const API_KEY = process.env.API_KEY;
|
|
if (!API_KEY) {
|
|
console.error("API_KEY environment variable not set.");
|
|
return new Response(JSON.stringify({ error: 'Server configuration error.' }), { status: 500, headers: { 'Content-Type': 'application/json' } });
|
|
}
|
|
|
|
const prompt = `You are an expert project manager. Your task is to take a user's goal and break it down into a detailed, step-by-step plan. Create a list of tasks required to achieve the following goal. For each task, provide a unique ID (a short, URL-friendly slug), a clear title, a concise description, an estimated duration in hours to complete the task, and list the IDs of any tasks that must be completed before this one can start (dependencies). Ensure the tasks are in a logical order. The final output must be a JSON array of these tasks.
|
|
|
|
Goal: "${goal}"`;
|
|
|
|
const generatePlanSchema = {
|
|
type: "ARRAY",
|
|
items: {
|
|
type: "OBJECT",
|
|
properties: {
|
|
id: { type: "STRING", description: 'A unique identifier for the task, preferably a short, URL-friendly slug (e.g., "setup-project").' },
|
|
title: { type: "STRING", description: 'A short, clear title for the task.' },
|
|
description: { type: "STRING", description: 'A detailed description of what needs to be done for this task.' },
|
|
dependencies: { type: "ARRAY", items: { type: "STRING" }, description: 'An array of task IDs that this task depends on. Leave empty if there are no dependencies.' },
|
|
durationInHours: { type: "NUMBER", description: 'The estimated number of hours required to complete this task. Can be a decimal for partial hours.' }
|
|
},
|
|
required: ['id', 'title', 'description', 'dependencies', 'durationInHours'],
|
|
},
|
|
};
|
|
|
|
const GEMINI_API_ENDPOINT = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${API_KEY}`;
|
|
|
|
const geminiReqBody = {
|
|
contents: [{ parts: [{ text: prompt }] }],
|
|
generationConfig: {
|
|
responseMimeType: "application/json",
|
|
responseSchema: generatePlanSchema,
|
|
}
|
|
};
|
|
|
|
const geminiRes = await fetch(GEMINI_API_ENDPOINT, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json' },
|
|
body: JSON.stringify(geminiReqBody),
|
|
});
|
|
|
|
if (!geminiRes.ok) {
|
|
const errorBody = await geminiRes.text();
|
|
console.error("Gemini API Error:", geminiRes.status, errorBody);
|
|
return new Response(JSON.stringify({ error: `Gemini API request failed with status ${geminiRes.status}` }), { status: 502, headers: { 'Content-Type': 'application/json' } });
|
|
}
|
|
|
|
const geminiData = await geminiRes.json();
|
|
const jsonText = geminiData?.candidates?.[0]?.content?.parts?.[0]?.text;
|
|
|
|
if (!jsonText) {
|
|
console.error("Invalid response structure from Gemini API:", geminiData);
|
|
return new Response(JSON.stringify({ error: "Failed to parse the plan from the AI's response." }), { status: 502, headers: { 'Content-Type': 'application/json' } });
|
|
}
|
|
|
|
// The response from the REST API is a string, so we return it directly.
|
|
// The client-side service will parse it.
|
|
return new Response(jsonText, { status: 200, headers: { 'Content-Type': 'application/json' } });
|
|
|
|
} catch (error) {
|
|
console.error('Error in generate-plan handler:', error);
|
|
const message = error instanceof Error ? error.message : 'An internal server error occurred.';
|
|
return new Response(JSON.stringify({ error: message }), { status: 500, headers: { 'Content-Type': 'application/json' } });
|
|
}
|
|
}
|
|
|
|
// Vercel specific configuration to ensure this runs on a Node.js runtime.
|
|
export const config = {
|
|
runtime: 'edge',
|
|
};
|